feat(link): the app's side of the relay: identity, line, TLS at the app, certificates (P15 B3)
The app keeps one durable address https://<secret>.<four-words>.wanderbooks.link: an Ed25519 key, a four-word name the app picks, and a 32-character base-36 secret label (about 165 bits), all in private (0600 / owner-only) files in the data root's link/ folder. One name per installation, as plan section 5 says; each company is a path under it. The line (yamux over TLS 1.3, the relay crate's own client) runs in the app's own process, not in the books server child: a window that dies takes its sockets with it, so the line can never keep a door open for books that closed. It reconnects with full-jitter backoff, pings every 30 s (the relay drops a line silent for 180 s), re-dials at once after a wall-clock jump (a sleep), and says in words what is wrong: no internet, the relay down, a busy relay, a wrong clock, a name the relay lost. TLS ends in the app with its own certificate (rustls, ALPN h2 and http/1.1), served only for the app's exact host name, then the plain stream goes to the remote door on 127.0.0.1 after the door's per-start secret and the relay's PROXY header. The private keys are never sent to the relay. Certificates are ordered by ACME DNS-01 (instant-acme, behind an Issuer trait so tests use an in-process authority) for the wildcard under the app's name, from the relay's authority list in its order (a not-usable one is skipped, a failing one falls to the next), stored, reused across restarts, and renewed at the time the authority's renewal information suggests, else two thirds through the life. New dependencies: instant-acme 0.8 (Apache-2.0; ring, hyper-rustls, time and x509-parser features, no aws-lc-rs), x509-parser 0.18 and webpki-root-certs 1 (already in the tree), time and async-trait for tests. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
a9fec9ee27
commit
9898e56950
14 files changed
+3852
-2
No files matched your search
@@ -0,0 +1,594 @@
|
||||
//! The link, end to end on localhost: an in-process relay (the relay
|
||||
//! crate's own), an in-process certificate authority that checks the proof
|
||||
//! in the relay's DNS, a stand-in for the remote door, and an assistant.
|
||||
//! Nothing here touches a network beyond 127.0.0.1.
|
||||
#![allow(missing_docs)]
|
||||
|
||||
mod support;
|
||||
|
||||
use ledger_link::{Dial, Step, Trouble};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use support::*;
|
||||
|
||||
fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// WB-link-1 to WB-link-3: claim, prove, line up, certificate; then a web
|
||||
/// caller's TLS connection through the relay is ended at the app and the
|
||||
/// door is given the secret, the caller's address and plain HTTP; and
|
||||
/// what crossed the relay was ciphertext.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_caller_through_the_relay_reaches_the_door_and_the_relay_sees_only_ciphertext() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
assert_eq!(w.link.status().step(), Step::Off);
|
||||
w.link.turn_on().unwrap();
|
||||
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
assert!(s.claimed && s.line_up && s.cert_expires.is_some());
|
||||
assert_eq!(w.env.relay.shared().lines.len(), 1);
|
||||
assert_eq!(
|
||||
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
|
||||
1
|
||||
);
|
||||
|
||||
let host = w.host();
|
||||
// The address is `<secret>.<four words>.<domain>`, the secret 25 or
|
||||
// more characters of a-z and 0-9.
|
||||
let parts: Vec<&str> = host.split('.').collect();
|
||||
assert_eq!(parts.len(), 4, "{host}");
|
||||
assert!(
|
||||
parts[0].len() >= 25
|
||||
&& parts[0]
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
);
|
||||
assert_eq!(format!("{}.{}", parts[2], parts[3]), DOMAIN);
|
||||
|
||||
let reply = w
|
||||
.assistant(&host)
|
||||
.await
|
||||
.expect("TLS completes with the app");
|
||||
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
|
||||
assert!(reply.ends_with(BODY));
|
||||
// The door was given the secret first, then the caller's address as
|
||||
// the relay saw it, then plain HTTP with no TLS in it.
|
||||
let seen = w.door.seen.lock().unwrap().clone();
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(seen[0].secret_ok);
|
||||
let from_relay = w.caller_tap.source_ports.lock().unwrap().clone();
|
||||
assert_eq!(seen[0].caller, from_relay.first().copied());
|
||||
assert!(seen[0].request.starts_with("GET /ping HTTP/1.1\r\n"));
|
||||
|
||||
// What crossed the relay, both ways, is TLS: the request and the reply
|
||||
// are not in it in the clear.
|
||||
for crossed in [
|
||||
w.caller_tap.seen_up(),
|
||||
w.caller_tap.seen_down(),
|
||||
w.tap.seen_up(),
|
||||
w.tap.seen_down(),
|
||||
] {
|
||||
assert!(!crossed.is_empty());
|
||||
assert!(!contains(&crossed, b"GET /ping"));
|
||||
assert!(!contains(&crossed, BODY.as_bytes()));
|
||||
assert!(!contains(&crossed, SECRET.as_bytes()));
|
||||
}
|
||||
// The caller's own bytes carried the name in the clear (the relay
|
||||
// routes on it) and the app's certificate only inside TLS 1.3.
|
||||
assert!(contains(&w.caller_tap.seen_up(), host.as_bytes()));
|
||||
// Nothing private was sent to the relay: not the line's key, not the
|
||||
// certificate's key, not the account.
|
||||
let key = std::fs::read(w.dir.path().join("link/line.key")).unwrap();
|
||||
let cert: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
|
||||
.unwrap();
|
||||
let cert_key = cert["key_pem"].as_str().unwrap().to_owned();
|
||||
for crossed in [w.tap.seen_up(), w.tap.seen_down(), w.caller_tap.seen_up()] {
|
||||
assert!(!contains(&crossed, &key));
|
||||
assert!(!contains(&crossed, cert_key.as_bytes()));
|
||||
assert!(!contains(&crossed, b"PRIVATE KEY"));
|
||||
}
|
||||
}
|
||||
|
||||
/// WB-link-1: the key and certificate files are private, and the secret
|
||||
/// label is in no status text.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_key_the_certificate_and_the_label_are_private() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let dir = w.dir.path().join("link");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode =
|
||||
|p: std::path::PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode(dir.clone()), 0o700);
|
||||
for f in ["identity.json", "line.key", "cert.json"] {
|
||||
assert_eq!(mode(dir.join(f)), 0o600, "{f}");
|
||||
}
|
||||
}
|
||||
let host = w.host();
|
||||
let label = host.split('.').next().unwrap();
|
||||
let status = format!("{:?} {}", w.link.status(), w.link.status().words());
|
||||
assert!(!status.contains(label));
|
||||
// The label is not the name's, nor guessable from the files' times.
|
||||
assert!(!host.split('.').nth(1).unwrap().contains(label));
|
||||
}
|
||||
|
||||
/// WB-link-1, 4: off means off (the line ends, the certificate stops being
|
||||
/// served), the name is kept, on again is the same address, and a restart
|
||||
/// of the app reuses the stored certificate: one order in all.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart() {
|
||||
let mut w = world(LIST, |_| {}).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let host = w.host();
|
||||
assert_eq!(w.fake.orders(), 1);
|
||||
|
||||
w.link.turn_off();
|
||||
let s = w.link.status();
|
||||
assert_eq!(s.step(), Step::Off);
|
||||
assert!(s.address.is_none());
|
||||
// The relay lost the line, and a caller is turned away.
|
||||
eventually("the relay lost the line", || {
|
||||
w.env.relay.shared().lines.is_empty()
|
||||
})
|
||||
.await;
|
||||
assert!(w.assistant(&host).await.is_err());
|
||||
// The name is kept.
|
||||
assert_eq!(
|
||||
w.link
|
||||
.kept_address()
|
||||
.unwrap()
|
||||
.trim_start_matches("https://"),
|
||||
host
|
||||
);
|
||||
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
|
||||
assert_eq!(w.host(), host);
|
||||
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
|
||||
assert_eq!(
|
||||
w.fake.orders(),
|
||||
1,
|
||||
"a certificate already held is not ordered again"
|
||||
);
|
||||
// The name was claimed once.
|
||||
assert_eq!(
|
||||
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
|
||||
1
|
||||
);
|
||||
|
||||
// The app is closed and started again.
|
||||
w.link.turn_off();
|
||||
w.restart(|_| {});
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected after a restart", |s| {
|
||||
s.step() == Step::Connected
|
||||
})
|
||||
.await;
|
||||
assert_eq!(w.host(), host);
|
||||
assert_eq!(w.fake.orders(), 1, "a restart orders nothing");
|
||||
assert_eq!(
|
||||
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
|
||||
1
|
||||
);
|
||||
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
|
||||
}
|
||||
|
||||
/// WB-link-1: a new address replaces the secret label and the old one
|
||||
/// stops working at once; the name, the key and the certificate stay.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_new_address_stops_the_old_one() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let old = w.host();
|
||||
assert!(w.assistant(&old).await.is_ok());
|
||||
|
||||
let new = w.link.new_address().unwrap();
|
||||
let new = new.trim_start_matches("https://").to_owned();
|
||||
assert_ne!(new, old);
|
||||
// Same name, a different label.
|
||||
assert_eq!(
|
||||
old.split_once('.').unwrap().1,
|
||||
new.split_once('.').unwrap().1
|
||||
);
|
||||
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
|
||||
assert_eq!(w.host(), new);
|
||||
assert!(
|
||||
w.assistant(&old).await.is_err(),
|
||||
"the old address no longer gets a certificate"
|
||||
);
|
||||
assert!(w.assistant(&new).await.unwrap().ends_with(BODY));
|
||||
assert_eq!(w.fake.orders(), 1, "the wildcard certificate still serves");
|
||||
// The apex and a made-up label get nothing either.
|
||||
let name = new.split_once('.').unwrap().1.to_owned();
|
||||
assert!(w.assistant(&name).await.is_err());
|
||||
assert!(
|
||||
w.assistant(&format!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.{name}"))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// WB-link-2: the relay drops the line, and the app dials again by itself.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_line_comes_back_after_the_relay_drops_it() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let before = w.tap.accepted.load(Ordering::SeqCst);
|
||||
let host = w.host();
|
||||
|
||||
w.tap.sever();
|
||||
eventually("the app dialled again", || {
|
||||
w.tap.accepted.load(Ordering::SeqCst) > before
|
||||
})
|
||||
.await;
|
||||
until(&w.link, "connected again", |s| {
|
||||
s.line_up && s.step() == Step::Connected
|
||||
})
|
||||
.await;
|
||||
eventually("the relay has the line", || {
|
||||
w.env.relay.shared().lines.len() == 1
|
||||
})
|
||||
.await;
|
||||
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
|
||||
// The name was not claimed again; the proof is the key.
|
||||
assert_eq!(
|
||||
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
/// WB-link-2: pings keep an idle line. The relay drops a line silent for
|
||||
/// its idle limit; this one outlives several of them.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn pings_keep_an_idle_line_and_silence_loses_it() {
|
||||
let mut limits = relay_limits();
|
||||
limits.line_idle_ms = 700;
|
||||
let w = world_with(limits, LIST, |t| {
|
||||
t.ping_every = Duration::from_millis(150);
|
||||
})
|
||||
.await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let dialled = w.tap.accepted.load(Ordering::SeqCst);
|
||||
tokio::time::sleep(Duration::from_millis(2500)).await;
|
||||
assert_eq!(
|
||||
w.tap.accepted.load(Ordering::SeqCst),
|
||||
dialled,
|
||||
"an idle but pinged line is never dropped and redialled"
|
||||
);
|
||||
assert!(w.link.status().line_up);
|
||||
// Without pings the same relay drops it.
|
||||
let silent = world_with(
|
||||
{
|
||||
let mut l = relay_limits();
|
||||
l.line_idle_ms = 500;
|
||||
l
|
||||
},
|
||||
LIST,
|
||||
|t| t.ping_every = Duration::from_secs(3600),
|
||||
)
|
||||
.await;
|
||||
silent.link.turn_on().unwrap();
|
||||
until(&silent.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let first = silent.tap.accepted.load(Ordering::SeqCst);
|
||||
eventually("the silent line was dropped and dialled again", || {
|
||||
silent.tap.accepted.load(Ordering::SeqCst) > first
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
fn relay_limits() -> relay::Limits {
|
||||
support::common::quick_limits()
|
||||
}
|
||||
|
||||
/// WB-link-5: with the relay unreachable the state says so in words and
|
||||
/// mends itself; the people at the window lose nothing.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn an_unreachable_relay_says_so_in_words_and_recovers_by_itself() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.tap.refuse.store(true, Ordering::SeqCst);
|
||||
w.link.turn_on().unwrap();
|
||||
let s = until(&w.link, "a trouble", |s| s.trouble.is_some()).await;
|
||||
assert_eq!(s.trouble, Some(Trouble::RelayDown));
|
||||
assert_eq!(s.step(), Step::GettingAddress);
|
||||
assert!(s.problem().unwrap().contains("keeps trying"));
|
||||
assert!(s.problem().unwrap().contains("on this computer still work"));
|
||||
// Several failed dials, spaced by backoff: not a hot loop.
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
assert!(w.tap.accepted.load(Ordering::SeqCst) < 25);
|
||||
// The network comes back.
|
||||
w.tap.refuse.store(false, Ordering::SeqCst);
|
||||
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
assert!(s.trouble.is_none() && s.cert_trouble.is_none());
|
||||
}
|
||||
|
||||
/// WB-link-5: no internet at all (the relay's name does not resolve) is
|
||||
/// said as that.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn no_internet_is_said_as_that() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
// Rebuild the link with a dial that cannot resolve.
|
||||
let mut cfg = config(&w);
|
||||
cfg.dial = Dial::Host("relay.nonexistent.invalid".into(), 443);
|
||||
cfg.dir = w.dir.path().join("link2");
|
||||
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
|
||||
link.turn_on().unwrap();
|
||||
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
|
||||
assert_eq!(s.trouble, Some(Trouble::NoInternet));
|
||||
assert!(s.problem().unwrap().contains("can't reach the internet"));
|
||||
link.turn_off();
|
||||
}
|
||||
|
||||
/// WB-link-5: a relay whose certificate is not valid yet or has ended
|
||||
/// means this clock is wrong; it is said so, and the state keeps trying.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_wrong_clock_is_said_as_that() {
|
||||
use rcgen::{CertificateParams, KeyPair};
|
||||
let w = world(LIST, |_| {}).await;
|
||||
// A TLS server with a certificate that ended yesterday.
|
||||
let mut params = CertificateParams::new(vec![RELAY_HOST.to_string()]).unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
params.not_before = now - time::Duration::days(30);
|
||||
params.not_after = now - time::Duration::days(1);
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let cert = params.self_signed(&key).unwrap();
|
||||
let chain = vec![cert.der().clone()];
|
||||
let pk = rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
|
||||
key.serialize_der(),
|
||||
));
|
||||
let server = relay::tls::server_config(chain, pk).unwrap();
|
||||
let acceptor = tokio_rustls::TlsAcceptor::from(server);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((s, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let a = acceptor.clone();
|
||||
tokio::spawn(async move {
|
||||
let _ = a.accept(s).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
roots.add(cert.der().clone()).unwrap();
|
||||
let mut cfg = config(&w);
|
||||
cfg.dial = Dial::Addr(addr);
|
||||
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
|
||||
cfg.dir = w.dir.path().join("link3");
|
||||
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
|
||||
link.turn_on().unwrap();
|
||||
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
|
||||
assert_eq!(s.trouble, Some(Trouble::ClockWrong));
|
||||
assert!(s.problem().unwrap().contains("clock"));
|
||||
assert!(Trouble::ClockWrong.mends_itself());
|
||||
link.turn_off();
|
||||
}
|
||||
|
||||
/// WB-link-1, 5: a relay that no longer knows the name says so in words,
|
||||
/// and a new address (a whole new identity) claims a new name and carries on.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on() {
|
||||
let mut w = world(LIST, |_| {}).await;
|
||||
// A second relay, with an empty registry, whose certificate this app
|
||||
// trusts too.
|
||||
let fresh = support::common::start_with(
|
||||
support::common::quick_limits(),
|
||||
relay::authorities::AuthorityList::from_toml(LIST).unwrap(),
|
||||
)
|
||||
.await;
|
||||
let mut roots = fresh.relay_ca.roots();
|
||||
roots
|
||||
.roots
|
||||
.extend(w.env.relay_ca.roots().roots.iter().cloned());
|
||||
let mut cfg = config(&w);
|
||||
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
|
||||
w.link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
|
||||
w.link.set_door(Some(w.door.target.clone()));
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let old = w.host();
|
||||
*w.tap.upstream.lock().unwrap() = fresh.router();
|
||||
w.tap.sever();
|
||||
let s = until(&w.link, "the name is lost", |s| {
|
||||
s.trouble == Some(Trouble::NameLost)
|
||||
})
|
||||
.await;
|
||||
assert!(s.problem().unwrap().contains("Get a new address"));
|
||||
let new = w.link.new_address().unwrap();
|
||||
assert_ne!(new.trim_start_matches("https://"), old);
|
||||
until(&w.link, "claimed a new name", |s| s.claimed && s.line_up).await;
|
||||
assert_eq!(
|
||||
fresh.relay.shared().metrics.claims.load(Ordering::Relaxed),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
/// WB-link-4: the authorities are the relay's list, in its order; one
|
||||
/// marked not usable is skipped; the first failing falls to the second;
|
||||
/// the certificate is kept 0600 and reused; and the wildcard is for this
|
||||
/// name and none other.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_first_authority_fails_and_the_second_issues() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.fake.state.lock().unwrap().fail.insert("first".into());
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let orders: Vec<String> = w
|
||||
.fake
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.orders
|
||||
.iter()
|
||||
.map(|o| o.authority.clone())
|
||||
.collect();
|
||||
assert_eq!(orders, ["first", "second"]);
|
||||
let host = w.host();
|
||||
let name = host.split_once('.').unwrap().1;
|
||||
let id = w.fake.state.lock().unwrap().orders[1].identifier.clone();
|
||||
assert_eq!(id, format!("*.{name}"));
|
||||
// The relay's DNS holds no proof once the order is done.
|
||||
let proofs = dns_txt(
|
||||
w.env.relay.dns_udp_addr(),
|
||||
&format!("_acme-challenge.{name}."),
|
||||
)
|
||||
.await;
|
||||
assert!(proofs.is_empty(), "{proofs:?}");
|
||||
}
|
||||
|
||||
/// WB-link-4: an authority that needs a binding the relay has none for is
|
||||
/// listed and not usable: it is skipped, and the next is used.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn an_authority_that_is_not_usable_is_skipped() {
|
||||
const LIST_BINDING: &str = r#"
|
||||
[[authority]]
|
||||
id = "needs-binding"
|
||||
directory = "https://fake.example/b"
|
||||
caa_domain = "b.example"
|
||||
needs_binding = true
|
||||
|
||||
[[authority]]
|
||||
id = "plain"
|
||||
directory = "https://fake.example/p"
|
||||
caa_domain = "p.example"
|
||||
"#;
|
||||
let w = world(LIST_BINDING, |_| {}).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let orders: Vec<String> = w
|
||||
.fake
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.orders
|
||||
.iter()
|
||||
.map(|o| o.authority.clone())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
orders,
|
||||
["plain"],
|
||||
"the one that is not usable was never asked"
|
||||
);
|
||||
}
|
||||
|
||||
/// WB-link-4: every authority failing is a state in words that is retried
|
||||
/// and mends itself; the line stays up meanwhile.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn every_authority_failing_is_said_and_retried_until_one_works() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
{
|
||||
let mut st = w.fake.state.lock().unwrap();
|
||||
st.fail.insert("first".into());
|
||||
st.fail.insert("second".into());
|
||||
}
|
||||
w.link.turn_on().unwrap();
|
||||
let s = until(&w.link, "a certificate trouble", |s| {
|
||||
s.cert_trouble.is_some()
|
||||
})
|
||||
.await;
|
||||
assert_eq!(s.step(), Step::GettingCertificate);
|
||||
assert!(s.line_up);
|
||||
let words = s.problem().unwrap();
|
||||
assert!(
|
||||
words.contains("could not get a certificate") && words.contains("keeps trying"),
|
||||
"{words}"
|
||||
);
|
||||
// Retried, with a wait.
|
||||
eventually("several tries", || w.fake.orders() >= 4).await;
|
||||
// The authority comes back.
|
||||
w.fake.state.lock().unwrap().fail.clear();
|
||||
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
assert!(s.cert_trouble.is_none());
|
||||
}
|
||||
|
||||
/// WB-link-4: renewal ahead of expiry, at the time the authority's
|
||||
/// renewal information suggests, naming the certificate it replaces; the
|
||||
/// certificate that serves keeps serving while a renewal fails.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn the_certificate_is_renewed_at_the_authoritys_suggested_time() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
w.fake.state.lock().unwrap().window = Some((1, 2));
|
||||
w.link.turn_on().unwrap();
|
||||
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let first_end = s.cert_expires.unwrap();
|
||||
assert_eq!(w.fake.orders(), 1);
|
||||
eventually("a renewal", || w.fake.orders() >= 2).await;
|
||||
{
|
||||
let st = w.fake.state.lock().unwrap();
|
||||
assert!(!st.orders[0].replaces);
|
||||
assert!(
|
||||
st.orders[1].replaces,
|
||||
"a renewal names the certificate it replaces"
|
||||
);
|
||||
assert_eq!(st.orders[0].authority, st.orders[1].authority);
|
||||
}
|
||||
until(&w.link, "the new certificate serves", |s| {
|
||||
s.cert_expires.is_some_and(|e| e >= first_end) && s.cert_trouble.is_none()
|
||||
})
|
||||
.await;
|
||||
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
|
||||
|
||||
// A renewal that fails leaves the one in use serving.
|
||||
{
|
||||
let mut st = w.fake.state.lock().unwrap();
|
||||
st.fail.insert("first".into());
|
||||
st.fail.insert("second".into());
|
||||
st.window = Some((1, 2));
|
||||
}
|
||||
let n = w.fake.orders();
|
||||
eventually("a failed renewal try", || w.fake.orders() > n + 1).await;
|
||||
let s = until(&w.link, "the renewal trouble", |s| s.cert_trouble.is_some()).await;
|
||||
assert!(s.cert_expires.is_some());
|
||||
assert!(
|
||||
s.cert_trouble
|
||||
.unwrap()
|
||||
.contains("the one in use still works")
|
||||
);
|
||||
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
|
||||
}
|
||||
|
||||
/// WB-link-4: with no renewal information a certificate is renewed two
|
||||
/// thirds of the way through its life.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn without_renewal_information_it_renews_two_thirds_through() {
|
||||
let w = world(LIST, |_| {}).await;
|
||||
// The authority's certificates are good for an hour from now and began
|
||||
// an hour ago: two thirds of two hours is 20 minutes from now.
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let cert: serde_json::Value =
|
||||
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
|
||||
.unwrap();
|
||||
let (b, e, r) = (
|
||||
cert["not_before"].as_i64().unwrap(),
|
||||
cert["not_after"].as_i64().unwrap(),
|
||||
cert["renew_at"].as_i64().unwrap(),
|
||||
);
|
||||
assert_eq!(r, b + (e - b) * 2 / 3);
|
||||
assert_eq!(w.fake.orders(), 1);
|
||||
}
|
||||
|
||||
/// WB-link-3: a caller that never finishes its handshake is dropped, and
|
||||
/// a connection while the door is gone is closed, not held.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_stalled_handshake_is_dropped_and_no_door_means_no_service() {
|
||||
let w = world(LIST, |t| t.handshake = Duration::from_millis(500)).await;
|
||||
w.link.turn_on().unwrap();
|
||||
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
|
||||
let host = w.host();
|
||||
// No door: the caller's connection ends.
|
||||
w.link.set_door(None);
|
||||
let r = w.assistant(&host).await;
|
||||
assert!(r.is_err() || r.unwrap().is_empty());
|
||||
w.link.set_door(Some(w.door.target.clone()));
|
||||
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
//! Shared setup for the link's tests: an in-process relay (the relay
|
||||
//! crate's own test setup), an in-process certificate authority, a stand-in
|
||||
//! for the remote door, a tap between the app and the relay, and an
|
||||
//! assistant. Everything stays on 127.0.0.1.
|
||||
#![allow(dead_code, missing_docs)]
|
||||
|
||||
#[path = "../../../relay/tests/common/mod.rs"]
|
||||
pub mod common;
|
||||
|
||||
use futures::future::BoxFuture;
|
||||
use hickory_proto::op::{Message, Query};
|
||||
use hickory_proto::rr::{Name as DnsName, RData, RecordType};
|
||||
use ledger_link::certs::{Issued, Issuer, OrderRequest};
|
||||
use ledger_link::{Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing};
|
||||
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose};
|
||||
use relay::proto::{Authority, Caller};
|
||||
use rustls::RootCertStore;
|
||||
use rustls::pki_types::ServerName;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::watch;
|
||||
use tokio_rustls::TlsConnector;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub use common::{DOMAIN, RELAY_HOST};
|
||||
|
||||
/// The words the fake authority speaks through.
|
||||
pub struct Order {
|
||||
pub authority: String,
|
||||
pub identifier: String,
|
||||
pub replaces: bool,
|
||||
pub had_binding: bool,
|
||||
}
|
||||
|
||||
pub struct FakeState {
|
||||
pub orders: Vec<Order>,
|
||||
/// Authority ids that refuse.
|
||||
pub fail: std::collections::HashSet<String>,
|
||||
/// Seconds the certificate lasts from now.
|
||||
pub lifetime: i64,
|
||||
/// The renewal window the authority suggests, as seconds from now.
|
||||
pub window: Option<(i64, i64)>,
|
||||
}
|
||||
|
||||
/// An in-process certificate authority: it asks the relay's own DNS for
|
||||
/// the proof, as a real one would, and signs with a CA of its own.
|
||||
pub struct Fake {
|
||||
ca: CertifiedIssuer<'static, KeyPair>,
|
||||
dns: SocketAddr,
|
||||
pub state: Mutex<FakeState>,
|
||||
}
|
||||
|
||||
pub fn txt_at(m: &Message) -> Vec<String> {
|
||||
m.answers
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::TXT(t) => Some(t.to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn dns_txt(addr: SocketAddr, name: &str) -> Vec<String> {
|
||||
let mut q = Message::query();
|
||||
q.queries.push(Query::query(
|
||||
DnsName::from_ascii(name).unwrap(),
|
||||
RecordType::TXT,
|
||||
));
|
||||
let sock = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
sock.send_to(&q.to_vec().unwrap(), addr).await.unwrap();
|
||||
let mut buf = [0u8; 2048];
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(5), sock.recv_from(&mut buf))
|
||||
.await
|
||||
.expect("an answer")
|
||||
.unwrap();
|
||||
txt_at(&Message::from_vec(&buf[..len]).unwrap())
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
pub fn new(dns: SocketAddr) -> Arc<Self> {
|
||||
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
|
||||
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
|
||||
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
|
||||
params
|
||||
.distinguished_name
|
||||
.push(rcgen::DnType::CommonName, "fake authority");
|
||||
let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap();
|
||||
Arc::new(Fake {
|
||||
ca,
|
||||
dns,
|
||||
state: Mutex::new(FakeState {
|
||||
orders: vec![],
|
||||
fail: Default::default(),
|
||||
lifetime: 3600,
|
||||
window: None,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn roots(&self) -> RootCertStore {
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.add(self.ca.der().clone()).unwrap();
|
||||
roots
|
||||
}
|
||||
|
||||
pub fn orders(&self) -> usize {
|
||||
self.state.lock().unwrap().orders.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn proof_value() -> String {
|
||||
// 43 base64url characters, as a DNS-01 value is.
|
||||
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
let r = relay::proto::random32();
|
||||
(0..43)
|
||||
.map(|i| char::from(alphabet[usize::from(r[i % 32] % 64)]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Issuer for Fake {
|
||||
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
|
||||
Box::pin(async move {
|
||||
let (fails, lifetime) = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.orders.push(Order {
|
||||
authority: req.authority.id.clone(),
|
||||
identifier: req.identifier.clone(),
|
||||
replaces: req.replaces.is_some(),
|
||||
had_binding: req.authority.binding.is_some(),
|
||||
});
|
||||
(st.fail.contains(&req.authority.id), st.lifetime)
|
||||
};
|
||||
if fails {
|
||||
return Err("the fake authority says no".into());
|
||||
}
|
||||
// The proof goes to the relay, and the authority reads it from
|
||||
// the relay's own DNS, as a real one does.
|
||||
let value = proof_value();
|
||||
req.dns.publish(&value).await?;
|
||||
let name = req.identifier.trim_start_matches("*.");
|
||||
let seen = dns_txt(self.dns, &format!("_acme-challenge.{name}.")).await;
|
||||
req.dns.clear().await;
|
||||
if !seen.contains(&value) {
|
||||
return Err("the proof of the name was not in the DNS".into());
|
||||
}
|
||||
let mut params = CertificateParams::new(vec![req.identifier.clone()]).unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
params.not_before = now - time::Duration::hours(1);
|
||||
params.not_after = now + time::Duration::seconds(lifetime);
|
||||
let key = KeyPair::generate().unwrap();
|
||||
let cert = params.signed_by(&key, &self.ca).unwrap();
|
||||
Ok(Issued {
|
||||
chain_pem: format!("{}{}", cert.pem(), self.ca.pem()),
|
||||
key_pem: Zeroizing::new(key.serialize_pem()),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn renewal_window<'a>(
|
||||
&'a self,
|
||||
_authority: &'a Authority,
|
||||
_chain_pem: &'a str,
|
||||
) -> BoxFuture<'a, Option<(i64, i64)>> {
|
||||
Box::pin(async move {
|
||||
let w = self.state.lock().unwrap().window;
|
||||
let now = ledger_link::certs::now();
|
||||
w.map(|(a, b)| (now + a, now + b))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What crosses between two ends, recorded, and cut on request.
|
||||
pub struct Tap {
|
||||
pub addr: SocketAddr,
|
||||
pub upstream: Arc<Mutex<SocketAddr>>,
|
||||
pub accepted: Arc<AtomicUsize>,
|
||||
pub refuse: Arc<AtomicBool>,
|
||||
pub to_upstream: Arc<Mutex<Vec<u8>>>,
|
||||
pub from_upstream: Arc<Mutex<Vec<u8>>>,
|
||||
cut: watch::Sender<u64>,
|
||||
/// The address the relay sees connections from.
|
||||
pub source_ports: Arc<Mutex<Vec<SocketAddr>>>,
|
||||
}
|
||||
|
||||
impl Tap {
|
||||
pub async fn new(upstream: SocketAddr) -> Tap {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let tap = Tap {
|
||||
addr,
|
||||
upstream: Arc::new(Mutex::new(upstream)),
|
||||
accepted: Arc::new(AtomicUsize::new(0)),
|
||||
refuse: Arc::new(AtomicBool::new(false)),
|
||||
to_upstream: Arc::new(Mutex::new(vec![])),
|
||||
from_upstream: Arc::new(Mutex::new(vec![])),
|
||||
cut: watch::channel(0).0,
|
||||
source_ports: Arc::new(Mutex::new(vec![])),
|
||||
};
|
||||
let (up, accepted, refuse, to, from, cut, ports) = (
|
||||
tap.upstream.clone(),
|
||||
tap.accepted.clone(),
|
||||
tap.refuse.clone(),
|
||||
tap.to_upstream.clone(),
|
||||
tap.from_upstream.clone(),
|
||||
tap.cut.clone(),
|
||||
tap.source_ports.clone(),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((client, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
accepted.fetch_add(1, Ordering::SeqCst);
|
||||
if refuse.load(Ordering::SeqCst) {
|
||||
continue; // dropped at once
|
||||
}
|
||||
let target = *up.lock().unwrap();
|
||||
let (to, from, ports) = (to.clone(), from.clone(), ports.clone());
|
||||
let mut watcher = cut.subscribe();
|
||||
tokio::spawn(async move {
|
||||
let Ok(server) = TcpStream::connect(target).await else {
|
||||
return;
|
||||
};
|
||||
if let Ok(local) = server.local_addr() {
|
||||
ports.lock().unwrap().push(local);
|
||||
}
|
||||
let (mut cr, mut cw) = client.into_split();
|
||||
let (mut sr, mut sw) = server.into_split();
|
||||
let a = async {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = cr.read(&mut buf).await.unwrap_or(0);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
to.lock().unwrap().extend_from_slice(&buf[..n]);
|
||||
if sw.write_all(&buf[..n]).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = sw.shutdown().await;
|
||||
};
|
||||
let b = async {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = sr.read(&mut buf).await.unwrap_or(0);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
from.lock().unwrap().extend_from_slice(&buf[..n]);
|
||||
if cw.write_all(&buf[..n]).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = cw.shutdown().await;
|
||||
};
|
||||
tokio::select! {
|
||||
() = async { tokio::join!(a, b); } => {}
|
||||
_ = watcher.changed() => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
tap
|
||||
}
|
||||
|
||||
/// Cut every connection now (the network dropped them).
|
||||
pub fn sever(&self) {
|
||||
self.cut.send_modify(|n| *n += 1);
|
||||
}
|
||||
|
||||
pub fn seen_up(&self) -> Vec<u8> {
|
||||
self.to_upstream.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn seen_down(&self) -> Vec<u8> {
|
||||
self.from_upstream.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the stand-in door was given.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Seen {
|
||||
pub secret_ok: bool,
|
||||
pub caller: Option<SocketAddr>,
|
||||
pub request: String,
|
||||
}
|
||||
|
||||
/// A stand-in for the remote door: it wants the secret, then the PROXY
|
||||
/// header, then plain HTTP, and answers a fixed body.
|
||||
pub struct Door {
|
||||
pub target: DoorTarget,
|
||||
pub seen: Arc<Mutex<Vec<Seen>>>,
|
||||
}
|
||||
|
||||
pub const SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
pub const BODY: &str = "the door says hello";
|
||||
|
||||
impl Door {
|
||||
pub async fn new() -> Door {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let seen = Arc::new(Mutex::new(vec![]));
|
||||
let record = seen.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((mut s, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let record = record.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut given = [0u8; 64];
|
||||
if s.read_exact(&mut given).await.is_err() {
|
||||
return;
|
||||
}
|
||||
let secret_ok = given.as_slice() == SECRET.as_bytes();
|
||||
let caller = Caller::read(&mut s).await.ok().map(|c| c.source);
|
||||
let mut req = Vec::new();
|
||||
let mut buf = [0u8; 1024];
|
||||
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
let n = s.read(&mut buf).await.unwrap_or(0);
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
req.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
record.lock().unwrap().push(Seen {
|
||||
secret_ok,
|
||||
caller,
|
||||
request: String::from_utf8_lossy(&req).into_owned(),
|
||||
});
|
||||
if secret_ok {
|
||||
let _ = s
|
||||
.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{BODY}",
|
||||
BODY.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Door {
|
||||
target: DoorTarget::new(addr, SECRET).unwrap(),
|
||||
seen,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The timings the tests run at.
|
||||
pub fn fast() -> Timing {
|
||||
Timing {
|
||||
ping_every: Duration::from_millis(200),
|
||||
ping_timeout: Duration::from_secs(2),
|
||||
tick: Duration::from_millis(100),
|
||||
connect_timeout: Duration::from_secs(3),
|
||||
backoff_min: Duration::from_millis(50),
|
||||
backoff_max: Duration::from_millis(400),
|
||||
handshake: Duration::from_secs(3),
|
||||
cert_retry_min: Duration::from_millis(100),
|
||||
cert_retry_max: Duration::from_millis(500),
|
||||
order_timeout: Duration::from_secs(10),
|
||||
ari_recheck: Duration::from_secs(1),
|
||||
wake_gap: Duration::from_secs(30),
|
||||
}
|
||||
}
|
||||
|
||||
pub const LIST: &str = r#"
|
||||
[[authority]]
|
||||
id = "first"
|
||||
directory = "https://fake.example/first"
|
||||
caa_domain = "first.example"
|
||||
|
||||
[[authority]]
|
||||
id = "second"
|
||||
directory = "https://fake.example/second"
|
||||
caa_domain = "second.example"
|
||||
"#;
|
||||
|
||||
pub struct World {
|
||||
pub env: common::Env,
|
||||
pub tap: Tap,
|
||||
pub caller_tap: Tap,
|
||||
pub door: Door,
|
||||
pub fake: Arc<Fake>,
|
||||
pub dir: tempfile::TempDir,
|
||||
pub link: Link,
|
||||
}
|
||||
|
||||
pub fn config(w: &World) -> LinkConfig {
|
||||
LinkConfig {
|
||||
dir: w.dir.path().join("link"),
|
||||
domain: DOMAIN.into(),
|
||||
relay_host: RELAY_HOST.into(),
|
||||
dial: Dial::Addr(w.tap.addr),
|
||||
relay_tls: w.env.line_tls(),
|
||||
issuer: w.fake.clone(),
|
||||
timing: fast(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn world(list: &str, timing: impl FnOnce(&mut Timing)) -> World {
|
||||
world_with(common::quick_limits(), list, timing).await
|
||||
}
|
||||
|
||||
pub async fn world_with(
|
||||
limits: relay::Limits,
|
||||
list: &str,
|
||||
timing: impl FnOnce(&mut Timing),
|
||||
) -> World {
|
||||
let authorities = relay::authorities::AuthorityList::from_toml(list).unwrap();
|
||||
let env = common::start_with(limits, authorities).await;
|
||||
let tap = Tap::new(env.router()).await;
|
||||
let caller_tap = Tap::new(env.router()).await;
|
||||
let door = Door::new().await;
|
||||
let fake = Fake::new(env.relay.dns_udp_addr());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = LinkConfig {
|
||||
dir: dir.path().join("link"),
|
||||
domain: DOMAIN.into(),
|
||||
relay_host: RELAY_HOST.into(),
|
||||
dial: Dial::Addr(tap.addr),
|
||||
relay_tls: env.line_tls(),
|
||||
issuer: fake.clone(),
|
||||
timing: fast(),
|
||||
};
|
||||
timing(&mut cfg.timing);
|
||||
let link = Link::start_on(tokio::runtime::Handle::current(), cfg);
|
||||
link.set_door(Some(door.target.clone()));
|
||||
World {
|
||||
env,
|
||||
tap,
|
||||
caller_tap,
|
||||
door,
|
||||
fake,
|
||||
dir,
|
||||
link,
|
||||
}
|
||||
}
|
||||
|
||||
impl World {
|
||||
/// A second link on the same folder (the app was restarted).
|
||||
pub fn restart(&mut self, timing: impl FnOnce(&mut Timing)) {
|
||||
let mut cfg = config(self);
|
||||
timing(&mut cfg.timing);
|
||||
let old = std::mem::replace(
|
||||
&mut self.link,
|
||||
Link::start_on(tokio::runtime::Handle::current(), cfg),
|
||||
);
|
||||
drop(old);
|
||||
self.link.set_door(Some(self.door.target.clone()));
|
||||
}
|
||||
|
||||
/// An assistant: TLS to `host` through the tap, one GET, the whole
|
||||
/// reply.
|
||||
pub async fn assistant(&self, host: &str) -> std::io::Result<String> {
|
||||
let tcp = TcpStream::connect(self.tap_for_callers()).await?;
|
||||
let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(self.fake.roots())
|
||||
.with_no_client_auth();
|
||||
let mut tls = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
TlsConnector::from(Arc::new(cfg))
|
||||
.connect(ServerName::try_from(host.to_owned()).unwrap(), tcp),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, "the handshake never finished")
|
||||
})??;
|
||||
tls.write_all(
|
||||
format!("GET /ping HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n").as_bytes(),
|
||||
)
|
||||
.await?;
|
||||
let mut out = Vec::new();
|
||||
let _ = tokio::time::timeout(Duration::from_secs(10), tls.read_to_end(&mut out)).await;
|
||||
Ok(String::from_utf8_lossy(&out).into_owned())
|
||||
}
|
||||
|
||||
fn tap_for_callers(&self) -> SocketAddr {
|
||||
// Callers reach the relay's router the way the internet does: not
|
||||
// through the app's tap, but through one of their own, which is
|
||||
// also where what crosses is recorded.
|
||||
self.caller_tap.addr
|
||||
}
|
||||
|
||||
pub fn host(&self) -> String {
|
||||
self.link
|
||||
.status()
|
||||
.address
|
||||
.or_else(|| self.link.kept_address())
|
||||
.unwrap()
|
||||
.trim_start_matches("https://")
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn until(link: &Link, what: &str, mut ok: impl FnMut(&LinkStatus) -> bool) -> LinkStatus {
|
||||
for _ in 0..400 {
|
||||
let s = link.status();
|
||||
if ok(&s) {
|
||||
return s;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
panic!("never: {what}; last status {:?}", link.status());
|
||||
}
|
||||
|
||||
pub async fn eventually(what: &str, mut ok: impl FnMut() -> bool) {
|
||||
for _ in 0..400 {
|
||||
if ok() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
panic!("never: {what}");
|
||||
}
|
||||
Reference in new issue
Block a user