diff --git a/Cargo.lock b/Cargo.lock index 069e9e90..73ecfbfd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1651,6 +1651,9 @@ name = "deranged" version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] [[package]] name = "deunicode" @@ -3215,6 +3218,8 @@ dependencies = [ "hyper", "hyper-util", "rustls", + "rustls-native-certs", + "rustls-platform-verifier", "tokio", "tokio-rustls", "tower-service", @@ -3610,6 +3615,34 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "instant-acme" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f05ad37c421b962354c358d347d4a6130151df9407978372d3ad7f0c8f71a64" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "http", + "http-body", + "http-body-util", + "httpdate", + "hyper", + "hyper-rustls", + "hyper-util", + "rcgen", + "ring", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "thiserror 2.0.21", + "time", + "tokio", + "x509-parser", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -4111,6 +4144,37 @@ dependencies = [ "zip", ] +[[package]] +name = "ledger-link" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64 0.22.1", + "bytes", + "futures", + "hickory-proto", + "http", + "http-body-util", + "instant-acme", + "ledger-store", + "rcgen", + "relay", + "ring", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "tokio-rustls", + "tokio-util", + "webpki-root-certs", + "x509-parser", + "zeroize", +] + [[package]] name = "ledger-mcp" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 4650103f..334675fb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/ledger-core", "crates/ledger-store", "crates/ledger-config", "crates/ledger-mcp", "crates/ledger-import", "crates/ledger-reader", "crates/ledger-cli", "crates/ledger-gui", "crates/ledger-vault", "crates/ledger-host", "crates/ledger-package", "crates/relay"] +members = ["crates/ledger-core", "crates/ledger-store", "crates/ledger-config", "crates/ledger-mcp", "crates/ledger-import", "crates/ledger-reader", "crates/ledger-cli", "crates/ledger-gui", "crates/ledger-vault", "crates/ledger-host", "crates/ledger-package", "crates/relay", "crates/ledger-link"] [workspace.package] edition = "2024" diff --git a/crates/ledger-link/Cargo.toml b/crates/ledger-link/Cargo.toml new file mode 100644 index 00000000..b63f40d8 --- /dev/null +++ b/crates/ledger-link/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "ledger-link" +version = "0.1.0" +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true +description = "wanderbooks: the app's side of the relay (plan P15 B3): its own name and key, the one outbound line, its own TLS and certificate, and the renewals." + +[dependencies] +# The relay crate's `proto`, `names`, `mux` and `client` modules are the +# app's side of the protocol too; one definition of the wire, never a copy. +relay = { path = "../relay" } +futures = "0.3" +# The certificate authority's protocol (RFC 8555) and ARI (RFC 9773). No +# default features: `ring` is the crypto the rest of the tree uses (the +# default, aws-lc-rs, needs a C toolchain at build time). +instant-acme = { version = "0.8", default-features = false, features = ["ring", "hyper-rustls", "time", "x509-parser"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "sync", "net", "time"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } +tokio-util = "0.7" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +base64 = "0.22" +ring = "0.17" +x509-parser = "0.18" +zeroize = "1" +webpki-root-certs = "1" + +# Owner-only DACLs for the key and certificate files (the helper the token +# files use). +[target.'cfg(windows)'.dependencies] +ledger-store = { path = "../ledger-store" } + +[dev-dependencies] +tempfile = "3" +rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] } +hickory-proto = { version = "0.26", default-features = false, features = ["std"] } +tokio = { version = "1", features = ["test-util"] } +http = "1" +http-body-util = "0.1" +bytes = "1" +async-trait = "0.1" +sha2 = "0.10" +time = "0.3" +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } + +[lints] +workspace = true diff --git a/crates/ledger-link/src/acme.rs b/crates/ledger-link/src/acme.rs new file mode 100644 index 00000000..fad9eb34 --- /dev/null +++ b/crates/ledger-link/src/acme.rs @@ -0,0 +1,290 @@ +//! The ACME client: an [`Issuer`] over `instant-acme` (RFC 8555, DNS-01, +//! wildcard, and RFC 9773 renewal information). +//! +//! ```text +//! GOAL: order a wildcard certificate for the app's own name from +//! whichever authority the relay lists, proving the name through +//! the relay's DNS and nowhere else, keeping the account and +//! certificate keys on this machine. +//! SOURCE: WB-link-4 (certificates), D-87; RFC 8555 (ACME; DNS-01 in +//! section 8.4; external account binding in section 7.3.4), +//! RFC 9773 (ARI). +//! INVARIANTS: +//! 1. One account per authority, made on first use and kept in a +//! private file (private.rs); its contact list is empty: the app +//! gives an authority no name, address or email of the person. +//! 2. The certificate key is made by the client library for each order +//! and returned to the caller; it is not sent anywhere. +//! 3. Only the DNS-01 challenge is used, and only its value is sent to +//! the relay (which publishes it for the app's own name); the relay +//! never orders. +//! 4. An authority that needs an account binding gets the credential +//! the relay gave this app; none is invented or reused across +//! authorities. +//! 5. Every failure comes back in words that name what failed (the +//! authority's own `detail` when it gave one), never a bare code. +//! SCENARIOS: +//! 1. Against an in-process authority (`tests/acme.rs`): account, +//! order, proof, finalize and download work; the second order reuses +//! the account; a renewal names the certificate it replaces; the +//! authority's renewal window is read. +//! ``` + +use crate::certs::{DnsProof, Issued, Issuer, OrderRequest, leaf_der}; +use crate::private; +use base64::Engine as _; +use futures::future::BoxFuture; +use instant_acme::{ + Account, AccountCredentials, AuthorizationStatus, CertificateIdentifier, ChallengeType, + ExternalAccountKey, HttpClient, Identifier, NewAccount, NewOrder, OrderStatus, RetryPolicy, +}; +use relay::proto::Authority; +use rustls::pki_types::CertificateDer; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; +use zeroize::Zeroizing; + +/// How to make the HTTP client an account speaks through. The default is +/// the platform's roots; tests give one that reaches an in-process +/// authority. +pub type HttpFactory = Arc Option> + Send + Sync>; + +/// The ACME client. +pub struct AcmeIssuer { + dir: PathBuf, + http: HttpFactory, + /// How long an order may take to be ready or issued. + patience: Duration, +} + +impl AcmeIssuer { + /// A client keeping its accounts in `dir` (the link folder). + pub fn new(dir: &Path) -> Self { + AcmeIssuer { + dir: dir.join("acme"), + http: Arc::new(|| None), + patience: Duration::from_secs(120), + } + } + + /// Speak through `http` (tests). + pub fn with_http(mut self, http: HttpFactory) -> Self { + self.http = http; + self + } + + /// Wait this long for an order (tests). + pub fn with_patience(mut self, patience: Duration) -> Self { + self.patience = patience; + self + } + + fn builder(&self) -> Result { + match (self.http)() { + Some(http) => Ok(Account::builder_with_http(http)), + None => Account::builder().map_err(|e| words("couldn't start", &e)), + } + } + + fn file(&self, authority: &Authority) -> PathBuf { + // The id is the relay's own short word; keep only what is safe in + // a file name. + let safe: String = authority + .id + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); + self.dir.join(format!("{safe}.json")) + } + + /// The account at this authority: the kept one, or a new one + /// (INVARIANTS 1 and 4). + async fn account(&self, authority: &Authority) -> Result { + let file = self.file(authority); + if let Ok(bytes) = std::fs::read(&file) { + let bytes = Zeroizing::new(bytes); + if let Ok(credentials) = serde_json::from_slice::(&bytes) { + match self.builder()?.from_credentials(credentials).await { + Ok(account) => return Ok(account), + // The authority forgot it, or cannot be reached: a new + // account is made below only for the first; a network + // failure is reported as it is. + Err(e) if is_network(&e) => return Err(words("couldn't be reached", &e)), + Err(_) => {} + } + } + } + let eab = match (&authority.binding, authority.needs_binding) { + (Some(b), _) => { + let key = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(b.hmac_key.trim_end_matches('=')) + .map_err(|_| { + "the account binding for this authority is not valid".to_string() + })?; + Some(ExternalAccountKey::new(b.kid.clone(), &key)) + } + (None, true) => { + return Err( + "this authority needs an account binding the relay has not given yet".into(), + ); + } + (None, false) => None, + }; + let (account, credentials) = self + .builder()? + .create( + &NewAccount { + contact: &[], + terms_of_service_agreed: true, + only_return_existing: false, + }, + authority.directory.clone(), + eab.as_ref(), + ) + .await + .map_err(|e| words("refused a new account", &e))?; + private::make_dir(&self.dir) + .map_err(|e| format!("can't keep the account ({})", e.kind()))?; + let text = Zeroizing::new( + serde_json::to_vec(&credentials).map_err(|_| "can't keep the account".to_string())?, + ); + private::write(&file, &text) + .map_err(|e| format!("can't keep the account ({})", e.kind()))?; + Ok(account) + } +} + +fn is_network(e: &instant_acme::Error) -> bool { + matches!( + e, + instant_acme::Error::Other(_) | instant_acme::Error::Http(_) + ) +} + +/// The authority's own words, as short as they can be (INVARIANT 5). +fn words(what: &str, e: &instant_acme::Error) -> String { + match e { + instant_acme::Error::Api(p) => { + let kind = p + .r#type + .as_deref() + .unwrap_or("") + .rsplit(':') + .next() + .unwrap_or(""); + let detail = p.detail.as_deref().unwrap_or(""); + match kind { + "rateLimited" => format!( + "the authority says too many certificates were asked for lately ({detail})" + ), + "" => format!("the authority {what}: {detail}"), + _ => format!("the authority {what} ({kind}): {detail}"), + } + } + _ => format!("the authority {what}: {e}"), + } +} + +impl Issuer for AcmeIssuer { + fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result> { + Box::pin(async move { + let account = self.account(req.authority).await?; + let identifiers = [Identifier::Dns(req.identifier.clone())]; + let replaces = req + .replaces + .as_deref() + .and_then(|der| CertificateIdentifier::try_from(&CertificateDer::from(der)).ok()); + let mut new = NewOrder::new(&identifiers); + if let Some(r) = replaces { + new = new.replaces(r); + } + let mut order = match account.new_order(&new).await { + Ok(o) => o, + // An authority without renewal information refuses the + // `replaces` hint: ordering again without it is how the + // certificate is renewed there. + Err(instant_acme::Error::Unsupported(_)) => account + .new_order(&NewOrder::new(&identifiers)) + .await + .map_err(|e| words("refused the order", &e))?, + Err(e) => return Err(words("refused the order", &e)), + }; + let mut authorizations = order.authorizations(); + let mut published = false; + while let Some(result) = authorizations.next().await { + let mut authz = result.map_err(|e| words("failed on the proof of the name", &e))?; + match authz.status { + AuthorizationStatus::Pending => {} + AuthorizationStatus::Valid => continue, + _ => return Err("the authority will not accept this name".into()), + } + let mut challenge = authz + .challenge(ChallengeType::Dns01) + .ok_or("the authority offers no DNS proof for this name")?; + let value = challenge.key_authorization().dns_value(); + req.dns.publish(&value).await.map_err(|why| { + format!("the relay would not publish the proof of the name ({why})") + })?; + published = true; + challenge + .set_ready() + .await + .map_err(|e| words("failed on the proof of the name", &e))?; + } + let result = async { + let policy = RetryPolicy::new().timeout(self.patience); + let status = order + .poll_ready(&policy) + .await + .map_err(|e| words("did not finish the order", &e))?; + if status != OrderStatus::Ready { + return Err("the authority could not check the name's proof".to_string()); + } + let key_pem = Zeroizing::new( + order + .finalize() + .await + .map_err(|e| words("refused to issue", &e))?, + ); + let chain_pem = order + .poll_certificate(&policy) + .await + .map_err(|e| words("did not hand over the certificate", &e))?; + Ok(Issued { chain_pem, key_pem }) + } + .await; + if published { + req.dns.clear().await; + } + result + }) + } + + fn renewal_window<'a>( + &'a self, + authority: &'a Authority, + chain_pem: &'a str, + ) -> BoxFuture<'a, Option<(i64, i64)>> { + Box::pin(async move { + let der = leaf_der(chain_pem)?; + let id = CertificateIdentifier::try_from(&CertificateDer::from(der)).ok()?; + let account = self.account(authority).await.ok()?; + let (info, _retry) = account.renewal_info(&id).await.ok()?; + Some(( + info.suggested_window.start.unix_timestamp(), + info.suggested_window.end.unix_timestamp(), + )) + }) + } +} + +// Silence the unused-import lint when no trait object use needs it. +#[allow(dead_code)] +fn _uses(_: &dyn DnsProof) {} diff --git a/crates/ledger-link/src/certs.rs b/crates/ledger-link/src/certs.rs new file mode 100644 index 00000000..8acc74b7 --- /dev/null +++ b/crates/ledger-link/src/certs.rs @@ -0,0 +1,356 @@ +//! The app's own certificate: kept on disk, served by rustls, ordered +//! from whichever authority the relay lists, renewed ahead of expiry. +//! +//! ```text +//! GOAL: the app terminates the web caller's TLS with a certificate whose +//! key was made here and never left; the certificate survives a +//! restart without a new order; it is renewed ahead of expiry (at +//! the time the authority's renewal information suggests, else two +//! thirds of the way through its life); and the authority is data: +//! the relay's list, in order, so a swap needs no release. +//! SOURCE: WB-link-3 (TLS at the app), WB-link-4 (certificates and their +//! renewal), D-80, D-87, plan p15-app-and-relay.md section 5 +//! ("Authorities are data, not code"); RFC 8555 (ACME), RFC 9773 +//! (renewal information). +//! INVARIANTS: +//! 1. The private key is made by the app's side of the order and is +//! written only to the app's own private file (private.rs): it is +//! never in a request to the relay, a status, a log or an error. +//! 2. The certificate stored is for exactly the wildcard under this +//! name; one for another name, or one that does not parse, is +//! ignored and ordered again. +//! 3. A stored certificate is read at start: a restart before its +//! renewal time orders nothing. +//! 4. The authorities are tried in the relay's order; one marked not +//! usable is skipped; a failure of one falls to the next; all failing +//! is a state in words that is retried with a growing, jittered wait. +//! 5. The certificate that is serving keeps serving while a renewal +//! fails, until it ends. +//! 6. The server name must be this app's host (`..`): +//! a hello for any other name gets no certificate, so a stranger who +//! knows the four words but not the label learns nothing and reaches +//! nothing. +//! SCENARIOS: +//! 1. An order with no stored certificate stores one and serves it; a +//! second start reads it and orders nothing. +//! 2. The renewal time passes: a second order is made and replaces the +//! first, naming the first as the one it replaces. +//! 3. The first authority fails and the second issues. +//! 4. A hello for another host name gets no certificate. +//! ``` + +use crate::private; +use futures::future::BoxFuture; +use relay::proto::Authority; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::server::{ClientHello, ResolvesServerCert}; +use rustls::sign::CertifiedKey; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; +use std::time::{SystemTime, UNIX_EPOCH}; +use zeroize::Zeroizing; + +/// The relay publishes and clears the proof record of the app's name. +pub trait DnsProof: Send + Sync { + /// Publish the DNS-01 proof value (the 43 characters) at + /// `_acme-challenge.`. + fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>>; + /// Remove the app's proof records. + fn clear(&self) -> BoxFuture<'_, ()>; +} + +/// One order. +pub struct OrderRequest<'a> { + /// The authority to order from. + pub authority: &'a Authority, + /// The one name asked for: `*..`. + pub identifier: String, + /// The certificate this one replaces (DER), if there is one still + /// valid from this authority: renewal information names it. + pub replaces: Option>, + /// Where the proof goes. + pub dns: &'a dyn DnsProof, +} + +/// A certificate got from an authority. +pub struct Issued { + /// The certificate and its chain, PEM, leaf first. + pub chain_pem: String, + /// The private key made for it, PEM. Never leaves the app. + pub key_pem: Zeroizing, +} + +/// An authority's protocol, behind one small trait: everything that +/// differs between authorities beyond ACME itself (renewal information, +/// lifetimes, limits) is behind it, and the tests give it an in-process +/// authority. +pub trait Issuer: Send + Sync { + /// Order a certificate (the whole of RFC 8555: account, order, + /// DNS-01 proof through `req.dns`, finalize, download). An error is + /// in words. + fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result>; + + /// The renewal window the authority suggests for this certificate + /// (unix seconds, start and end), if it offers one. + fn renewal_window<'a>( + &'a self, + authority: &'a Authority, + chain_pem: &'a str, + ) -> BoxFuture<'a, Option<(i64, i64)>>; +} + +/// Seconds since the epoch. +pub fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)) + .unwrap_or(0) +} + +/// The certificate and its key, as kept (one file, so one atomic write). +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StoredCert { + v: u8, + /// The four-word name it is for. + pub name: String, + /// The authority that issued it. + pub authority: String, + /// The chain, PEM. + pub chain_pem: String, + key_pem: String, + /// Valid from (unix seconds). + pub not_before: i64, + /// Valid until (unix seconds). + pub not_after: i64, + /// When to order the next one (unix seconds). + pub renew_at: i64, +} + +impl std::fmt::Debug for StoredCert { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Never the key (INVARIANT 1). + f.debug_struct("StoredCert") + .field("name", &self.name) + .field("authority", &self.authority) + .field("not_after", &self.not_after) + .field("renew_at", &self.renew_at) + .finish_non_exhaustive() + } +} + +const FILE: &str = "cert.json"; + +/// The first certificate of a chain, DER. +pub fn leaf_der(chain_pem: &str) -> Option> { + CertificateDer::pem_slice_iter(chain_pem.as_bytes()) + .next()? + .ok() + .map(|c| c.as_ref().to_vec()) +} + +/// A certificate's validity (unix seconds) and its names. +pub fn inspect(der: &[u8]) -> Option<(i64, i64, Vec)> { + let (_, cert) = x509_parser::parse_x509_certificate(der).ok()?; + let v = cert.validity(); + let names = cert + .subject_alternative_name() + .ok() + .flatten() + .map(|san| { + san.value + .general_names + .iter() + .filter_map(|n| match n { + x509_parser::extensions::GeneralName::DNSName(d) => Some((*d).to_string()), + _ => None, + }) + .collect() + }) + .unwrap_or_default(); + Some((v.not_before.timestamp(), v.not_after.timestamp(), names)) +} + +impl StoredCert { + /// A certificate just issued, checked: it must be for `identifier`, + /// valid now and have a key that matches (INVARIANT 2). + pub fn new( + name: &str, + authority: &str, + issued: &Issued, + identifier: &str, + renew_at: Option, + ) -> Result { + let der = leaf_der(&issued.chain_pem) + .ok_or("the authority sent something that is not a certificate")?; + let (not_before, not_after, names) = + inspect(&der).ok_or("the authority sent a certificate that can't be read")?; + if !names.iter().any(|n| n.eq_ignore_ascii_case(identifier)) { + return Err("the authority sent a certificate for another name".into()); + } + let t = now(); + if not_after <= t { + return Err("the authority sent a certificate that has already ended".into()); + } + certified(&issued.chain_pem, &issued.key_pem) + .ok_or("the certificate and its key do not go together")?; + let renew_at = renew_at.unwrap_or_else(|| default_renewal(not_before, not_after)); + Ok(StoredCert { + v: 1, + name: name.to_owned(), + authority: authority.to_owned(), + chain_pem: issued.chain_pem.clone(), + key_pem: issued.key_pem.to_string(), + not_before, + not_after, + renew_at: renew_at.min(not_after - (not_after - not_before) / 10), + }) + } + + /// The key and chain, ready for rustls. + pub fn certified(&self) -> Option> { + certified(&self.chain_pem, &self.key_pem) + } + + /// The certificate's DER (for renewal information). + pub fn der(&self) -> Option> { + leaf_der(&self.chain_pem) + } + + /// Whether it still serves. + pub fn valid_at(&self, t: i64) -> bool { + self.not_after > t + } +} + +/// Two thirds of the way through its life: a third is left to renew in. +pub fn default_renewal(not_before: i64, not_after: i64) -> i64 { + not_before + (not_after - not_before) * 2 / 3 +} + +fn certified(chain_pem: &str, key_pem: &str) -> Option> { + let chain: Vec> = CertificateDer::pem_slice_iter(chain_pem.as_bytes()) + .collect::>() + .ok()?; + if chain.is_empty() { + return None; + } + let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).ok()?; + let provider = rustls::crypto::ring::default_provider(); + let signing = provider.key_provider.load_private_key(key).ok()?; + let ck = CertifiedKey::new(chain, signing); + ck.keys_match().ok()?; + Some(Arc::new(ck)) +} + +/// The certificate on disk. +pub struct CertStore { + path: PathBuf, +} + +impl CertStore { + /// The store in the link folder `dir`. + pub fn new(dir: &Path) -> Self { + CertStore { + path: dir.join(FILE), + } + } + + /// The stored certificate for `name`, if there is a good one + /// (INVARIANT 2). A file that does not read is as if there were none. + pub fn load(&self, name: &str) -> Option { + let bytes = std::fs::read(&self.path).ok()?; + let c: StoredCert = serde_json::from_slice(&bytes).ok()?; + (c.v == 1 && c.name == name && c.certified().is_some()).then_some(c) + } + + /// Keep a certificate, privately and atomically. + pub fn save(&self, c: &StoredCert) -> std::io::Result<()> { + let text = serde_json::to_vec(c).map_err(std::io::Error::other)?; + private::write(&self.path, &text) + } + + /// Forget the certificate (a new identity). + pub fn forget(&self) { + let _ = std::fs::remove_file(&self.path); + } +} + +/// What rustls serves: the current certificate, to the app's own host +/// name and no other (INVARIANT 6). +pub struct Resolver { + host: RwLock, + key: RwLock>>, +} + +impl std::fmt::Debug for Resolver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Resolver").finish_non_exhaustive() + } +} + +impl Resolver { + /// A resolver with no certificate and no host. + pub fn new() -> Arc { + Arc::new(Resolver { + host: RwLock::new(String::new()), + key: RwLock::new(None), + }) + } + + /// The one host name served. + pub fn set_host(&self, host: &str) { + *self.host.write().unwrap_or_else(|e| e.into_inner()) = host.to_ascii_lowercase(); + } + + /// The certificate to serve, or none. + pub fn set_key(&self, key: Option>) { + *self.key.write().unwrap_or_else(|e| e.into_inner()) = key; + } + + /// Whether a certificate is being served. + pub fn has_key(&self) -> bool { + self.key.read().unwrap_or_else(|e| e.into_inner()).is_some() + } +} + +impl ResolvesServerCert for Resolver { + fn resolve(&self, hello: ClientHello<'_>) -> Option> { + let sni = hello.server_name()?.to_ascii_lowercase(); + let host = self.host.read().unwrap_or_else(|e| e.into_inner()); + if host.is_empty() || sni != *host { + return None; + } + drop(host); + self.key.read().unwrap_or_else(|e| e.into_inner()).clone() + } +} + +/// The server settings the app terminates TLS with: TLS 1.3 and 1.2, the +/// resolver, and HTTP/2 or HTTP/1.1 by ALPN. +pub fn server_config(resolver: Arc) -> Arc { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut cfg = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap_or_else(|_| unreachable!("the ring provider has the default versions")) + .with_no_client_auth() + .with_cert_resolver(resolver); + cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + // The line is the relay's; a ticket resumed there is one more thing + // to hold for nothing. + cfg.send_tls13_tickets = 0; + Arc::new(cfg) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_thirds_of_a_life() { + assert_eq!(default_renewal(0, 90), 60); + assert_eq!(default_renewal(100, 106), 104); + } +} diff --git a/crates/ledger-link/src/identity.rs b/crates/ledger-link/src/identity.rs new file mode 100644 index 00000000..41321029 --- /dev/null +++ b/crates/ledger-link/src/identity.rs @@ -0,0 +1,329 @@ +//! The app's identity at the relay: its key, its four-word name and the +//! secret label of its address. +//! +//! ```text +//! GOAL: an installation has one durable public address, +//! `https://..wanderbooks.link`; its key never +//! leaves the machine; and a person can have a new address, after +//! which the old one stops working. +//! SOURCE: WB-link-1 (the identity), plan/p15-app-and-relay.md section 5 +//! ("Names": one name per installation, each company a path under +//! it; the secret label stops listing and guessing), D-82, D-85, +//! D-87; relay `names.rs` (a secret label is 25 to 63 characters +//! of a-z and 0-9; the app makes it from at least 128 random bits). +//! INVARIANTS: +//! 1. The name is four words from the relay's list, picked here at +//! random and kept: the same installation has the same name until it +//! is asked for a new address after the relay lost it. +//! 2. The secret label is 32 random characters of a-z and 0-9 (about +//! 165 bits; the relay needs 128 at least), made by rejection +//! sampling with no modulo bias, never from the name, a time or a +//! counter. +//! 3. The key (Ed25519, PKCS#8) and the label are in the data root's +//! private `link/` folder, owner-only files (private.rs); neither is +//! ever sent to the relay (the relay is sent the public key) or +//! written to a log, an error or a status. +//! 4. A new label replaces the old one in one atomic write: the old +//! address stops being served the moment this returns. +//! 5. A file that is damaged is not guessed at: it is an error in +//! words, and nothing is overwritten. +//! SCENARIOS: +//! 1. The first call makes a name, a label and a key; the second +//! reads the same ones. +//! 2. A new label differs and is persisted; the name and key stay. +//! 3. A reset makes a new key and a new name too. +//! ``` + +use crate::private; +use relay::names::{Name, SECRET_LEN}; +use relay::proto::AppKey; +use ring::rand::{SecureRandom, SystemRandom}; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; +use zeroize::Zeroizing; + +/// The length of the secret label this app makes. +pub const LABEL_LEN: usize = 32; + +const FILE: &str = "identity.json"; +const KEY_FILE: &str = "line.key"; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Stored { + v: u8, + name: String, + label: String, + /// True once the relay said the name is ours. + claimed: bool, +} + +/// Why the identity could not be read or kept. +#[derive(Debug, thiserror::Error)] +pub enum IdentityError { + /// The folder could not be read or written. + #[error("Wanderbooks can't keep its web address on this computer ({0})")] + Io(std::io::ErrorKind), + /// A file is not what it should be. + #[error("the file that keeps the web address is damaged")] + Damaged, +} + +/// One installation's identity. +pub struct Identity { + dir: PathBuf, + name: Name, + label: String, + claimed: bool, + key: AppKey, + pkcs8: Zeroizing>, +} + +fn base36(n: usize) -> String { + let rng = SystemRandom::new(); + let mut out = String::with_capacity(n); + while out.len() < n { + let mut b = [0u8; 64]; + if rng.fill(&mut b).is_err() { + // The system generator failing is not recoverable. + panic!("the system random number generator failed"); + } + for byte in b { + // 252 is the largest multiple of 36 that fits in a byte: + // anything above is dropped, so no character is likelier. + if byte < 252 && out.len() < n { + let v = byte % 36; + out.push(char::from(if v < 10 { b'0' + v } else { b'a' + v - 10 })); + } + } + } + out +} + +/// A new secret label. +pub fn new_label() -> String { + base36(LABEL_LEN) +} + +fn label_ok(label: &str) -> bool { + SECRET_LEN.contains(&label.len()) + && label + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) +} + +impl Identity { + /// Read the identity kept in `dir`, or make one (INVARIANT 1). + pub fn load_or_create(dir: &Path) -> Result { + private::make_dir(dir).map_err(|e| IdentityError::Io(e.kind()))?; + match std::fs::read(dir.join(FILE)) { + Ok(bytes) => Self::read(dir, &bytes), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::make(dir), + Err(e) => Err(IdentityError::Io(e.kind())), + } + } + + /// The identity kept in `dir`, if there is one. + pub fn load(dir: &Path) -> Result, IdentityError> { + match std::fs::read(dir.join(FILE)) { + Ok(bytes) => Self::read(dir, &bytes).map(Some), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(IdentityError::Io(e.kind())), + } + } + + fn read(dir: &Path, bytes: &[u8]) -> Result { + let stored: Stored = serde_json::from_slice(bytes).map_err(|_| IdentityError::Damaged)?; + let name = Name::parse(&stored.name).map_err(|_| IdentityError::Damaged)?; + if stored.v != 1 || !label_ok(&stored.label) { + return Err(IdentityError::Damaged); + } + let pkcs8 = Zeroizing::new( + std::fs::read(dir.join(KEY_FILE)).map_err(|e| IdentityError::Io(e.kind()))?, + ); + let key = AppKey::from_pkcs8(&pkcs8).ok_or(IdentityError::Damaged)?; + Ok(Identity { + dir: dir.to_path_buf(), + name, + label: stored.label, + claimed: stored.claimed, + key, + pkcs8, + }) + } + + fn make(dir: &Path) -> Result { + let (key, pkcs8) = AppKey::generate(); + let me = Identity { + dir: dir.to_path_buf(), + name: Name::random(), + label: new_label(), + claimed: false, + key, + pkcs8: Zeroizing::new(pkcs8), + }; + // The key first: a name with no key is damaged; a key with no + // name is just unused. + private::write(&dir.join(KEY_FILE), &me.pkcs8).map_err(|e| IdentityError::Io(e.kind()))?; + me.save()?; + Ok(me) + } + + fn save(&self) -> Result<(), IdentityError> { + let stored = Stored { + v: 1, + name: self.name.to_string(), + label: self.label.clone(), + claimed: self.claimed, + }; + let text = serde_json::to_vec_pretty(&stored).map_err(|_| IdentityError::Damaged)?; + private::write(&self.dir.join(FILE), &text).map_err(|e| IdentityError::Io(e.kind())) + } + + /// The four-word name. + pub fn name(&self) -> Name { + self.name + } + + /// The address: `https://..`. + pub fn address(&self, domain: &str) -> String { + format!("https://{}", self.host(domain)) + } + + /// The host name of the address. + pub fn host(&self, domain: &str) -> String { + format!("{}.{}.{domain}", self.label, self.name) + } + + /// The key, to prove the name to the relay. + pub fn key(&self) -> &AppKey { + &self.key + } + + /// A second handle on the same key (the line signs with it while the + /// identity stays behind its lock). + pub fn key_copy(&self) -> AppKey { + AppKey::from_pkcs8(&self.pkcs8) + .unwrap_or_else(|| unreachable!("a key that parsed parses again")) + } + + /// Whether the relay has said the name is ours. + pub fn claimed(&self) -> bool { + self.claimed + } + + /// Keep that the relay said the name is ours. + pub fn set_claimed(&mut self) -> Result<(), IdentityError> { + if !self.claimed { + self.claimed = true; + self.save()?; + } + Ok(()) + } + + /// Another name, for a name somebody else holds (only while this one + /// is not claimed). + pub fn retry_name(&mut self) -> Result<(), IdentityError> { + self.name = Name::random(); + self.save() + } + + /// A new secret label: the old address stops being served + /// (INVARIANT 4). + pub fn new_label(&mut self) -> Result<(), IdentityError> { + self.label = new_label(); + self.save() + } + + /// A whole new identity: key, name and label (the relay no longer + /// knows this one). + pub fn reset(dir: &Path) -> Result { + Self::make(dir) + } +} + +impl std::fmt::Debug for Identity { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Never the key, never the label (INVARIANT 3). + f.debug_struct("Identity") + .field("name", &self.name.to_string()) + .field("claimed", &self.claimed) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_first_call_makes_and_the_second_reads_the_same() { + let dir = tempfile::tempdir().unwrap(); + let a = Identity::load_or_create(dir.path()).unwrap(); + let b = Identity::load_or_create(dir.path()).unwrap(); + assert_eq!(a.name(), b.name()); + assert_eq!(a.host("wanderbooks.link"), b.host("wanderbooks.link")); + assert_eq!(a.key().public_key(), b.key().public_key()); + assert!(!a.claimed()); + assert!(a.address("wanderbooks.link").starts_with("https://")); + } + + #[test] + fn labels_are_long_enough_and_use_only_the_relays_characters() { + for _ in 0..200 { + let l = new_label(); + assert_eq!(l.len(), LABEL_LEN); + assert!(label_ok(&l)); + } + // 32 characters of base 36 are far over 128 bits. + assert!(32.0 * 36f64.log2() > 128.0); + // Every character is reached: no modulo bias hides one. + let mut seen = std::collections::BTreeSet::new(); + for _ in 0..400 { + seen.extend(new_label().chars()); + } + assert_eq!(seen.len(), 36); + assert_ne!(new_label(), new_label()); + } + + #[test] + fn a_new_label_replaces_the_old_and_a_reset_replaces_everything() { + let dir = tempfile::tempdir().unwrap(); + let mut a = Identity::load_or_create(dir.path()).unwrap(); + let (name, host, key) = (a.name(), a.host("x.link"), a.key().public_key()); + a.set_claimed().unwrap(); + a.new_label().unwrap(); + assert_ne!(a.host("x.link"), host); + let b = Identity::load_or_create(dir.path()).unwrap(); + assert_eq!(b.host("x.link"), a.host("x.link")); + assert_eq!(b.name(), name); + assert_eq!(b.key().public_key(), key); + assert!(b.claimed()); + let c = Identity::reset(dir.path()).unwrap(); + assert_ne!(c.key().public_key(), key); + assert!(!c.claimed()); + } + + #[test] + fn a_damaged_file_is_an_error_not_a_new_identity() { + let dir = tempfile::tempdir().unwrap(); + Identity::load_or_create(dir.path()).unwrap(); + std::fs::write(dir.path().join(FILE), b"{ not json").unwrap(); + assert!(matches!( + Identity::load_or_create(dir.path()), + Err(IdentityError::Damaged) + )); + // Nothing was overwritten. + assert_eq!(std::fs::read(dir.path().join(FILE)).unwrap(), b"{ not json"); + } + + #[test] + fn debug_shows_neither_key_nor_label() { + let dir = tempfile::tempdir().unwrap(); + let a = Identity::load_or_create(dir.path()).unwrap(); + let shown = format!("{a:?}"); + let label = a.host("x.link"); + let label = label.split('.').next().unwrap(); + assert!(!shown.contains(label)); + } +} diff --git a/crates/ledger-link/src/lib.rs b/crates/ledger-link/src/lib.rs new file mode 100644 index 00000000..6d74c4bf --- /dev/null +++ b/crates/ledger-link/src/lib.rs @@ -0,0 +1,59 @@ +//! The app's side of the relay (plan P15 unit B3). +//! +//! A person turns on "Allow web assistants" for a company. This crate then +//! gives the app a durable public address, `https://..wanderbooks.link`, +//! holds its own private key and its own certificate, keeps one outbound +//! line to the relay, and serves the sign-in and the books to Claude or +//! ChatGPT on the web through it. The relay forwards encrypted bytes and +//! can read nothing (D-80): TLS ends here. +//! +//! The crate depends on the relay crate for the wire (`proto`, `names`, +//! the client's line) and on no other `ledger-*` crate except, on Windows +//! only, `ledger-store` for the owner-only file helper. +//! +//! ```text +//! GOAL: the app's side of D-80: an address that is durable and secret, a +//! line that comes back by itself, TLS ended with a key that never +//! left the machine, a certificate that is ordered, kept and +//! renewed with the authority as data, and every failure in words. +//! SOURCE: WB-link-1 (the identity and name), WB-link-2 (the line), +//! WB-link-3 (TLS at the app and the hand to the door), WB-link-4 +//! (certificates), WB-link-5 (the states in words); D-80, D-82, +//! D-85, D-87. +//! INVARIANTS: +//! 1. No key, secret label or token is in a log, an error, a status +//! Debug or a test's output; the files that hold them are owner-only. +//! 2. Nothing the relay could use to read traffic leaves the machine: +//! the relay is sent a public key, a proof and a DNS value. +//! 3. The relay protocol is not changed here; this crate only uses it. +//! SCENARIOS: +//! 1. See `tests/link.rs` and `tests/acme.rs`. +//! ``` + +#![forbid(unsafe_code)] + +pub mod acme; +pub mod certs; +pub mod identity; +pub mod line; +pub mod link; +pub mod private; +pub mod status; + +pub use acme::AcmeIssuer; +pub use certs::{DnsProof, Issued, Issuer, OrderRequest}; +pub use line::{Dial, Timing}; +pub use link::{DoorTarget, Link, LinkConfig, LinkError}; +pub use status::{LinkStatus, Step, Trouble}; + +/// The relay trust roots for the line, from the roots the program ships +/// (Mozilla's, as `webpki-root-certs`), for a relay with a public +/// certificate. +pub fn public_relay_tls() -> Result, rustls::Error> { + let mut roots = rustls::RootCertStore::empty(); + for der in webpki_root_certs::TLS_SERVER_ROOT_CERTS { + // A root the parser can't read is skipped, not fatal. + let _ = roots.add(der.clone()); + } + relay::tls::client_config(roots) +} diff --git a/crates/ledger-link/src/line.rs b/crates/ledger-link/src/line.rs new file mode 100644 index 00000000..2e420dbe --- /dev/null +++ b/crates/ledger-link/src/line.rs @@ -0,0 +1,351 @@ +//! The line to the relay, as the app holds it: dialling, the words for +//! what goes wrong, backoff, and keeping watch for a computer that slept. +//! +//! ```text +//! GOAL: one outbound connection to the relay that comes back by itself +//! after anything (no network, the relay down, a laptop that slept +//! and woke on another network), never spins hot against a relay +//! that is down, and never keeps a door open once it is told to +//! close. +//! SOURCE: WB-link-2 (the line), plan p15-app-and-relay.md 6a ("Unit +//! B3's duties: ping at least every 60 s (a line silent for 180 s +//! is dropped) ... a yamux stream limit at least the relay's"), +//! D-80; relay `client.rs` (the line), `config.rs` (limits). +//! INVARIANTS: +//! 1. A dial that fails waits a growing, jittered time (full jitter, at +//! most `backoff_max`, at least `backoff_min` after a failure) and +//! starts again; a line that held resets it. A nudge (the network +//! changed) resets it and dials now. +//! 2. The line is pinged at most every `ping_every` (30 s, under the +//! relay's 60 s duty and 180 s silence limit); a ping that is not +//! answered in `ping_timeout` ends the line and a new one is made. +//! 3. A step of wall-clock time much longer than the monotonic time +//! that passed (the computer slept) ends the line and dials again at +//! once: a connection held across a sleep is not trusted. +//! 4. A relay certificate that is expired or not yet valid is a wrong +//! clock, said so in words, not "the relay is down". +//! 5. The stream limit offered the relay is more than the relay's own +//! (callers, control streams and slack). +//! SCENARIOS: +//! 1. The backoff grows from its minimum to its maximum and no further, +//! never exceeds the maximum with jitter, and resets. +//! 2. A wall-clock jump with no monotonic jump is a wake; a small one is +//! not. +//! 3. Errors read as the right trouble: a refused connection is the +//! relay down, a name that does not resolve is no internet, an +//! expired relay certificate is a wrong clock. +//! ``` + +use crate::status::Trouble; +use relay::client::ClientError; +use relay::proto::Refusal; +use ring::rand::{SecureRandom, SystemRandom}; +use std::io; +use std::net::SocketAddr; +use std::time::{Duration, Instant, SystemTime}; + +/// Where the relay is. +#[derive(Clone, Debug)] +pub enum Dial { + /// A host name and port, resolved at every dial (so a new network + /// finds the relay again). + Host(String, u16), + /// A fixed address (tests). + Addr(SocketAddr), +} + +/// Every time the link waits, in one place (tests make them short). +#[derive(Clone, Copy, Debug)] +pub struct Timing { + /// A ping at least this often. + pub ping_every: Duration, + /// A ping not answered in this long ends the line. + pub ping_timeout: Duration, + /// How often the line looks for a sleep and for a ping due. + pub tick: Duration, + /// A dial that takes longer than this has failed. + pub connect_timeout: Duration, + /// The shortest wait after a failed dial. + pub backoff_min: Duration, + /// The longest wait after a failed dial. + pub backoff_max: Duration, + /// A caller's TLS handshake must finish in this long. + pub handshake: Duration, + /// The shortest wait after a failed certificate order. + pub cert_retry_min: Duration, + /// The longest wait after a failed certificate order. + pub cert_retry_max: Duration, + /// An order is given up on after this long. + pub order_timeout: Duration, + /// Renewal information is asked again this often. + pub ari_recheck: Duration, + /// A wall-clock step this much longer than the monotonic one is a + /// sleep. + pub wake_gap: Duration, +} + +impl Default for Timing { + fn default() -> Self { + Timing { + ping_every: Duration::from_secs(30), + ping_timeout: Duration::from_secs(15), + tick: Duration::from_secs(5), + connect_timeout: Duration::from_secs(20), + backoff_min: Duration::from_secs(1), + backoff_max: Duration::from_secs(300), + handshake: Duration::from_secs(10), + cert_retry_min: Duration::from_secs(60), + cert_retry_max: Duration::from_secs(6 * 3600), + order_timeout: Duration::from_secs(300), + ari_recheck: Duration::from_secs(6 * 3600), + wake_gap: Duration::from_secs(30), + } + } +} + +/// Streams the app lets the line carry at once: the relay's own limits +/// (8 callers, 2 control, plus slack, relay `config.rs`) with room to +/// spare (INVARIANT 5). +pub const MAX_STREAMS: usize = 64; + +/// A random duration in `0..=max`. +pub fn jitter(max: Duration) -> Duration { + let mut b = [0u8; 4]; + if SystemRandom::new().fill(&mut b).is_err() { + return max / 2; + } + let frac = f64::from(u32::from_be_bytes(b)) / f64::from(u32::MAX); + max.mul_f64(frac) +} + +/// The wait between tries: doubling, with full jitter (INVARIANT 1). +#[derive(Debug)] +pub struct Backoff { + min: Duration, + max: Duration, + failures: u32, +} + +impl Backoff { + /// A backoff from `min` to `max`. + pub fn new(min: Duration, max: Duration) -> Self { + Backoff { + min, + max, + failures: 0, + } + } + + /// A line held: start from the minimum again. + pub fn reset(&mut self) { + self.failures = 0; + } + + /// The ceiling of the next wait, before jitter. + pub fn ceiling(&self) -> Duration { + let doubled = self + .min + .saturating_mul(1u32.checked_shl(self.failures.min(20)).unwrap_or(u32::MAX)); + doubled.min(self.max) + } + + /// The next wait: between the minimum (or the ceiling, if lower) and + /// the ceiling. + pub fn wait(&mut self) -> Duration { + let ceiling = self.ceiling(); + self.failures = self.failures.saturating_add(1); + let floor = self.min.min(ceiling); + floor + jitter(ceiling - floor) + } +} + +/// Notices a computer that slept (INVARIANT 3). +pub struct WakeDetector { + mono: Instant, + wall: SystemTime, + gap: Duration, +} + +impl WakeDetector { + /// Start watching. + pub fn new(gap: Duration) -> Self { + WakeDetector { + mono: Instant::now(), + wall: SystemTime::now(), + gap, + } + } + + /// Whether more wall-clock time than monotonic time has passed since + /// the last look (and now look again from here). + pub fn woke(&mut self) -> bool { + self.woke_with(Instant::now(), SystemTime::now()) + } + + /// [`WakeDetector::woke`] with the two clocks given. + pub fn woke_with(&mut self, mono: Instant, wall: SystemTime) -> bool { + let m = mono.saturating_duration_since(self.mono); + // The wall clock may go backwards (set by hand, or by the network): + // that is not a sleep. + let w = wall.duration_since(self.wall).unwrap_or_default(); + self.mono = mono; + self.wall = wall; + w > m + self.gap + } +} + +fn is_clock_error(e: &io::Error) -> bool { + use rustls::CertificateError as C; + let mut inner: Option<&(dyn std::error::Error + 'static)> = + e.get_ref().map(|e| e as &(dyn std::error::Error + 'static)); + while let Some(err) = inner { + if let Some(rustls::Error::InvalidCertificate(c)) = err.downcast_ref::() { + return matches!( + c, + C::Expired + | C::NotValidYet + | C::ExpiredContext { .. } + | C::NotValidYetContext { .. } + ); + } + inner = err.source(); + } + false +} + +/// An i/o error from dialling, as the trouble a person is told. +pub fn trouble_of_io(e: &io::Error) -> Trouble { + use io::ErrorKind as K; + if is_clock_error(e) { + return Trouble::ClockWrong; + } + match e.kind() { + K::NetworkUnreachable | K::HostUnreachable | K::NetworkDown | K::NotFound => { + Trouble::NoInternet + } + // A name that does not resolve comes back as `Uncategorized` or + // `Other` from the resolver; the callers say so with `NotFound`. + _ => Trouble::RelayDown, + } +} + +/// What a line's failure means. +pub enum Failure { + /// Nothing wrong with this app: say it and try again. + Trouble(Trouble), + /// The relay refused. + Refused(Refusal), +} + +/// A client error, as what to do about it. +pub fn failure_of(e: &ClientError) -> Failure { + match e { + ClientError::Io(e) => Failure::Trouble(trouble_of_io(e)), + ClientError::Timeout | ClientError::Closed => Failure::Trouble(Trouble::RelayDown), + ClientError::Frame(_) => Failure::Trouble(Trouble::Protocol), + ClientError::Refused(r) => Failure::Refused(*r), + } +} + +/// A refusal, as the trouble a person is told (a name taken is handled by +/// the caller before this). +pub fn trouble_of_refusal(r: Refusal, claimed: bool) -> Trouble { + match r { + Refusal::Busy => Trouble::RelayBusy, + Refusal::RateLimited => Trouble::RateLimited, + Refusal::Blocked => Trouble::Blocked, + Refusal::BadRequest => Trouble::Protocol, + // A claimed name the relay turns away as unknown is one it lost + // (the relay answers a wrong key and an unknown name alike). + Refusal::BadProof | Refusal::UnknownName | Refusal::Taken => { + if claimed { + Trouble::NameLost + } else { + Trouble::RelayBusy + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_backoff_grows_stays_under_its_ceiling_and_resets() { + let mut b = Backoff::new(Duration::from_secs(1), Duration::from_secs(300)); + let mut ceilings = vec![]; + for _ in 0..14 { + ceilings.push(b.ceiling()); + let w = b.wait(); + assert!(w >= Duration::from_secs(1), "{w:?}"); + assert!(w <= Duration::from_secs(300), "{w:?}"); + } + assert_eq!(ceilings[0], Duration::from_secs(1)); + assert_eq!(ceilings[1], Duration::from_secs(2)); + assert_eq!(ceilings[3], Duration::from_secs(8)); + assert_eq!(*ceilings.last().unwrap(), Duration::from_secs(300)); + assert!(ceilings.windows(2).all(|w| w[0] <= w[1])); + b.reset(); + assert_eq!(b.ceiling(), Duration::from_secs(1)); + // Jitter really varies. + let mut b = Backoff::new(Duration::from_secs(1), Duration::from_secs(1000)); + for _ in 0..8 { + b.wait(); + } + let spread: std::collections::BTreeSet = (0..20) + .map(|_| { + let mut c = Backoff::new(Duration::from_secs(1), Duration::from_secs(1000)); + c.failures = 8; + c.wait().as_millis() + }) + .collect(); + assert!(spread.len() > 5); + } + + #[test] + fn a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep() { + let mut w = WakeDetector::new(Duration::from_secs(30)); + let (m0, s0) = (w.mono, w.wall); + // Five seconds of both: not a sleep. + assert!(!w.woke_with(m0 + Duration::from_secs(5), s0 + Duration::from_secs(5))); + // Ten minutes of wall time in five seconds of monotonic time. + let (m1, s1) = (w.mono, w.wall); + assert!(w.woke_with(m1 + Duration::from_secs(5), s1 + Duration::from_secs(605))); + // The clock set backwards is not a sleep. + let (m2, s2) = (w.mono, w.wall); + assert!(!w.woke_with(m2 + Duration::from_secs(5), s2 - Duration::from_secs(3600))); + } + + #[test] + fn errors_read_as_the_right_trouble() { + let refused = io::Error::from(io::ErrorKind::ConnectionRefused); + assert_eq!(trouble_of_io(&refused), Trouble::RelayDown); + let down = io::Error::from(io::ErrorKind::NetworkUnreachable); + assert_eq!(trouble_of_io(&down), Trouble::NoInternet); + let expired = io::Error::new( + io::ErrorKind::InvalidData, + rustls::Error::InvalidCertificate(rustls::CertificateError::Expired), + ); + assert_eq!(trouble_of_io(&expired), Trouble::ClockWrong); + let early = io::Error::new( + io::ErrorKind::InvalidData, + rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidYet), + ); + assert_eq!(trouble_of_io(&early), Trouble::ClockWrong); + let unknown_ca = io::Error::new( + io::ErrorKind::InvalidData, + rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer), + ); + assert_eq!(trouble_of_io(&unknown_ca), Trouble::RelayDown); + assert_eq!( + trouble_of_refusal(Refusal::BadProof, true), + Trouble::NameLost + ); + assert_eq!( + trouble_of_refusal(Refusal::RateLimited, false), + Trouble::RateLimited + ); + assert_eq!(trouble_of_refusal(Refusal::Blocked, true), Trouble::Blocked); + } +} diff --git a/crates/ledger-link/src/link.rs b/crates/ledger-link/src/link.rs new file mode 100644 index 00000000..f775f061 --- /dev/null +++ b/crates/ledger-link/src/link.rs @@ -0,0 +1,893 @@ +//! The link: the app's one durable address, its line to the relay, its +//! own TLS, and what it serves to the remote door. +//! +//! ```text +//! GOAL: a person turns web assistants on and the app holds a durable +//! public address, one line to the relay, its own certificate and +//! key, and hands each web caller, decrypted here and nowhere else, +//! to the remote door on this computer; turned off, nothing is +//! listening and nothing is dialled; and the line is never alive +//! longer than this process. +//! SOURCE: WB-link-1 to WB-link-5; plan p15-app-and-relay.md 3 (the shape), +//! 5 (the relay), 6a (unit B3's duties); D-80, D-84, D-87. +//! INVARIANTS: +//! 1. The line runs in the app's own process (the window), not in the +//! books server it started: the server is a child that closes when +//! the window's input to it closes, and the window's death takes the +//! line with it (a socket this process holds ends with it), so the +//! line can never keep a door open for books that closed, and the +//! key and certificate are in one process only. +//! 2. Everything the relay is sent is the public key, the name, the +//! proof of the key over this TLS session and the DNS proof value; +//! the private keys (the line key, the certificate's key, the ACME +//! account) are never sent anywhere. +//! 3. A caller's TLS ends here: the relay's bytes are TLS, decrypted by +//! this app with its own certificate, only for the one host name of +//! its address. What goes to the door is plain HTTP on 127.0.0.1, +//! after the door's per-start secret and the relay's PROXY header +//! (the first SECRET + header bytes of the connection), which is how +//! the door knows the caller's address and that this app sent it. +//! 4. Off means off: turning the link off ends the line and the +//! certificate stops being served before `turn_off` returns, and the +//! name is kept so the address is the same when it is turned on again. +//! 5. A new address replaces the secret label and the old address stops +//! being served at once (no certificate for its host name); if the +//! relay lost the name, a whole new identity. +//! 6. The line, the certificate and the door each fail on their own: +//! with no internet the window and the local assistants are untouched, +//! the state says so in words, and everything resumes by itself. +//! 7. At most `MAX_CALLERS` callers are served at once; a caller whose +//! TLS does not finish in `handshake` is dropped. +//! SCENARIOS: +//! 1. See `tests/link.rs`: claim, prove, line up, certificate, a caller +//! through the relay to a stand-in door, off, on again with the same +//! address, a new address. +//! ``` + +use crate::certs::{ + CertStore, DnsProof, Issuer, OrderRequest, Resolver, StoredCert, now, server_config, +}; +use crate::identity::{Identity, IdentityError}; +use crate::line::{ + Backoff, Dial, Failure, MAX_STREAMS, Timing, WakeDetector, failure_of, jitter, + trouble_of_refusal, +}; +use crate::status::{LinkStatus, Trouble}; +use futures::future::BoxFuture; +use relay::client::{self, Incoming, Line, LineHandle, LineOptions}; +use relay::proto::{Refusal, Request}; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::Duration; +use tokio::io::AsyncWriteExt; +use tokio::net::TcpStream; +use tokio::sync::{Notify, Semaphore, watch}; +use tokio::time::timeout; +use tokio_rustls::TlsAcceptor; +use tokio_util::sync::CancellationToken; +use zeroize::Zeroizing; + +/// The most callers served at once (INVARIANT 7). +pub const MAX_CALLERS: usize = 16; + +/// How the link is set up. +#[derive(Clone)] +pub struct LinkConfig { + /// The link folder in the data root (`/link`). + pub dir: PathBuf, + /// The relay's domain (`wanderbooks.link`). + pub domain: String, + /// The relay's own host name, which its certificate is for. + pub relay_host: String, + /// Where to dial. + pub dial: Dial, + /// How to check the relay's certificate. + pub relay_tls: Arc, + /// The certificate authority client. + pub issuer: Arc, + /// Every wait. + pub timing: Timing, +} + +/// The remote door on this computer, as the server gave it. +#[derive(Clone)] +pub struct DoorTarget { + /// Where it listens (127.0.0.1:port). + pub addr: SocketAddr, + secret: Zeroizing, +} + +impl DoorTarget { + /// The door at `addr` with this start's secret (64 lowercase hex + /// characters, as the server gives it). + pub fn new(addr: SocketAddr, secret: &str) -> Result { + let hex = secret.len() == 64 + && secret + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)); + if !hex { + return Err( + "the books server gave a secret that isn't the expected 64 characters".into(), + ); + } + if !addr.ip().is_loopback() { + return Err("the door is not on this computer".into()); + } + Ok(DoorTarget { + addr, + secret: Zeroizing::new(secret.to_owned()), + }) + } +} + +impl std::fmt::Debug for DoorTarget { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DoorTarget") + .field("addr", &self.addr) + .finish_non_exhaustive() + } +} + +/// Why the link could not do what was asked. +#[derive(Debug, thiserror::Error)] +pub enum LinkError { + /// The identity files. + #[error("{0}")] + Identity(#[from] IdentityError), + /// The link is already shutting down. + #[error("the link is shutting down")] + Gone, +} + +struct Run { + stop: CancellationToken, + done: tokio::task::JoinHandle<()>, +} + +pub(crate) struct Inner { + cfg: LinkConfig, + identity: Mutex>, + status: watch::Sender, + resolver: Arc, + door: RwLock>, + line: watch::Sender>, + run: tokio::sync::Mutex>, + nudge: Notify, + served: AtomicU64, +} + +struct LineProof(LineHandle); + +impl DnsProof for LineProof { + fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + match self.0.publish_txt(value).await { + Ok(r) if r.ok => Ok(()), + Ok(r) => Err(r.error.unwrap_or_else(|| "refused".into())), + Err(_) => Err("the line to the relay failed".into()), + } + }) + } + + fn clear(&self) -> BoxFuture<'_, ()> { + Box::pin(async move { + let _ = self.0.request(Request::ClearTxt).await; + }) + } +} + +fn pick_in(start: i64, end: i64) -> i64 { + if end <= start { + return start; + } + let span = u64::try_from(end - start).unwrap_or(0); + let off = jitter(Duration::from_secs(span)).as_secs(); + start + i64::try_from(off).unwrap_or(0) +} + +impl Inner { + fn set(&self, f: impl FnOnce(&mut LinkStatus)) { + self.status.send_modify(f); + } + + fn identity_do(&self, f: impl FnOnce(&mut Identity) -> T) -> Option { + self.identity + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .map(f) + } + + // ---- lifecycle ------------------------------------------------------- + + pub(crate) async fn turn_on(self: &Arc) -> Result<(), LinkError> { + let mut run = self.run.lock().await; + if run.is_some() { + return Ok(()); + } + self.begin(&mut run).await + } + + async fn begin(self: &Arc, run: &mut Option) -> Result<(), LinkError> { + let dir = self.cfg.dir.clone(); + let loaded = tokio::task::spawn_blocking(move || Identity::load_or_create(&dir)) + .await + .map_err(|_| LinkError::Gone)?; + let id = match loaded { + Ok(id) => id, + Err(e) => { + self.set(|s| { + s.on = true; + s.trouble = Some(Trouble::Files(e.to_string())); + }); + return Err(e.into()); + } + }; + let host = id.host(&self.cfg.domain); + let address = id.address(&self.cfg.domain); + let claimed = id.claimed(); + *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = Some(id); + self.resolver.set_host(&host); + self.set(|s| { + *s = LinkStatus { + on: true, + address: Some(address), + claimed, + served: s.served, + ..LinkStatus::default() + }; + }); + let stop = CancellationToken::new(); + let me = self.clone(); + let token = stop.clone(); + let done = tokio::spawn(async move { + tokio::join!(me.line_loop(token.clone()), me.cert_loop(token)); + }); + *run = Some(Run { stop, done }); + Ok(()) + } + + pub(crate) async fn turn_off(self: &Arc) { + let mut run = self.run.lock().await; + self.end(&mut run).await; + } + + async fn end(self: &Arc, run: &mut Option) { + if let Some(r) = run.take() { + r.stop.cancel(); + // The tasks end at their next await; give them a moment, then + // let go of them (the line closes with its task). + let abort = r.done.abort_handle(); + if timeout(Duration::from_secs(5), r.done).await.is_err() { + abort.abort(); + } + } + self.line.send_replace(None); + self.resolver.set_key(None); + let served = self.served.load(Ordering::Relaxed); + self.set(|s| { + *s = LinkStatus { + served, + ..LinkStatus::default() + } + }); + } + + pub(crate) async fn new_address(self: &Arc) -> Result { + let mut run = self.run.lock().await; + let was_on = run.is_some(); + // The relay no longer knows the name, or turned it off: a new + // label would not help; a new identity does. + let lost = self + .status + .borrow() + .trouble + .as_ref() + .is_some_and(|t| *t == Trouble::NameLost || *t == Trouble::Blocked); + self.end(&mut run).await; + let dir = self.cfg.dir.clone(); + let domain = self.cfg.domain.clone(); + let made = tokio::task::spawn_blocking(move || -> Result { + if lost { + let id = Identity::reset(&dir)?; + CertStore::new(&dir).forget(); + Ok(id.address(&domain)) + } else { + let mut id = Identity::load_or_create(&dir)?; + id.new_label()?; + Ok(id.address(&domain)) + } + }) + .await + .map_err(|_| LinkError::Gone)??; + if was_on { + self.begin(&mut run).await?; + } else { + *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + Ok(made) + } + + // ---- the line -------------------------------------------------------- + + async fn addresses(&self) -> Result, Trouble> { + match &self.cfg.dial { + Dial::Addr(a) => Ok(vec![*a]), + Dial::Host(host, port) => { + // Looked up at every dial: a laptop on a new network finds + // the relay again. + match timeout( + self.cfg.timing.connect_timeout, + tokio::net::lookup_host((host.as_str(), *port)), + ) + .await + { + Ok(Ok(found)) => { + let found: Vec = found.collect(); + if found.is_empty() { + Err(Trouble::NoInternet) + } else { + Ok(found) + } + } + // A name that does not resolve is, nearly always, no + // internet. + _ => Err(Trouble::NoInternet), + } + } + } + } + + /// One try at a line. `Ok(Err(refusal))` is the relay saying no. + async fn dial(&self) -> Result, Trouble> { + let (name, key, claim) = self + .identity_do(|id| (id.name(), id.key_copy(), !id.claimed())) + .ok_or_else(|| Trouble::Files("no identity".into()))?; + let opts = LineOptions { + max_streams: MAX_STREAMS, + ..LineOptions::default() + }; + let mut last = Trouble::RelayDown; + for addr in self.addresses().await? { + let tried = timeout( + self.cfg.timing.connect_timeout, + client::connect( + addr, + self.cfg.relay_tls.clone(), + &self.cfg.relay_host, + name, + &key, + claim, + opts, + ), + ) + .await; + match tried { + Ok(Ok(line)) => return Ok(Ok(line)), + Ok(Err(e)) => match failure_of(&e) { + Failure::Refused(r) => return Ok(Err(r)), + Failure::Trouble(t) => last = t, + }, + Err(_) => last = Trouble::RelayDown, + } + } + Err(last) + } + + async fn line_loop(self: &Arc, stop: CancellationToken) { + let t = self.cfg.timing; + let mut backoff = Backoff::new(t.backoff_min, t.backoff_max); + let mut name_tries = 0u32; + loop { + if stop.is_cancelled() { + return; + } + let dialled = tokio::select! { + () = stop.cancelled() => return, + d = self.dial() => d, + }; + match dialled { + Ok(Ok(line)) => { + backoff.reset(); + name_tries = 0; + self.line_is_up(); + let ended = self.hold(line, &stop).await; + self.line_is_down(); + if stop.is_cancelled() { + return; + } + // A line that ended on its own (the relay restarted, the + // network went, the computer slept) is dialled again at + // once, with a little jitter so a relay coming back + // is not hit by every app in the same instant. + if ended != Ended::Woke { + let wait = t.backoff_min + jitter(t.backoff_min); + tokio::select! { + () = stop.cancelled() => return, + () = tokio::time::sleep(wait) => {} + } + } + continue; + } + Ok(Err(Refusal::Taken)) if !self.identity_do(|i| i.claimed()).unwrap_or(true) => { + // Somebody else has this name: another, at once. + name_tries += 1; + if name_tries <= 8 { + let _ = self.identity_do(|i| i.retry_name()); + if let Some(host) = self.identity_do(|i| i.host(&self.cfg.domain)) { + self.resolver.set_host(&host); + let address = format!("https://{host}"); + self.set(|s| s.address = Some(address)); + } + continue; + } + self.set(|s| s.trouble = Some(Trouble::RelayBusy)); + } + Ok(Err(refusal)) => { + let claimed = self.identity_do(|i| i.claimed()).unwrap_or(false); + let trouble = trouble_of_refusal(refusal, claimed); + self.set(|s| s.trouble = Some(trouble)); + } + Err(trouble) => self.set(|s| s.trouble = Some(trouble)), + } + let mut wait = backoff.wait(); + // A relay that said "wait" is not asked again at once. + if matches!( + self.status.borrow().trouble, + Some(Trouble::RateLimited | Trouble::RelayBusy) + ) { + wait = wait.max(t.backoff_min * 4); + } + tokio::select! { + () = stop.cancelled() => return, + () = tokio::time::sleep(wait) => {} + () = self.nudge.notified() => backoff.reset(), + } + } + } + + fn line_is_up(&self) { + let _ = self.identity_do(|i| i.set_claimed()); + self.set(|s| { + s.claimed = true; + s.line_up = true; + s.trouble = None; + }); + } + + fn line_is_down(&self) { + self.line.send_replace(None); + self.set(|s| s.line_up = false); + } + + /// Hold a line: serve its callers, keep it alive, end it when told + /// or when it is no good. + async fn hold(self: &Arc, mut line: Line, stop: &CancellationToken) -> Ended { + let t = self.cfg.timing; + let handle = line.handle(); + self.line.send_replace(Some(handle.clone())); + let acceptor = TlsAcceptor::from(server_config(self.resolver.clone())); + let callers = Arc::new(Semaphore::new(MAX_CALLERS)); + // The pings are their own task: a slow answer must not stop + // callers being taken. + let (failed_tx, mut failed) = tokio::sync::oneshot::channel::<()>(); + let pinger = { + let handle = handle.clone(); + tokio::spawn(async move { + loop { + tokio::time::sleep(t.ping_every).await; + let answered = timeout(t.ping_timeout, handle.request(Request::Ping)).await; + if !matches!(answered, Ok(Ok(_))) { + let _ = failed_tx.send(()); + return; + } + } + }) + }; + let mut tick = tokio::time::interval(t.tick); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut wake = WakeDetector::new(t.wake_gap); + let ended = loop { + tokio::select! { + () = stop.cancelled() => break Ended::Stopped, + () = self.nudge.notified() => break Ended::Nudged, + _ = &mut failed => break Ended::PingFailed, + _ = tick.tick() => { + if wake.woke() { + break Ended::Woke; + } + if handle.is_closed() { + break Ended::Closed; + } + } + inc = line.accept() => match inc { + None => break Ended::Closed, + Some(inc) => { + let Ok(permit) = callers.clone().try_acquire_owned() else { + continue; // too many at once: this one is dropped + }; + let me = self.clone(); + let acceptor = acceptor.clone(); + tokio::spawn(async move { + me.serve_caller(inc, acceptor).await; + drop(permit); + }); + } + }, + } + }; + pinger.abort(); + handle.close(); + ended + } + + /// One caller: end its TLS here, then give the plain bytes to the + /// door after the secret and the PROXY header (INVARIANT 3). + async fn serve_caller(&self, mut inc: Incoming, acceptor: TlsAcceptor) { + let Some(door) = self.door.read().unwrap_or_else(|e| e.into_inner()).clone() else { + // No door to give the caller to: end the stream, so the caller + // is turned away now and not left waiting. + let _ = inc.stream.shutdown().await; + return; + }; + let Ok(Ok(mut tls)) = timeout(self.cfg.timing.handshake, acceptor.accept(inc.stream)).await + else { + return; + }; + let Ok(Ok(mut up)) = timeout(Duration::from_secs(5), TcpStream::connect(door.addr)).await + else { + return; + }; + let _ = up.set_nodelay(true); + let mut front = Vec::with_capacity(64 + 52); + front.extend_from_slice(door.secret.as_bytes()); + front.extend(inc.caller.encode()); + if up.write_all(&front).await.is_err() { + return; + } + self.served.fetch_add(1, Ordering::Relaxed); + let served = self.served.load(Ordering::Relaxed); + self.set(|s| s.served = served); + let _ = tokio::io::copy_bidirectional(&mut tls, &mut up).await; + let _ = tls.shutdown().await; + } + + // ---- the certificate ------------------------------------------------- + + fn install(&self, c: &StoredCert) { + self.resolver.set_key(c.certified()); + let (end, renew) = (c.not_after, c.renew_at); + let _ = renew; + self.set(|s| { + s.cert_expires = Some(end); + }); + } + + fn uninstall(&self) { + self.resolver.set_key(None); + self.set(|s| s.cert_expires = None); + } + + async fn wait_for_line(&self, stop: &CancellationToken) -> Option { + let mut rx = self.line.subscribe(); + loop { + if let Some(h) = rx.borrow_and_update().clone() { + return Some(h); + } + tokio::select! { + () = stop.cancelled() => return None, + r = rx.changed() => if r.is_err() { return None }, + } + } + } + + async fn cert_loop(self: &Arc, stop: CancellationToken) { + let t = self.cfg.timing; + let Some((name, host)) = + self.identity_do(|i| (i.name().to_string(), i.host(&self.cfg.domain))) + else { + return; + }; + let identifier = format!("*.{name}.{}", self.cfg.domain); + let _ = host; + let store = CertStore::new(&self.cfg.dir); + let mut backoff = Backoff::new(t.cert_retry_min, t.cert_retry_max); + loop { + if stop.is_cancelled() { + return; + } + let stored = store.load(&name); + let tnow = now(); + match &stored { + Some(c) if c.valid_at(tnow) => self.install(c), + _ => self.uninstall(), + } + if let Some(c) = &stored + && c.valid_at(tnow) + && tnow < c.renew_at + { + // Wait for the renewal time; now and then ask the authority + // whether it wants the certificate renewed sooner. + let secs = u64::try_from(c.renew_at - tnow).unwrap_or(0); + let wait = Duration::from_secs(secs).min(t.ari_recheck); + tokio::select! { + () = stop.cancelled() => return, + () = tokio::time::sleep(wait) => {} + } + if now() < c.renew_at { + self.recheck_window(&store, c).await; + continue; + } + } + // Time to order. A line is needed for the proof. + let Some(_line) = self.wait_for_line(&stop).await else { + return; + }; + let ordered = tokio::select! { + () = stop.cancelled() => return, + o = self.order(&name, &identifier, stored.as_ref()) => o, + }; + match ordered { + Ok(new) => { + if store.save(&new).is_err() { + self.set(|s| { + s.cert_trouble = Some( + "Wanderbooks got a certificate but can't keep it on this computer." + .into(), + ); + }); + } else { + self.set(|s| s.cert_trouble = None); + } + self.install(&new); + backoff.reset(); + } + Err(why) => { + let ends = stored + .as_ref() + .filter(|c| c.valid_at(now())) + .map(|c| c.not_after); + let words = match ends { + Some(_) => format!( + "The certificate could not be renewed yet: {why}. It keeps trying; the one in use still works." + ), + None => format!( + "Wanderbooks could not get a certificate yet: {why}. It keeps trying." + ), + }; + self.set(|s| s.cert_trouble = Some(words)); + let wait = backoff.wait(); + tokio::select! { + () = stop.cancelled() => return, + () = tokio::time::sleep(wait) => {} + } + } + } + } + } + + /// Ask the authority again when it wants this certificate renewed + /// (RFC 9773): a window that opens sooner than the time kept brings + /// the renewal forward. + async fn recheck_window(&self, store: &CertStore, c: &StoredCert) { + let Some(line) = self.line.borrow().clone() else { + return; + }; + let Ok(list) = line.authorities().await else { + return; + }; + let Some(a) = list.iter().find(|a| a.id == c.authority) else { + return; + }; + let Some((start, end)) = self.cfg.issuer.renewal_window(a, &c.chain_pem).await else { + return; + }; + let at = pick_in(start, end); + if at < c.renew_at { + let mut sooner = c.clone(); + sooner.renew_at = at; + let _ = store.save(&sooner); + } + } + + async fn order( + &self, + name: &str, + identifier: &str, + previous: Option<&StoredCert>, + ) -> Result { + let line = self + .line + .borrow() + .clone() + .ok_or("the line to the relay is down")?; + let list = line + .authorities() + .await + .map_err(|_| "the relay would not say which certificate authorities to use")?; + if list.is_empty() { + return Err("the relay named no certificate authority".into()); + } + let usable: Vec<_> = list.iter().filter(|a| a.usable).collect(); + if usable.is_empty() { + return Err("no certificate authority is ready for this installation yet".into()); + } + let proof = LineProof(line); + let mut problems: Vec = Vec::new(); + for a in usable { + let replaces = previous + .filter(|p| p.authority == a.id && p.valid_at(now())) + .and_then(StoredCert::der); + let order = self.cfg.issuer.issue(OrderRequest { + authority: a, + identifier: identifier.to_owned(), + replaces, + dns: &proof, + }); + let result = match timeout(self.cfg.timing.order_timeout, order).await { + Ok(r) => r, + Err(_) => Err("took too long".to_string()), + }; + proof.clear().await; + match result { + Ok(issued) => { + let window = self.cfg.issuer.renewal_window(a, &issued.chain_pem).await; + let renew_at = window.map(|(s, e)| pick_in(s, e)); + match StoredCert::new(name, &a.id, &issued, identifier, renew_at) { + Ok(c) => return Ok(c), + Err(why) => problems.push(format!("{}: {why}", a.id)), + } + } + Err(why) => problems.push(format!("{}: {why}", a.id)), + } + } + Err(problems.join("; ")) + } +} + +/// Why a held line ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Ended { + Stopped, + Nudged, + PingFailed, + Woke, + Closed, +} + +/// The link, for the app: a handle with plain (blocking) methods over its +/// own small runtime, so the window and the books server's glue need no +/// async of their own. +pub struct Link { + inner: Arc, + handle: tokio::runtime::Handle, + owned: Mutex>, +} + +impl Link { + fn make(cfg: LinkConfig) -> Arc { + let resolver = Resolver::new(); + let (status, _) = watch::channel(LinkStatus::default()); + let (line, _) = watch::channel(None); + Arc::new(Inner { + cfg, + identity: Mutex::new(None), + status, + resolver, + door: RwLock::new(None), + line, + run: tokio::sync::Mutex::new(None), + nudge: Notify::new(), + served: AtomicU64::new(0), + }) + } + + /// A link with a runtime of its own: two threads, ended with the link. + pub fn start(cfg: LinkConfig) -> Result { + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("wanderbooks-link") + .enable_all() + .build() + .map_err(|e| format!("can't start the web link ({})", e.kind()))?; + let handle = rt.handle().clone(); + Ok(Link { + inner: Self::make(cfg), + handle, + owned: Mutex::new(Some(rt)), + }) + } + + /// A link on a runtime that is already running (tests). Its blocking + /// methods need a multi-threaded runtime. + pub fn start_on(handle: tokio::runtime::Handle, cfg: LinkConfig) -> Link { + Link { + inner: Self::make(cfg), + handle, + owned: Mutex::new(None), + } + } + + fn block( + &self, + fut: impl std::future::Future + Send + 'static, + ) -> Option { + let (tx, rx) = std::sync::mpsc::channel(); + self.handle.spawn(async move { + let _ = tx.send(fut.await); + }); + rx.recv().ok() + } + + /// The link as it stands: a read of memory, never a wait. + pub fn status(&self) -> LinkStatus { + self.inner.status.borrow().clone() + } + + /// Changes of status, for a caller that wants to wait. + pub fn watch(&self) -> watch::Receiver { + self.inner.status.subscribe() + } + + /// The address kept for this installation, whether or not the link is + /// on (it is the same when turned on again). `None` before the first + /// time it was turned on. + pub fn kept_address(&self) -> Option { + Identity::load(&self.inner.cfg.dir) + .ok() + .flatten() + .map(|i| i.address(&self.inner.cfg.domain)) + } + + /// Where the books server's remote door listens, or none. + pub fn set_door(&self, door: Option) { + *self.inner.door.write().unwrap_or_else(|e| e.into_inner()) = door; + } + + /// Turn the link on: make or read the identity, and start the line + /// and the certificate. Returns when they are started, not when they + /// are done: [`Link::status`] says how far they are. + pub fn turn_on(&self) -> Result<(), LinkError> { + let me = self.inner.clone(); + self.block(async move { me.turn_on().await }) + .unwrap_or(Err(LinkError::Gone)) + } + + /// Turn the link off: the line ends and the certificate is no longer + /// served before this returns. The name is kept. + pub fn turn_off(&self) { + let me = self.inner.clone(); + let _ = self.block(async move { me.turn_off().await }); + } + + /// A new address (INVARIANT 5): the address it will have. + pub fn new_address(&self) -> Result { + let me = self.inner.clone(); + self.block(async move { me.new_address().await }) + .unwrap_or(Err(LinkError::Gone)) + } + + /// The network may have changed: dial again now. + pub fn nudge(&self) { + self.inner.nudge.notify_waiters(); + } +} + +impl Drop for Link { + fn drop(&mut self) { + // Nothing outlives the link (INVARIANT 1): the line is closed, then + // the runtime, if it is ours, is let go without waiting. + let me = self.inner.clone(); + let (tx, rx) = std::sync::mpsc::channel(); + self.handle.spawn(async move { + me.turn_off().await; + let _ = tx.send(()); + }); + let _ = rx.recv_timeout(Duration::from_secs(6)); + if let Some(rt) = self.owned.lock().unwrap_or_else(|e| e.into_inner()).take() { + rt.shutdown_background(); + } + } +} diff --git a/crates/ledger-link/src/private.rs b/crates/ledger-link/src/private.rs new file mode 100644 index 00000000..3e52c664 --- /dev/null +++ b/crates/ledger-link/src/private.rs @@ -0,0 +1,88 @@ +//! Files only this account can read: the app's key, its certificate's key, +//! the secret in its address. +//! +//! ```text +//! GOAL: nothing the relay could use to read traffic, and nothing that +//! makes the address guessable, is ever readable by another account +//! on this computer, nor half-written after a crash. +//! SOURCE: WB-link-1 (the app's identity), D-80, D-87; the token files' +//! own rule (ledger-host tokens.rs: 0600, the owner-only DACL on +//! Windows). +//! INVARIANTS: +//! 1. A file is made with mode 0600 (Unix) before a byte of it is +//! written, or made owner-only before a byte is written (Windows, +//! `ledger_store::winsec::set_owner_only`, the helper the token +//! files use), and its folder 0700 or owner-only. +//! 2. A write is a temporary file, synced, then renamed over the old +//! one: a reader sees the old file or the new one, never a part. +//! SCENARIOS: +//! 1. A file written here reads back, has mode 0600, and its folder +//! 0700, on Unix. +//! ``` + +use std::io::{self, Write}; +use std::path::Path; + +/// Make `dir` (and its parents) private to this account. +pub fn make_dir(dir: &Path) -> io::Result<()> { + std::fs::create_dir_all(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + #[cfg(windows)] + ledger_store::winsec::set_owner_only(dir)?; + Ok(()) +} + +/// Write `bytes` to `path`, privately and atomically (INVARIANTS 1, 2). +pub fn write(path: &Path, bytes: &[u8]) -> io::Result<()> { + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + let _ = std::fs::remove_file(&tmp); + let result = (|| { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let mut file = options.open(&tmp)?; + #[cfg(windows)] + ledger_store::winsec::set_owner_only(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&tmp, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_private_file_reads_back_and_is_mode_0600() { + let dir = tempfile::tempdir().unwrap(); + let sub = dir.path().join("link"); + make_dir(&sub).unwrap(); + let f = sub.join("k"); + write(&f, b"one").unwrap(); + write(&f, b"two").unwrap(); + assert_eq!(std::fs::read(&f).unwrap(), b"two"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&f), 0o600); + assert_eq!(mode(&sub), 0o700); + } + // No temporary file is left behind. + assert_eq!(std::fs::read_dir(&sub).unwrap().count(), 1); + } +} diff --git a/crates/ledger-link/src/status.rs b/crates/ledger-link/src/status.rs new file mode 100644 index 00000000..ae799767 --- /dev/null +++ b/crates/ledger-link/src/status.rs @@ -0,0 +1,248 @@ +//! What the link says about itself, in words a person can use. +//! +//! ```text +//! GOAL: every state the link can be in ends in plain words and in a +//! state that recovers by itself: no spinner forever, no jargon, and +//! never a claim that the local assistants or the window are +//! affected by the network. +//! SOURCE: WB-link-5 (the states the Connect page can show), plan +//! p15-app-and-relay.md 3.3 ("progress in plain words ... the +//! state when the relay cannot be reached, in words, with nothing +//! lost locally"). +//! INVARIANTS: +//! 1. A status is data; the words come from [`LinkStatus::words`] and +//! [`Trouble::words`], one place, so a test can read what a person +//! reads. +//! 2. A trouble that ends by itself (no internet, the relay down, a +//! busy relay) says it is trying again; one that needs the person +//! (a wrong clock, the address lost) says what to do. +//! 3. No status holds a key, a secret label or a token: the address in +//! it is only there while the link is on, and a status prints +//! without it. +//! SCENARIOS: +//! 1. A status with no line and no trouble reads "Connecting to the +//! relay"; with a line and no certificate, "Getting a certificate"; +//! with both, "Connected". +//! 2. Every trouble has words, and the words of one that mend +//! themselves say so. +//! ``` + +/// Where the link has got to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Step { + /// Off: no line, no address served. + Off, + /// Getting the address: making the name and having the relay accept it. + GettingAddress, + /// The line to the relay is being made again. + Connecting, + /// The line is up and the certificate is being got. + GettingCertificate, + /// The line is up and the certificate is in place. + Connected, +} + +/// Why the link is not further along. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Trouble { + /// The computer cannot reach the internet (no network, or no way to + /// find the relay). + NoInternet, + /// The internet is there; the relay does not answer. + RelayDown, + /// The relay is busy. + RelayBusy, + /// Too many new addresses lately, here or everywhere. + RateLimited, + /// The relay has turned this address off. + Blocked, + /// The relay no longer knows this address. + NameLost, + /// The computer's clock is wrong: the relay's certificate looks + /// expired or not yet valid. + ClockWrong, + /// The relay answered in a way this version does not understand. + Protocol, + /// The files that keep the address could not be read or written. + Files(String), +} + +impl Trouble { + /// What a person reads, and what happens next (INVARIANT 2). + pub fn words(&self) -> String { + match self { + Trouble::NoInternet => "This computer can't reach the internet. Your assistants on this computer still work. Web assistants will connect again as soon as the internet is back.".into(), + Trouble::RelayDown => "Wanderbooks can't reach its relay right now. Nothing is lost, and your assistants on this computer still work. It keeps trying.".into(), + Trouble::RelayBusy => "The relay is busy. It keeps trying.".into(), + Trouble::RateLimited => "Many people are setting up web assistants right now, so the relay asked Wanderbooks to wait. It keeps trying, a little later each time.".into(), + Trouble::Blocked => "The relay has turned this address off. Get a new address, or write to us if you think this is a mistake.".into(), + Trouble::NameLost => "The relay doesn't know this address any more. Get a new address to carry on; web assistants will need the new one.".into(), + Trouble::ClockWrong => "This computer's clock looks wrong, so the relay can't be trusted yet. Set the date and time (turn on \"set automatically\"), and Wanderbooks will connect by itself.".into(), + Trouble::Protocol => "The relay speaks a newer version than this Wanderbooks. Update Wanderbooks to connect.".into(), + Trouble::Files(why) => format!("Wanderbooks can't keep its web address on this computer: {why}."), + } + } + + /// Whether this ends without the person doing anything. + pub fn mends_itself(&self) -> bool { + matches!( + self, + Trouble::NoInternet + | Trouble::RelayDown + | Trouble::RelayBusy + | Trouble::RateLimited + | Trouble::ClockWrong + ) + } +} + +/// The link, as it stands. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct LinkStatus { + /// On or off (the person's switch). + pub on: bool, + /// The address, once there is one and while the link is on. + pub address: Option, + /// The relay has accepted the name. + pub claimed: bool, + /// The line is up. + pub line_up: bool, + /// A certificate is in place and valid: when it ends (unix seconds). + pub cert_expires: Option, + /// Why the line is not up. + pub trouble: Option, + /// Why the certificate is not in place (or not renewed), in words. + pub cert_trouble: Option, + /// Callers served so far. + pub served: u64, +} + +impl std::fmt::Debug for LinkStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // The address holds the secret label: it is not printed (3). + f.debug_struct("LinkStatus") + .field("on", &self.on) + .field("has_address", &self.address.is_some()) + .field("claimed", &self.claimed) + .field("line_up", &self.line_up) + .field("cert_expires", &self.cert_expires) + .field("trouble", &self.trouble) + .field("cert_trouble", &self.cert_trouble) + .field("served", &self.served) + .finish() + } +} + +impl LinkStatus { + /// Where the link has got to. + pub fn step(&self) -> Step { + if !self.on { + Step::Off + } else if !self.line_up && !self.claimed { + Step::GettingAddress + } else if !self.line_up { + Step::Connecting + } else if self.cert_expires.is_none() { + Step::GettingCertificate + } else { + Step::Connected + } + } + + /// True when a web assistant can reach the books now. + pub fn reachable(&self) -> bool { + self.step() == Step::Connected + } + + /// The one line a person reads about progress. + pub fn words(&self) -> String { + match self.step() { + Step::Off => "Web assistants are off.".into(), + Step::GettingAddress => "Getting an address…".into(), + Step::Connecting => "Connecting to the relay…".into(), + Step::GettingCertificate => "Getting a certificate…".into(), + Step::Connected => "Connected. Web assistants can reach these books.".into(), + } + } + + /// What is wrong, in words, if anything: the line's trouble, else the + /// certificate's. + pub fn problem(&self) -> Option { + if let Some(t) = &self.trouble { + return Some(t.words()); + } + self.cert_trouble.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_steps_read_in_order() { + let mut s = LinkStatus::default(); + assert_eq!(s.step(), Step::Off); + s.on = true; + assert_eq!(s.step(), Step::GettingAddress); + assert_eq!(s.words(), "Getting an address…"); + s.claimed = true; + assert_eq!(s.step(), Step::Connecting); + s.line_up = true; + assert_eq!(s.step(), Step::GettingCertificate); + s.cert_expires = Some(1); + assert_eq!(s.step(), Step::Connected); + assert!(s.reachable()); + } + + #[test] + fn every_trouble_has_words_and_the_mending_ones_say_so() { + let all = [ + Trouble::NoInternet, + Trouble::RelayDown, + Trouble::RelayBusy, + Trouble::RateLimited, + Trouble::Blocked, + Trouble::NameLost, + Trouble::ClockWrong, + Trouble::Protocol, + Trouble::Files("the disk is full".into()), + ]; + for t in all { + let w = t.words(); + assert!(w.ends_with('.'), "{w}"); + assert!(!w.to_lowercase().contains("mcp")); + if matches!( + t, + Trouble::NoInternet + | Trouble::RelayDown + | Trouble::RelayBusy + | Trouble::RateLimited + ) { + assert!( + w.contains("keeps trying") || w.contains("as soon as"), + "{w}" + ); + } + } + // The ones that need the person say what to do. + assert!(Trouble::ClockWrong.words().contains("Set the date")); + assert!(Trouble::NameLost.words().contains("Get a new address")); + // Only local assistants are said to keep working, never anything + // about the window. + assert!( + Trouble::NoInternet + .words() + .contains("on this computer still work") + ); + } + + #[test] + fn a_status_prints_without_its_address() { + let s = LinkStatus { + address: Some("https://secretlabel.a-b-c-d.wanderbooks.link".into()), + ..LinkStatus::default() + }; + assert!(!format!("{s:?}").contains("secretlabel")); + } +} diff --git a/crates/ledger-link/tests/link.rs b/crates/ledger-link/tests/link.rs new file mode 100644 index 00000000..0d094262 --- /dev/null +++ b/crates/ledger-link/tests/link.rs @@ -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 `..`, 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 = 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 = 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)); +} diff --git a/crates/ledger-link/tests/support/mod.rs b/crates/ledger-link/tests/support/mod.rs new file mode 100644 index 00000000..ea3ca2a6 --- /dev/null +++ b/crates/ledger-link/tests/support/mod.rs @@ -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, + /// Authority ids that refuse. + pub fail: std::collections::HashSet, + /// 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, +} + +pub fn txt_at(m: &Message) -> Vec { + 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 { + 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 { + let mut params = CertificateParams::new(Vec::::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> { + 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>, + pub accepted: Arc, + pub refuse: Arc, + pub to_upstream: Arc>>, + pub from_upstream: Arc>>, + cut: watch::Sender, + /// The address the relay sees connections from. + pub source_ports: Arc>>, +} + +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 { + self.to_upstream.lock().unwrap().clone() + } + + pub fn seen_down(&self) -> Vec { + 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, + 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>>, +} + +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, + 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 { + 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}"); +} diff --git a/justfile b/justfile index 8d237ff2..8db57ebf 100644 --- a/justfile +++ b/justfile @@ -63,7 +63,7 @@ check-shard shard: # the workspace, since K-U12. None leaves the list, and `kernel-only` # fails when a folder under crates/ is not in it, so a new crate joins it # on the day it is added. -kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault ledger-store ledger-config ledger-import ledger-package ledger-mcp ledger-gui relay" +kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault ledger-store ledger-config ledger-import ledger-package ledger-mcp ledger-gui relay ledger-link" # Money arithmetic lives in the kernel and nowhere else (AGENTS.md, bar # item 1). The compiler is asked (scripts/raw-decimal-arith.sh): a raw