diff --git a/crates/ledger-cli/tests/web_link.rs b/crates/ledger-cli/tests/web_link.rs index 0d49ddaf..76ec7c25 100644 --- a/crates/ledger-cli/tests/web_link.rs +++ b/crates/ledger-cli/tests/web_link.rs @@ -40,7 +40,7 @@ use common::{BOOK, Home, clean_env}; use futures::future::BoxFuture; use ledger_host::app_server::AppServer; use ledger_host::web::{Admin, WebAssistants}; -use ledger_link::{Dial, Issued, Issuer, LinkConfig, OrderRequest, Step, Timing}; +use ledger_link::{CertTrust, Dial, Issued, Issuer, LinkConfig, OrderRequest, Step, Timing}; use ledger_mcp::admin::{Request, Response}; use rcgen::{CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose}; use relay::proto::Authority; @@ -152,6 +152,7 @@ fn start_server(home: &Home) -> AppServer { fn web_for(home: &Home, env: &relay_common::Env, ca: &Arc) -> WebAssistants { let (relay_tls, router, issuer) = (env.line_tls(), env.router(), ca.clone()); + let roots = ca.roots(); WebAssistants::with_maker( Some(home.root()), Box::new(move |dir| { @@ -162,6 +163,7 @@ fn web_for(home: &Home, env: &relay_common::Env, ca: &Arc) -> WebAss dial: Dial::Addr(router), relay_tls: relay_tls.clone(), issuer: issuer.clone(), + trust: CertTrust::for_tests(roots.clone()), timing: Timing { ping_every: Duration::from_millis(500), backoff_min: Duration::from_millis(50), diff --git a/crates/ledger-link/Cargo.toml b/crates/ledger-link/Cargo.toml index 7597dcd3..999e98e9 100644 --- a/crates/ledger-link/Cargo.toml +++ b/crates/ledger-link/Cargo.toml @@ -27,6 +27,7 @@ base64 = "0.22" ring = "0.17" x509-parser = "0.18" zeroize = "1" +http = "1" webpki-root-certs = "1" # Owner-only DACLs for the key and certificate files (the helper the token @@ -39,7 +40,6 @@ tempfile = "3" rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "x509-parser"] } 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" diff --git a/crates/ledger-link/src/acme.rs b/crates/ledger-link/src/acme.rs index fad9eb34..1dee0180 100644 --- a/crates/ledger-link/src/acme.rs +++ b/crates/ledger-link/src/acme.rs @@ -21,17 +21,33 @@ //! 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. +//! 5. Every failure comes back in the app's own words, chosen from the +//! kind of failure; what the authority said is only a short quoted +//! detail at the end (text.rs), never a bare code and never the +//! authority's text on its own. +//! 6. The app sends a request only to an authority's directory on a host +//! from [`DIRECTORY_HOSTS`], which is compiled in: the relay chooses +//! which of them and in what order, but cannot name a new host, so it +//! cannot make the app send requests to any server it likes. An +//! authority on another host, over http, with a port or with a name +//! and password in its address, is skipped and said so. A kept +//! account is only used if the directory it was made at is on the list +//! too. Adding a brand-new authority takes a new release of the app; +//! that is the price of the relay not being trusted with the choice of +//! where the app sends its requests (plan p15-app-and-relay.md 5). //! 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. +//! 2. An authority on a host that is not in the list is refused before +//! any request; the hosts in the list are accepted; the authority's +//! words are bounded and plain (unit tests here). //! ``` use crate::certs::{DnsProof, Issued, Issuer, OrderRequest, leaf_der}; use crate::private; +use crate::text::detail; use base64::Engine as _; use futures::future::BoxFuture; use instant_acme::{ @@ -50,9 +66,36 @@ use zeroize::Zeroizing; /// authority. pub type HttpFactory = Arc Option> + Send + Sync>; +/// The hosts an authority's ACME directory may be on (INVARIANT 6), each +/// from the authority's own documentation. The relay's list says which of +/// these to use; a host that is not here is never contacted. +pub const DIRECTORY_HOSTS: &[(&str, &str)] = &[ + // https://letsencrypt.org/docs/acme-protocol-updates/ + ("acme-v02.api.letsencrypt.org", "Let's Encrypt"), + // https://letsencrypt.org/docs/staging-environment/ + ( + "acme-staging-v02.api.letsencrypt.org", + "Let's Encrypt (staging)", + ), + // https://cloud.google.com/certificate-manager/docs/public-ca-tutorial + ("dv.acme-v02.api.pki.goog", "Google Trust Services"), + ( + "dv.acme-v02.test-api.pki.goog", + "Google Trust Services (test)", + ), + // https://zerossl.com/documentation/acme/ + ("acme.zerossl.com", "ZeroSSL"), + // https://community.buypass.com/t/63d4ay/buypass-go-ssl-endpoints + ("api.buypass.com", "Buypass"), + ("api.test4.buypass.no", "Buypass (test)"), + // https://www.ssl.com/guide/ssl-tls-certificate-issuance-and-revocation-with-acme/ + ("acme.ssl.com", "SSL.com"), +]; + /// The ACME client. pub struct AcmeIssuer { dir: PathBuf, + hosts: Vec, http: HttpFactory, /// How long an order may take to be ready or issued. patience: Duration, @@ -63,11 +106,23 @@ impl AcmeIssuer { pub fn new(dir: &Path) -> Self { AcmeIssuer { dir: dir.join("acme"), + hosts: DIRECTORY_HOSTS + .iter() + .map(|(h, _)| (*h).to_owned()) + .collect(), http: Arc::new(|| None), patience: Duration::from_secs(120), } } + /// Accept directories on these hosts instead of [`DIRECTORY_HOSTS`] + /// (tests: a stand-in authority on localhost). Nothing in the program + /// calls this; the relay cannot reach it (INVARIANT 6). + pub fn with_directory_hosts_for_tests(mut self, hosts: &[&str]) -> Self { + self.hosts = hosts.iter().map(|h| (*h).to_ascii_lowercase()).collect(); + self + } + /// Speak through `http` (tests). pub fn with_http(mut self, http: HttpFactory) -> Self { self.http = http; @@ -80,10 +135,46 @@ impl AcmeIssuer { self } + /// Whether `url` is a directory the app may contact (INVARIANT 6): https, + /// on a listed host, with no port other than 443 and no name or + /// password in front. It is read with the parser the ACME library + /// reads it with, so the two agree on what the host is. + fn directory_allowed(&self, url: &str) -> Result<(), String> { + let refused = |why: &str| { + format!( + "The directory {} is {why}, so this version of Wanderbooks does not use it.", + detail(url) + ) + }; + if url + .chars() + .any(|c| c.is_control() || c.is_whitespace() || c == '\\') + { + return Err(refused("not a plain address")); + } + let uri: http::Uri = url.parse().map_err(|_| refused("not an address"))?; + if uri.scheme_str() != Some("https") { + return Err(refused("not an https address")); + } + let authority = uri.authority().ok_or_else(|| refused("not an address"))?; + if authority.as_str().contains('@') { + return Err(refused("an address with a name in front")); + } + if authority.port_u16().is_some_and(|p| p != 443) { + return Err(refused("on an unusual port")); + } + let host = authority.host().to_ascii_lowercase(); + if self.hosts.contains(&host) { + Ok(()) + } else { + Err(refused("on a host it does not know")) + } + } + 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)), + None => Account::builder().map_err(|e| words(Kind::Start, &e)), } } @@ -107,16 +198,29 @@ impl AcmeIssuer { /// The account at this authority: the kept one, or a new one /// (INVARIANTS 1 and 4). async fn account(&self, authority: &Authority) -> Result { + self.directory_allowed(&authority.directory)?; 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) { + // A kept account is used only for a directory on the list: what + // is in the file is what the library will contact. + let kept_at_a_listed_host = serde_json::from_slice::(&bytes) + .ok() + .is_some_and(|v| { + v.get("urls").is_none_or(serde_json::Value::is_null) + && v.get("directory") + .and_then(serde_json::Value::as_str) + .is_some_and(|d| self.directory_allowed(d).is_ok()) + }); + if kept_at_a_listed_host + && 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(e) if is_network(&e) => return Err(words(Kind::Unreachable, &e)), Err(_) => {} } } @@ -126,13 +230,13 @@ impl AcmeIssuer { 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() + "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(), + "this authority needs an account binding the relay has not given yet.".into(), ); } (None, false) => None, @@ -149,7 +253,7 @@ impl AcmeIssuer { eab.as_ref(), ) .await - .map_err(|e| words("refused a new account", &e))?; + .map_err(|e| words(Kind::NewAccount, &e))?; private::make_dir(&self.dir) .map_err(|e| format!("can't keep the account ({})", e.kind()))?; let text = Zeroizing::new( @@ -168,27 +272,61 @@ fn is_network(e: &instant_acme::Error) -> bool { ) } -/// The authority's own words, as short as they can be (INVARIANT 5). -fn words(what: &str, e: &instant_acme::Error) -> String { +/// What kind of thing went wrong: the app's words are chosen from this, +/// never from what the authority said (INVARIANT 5). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Start, + Unreachable, + NewAccount, + Order, + Proof, + Finish, + Issue, + Download, +} + +impl Kind { + fn words(self) -> &'static str { + match self { + Kind::Start => "the app could not start talking to the authority", + Kind::Unreachable => "the authority could not be reached", + Kind::NewAccount => "the authority would not open an account", + Kind::Order => "the authority refused the order", + Kind::Proof => "the authority could not check the proof of the name", + Kind::Finish => "the authority did not finish the order", + Kind::Issue => "the authority refused to issue the certificate", + Kind::Download => "the authority did not hand over the certificate", + } + } +} + +/// A failure as the app says it (INVARIANT 5): its own words for the kind +/// of failure, and what the authority said only as a short quoted detail. +fn words(kind: Kind, 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}"), + let said = detail(p.detail.as_deref().unwrap_or("")); + let what = match p.r#type.as_deref().unwrap_or("").rsplit(':').next() { + Some("rateLimited") => { + "the authority says too many certificates were asked for lately" + } + _ => kind.words(), + }; + if said.is_empty() { + format!("{what}.") + } else { + format!("{what}. It said {said}.") + } + } + other => { + let said = detail(&other.to_string()); + if said.is_empty() { + format!("{}.", kind.words()) + } else { + format!("{}. The detail was {said}.", kind.words()) } } - _ => format!("the authority {what}: {e}"), } } @@ -213,50 +351,49 @@ impl Issuer for AcmeIssuer { 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)), + .map_err(|e| words(Kind::Order, &e))?, + Err(e) => return Err(words(Kind::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))?; + let mut authz = result.map_err(|e| words(Kind::Proof, &e))?; match authz.status { AuthorizationStatus::Pending => {} AuthorizationStatus::Valid => continue, - _ => return Err("the authority will not accept this name".into()), + _ => 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")?; + .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})") + format!( + "the relay would not publish the proof of the name. It said {}.", + detail(&why) + ) })?; published = true; challenge .set_ready() .await - .map_err(|e| words("failed on the proof of the name", &e))?; + .map_err(|e| words(Kind::Proof, &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))?; + .map_err(|e| words(Kind::Finish, &e))?; if status != OrderStatus::Ready { - return Err("the authority could not check the name's proof".to_string()); + 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 key_pem = + Zeroizing::new(order.finalize().await.map_err(|e| words(Kind::Issue, &e))?); let chain_pem = order .poll_certificate(&policy) .await - .map_err(|e| words("did not hand over the certificate", &e))?; + .map_err(|e| words(Kind::Download, &e))?; Ok(Issued { chain_pem, key_pem }) } .await; @@ -288,3 +425,67 @@ impl Issuer for AcmeIssuer { // Silence the unused-import lint when no trait object use needs it. #[allow(dead_code)] fn _uses(_: &dyn DnsProof) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_listed_host_is_accepted_at_its_directory_and_no_other_is() { + let dir = std::env::temp_dir(); + let issuer = AcmeIssuer::new(&dir); + for (host, _) in DIRECTORY_HOSTS { + assert!( + issuer + .directory_allowed(&format!("https://{host}/directory")) + .is_ok(), + "{host}" + ); + assert!( + issuer + .directory_allowed(&format!("https://{host}:443/directory")) + .is_ok(), + "{host} on 443" + ); + assert!( + issuer + .directory_allowed(&format!("https://x.{host}/directory")) + .is_err(), + "a host under {host}" + ); + assert!( + issuer + .directory_allowed(&format!("http://{host}/directory")) + .is_err(), + "{host} over http" + ); + } + // The hosts' own documentation names these; a brand-new one is a + // release of the app. + let hosts: Vec<&str> = DIRECTORY_HOSTS.iter().map(|(h, _)| *h).collect(); + for want in [ + "acme-v02.api.letsencrypt.org", + "acme-staging-v02.api.letsencrypt.org", + "dv.acme-v02.api.pki.goog", + "acme.zerossl.com", + "api.buypass.com", + "acme.ssl.com", + ] { + assert!(hosts.contains(&want), "{want}"); + } + } + + #[test] + fn an_authoritys_problem_is_the_apps_words_and_a_short_quoted_detail() { + let hostile = format!("a\u{7}\n\u{202e}b {}", "x".repeat(5000)); + let problem: instant_acme::Problem = serde_json::from_value(serde_json::json!({ + "type": "urn:made:up:evil", + "detail": hostile, + })) + .unwrap(); + let said = words(Kind::Order, &instant_acme::Error::Api(problem)); + assert!(said.starts_with("the authority refused the order. It said \u{201c}a b ")); + assert!(said.chars().count() < 200, "{}", said.chars().count()); + assert!(!said.chars().any(|c| c.is_control() || c == '\u{202e}')); + } +} diff --git a/crates/ledger-link/src/certs.rs b/crates/ledger-link/src/certs.rs index 8acc74b7..3120e4af 100644 --- a/crates/ledger-link/src/certs.rs +++ b/crates/ledger-link/src/certs.rs @@ -30,6 +30,18 @@ //! 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. +//! 7. A certificate is believed only if its chain ends at one of the +//! public roots the program ships ([`CertTrust::public`]), for the +//! app's wildcard, at the moment it is issued and at every load: the +//! relay names the authorities, so a certificate from one it made up +//! (a self-signed one valid for centuries) is refused, and one kept +//! on disk that fails is ignored and ordered again. Only a test makes +//! a [`CertTrust`] of its own roots; nothing at run time can. +//! 8. A lifetime over [`MAX_LIFETIME_DAYS`] days is refused, and the +//! renewal is never later than two thirds of the life or +//! [`MAX_RENEW_DAYS`] days into it, whichever is sooner. +//! 9. A certificate is never served at or after its `not_after`, even +//! when a renewal is failing or the next look is hours away. //! SCENARIOS: //! 1. An order with no stored certificate stores one and serves it; a //! second start reads it and orders nothing. @@ -37,19 +49,25 @@ //! 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. +//! 5. A certificate from an authority that is not in the trusted roots, +//! one that lives over the cap, and one past its end are refused or +//! not served (unit tests here, `tests/link.rs`). //! ``` use crate::private; use futures::future::BoxFuture; use relay::proto::Authority; +use rustls::RootCertStore; +use rustls::client::WebPkiServerVerifier; +use rustls::client::danger::ServerCertVerifier; use rustls::pki_types::pem::PemObject; -use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; 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 std::time::{Duration, SystemTime, UNIX_EPOCH}; use zeroize::Zeroizing; /// The relay publishes and clears the proof record of the app's name. @@ -109,6 +127,82 @@ pub fn now() -> i64 { .unwrap_or(0) } +/// The longest a certificate may live (INVARIANT 8): public authorities +/// issue for 90 days or fewer, so a longer one is not from one. +pub const MAX_LIFETIME_DAYS: i64 = 100; + +/// The latest, in days from the start of its life, a renewal is planned +/// (INVARIANT 8). +pub const MAX_RENEW_DAYS: i64 = 60; + +const DAY: i64 = 86_400; + +/// Which certificate authorities this app believes (INVARIANT 7): the +/// public roots the program ships. Not data, not the relay's to change. +#[derive(Clone)] +pub struct CertTrust { + verifier: Arc, +} + +impl std::fmt::Debug for CertTrust { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CertTrust").finish_non_exhaustive() + } +} + +impl CertTrust { + /// The public roots the program ships (Mozilla's, as + /// `webpki-root-certs`). + pub fn public() -> Result { + let mut roots = 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()); + } + Self::from_roots(roots) + } + + /// Trust exactly these roots: for a test's own authority. Nothing in + /// the program calls this; the relay cannot reach it (INVARIANT 7). + pub fn for_tests(roots: RootCertStore) -> Self { + Self::from_roots(roots) + .unwrap_or_else(|why| panic!("a test's roots must make a verifier: {why}")) + } + + fn from_roots(roots: RootCertStore) -> Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let verifier = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider) + .build() + .map_err(|_| "no trusted certificate authorities".to_string())?; + Ok(CertTrust { verifier }) + } + + /// Whether `chain_pem` (leaf first) is a good chain, at time `t`, for + /// the wildcard `identifier` (`*..`). + pub fn check(&self, chain_pem: &str, identifier: &str, t: i64) -> Result<(), String> { + let chain: Vec> = + CertificateDer::pem_slice_iter(chain_pem.as_bytes()) + .collect::>() + .map_err(|_| "the certificate can't be read".to_string())?; + let (leaf, rest) = chain + .split_first() + .ok_or("the authority sent no certificate")?; + // A host the wildcard covers: the chain is checked for a name a + // caller will really use. + let host = identifier.replacen('*', "check", 1); + let name = ServerName::try_from(host) + .map_err(|_| "the certificate's name is not a host name".to_string())?; + let at = UnixTime::since_unix_epoch(Duration::from_secs(u64::try_from(t).unwrap_or(0))); + self.verifier + .verify_server_cert(leaf, rest, &name, &[], at) + .map(|_| ()) + .map_err(|_| { + "the certificate does not come from a public certificate authority this program trusts" + .to_string() + }) + } +} + /// The certificate and its key, as kept (one file, so one atomic write). #[derive(Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -175,13 +269,15 @@ pub fn inspect(der: &[u8]) -> Option<(i64, i64, Vec)> { impl StoredCert { /// A certificate just issued, checked: it must be for `identifier`, - /// valid now and have a key that matches (INVARIANT 2). + /// valid now, chain to a trusted root, live no longer than the cap and + /// have a key that matches (INVARIANTS 2, 7 and 8). pub fn new( name: &str, authority: &str, issued: &Issued, identifier: &str, renew_at: Option, + trust: &CertTrust, ) -> Result { let der = leaf_der(&issued.chain_pem) .ok_or("the authority sent something that is not a certificate")?; @@ -194,9 +290,12 @@ impl StoredCert { if not_after <= t { return Err("the authority sent a certificate that has already ended".into()); } + let cap = renewal_cap(not_before, not_after); + check_life(not_before, not_after)?; + trust.check(&issued.chain_pem, identifier, t)?; 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)); + let renew_at = renew_at.unwrap_or(cap).min(cap); Ok(StoredCert { v: 1, name: name.to_owned(), @@ -205,10 +304,32 @@ impl StoredCert { key_pem: issued.key_pem.to_string(), not_before, not_after, - renew_at: renew_at.min(not_after - (not_after - not_before) / 10), + renew_at, }) } + /// A stored certificate, checked again as it is read (INVARIANTS 2, 7, + /// 8): the same tests as when it was issued, against the file's own + /// words and the clock now. A renewal time set too late is brought in. + fn vetted(mut self, name: &str, identifier: &str, trust: &CertTrust) -> Option { + if self.v != 1 || self.name != name || self.certified().is_none() { + return None; + } + let der = self.der()?; + let (not_before, not_after, names) = inspect(&der)?; + if !names.iter().any(|n| n.eq_ignore_ascii_case(identifier)) { + return None; + } + check_life(not_before, not_after).ok()?; + trust.check(&self.chain_pem, identifier, now()).ok()?; + // What is in the certificate is what counts, not what the file says + // about it. + self.not_before = not_before; + self.not_after = not_after; + self.renew_at = self.renew_at.min(renewal_cap(not_before, not_after)); + Some(self) + } + /// The key and chain, ready for rustls. pub fn certified(&self) -> Option> { certified(&self.chain_pem, &self.key_pem) @@ -230,6 +351,21 @@ pub fn default_renewal(not_before: i64, not_after: i64) -> i64 { not_before + (not_after - not_before) * 2 / 3 } +/// The latest a renewal may be planned (INVARIANT 8): two thirds of the +/// life or [`MAX_RENEW_DAYS`] days in, whichever is sooner. +pub fn renewal_cap(not_before: i64, not_after: i64) -> i64 { + default_renewal(not_before, not_after).min(not_before.saturating_add(MAX_RENEW_DAYS * DAY)) +} + +fn check_life(not_before: i64, not_after: i64) -> Result<(), String> { + if not_after.saturating_sub(not_before) > MAX_LIFETIME_DAYS * DAY { + return Err(format!( + "the certificate would live longer than {MAX_LIFETIME_DAYS} days, which no public authority issues" + )); + } + Ok(()) +} + fn certified(chain_pem: &str, key_pem: &str) -> Option> { let chain: Vec> = CertificateDer::pem_slice_iter(chain_pem.as_bytes()) .collect::>() @@ -259,11 +395,12 @@ impl CertStore { } /// 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 { + /// (INVARIANTS 2, 7, 8): one that fails any check is as if there were + /// none, and is ordered again. A file that does not read is the same. + pub fn load(&self, name: &str, identifier: &str, trust: &CertTrust) -> 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) + c.vetted(name, identifier, trust) } /// Keep a certificate, privately and atomically. @@ -279,10 +416,11 @@ impl CertStore { } /// What rustls serves: the current certificate, to the app's own host -/// name and no other (INVARIANT 6). +/// name and no other (INVARIANT 6), and never at or after its end +/// (INVARIANT 9). pub struct Resolver { host: RwLock, - key: RwLock>>, + key: RwLock, i64)>>, } impl std::fmt::Debug for Resolver { @@ -305,26 +443,34 @@ impl Resolver { *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; + /// The certificate to serve, with when it ends (unix seconds), or none. + pub fn set_cert(&self, cert: Option<(Arc, i64)>) { + *self.key.write().unwrap_or_else(|e| e.into_inner()) = cert; } /// Whether a certificate is being served. pub fn has_key(&self) -> bool { self.key.read().unwrap_or_else(|e| e.into_inner()).is_some() } + + /// The certificate for a hello naming `sni` at time `t`: only for the + /// app's own host, and only while it lasts. + pub fn pick(&self, sni: &str, t: i64) -> Option> { + let host = self.host.read().unwrap_or_else(|e| e.into_inner()); + if host.is_empty() || !sni.eq_ignore_ascii_case(&host) { + return None; + } + drop(host); + let held = self.key.read().unwrap_or_else(|e| e.into_inner()); + held.as_ref() + .filter(|(_, not_after)| t < *not_after) + .map(|(key, _)| key.clone()) + } } 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() + self.pick(hello.server_name()?, now()) } } @@ -347,10 +493,160 @@ pub fn server_config(resolver: Arc) -> Arc { #[cfg(test)] mod tests { use super::*; + use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair}; + + const IDENT: &str = "*.a-b-c-d.wanderbooks.link"; + + fn ca() -> CertifiedIssuer<'static, KeyPair> { + let mut params = CertificateParams::new(Vec::::new()).unwrap(); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params.key_usages = vec![ + rcgen::KeyUsagePurpose::KeyCertSign, + rcgen::KeyUsagePurpose::CrlSign, + ]; + CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap() + } + + /// A certificate for `IDENT` from `ca`, living `days` days from an hour + /// ago. + fn issue(ca: &CertifiedIssuer<'static, KeyPair>, days: i64) -> Issued { + let mut params = CertificateParams::new(vec![IDENT.to_string()]).unwrap(); + let t = time::OffsetDateTime::now_utc(); + params.not_before = t - time::Duration::hours(1); + params.not_after = t + time::Duration::days(days); + let key = KeyPair::generate().unwrap(); + let cert = params.signed_by(&key, ca).unwrap(); + Issued { + chain_pem: format!("{}{}", cert.pem(), ca.pem()), + key_pem: Zeroizing::new(key.serialize_pem()), + } + } + + fn trusting(ca: &CertifiedIssuer<'static, KeyPair>) -> CertTrust { + let mut roots = RootCertStore::empty(); + roots.add(ca.der().clone()).unwrap(); + CertTrust::for_tests(roots) + } #[test] fn two_thirds_of_a_life() { assert_eq!(default_renewal(0, 90), 60); assert_eq!(default_renewal(100, 106), 104); } + + #[test] + fn a_certificate_from_an_authority_the_program_trusts_is_kept() { + let ca = ca(); + let c = StoredCert::new("a-b-c-d", "x", &issue(&ca, 60), IDENT, None, &trusting(&ca)) + .expect("a good certificate"); + assert!(c.valid_at(now())); + } + + #[test] + fn a_certificate_from_an_authority_the_relay_made_up_is_refused() { + // The authority the relay listed signs for any name, for 8000 days + // (and, separately, for 60): neither chains to a public root. + let fake = ca(); + let public = CertTrust::public().unwrap(); + let why = + StoredCert::new("a-b-c-d", "x", &issue(&fake, 60), IDENT, None, &public).unwrap_err(); + assert!(why.contains("public certificate authority"), "{why}"); + // Valid until the year 9999, as a hostile relay's would be. + assert!( + StoredCert::new("a-b-c-d", "x", &issue(&fake, 8000), IDENT, None, &public).is_err() + ); + // A self-signed leaf with nothing above it is no better. + let key = KeyPair::generate().unwrap(); + let mut params = CertificateParams::new(vec![IDENT.to_string()]).unwrap(); + params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(60); + let own = params.self_signed(&key).unwrap(); + let issued = Issued { + chain_pem: own.pem(), + key_pem: Zeroizing::new(key.serialize_pem()), + }; + assert!(StoredCert::new("a-b-c-d", "x", &issued, IDENT, None, &public).is_err()); + } + + #[test] + fn a_lifetime_over_the_cap_is_refused() { + let ca = ca(); + let trust = trusting(&ca); + let why = + StoredCert::new("a-b-c-d", "x", &issue(&ca, 101), IDENT, None, &trust).unwrap_err(); + assert!(why.contains("100 days"), "{why}"); + assert!(StoredCert::new("a-b-c-d", "x", &issue(&ca, 99), IDENT, None, &trust).is_ok()); + } + + #[test] + fn renewal_is_never_later_than_two_thirds_or_sixty_days() { + let ca = ca(); + let trust = trusting(&ca); + // 99 days: two thirds is 66 days in, so sixty days is sooner. + let c = StoredCert::new( + "a-b-c-d", + "x", + &issue(&ca, 99), + IDENT, + Some(i64::MAX), + &trust, + ) + .unwrap(); + assert_eq!(c.renew_at, c.not_before + 60 * DAY); + // 30 days: two thirds (20 days) is sooner. + let c = StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, None, &trust).unwrap(); + assert_eq!(c.renew_at, default_renewal(c.not_before, c.not_after)); + // An earlier time the authority suggests is kept. + let early = now() + 100; + let c = + StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, Some(early), &trust).unwrap(); + assert_eq!(c.renew_at, early); + } + + #[test] + fn a_stored_certificate_that_fails_is_ignored_when_read() { + let ca = ca(); + let trust = trusting(&ca); + let dir = tempfile::tempdir().unwrap(); + let store = CertStore::new(dir.path()); + let good = StoredCert::new("a-b-c-d", "x", &issue(&ca, 60), IDENT, None, &trust).unwrap(); + store.save(&good).unwrap(); + assert!(store.load("a-b-c-d", IDENT, &trust).is_some()); + // The same file, read by a program that does not trust that + // authority (the relay's made-up one): ignored. + let public = CertTrust::public().unwrap(); + assert!(store.load("a-b-c-d", IDENT, &public).is_none()); + // Another name: ignored. + assert!(store.load("e-f-g-h", IDENT, &trust).is_none()); + // A file whose renewal time was set far out is brought in. + let mut late = good.clone(); + late.renew_at = i64::MAX / 2; + store.save(&late).unwrap(); + let read = store.load("a-b-c-d", IDENT, &trust).unwrap(); + assert!(read.renew_at <= read.not_before + 60 * DAY); + // A certificate that lives over the cap, put on disk by hand. + let long = issue(&ca, 400); + let mut f = good; + f.chain_pem = long.chain_pem; + f.key_pem = long.key_pem.to_string(); + store.save(&f).unwrap(); + assert!(store.load("a-b-c-d", IDENT, &trust).is_none()); + } + + #[test] + fn the_resolver_serves_only_its_host_and_only_until_the_certificate_ends() { + let ca = ca(); + let c = + StoredCert::new("a-b-c-d", "x", &issue(&ca, 30), IDENT, None, &trusting(&ca)).unwrap(); + let r = Resolver::new(); + r.set_host("Secret.a-b-c-d.wanderbooks.link"); + r.set_cert(c.certified().map(|k| (k, c.not_after))); + let host = "secret.a-b-c-d.wanderbooks.link"; + assert!(r.pick(host, c.not_after - 1).is_some()); + assert!(r.pick(host, c.not_after).is_none(), "at its end"); + assert!( + r.pick(host, c.not_after + 3600 * 6).is_none(), + "hours after" + ); + assert!(r.pick("other.a-b-c-d.wanderbooks.link", 0).is_none()); + } } diff --git a/crates/ledger-link/src/lib.rs b/crates/ledger-link/src/lib.rs index 6d74c4bf..fffa8695 100644 --- a/crates/ledger-link/src/lib.rs +++ b/crates/ledger-link/src/lib.rs @@ -39,9 +39,10 @@ pub mod line; pub mod link; pub mod private; pub mod status; +pub mod text; pub use acme::AcmeIssuer; -pub use certs::{DnsProof, Issued, Issuer, OrderRequest}; +pub use certs::{CertTrust, DnsProof, Issued, Issuer, OrderRequest}; pub use line::{Dial, Timing}; pub use link::{DoorTarget, Link, LinkConfig, LinkError}; pub use status::{LinkStatus, Step, Trouble}; diff --git a/crates/ledger-link/src/line.rs b/crates/ledger-link/src/line.rs index 2e420dbe..40ab10b1 100644 --- a/crates/ledger-link/src/line.rs +++ b/crates/ledger-link/src/line.rs @@ -14,8 +14,13 @@ //! 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. +//! starts again. A line that held for `line_stable` (60 s) resets the +//! backoff and is redialled after a wait spread over `redial_spread` +//! (0 to 30 s, jittered), so a relay that restarts is not met by +//! every app in the same second; a line that ended sooner (a relay +//! that accepts and then drops) does not reset it and waits as a +//! failed dial does. 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. @@ -28,7 +33,9 @@ //! (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. +//! never exceeds the maximum with jitter, and resets; a line that +//! ended young does not reset it, one that held does, and its +//! redial is spread over `redial_spread`. //! 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 @@ -82,6 +89,12 @@ pub struct Timing { /// A wall-clock step this much longer than the monotonic one is a /// sleep. pub wake_gap: Duration, + /// A line must have held this long for the backoff to start again from + /// its minimum. + pub line_stable: Duration, + /// A line that held and then ended is redialled after a wait spread + /// over this long. + pub redial_spread: Duration, } impl Default for Timing { @@ -99,6 +112,8 @@ impl Default for Timing { order_timeout: Duration::from_secs(300), ari_recheck: Duration::from_secs(6 * 3600), wake_gap: Duration::from_secs(30), + line_stable: Duration::from_secs(60), + redial_spread: Duration::from_secs(30), } } } @@ -159,6 +174,52 @@ impl Backoff { } } +/// When to dial again, after a dial that failed or a line that ended +/// (INVARIANT 1). +#[derive(Debug)] +pub struct Redial { + backoff: Backoff, + stable: Duration, + spread: Duration, +} + +impl Redial { + /// The waits `t` sets. + pub fn new(t: &Timing) -> Self { + Redial { + backoff: Backoff::new(t.backoff_min, t.backoff_max), + stable: t.line_stable, + spread: t.redial_spread, + } + } + + /// A dial failed: the next wait. + pub fn failed(&mut self) -> Duration { + self.backoff.wait() + } + + /// A line that was up for `held` has ended: the wait before the next + /// dial. Only a line that held `line_stable` starts the backoff over. + pub fn ended(&mut self, held: Duration) -> Duration { + if held >= self.stable { + self.backoff.reset(); + jitter(self.spread) + } else { + self.backoff.wait() + } + } + + /// The network changed: start over. + pub fn reset(&mut self) { + self.backoff.reset(); + } + + /// The ceiling of the next failed wait (tests). + pub fn ceiling(&self) -> Duration { + self.backoff.ceiling() + } +} + /// Notices a computer that slept (INVARIANT 3). pub struct WakeDetector { mono: Instant, @@ -303,6 +364,45 @@ mod tests { assert!(spread.len() > 5); } + #[test] + fn a_line_that_ends_young_keeps_the_backoff_and_one_that_held_is_spread() { + let t = Timing::default(); + let mut r = Redial::new(&t); + // A relay that accepts and then drops, again and again: the waits + // grow to the ceiling and stay there, never the old 1 to 2 s. + let mut last = Duration::ZERO; + for _ in 0..12 { + let c = r.ceiling(); + let w = r.ended(Duration::from_secs(2)); + assert!( + w >= t.backoff_min && w <= c.max(t.backoff_min), + "{w:?} {c:?}" + ); + last = last.max(c); + } + assert_eq!(last, t.backoff_max); + assert_eq!(r.ceiling(), t.backoff_max); + // A line that held 60 s resets it, and the redial is spread over 0 + // to 30 s: many apps do not come back in the same second. + let waits: Vec = (0..200) + .map(|_| { + let mut r = Redial::new(&t); + r.ended(Duration::from_secs(61)) + }) + .collect(); + assert!(waits.iter().all(|w| *w <= t.redial_spread)); + assert!(waits.iter().any(|w| *w > Duration::from_secs(20))); + assert!(waits.iter().any(|w| *w < Duration::from_secs(10))); + r.ended(Duration::from_secs(61)); + assert_eq!(r.ceiling(), t.backoff_min, "held: the backoff starts over"); + // A line that held 59 s does not. + let mut r = Redial::new(&t); + r.failed(); + r.failed(); + r.ended(Duration::from_secs(59)); + assert!(r.ceiling() > t.backoff_min * 4); + } + #[test] fn a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep() { let mut w = WakeDetector::new(Duration::from_secs(30)); diff --git a/crates/ledger-link/src/link.rs b/crates/ledger-link/src/link.rs index f775f061..a5034cfe 100644 --- a/crates/ledger-link/src/link.rs +++ b/crates/ledger-link/src/link.rs @@ -45,14 +45,15 @@ //! ``` use crate::certs::{ - CertStore, DnsProof, Issuer, OrderRequest, Resolver, StoredCert, now, server_config, + CertStore, CertTrust, 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, + Backoff, Dial, Failure, MAX_STREAMS, Redial, Timing, WakeDetector, failure_of, jitter, trouble_of_refusal, }; use crate::status::{LinkStatus, Trouble}; +use crate::text::{clean, detail}; use futures::future::BoxFuture; use relay::client::{self, Incoming, Line, LineHandle, LineOptions}; use relay::proto::{Refusal, Request}; @@ -87,6 +88,8 @@ pub struct LinkConfig { pub relay_tls: Arc, /// The certificate authority client. pub issuer: Arc, + /// Which certificate authorities' certificates are believed. + pub trust: CertTrust, /// Every wait. pub timing: Timing, } @@ -156,6 +159,9 @@ pub(crate) struct Inner { run: tokio::sync::Mutex>, nudge: Notify, served: AtomicU64, + /// The address kept for this installation, read once and held (the + /// window asks every frame): `None` until read. + kept: Mutex>>, } struct LineProof(LineHandle); @@ -165,7 +171,12 @@ impl DnsProof for LineProof { 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())), + // The relay's words are a stranger's: short and plain + // before they go anywhere (text.rs). + Ok(r) => Err(clean( + &r.error.unwrap_or_else(|| "refused".into()), + crate::text::DETAIL_CHARS, + )), Err(_) => Err("the line to the relay failed".into()), } }) @@ -192,6 +203,11 @@ impl Inner { self.status.send_modify(f); } + /// The address kept, as it now stands. + fn keep(&self, address: Option) { + *self.kept.lock().unwrap_or_else(|e| e.into_inner()) = Some(address); + } + fn identity_do(&self, f: impl FnOnce(&mut Identity) -> T) -> Option { self.identity .lock() @@ -228,6 +244,7 @@ impl Inner { let host = id.host(&self.cfg.domain); let address = id.address(&self.cfg.domain); let claimed = id.claimed(); + self.keep(Some(address.clone())); *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = Some(id); self.resolver.set_host(&host); self.set(|s| { @@ -265,7 +282,7 @@ impl Inner { } } self.line.send_replace(None); - self.resolver.set_key(None); + self.resolver.set_cert(None); let served = self.served.load(Ordering::Relaxed); self.set(|s| { *s = LinkStatus { @@ -292,6 +309,7 @@ impl Inner { let made = tokio::task::spawn_blocking(move || -> Result { if lost { let id = Identity::reset(&dir)?; + // The name is being abandoned: nothing for it is kept. CertStore::new(&dir).forget(); Ok(id.address(&domain)) } else { @@ -302,6 +320,7 @@ impl Inner { }) .await .map_err(|_| LinkError::Gone)??; + self.keep(Some(made.clone())); if was_on { self.begin(&mut run).await?; } else { @@ -378,7 +397,7 @@ impl Inner { 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 redial = Redial::new(&t); let mut name_tries = 0u32; loop { if stop.is_cancelled() { @@ -390,35 +409,49 @@ impl Inner { }; match dialled { Ok(Ok(line)) => { - backoff.reset(); name_tries = 0; self.line_is_up(); + let up = tokio::time::Instant::now(); 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) => {} + // network went) is dialled again after a wait spread + // over `redial_spread`, so a relay coming back is not + // hit by every app in the same second; one that held + // less than `line_stable` waits as a failed dial does, + // so a relay that accepts and drops is not redialled + // at a steady rate for ever (INVARIANT 1). A sleep or a + // network change dials at once: that is one machine + // that moved, not a crowd. + let wait = match ended { + Ended::Woke | Ended::Nudged => { + redial.reset(); + Duration::ZERO } + _ => redial.ended(up.elapsed()), + }; + 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. + // Somebody else has this name: another, at once. Nothing + // else has used the name yet: the certificate waits for + // the line, and the door is not started until the name + // is claimed (`Link::wait_settled`). 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)) { + if let Some((host, address)) = self.identity_do(|i| { + (i.host(&self.cfg.domain), i.address(&self.cfg.domain)) + }) { self.resolver.set_host(&host); - let address = format!("https://{host}"); + self.keep(Some(address.clone())); self.set(|s| s.address = Some(address)); } continue; @@ -432,7 +465,7 @@ impl Inner { } Err(trouble) => self.set(|s| s.trouble = Some(trouble)), } - let mut wait = backoff.wait(); + let mut wait = redial.failed(); // A relay that said "wait" is not asked again at once. if matches!( self.status.borrow().trouble, @@ -443,7 +476,7 @@ impl Inner { tokio::select! { () = stop.cancelled() => return, () = tokio::time::sleep(wait) => {} - () = self.nudge.notified() => backoff.reset(), + () = self.nudge.notified() => redial.reset(), } } } @@ -495,6 +528,7 @@ impl Inner { () = self.nudge.notified() => break Ended::Nudged, _ = &mut failed => break Ended::PingFailed, _ = tick.tick() => { + self.expire_if_due(); if wake.woke() { break Ended::Woke; } @@ -557,19 +591,33 @@ impl Inner { // ---- 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.resolver + .set_cert(c.certified().map(|k| (k, c.not_after))); + let end = c.not_after; self.set(|s| { s.cert_expires = Some(end); }); } fn uninstall(&self) { - self.resolver.set_key(None); + self.resolver.set_cert(None); self.set(|s| s.cert_expires = None); } + /// A certificate that has ended is not in place, whatever is waiting + /// to renew it (INVARIANT 9 of certs.rs): the resolver already refuses + /// it; this makes the state say so. + fn expire_if_due(&self) { + let ended = self + .status + .borrow() + .cert_expires + .is_some_and(|end| now() >= end); + if ended { + self.uninstall(); + } + } + async fn wait_for_line(&self, stop: &CancellationToken) -> Option { let mut rx = self.line.subscribe(); loop { @@ -583,22 +631,37 @@ impl Inner { } } + /// `wait`, cut short at `ends` (unix seconds) if that comes first: a + /// sleep never runs past the end of the certificate in use. + fn until(wait: Duration, ends: Option) -> Duration { + match ends { + Some(end) => wait.min(Duration::from_secs( + u64::try_from(end.saturating_sub(now())).unwrap_or(0), + )), + None => wait, + } + } + 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); + // Nothing about a certificate is done until the line is up: the + // relay has then accepted the name, so the name is settled and the + // certificate is for it, never for one the first claim gave up + // (a "taken" answer picks another). + let Some(_line) = self.wait_for_line(&stop).await else { + return; + }; loop { if stop.is_cancelled() { return; } - let stored = store.load(&name); + let Some(name) = self.identity_do(|i| i.name().to_string()) else { + return; + }; + let identifier = format!("*.{name}.{}", self.cfg.domain); + let stored = store.load(&name, &identifier, &self.cfg.trust); let tnow = now(); match &stored { Some(c) if c.valid_at(tnow) => self.install(c), @@ -611,7 +674,10 @@ impl Inner { // 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); + let wait = Self::until( + Duration::from_secs(secs).min(t.ari_recheck), + Some(c.not_after), + ); tokio::select! { () = stop.cancelled() => return, () = tokio::time::sleep(wait) => {} @@ -651,14 +717,17 @@ impl Inner { .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." + "The certificate could not be renewed yet. It keeps trying; the one in use still works. {why}" ), None => format!( - "Wanderbooks could not get a certificate yet: {why}. It keeps trying." + "Wanderbooks could not get a certificate yet. It keeps trying. {why}" ), }; self.set(|s| s.cert_trouble = Some(words)); - let wait = backoff.wait(); + // Never asleep past the end of the certificate in use: + // at its end it stops being served and the state says + // so. + let wait = Self::until(backoff.wait(), ends); tokio::select! { () = stop.cancelled() => return, () = tokio::time::sleep(wait) => {} @@ -702,21 +771,28 @@ impl Inner { .line .borrow() .clone() - .ok_or("the line to the relay is down")?; + .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")?; + .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()); + 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()); + 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 { + // What the relay and the authority say is a stranger's: the + // words here are the app's, and theirs is a short quoted detail + // (text.rs). + let which = match detail(&a.id) { + d if d.is_empty() => "an authority".to_string(), + d => format!("authority {d}"), + }; let replaces = previous .filter(|p| p.authority == a.id && p.valid_at(now())) .and_then(StoredCert::der); @@ -735,18 +811,53 @@ impl Inner { 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) { + match StoredCert::new( + name, + &a.id, + &issued, + identifier, + renew_at, + &self.cfg.trust, + ) { Ok(c) => return Ok(c), - Err(why) => problems.push(format!("{}: {why}", a.id)), + Err(why) => problems.push(format!("{which}: {why}")), } } - Err(why) => problems.push(format!("{}: {why}", a.id)), + // An issuer's own words are kept short whatever they are. + Err(why) => problems.push(format!("{which}: {}", clean(&why, PROBLEM_CHARS))), } } - Err(problems.join("; ")) + Err(problems_in_words(&problems)) } } +/// The most characters of one authority's failure kept in the window's +/// words. +const PROBLEM_CHARS: usize = 300; + +/// The most authorities' failures spelled out; the rest are counted. +const PROBLEMS_SHOWN: usize = 3; + +/// The failures of the authorities tried, as one bounded text. +fn problems_in_words(problems: &[String]) -> String { + let mut out: Vec = problems + .iter() + .take(PROBLEMS_SHOWN) + .map(|p| { + let p = clean(p, PROBLEM_CHARS); + if p.ends_with(['.', '?', '!']) { + p + } else { + format!("{p}.") + } + }) + .collect(); + if problems.len() > PROBLEMS_SHOWN { + out.push(format!("And {} more.", problems.len() - PROBLEMS_SHOWN)); + } + out.join(" ") +} + /// Why a held line ended. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Ended { @@ -781,6 +892,7 @@ impl Link { run: tokio::sync::Mutex::new(None), nudge: Notify::new(), served: AtomicU64::new(0), + kept: Mutex::new(None), }) } @@ -833,12 +945,51 @@ impl Link { /// 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. + /// time it was turned on. Read from the folder once and held: the + /// window asks every frame, and the key beside it is not read again + /// for that (it is read where it signs, in `dial`). pub fn kept_address(&self) -> Option { - Identity::load(&self.inner.cfg.dir) - .ok() - .flatten() - .map(|i| i.address(&self.inner.cfg.domain)) + let mut kept = self.inner.kept.lock().unwrap_or_else(|e| e.into_inner()); + kept.get_or_insert_with(|| { + Identity::load(&self.inner.cfg.dir) + .ok() + .flatten() + .map(|i| i.address(&self.inner.cfg.domain)) + }) + .clone() + } + + /// Wait until the relay has accepted this installation's name, so the + /// address is settled, or say why not: the door is started as this + /// address, and a first claim that finds the name taken picks another + /// (INVARIANT 5 of web.rs). + pub fn wait_settled(&self, within: Duration) -> Result<(), String> { + let mut rx = self.inner.status.subscribe(); + self.block(async move { + // Copied out at once: the borrow of the watch is not held. + let seen = match timeout( + within, + rx.wait_for(|s| s.claimed || s.trouble.as_ref().is_some_and(|t| !t.mends_itself())), + ) + .await + { + Ok(Ok(r)) => Some(r.clone()), + Ok(Err(_)) => return Err("The link is shutting down.".to_string()), + Err(_) => None, + }; + let s = match seen { + Some(s) => s, + None => rx.borrow().clone(), + }; + if s.claimed { + Ok(()) + } else { + Err(s.problem().unwrap_or_else(|| { + "Wanderbooks has not been given its address by the relay yet.".into() + })) + } + }) + .unwrap_or_else(|| Err("The link is shutting down.".into())) } /// Where the books server's remote door listens, or none. @@ -891,3 +1042,39 @@ impl Drop for Link { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_wait_never_runs_past_the_end_of_the_certificate_in_use() { + let hours = Duration::from_secs(6 * 3600); + let t = now(); + // Nothing in use: the wait is as long as asked. + assert_eq!(Inner::until(hours, None), hours); + // One that ends in a minute: the wait ends with it. + let w = Inner::until(hours, Some(t + 60)); + assert!( + w <= Duration::from_secs(60) && w >= Duration::from_secs(58), + "{w:?}" + ); + // One that has ended already: no wait at all. + assert_eq!(Inner::until(hours, Some(t - 5)), Duration::ZERO); + // A short wait stays short. + assert_eq!( + Inner::until(Duration::from_secs(5), Some(t + 3600)), + Duration::from_secs(5) + ); + } + + #[test] + fn authorities_that_all_fail_are_told_in_bounded_words() { + let many: Vec = (0..20) + .map(|i| format!("authority {i}: {}", "x".repeat(2000))) + .collect(); + let said = problems_in_words(&many); + assert!(said.chars().count() < 1000, "{}", said.chars().count()); + assert!(said.ends_with("And 17 more."), "{said}"); + } +} diff --git a/crates/ledger-link/src/private.rs b/crates/ledger-link/src/private.rs index 3e52c664..64953286 100644 --- a/crates/ledger-link/src/private.rs +++ b/crates/ledger-link/src/private.rs @@ -14,10 +14,14 @@ //! `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. +//! one, and the folder is synced after the rename (Unix; Windows has +//! no such call and the rename is made durable by the file system): +//! a reader sees the old file or the new one, never a part, and a +//! crash right after cannot lose the rename. //! SCENARIOS: //! 1. A file written here reads back, has mode 0600, and its folder -//! 0700, on Unix. +//! 0700, on Unix; on Windows the file and its folder are owner-only +//! (`ledger_store::winsec::is_private`). //! ``` use std::io::{self, Write}; @@ -54,7 +58,8 @@ pub fn write(path: &Path, bytes: &[u8]) -> io::Result<()> { file.write_all(bytes)?; file.sync_all()?; drop(file); - std::fs::rename(&tmp, path) + std::fs::rename(&tmp, path)?; + sync_folder(path) })(); if result.is_err() { let _ = std::fs::remove_file(&tmp); @@ -62,6 +67,23 @@ pub fn write(path: &Path, bytes: &[u8]) -> io::Result<()> { result } +/// Make the rename durable: the folder that holds the file is synced +/// (INVARIANT 2). Windows cannot open a folder to sync it; there the +/// rename is the file system's own. +fn sync_folder(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + let dir = match path.parent() { + Some(p) if !p.as_os_str().is_empty() => p, + _ => Path::new("."), + }; + std::fs::File::open(dir)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -85,4 +107,21 @@ mod tests { // No temporary file is left behind. assert_eq!(std::fs::read_dir(&sub).unwrap().count(), 1); } + + /// Windows: the file and its folder are owner-only, as the token files + /// are (the helper is `ledger_store::winsec`). Compiled for Windows + /// only; it runs on the Windows jobs of the full test run. + #[cfg(windows)] + #[test] + fn a_private_file_and_its_folder_are_owner_only_on_windows() { + 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"); + assert!(ledger_store::winsec::is_private(&sub).unwrap()); + assert!(ledger_store::winsec::is_private(&f).unwrap()); + } } diff --git a/crates/ledger-link/src/text.rs b/crates/ledger-link/src/text.rs new file mode 100644 index 00000000..15e67173 --- /dev/null +++ b/crates/ledger-link/src/text.rs @@ -0,0 +1,128 @@ +//! Words that come from outside, made safe to show. +//! +//! ```text +//! GOAL: the relay and a certificate authority are strangers: anything +//! they send that reaches the window is short, plain and visibly +//! quoted, so it can neither fill the window, nor hide behind +//! invisible characters, nor pass for the app's own words. +//! SOURCE: WB-link-5 (the states in words); plan p15-app-and-relay.md 5 +//! (the relay and the authorities are not trusted). +//! INVARIANTS: +//! 1. The window's words are the app's own, chosen from the kind of +//! failure; outside text is only ever a quoted detail at the end. +//! 2. A detail has no control character and no invisible one (the +//! zero-width, direction-changing and tag characters, the line and +//! paragraph separators), runs of white space are one space, and it +//! is at most [`DETAIL_CHARS`] characters, cut with an ellipsis. +//! 3. Cleaning twice is the same as cleaning once. +//! SCENARIOS: +//! 1. A long text with a newline, a bell and a right-to-left override +//! comes out short, on one line and with none of them. +//! 2. Text that is already clean and short comes out as it went in. +//! ``` + +/// The most characters of outside text shown (INVARIANT 2). +pub const DETAIL_CHARS: usize = 120; + +/// Whether a character is one that must never be shown: a control +/// character, or one that draws nothing or changes how the text around it +/// reads. +fn hidden(c: char) -> bool { + c.is_control() + || matches!( + c, + '\u{00AD}' + | '\u{034F}' + | '\u{061C}' + | '\u{115F}' + | '\u{1160}' + | '\u{17B4}' + | '\u{17B5}' + | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200F}' + | '\u{2028}'..='\u{202E}' + | '\u{2060}'..='\u{206F}' + | '\u{3164}' + | '\u{FE00}'..='\u{FE0F}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF0}'..='\u{FFFB}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E0FFF}' + ) +} + +/// `text` with the hidden characters gone, white space made single spaces, +/// and at most `max` characters (INVARIANT 2). +pub fn clean(text: &str, max: usize) -> String { + let mut out = String::new(); + let mut count = 0usize; + let mut space = false; + for c in text.chars() { + // A line break or tab is white space, not a character to drop: the + // words either side of it stay apart. + if c.is_whitespace() || matches!(c, '\n' | '\r' | '\t') { + space = !out.is_empty(); + continue; + } + if hidden(c) { + continue; + } + if count >= max { + out.push('\u{2026}'); + return out; + } + if space { + out.push(' '); + count += 1; + space = false; + } + out.push(c); + count += 1; + } + out +} + +/// Outside text as a short quoted detail (INVARIANT 1): empty when there is +/// nothing left to show. +pub fn detail(text: &str) -> String { + let c = clean(text, DETAIL_CHARS); + if c.is_empty() { + String::new() + } else { + format!("\u{201c}{c}\u{201d}") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn long_text_with_tricks_comes_out_short_and_plain() { + let nasty = format!( + "bad\u{7}\nnews\u{202e}gnp.exe\u{200b} {}", + "word ".repeat(2000) + ); + let d = detail(&nasty); + assert!(d.chars().count() <= DETAIL_CHARS + 3, "{}", d.len()); + assert!(d.starts_with("\u{201c}bad news"), "{d}"); + assert!(d.ends_with("\u{2026}\u{201d}"), "{d}"); + assert!( + !d.chars() + .any(|c| hidden(c) || (c.is_whitespace() && c != ' ')) + ); + assert_eq!(clean(&clean(&nasty, 50), 50), clean(&nasty, 50)); + } + + #[test] + fn short_clean_text_is_unchanged_and_nothing_is_nothing() { + assert_eq!( + detail("too many requests"), + "\u{201c}too many requests\u{201d}" + ); + assert_eq!(detail("\u{200b}\u{202e} \n"), ""); + assert_eq!(clean(" a b ", 10), "a b"); + } +} diff --git a/crates/ledger-link/tests/acme.rs b/crates/ledger-link/tests/acme.rs index 10693695..66369e5f 100644 --- a/crates/ledger-link/tests/acme.rs +++ b/crates/ledger-link/tests/acme.rs @@ -34,6 +34,8 @@ struct Server { orders: Vec, ari_gets: u32, refuse_orders: bool, + /// What a refusal says in its detail (else a short one). + detail: Option, certs: HashMap, } @@ -81,6 +83,12 @@ fn json(status: u16, extra: Vec<(&'static str, String)>, v: serde_json::Value) - } impl FakeAcme { + fn roots(&self) -> rustls::RootCertStore { + let mut roots = rustls::RootCertStore::empty(); + roots.add(self.ca.der().clone()).unwrap(); + roots + } + async fn handle(&self, method: &str, path: &str, body: &[u8]) -> Reply { let nonce = { let mut s = self.state.lock().unwrap(); @@ -124,7 +132,7 @@ impl FakeAcme { return with_nonce(json( 429, vec![], - serde_json::json!({"type":"urn:ietf:params:acme:error:rateLimited","detail":"too many certificates already issued"}), + serde_json::json!({"type":"urn:ietf:params:acme:error:rateLimited","detail":s.detail.clone().unwrap_or_else(|| "too many certificates already issued".into())}), )); } let thumb = s.accounts[protected["kid"].as_str().unwrap()].clone(); @@ -348,9 +356,11 @@ async fn rig(window: (i64, i64)) -> Rig { }); let dir = tempfile::tempdir().unwrap(); let a2 = acme.clone(); - let issuer = AcmeIssuer::new(dir.path()).with_http(Arc::new(move || { - Some(Box::new(Http(a2.clone())) as Box) - })); + let issuer = AcmeIssuer::new(dir.path()) + .with_directory_hosts_for_tests(&["acme.test"]) + .with_http(Arc::new(move || { + Some(Box::new(Http(a2.clone())) as Box) + })); let (key, _) = relay::proto::AppKey::generate(); let name = n("ledger-accrual-tally-mint"); let line = env.connect(name, &key, true).await.unwrap(); @@ -403,7 +413,15 @@ async fn an_order_goes_through_account_proof_finalize_and_download() { assert!(issued.key_pem.contains("PRIVATE KEY")); // The certificate and key go together (the store checks it). assert!( - certs::StoredCert::new("ledger-accrual-tally-mint", "fake", &issued, &ident, None).is_ok() + certs::StoredCert::new( + "ledger-accrual-tally-mint", + "fake", + &issued, + &ident, + None, + &certs::CertTrust::for_tests(r.acme.roots()) + ) + .is_ok() ); // The account is kept in a private file, with no contact in it. @@ -551,3 +569,126 @@ async fn a_refusal_comes_back_in_the_authoritys_words() { .unwrap(); assert!(err.contains("too many certificates"), "{err}"); } + +fn order_for(r: &Rig, authority: &Authority) -> OrderRequest<'static> { + // The proof is never reached by the tests that use this: they stop at + // the directory. + struct Never; + impl DnsProof for Never { + fn publish<'a>(&'a self, _: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async { Err("not reached".into()) }) + } + fn clear(&self) -> BoxFuture<'_, ()> { + Box::pin(async {}) + } + } + static NEVER: Never = Never; + OrderRequest { + authority: Box::leak(Box::new(authority.clone())), + identifier: format!("*.{}.{DOMAIN}", r.name), + replaces: None, + dns: &NEVER, + } +} + +/// WB-link-4 (INVARIANT 6): the relay's list can name any directory, and +/// the app contacts only a host compiled into it: no request is made for +/// any other, however it is spelled. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_directory_on_a_host_the_app_does_not_know_is_refused_before_any_request() { + let r = rig((60, 120)).await; + let reached = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (a2, seen) = (r.acme.clone(), reached.clone()); + // The default list: no host of a test in it. + let issuer = AcmeIssuer::new(r.dir.path()).with_http(Arc::new(move || { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Some(Box::new(Http(a2.clone())) as Box) + })); + for directory in [ + "https://acme.test/dir", + "https://evil.example/directory", + "http://acme-v02.api.letsencrypt.org/directory", + "https://acme-v02.api.letsencrypt.org@evil.example/directory", + "https://acme-v02.api.letsencrypt.org:8443/directory", + "https://acme-v02.api.letsencrypt.org.evil.example/directory", + "https://evil.example\\@acme-v02.api.letsencrypt.org/directory", + "https://127.0.0.1:9/directory", + "not an address", + ] { + let mut a = authority(false); + a.directory = directory.into(); + let err = issuer.issue(order_for(&r, &a)).await.err().unwrap(); + assert!(err.contains("does not use it"), "{directory}: {err}"); + } + assert_eq!( + reached.load(std::sync::atomic::Ordering::SeqCst), + 0, + "not one request was made" + ); + assert!(r.acme.state.lock().unwrap().new_accounts.is_empty()); +} + +/// WB-link-4 (INVARIANT 6): an account kept for a directory that is not on +/// the list is not used; a new one is made at the authority named. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_kept_account_for_an_unlisted_directory_is_not_used() { + let r = rig((60, 120)).await; + let order = |r: &Rig| OrderRequest { + authority: Box::leak(Box::new(authority(false))), + identifier: format!("*.{}.{DOMAIN}", r.name), + replaces: None, + dns: Box::leak(Box::new(Proof(r.line.handle()))), + }; + r.issuer.issue(order(&r)).await.unwrap(); + assert_eq!(r.acme.state.lock().unwrap().new_accounts.len(), 1); + // The same account file, as if the relay had once had it made at another + // host. + let file = r.dir.path().join("acme/fake.json"); + let mut kept: serde_json::Value = + serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(kept["directory"], format!("{BASE}/dir")); + kept["directory"] = "https://evil.example/dir".into(); + std::fs::write(&file, serde_json::to_vec(&kept).unwrap()).unwrap(); + r.issuer.issue(order(&r)).await.unwrap(); + assert_eq!( + r.acme.state.lock().unwrap().new_accounts.len(), + 2, + "the account kept for another host was left alone and a new one made" + ); +} + +/// WB-link-5: what an authority says is a short, plain, quoted detail in +/// the app's own words, never its text as it came. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn what_the_authority_says_is_short_plain_and_quoted() { + let r = rig((60, 120)).await; + r.acme.state.lock().unwrap().refuse_orders = true; + r.acme.state.lock().unwrap().detail = Some(format!( + "pay now\u{7}\n\u{202e}{}", + "give us your password ".repeat(500) + )); + let proof = Proof(r.line.handle()); + let err = r + .issuer + .issue(OrderRequest { + authority: &authority(false), + identifier: format!("*.{}.{DOMAIN}", r.name), + replaces: None, + dns: &proof, + }) + .await + .err() + .unwrap(); + assert!( + err.chars().count() < 260, + "{} characters", + err.chars().count() + ); + assert!( + !err.chars().any(|c| c.is_control() || c == '\u{202e}'), + "{err:?}" + ); + assert!(err.contains("too many certificates"), "{err}"); + assert!(err.contains("It said \u{201c}pay now give us"), "{err}"); + assert!(err.contains("\u{2026}\u{201d}"), "{err}"); +} diff --git a/crates/ledger-link/tests/link.rs b/crates/ledger-link/tests/link.rs index 0d094262..6aa14a31 100644 --- a/crates/ledger-link/tests/link.rs +++ b/crates/ledger-link/tests/link.rs @@ -6,7 +6,7 @@ mod support; -use ledger_link::{Dial, Step, Trouble}; +use ledger_link::{CertTrust, Dial, Step, Trouble}; use std::sync::atomic::Ordering; use std::time::Duration; use support::*; @@ -592,3 +592,196 @@ async fn a_stalled_handshake_is_dropped_and_no_door_means_no_service() { w.link.set_door(Some(w.door.target.clone())); assert!(w.assistant(&host).await.unwrap().ends_with(BODY)); } + +/// WB-link-4 (INVARIANTS 7 and 8 of certs.rs): the relay names the +/// authorities, so a certificate from one it made up is refused (the +/// program trusts the public roots, not the relay's list): nothing is +/// stored or served, the state says so, and a lifetime over the cap is +/// refused too. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_certificate_from_an_authority_the_relay_made_up_is_never_stored_or_served() { + let mut w = world(LIST, |_| {}).await; + // The real program's trust: the public roots. The fake authority is + // not one of them. + w.remake(|cfg| cfg.trust = CertTrust::public().unwrap()); + w.link.turn_on().unwrap(); + let s = until(&w.link, "the refusal is said", |s| { + s.cert_trouble + .as_deref() + .is_some_and(|t| t.contains("public certificate authority")) + }) + .await; + assert_ne!(s.step(), Step::Connected); + assert!(s.cert_expires.is_none()); + assert!(!w.dir.path().join("link/cert.json").exists()); + assert!(w.fake.orders() >= 1); + // Nobody is served a certificate from it. + assert!(w.assistant(&w.host()).await.is_err()); + w.link.turn_off(); + + // A certificate from an authority the program does trust, but that + // lives over 100 days, is refused as well. + w.remake(|_| {}); + w.fake.state.lock().unwrap().lifetime = 101 * 86_400; + w.link.turn_on().unwrap(); + let s = until(&w.link, "the lifetime is refused", |s| { + s.cert_trouble + .as_deref() + .is_some_and(|t| t.contains("100 days")) + }) + .await; + assert!(s.cert_expires.is_none()); + assert!(!w.dir.path().join("link/cert.json").exists()); +} + +/// WB-link-4 (INVARIANT 7): a certificate kept on disk that the program +/// would not trust is discarded and ordered again, and "a new address" +/// does not bring it back. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_stored_certificate_from_a_made_up_authority_is_discarded_and_ordered_again() { + let mut w = world(LIST, |_| {}).await; + w.link.turn_on().unwrap(); + until(&w.link, "connected", |s| s.step() == Step::Connected).await; + assert_eq!(w.fake.orders(), 1); + w.link.turn_off(); + // The file is there, from the authority the test trusts; a program that + // trusts only the public roots reads it as no certificate at all. + assert!(w.dir.path().join("link/cert.json").exists()); + w.remake(|cfg| cfg.trust = CertTrust::public().unwrap()); + w.link.turn_on().unwrap(); + until(&w.link, "it orders again", |s| { + s.cert_trouble + .as_deref() + .is_some_and(|t| t.contains("public certificate authority")) + }) + .await; + assert!(w.fake.orders() >= 2, "the stored one was not believed"); + assert!(w.link.status().cert_expires.is_none()); + // A new address carries on the same way: nothing is loaded from the + // file that fails. + w.link.new_address().unwrap(); + until(&w.link, "the refusal again", |s| { + s.cert_trouble.is_some() && s.line_up + }) + .await; + assert!(w.link.status().cert_expires.is_none()); + assert!(w.assistant(&w.host()).await.is_err()); +} + +/// WB-link-3: a first claim that finds the name taken picks another, and +/// the address, the certificate and the door all follow the one that was +/// claimed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_name_taken_on_the_first_claim_settles_before_the_certificate_and_the_address() { + let w = world(LIST, |_| {}).await; + // The identity is made, and somebody else (another key) takes its name + // first. + let dir = w.dir.path().join("link"); + let id = ledger_link::identity::Identity::load_or_create(&dir).unwrap(); + let taken = id.name(); + let (other, _) = relay::proto::AppKey::generate(); + let _held = w.env.connect(taken, &other, true).await.unwrap(); + + w.link.turn_on().unwrap(); + w.link.wait_settled(Duration::from_secs(20)).unwrap(); + let settled = w.link.status(); + assert!(settled.claimed); + let address = settled.address.clone().unwrap(); + let host = address.trim_start_matches("https://").to_owned(); + let name = host.split_once('.').unwrap().1.to_owned(); + assert_ne!(name, format!("{taken}.{DOMAIN}"), "another name was picked"); + + until(&w.link, "connected", |s| s.step() == Step::Connected).await; + // Every certificate order was for the name that was claimed. + { + let st = w.fake.state.lock().unwrap(); + assert!(!st.orders.is_empty()); + for o in &st.orders { + assert_eq!(o.identifier, format!("*.{name}")); + } + } + assert_eq!(w.link.status().address.as_deref(), Some(address.as_str())); + assert_eq!(w.link.kept_address().as_deref(), Some(address.as_str())); + assert!(w.assistant(&host).await.unwrap().ends_with(BODY)); +} + +/// WB-link-4 (INVARIANT 9 of certs.rs): a certificate is not served after +/// its end, even when it cannot be renewed, and the state says it is gone. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_expired_certificate_is_not_served_and_the_state_says_so() { + // Renewals that fail are tried again only after an hour: nothing but + // the end of the certificate wakes the app. + let w = world(LIST, |t| { + t.cert_retry_min = Duration::from_secs(3600); + t.cert_retry_max = Duration::from_secs(3600); + t.ari_recheck = Duration::from_secs(3600); + }) + .await; + w.fake.state.lock().unwrap().lifetime = 3; + w.link.turn_on().unwrap(); + until(&w.link, "connected", |s| s.step() == Step::Connected).await; + let host = w.host(); + { + let mut st = w.fake.state.lock().unwrap(); + st.fail.insert("first".into()); + st.fail.insert("second".into()); + } + // Served while it lasts ... + let early = w.link.status().cert_expires.unwrap(); + // ... and, once it has ended, neither served nor said to be in place. + until(&w.link, "the certificate has ended", |s| { + s.cert_expires.is_none() + }) + .await; + assert!(ledger_link::certs::now() >= early); + assert_ne!(w.link.status().step(), Step::Connected); + assert!(w.assistant(&host).await.is_err()); +} + +/// WB-link-5 (text.rs): what a certificate authority says to the app does +/// not reach the window unbounded. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_authority_that_shouts_is_shown_short_and_plain() { + let w = world(LIST, |_| {}).await; + { + let mut st = w.fake.state.lock().unwrap(); + st.fail.insert("first".into()); + st.fail.insert("second".into()); + st.say = Some(format!("send money\u{7}\n\u{202e}{}", "now ".repeat(5000))); + } + w.link.turn_on().unwrap(); + let s = until(&w.link, "the trouble is said", |s| s.cert_trouble.is_some()).await; + let words = s.problem().unwrap(); + assert!( + words.chars().count() < 1200, + "{} characters", + words.chars().count() + ); + assert!( + !words.chars().any(|c| c.is_control() || c == '\u{202e}'), + "{words:?}" + ); + assert!(words.contains("send money")); + assert!(words.starts_with("Wanderbooks could not get a certificate yet.")); +} + +/// The window asks for the kept address every frame: it is read from the +/// folder once, not each time (the key lives in the same file). +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_kept_address_is_read_once_not_every_frame() { + let w = world(LIST, |_| {}).await; + assert!(w.link.kept_address().is_none(), "before the first start"); + w.link.turn_on().unwrap(); + until(&w.link, "claimed", |s| s.claimed).await; + let first = w.link.kept_address().unwrap(); + w.link.turn_off(); + // With the file gone, the answer is still the one held: nothing reads + // the folder again. + for f in std::fs::read_dir(w.dir.path().join("link")).unwrap() { + let f = f.unwrap().path(); + if f.is_file() { + std::fs::remove_file(f).unwrap(); + } + } + assert_eq!(w.link.kept_address().as_deref(), Some(first.as_str())); +} diff --git a/crates/ledger-link/tests/support/mod.rs b/crates/ledger-link/tests/support/mod.rs index ea3ca2a6..7e115fb8 100644 --- a/crates/ledger-link/tests/support/mod.rs +++ b/crates/ledger-link/tests/support/mod.rs @@ -11,7 +11,7 @@ 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 ledger_link::{CertTrust, Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing}; use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose}; use relay::proto::{Authority, Caller}; use rustls::RootCertStore; @@ -42,6 +42,8 @@ pub struct FakeState { pub fail: std::collections::HashSet, /// Seconds the certificate lasts from now. pub lifetime: i64, + /// What a refusal says, when it is not the fixed words. + pub say: Option, /// The renewal window the authority suggests, as seconds from now. pub window: Option<(i64, i64)>, } @@ -96,6 +98,7 @@ impl Fake { orders: vec![], fail: Default::default(), lifetime: 3600, + say: None, window: None, }), }) @@ -124,7 +127,7 @@ fn proof_value() -> String { impl Issuer for Fake { fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result> { Box::pin(async move { - let (fails, lifetime) = { + let (fails, lifetime, say) = { let mut st = self.state.lock().unwrap(); st.orders.push(Order { authority: req.authority.id.clone(), @@ -132,10 +135,14 @@ impl Issuer for Fake { replaces: req.replaces.is_some(), had_binding: req.authority.binding.is_some(), }); - (st.fail.contains(&req.authority.id), st.lifetime) + ( + st.fail.contains(&req.authority.id), + st.lifetime, + st.say.clone(), + ) }; if fails { - return Err("the fake authority says no".into()); + return Err(say.unwrap_or_else(|| "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. @@ -369,6 +376,8 @@ pub fn fast() -> Timing { order_timeout: Duration::from_secs(10), ari_recheck: Duration::from_secs(1), wake_gap: Duration::from_secs(30), + line_stable: Duration::from_millis(300), + redial_spread: Duration::from_millis(200), } } @@ -402,6 +411,7 @@ pub fn config(w: &World) -> LinkConfig { dial: Dial::Addr(w.tap.addr), relay_tls: w.env.line_tls(), issuer: w.fake.clone(), + trust: CertTrust::for_tests(w.fake.roots()), timing: fast(), } } @@ -429,6 +439,7 @@ pub async fn world_with( dial: Dial::Addr(tap.addr), relay_tls: env.line_tls(), issuer: fake.clone(), + trust: CertTrust::for_tests(fake.roots()), timing: fast(), }; timing(&mut cfg.timing); @@ -446,6 +457,19 @@ pub async fn world_with( } impl World { + /// The link made again with `change` applied to its setup (the same + /// folder, relay and authority). + pub fn remake(&mut self, change: impl FnOnce(&mut LinkConfig)) { + let mut cfg = config(self); + change(&mut cfg); + 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())); + } + /// 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);