From 9898e56950510abe66b7e25b203d8b26bb70cd04 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:57:51 -0700 Subject: [PATCH 01/11] feat(link): the app's side of the relay: identity, line, TLS at the app, certificates (P15 B3) The app keeps one durable address https://..wanderbooks.link: an Ed25519 key, a four-word name the app picks, and a 32-character base-36 secret label (about 165 bits), all in private (0600 / owner-only) files in the data root's link/ folder. One name per installation, as plan section 5 says; each company is a path under it. The line (yamux over TLS 1.3, the relay crate's own client) runs in the app's own process, not in the books server child: a window that dies takes its sockets with it, so the line can never keep a door open for books that closed. It reconnects with full-jitter backoff, pings every 30 s (the relay drops a line silent for 180 s), re-dials at once after a wall-clock jump (a sleep), and says in words what is wrong: no internet, the relay down, a busy relay, a wrong clock, a name the relay lost. TLS ends in the app with its own certificate (rustls, ALPN h2 and http/1.1), served only for the app's exact host name, then the plain stream goes to the remote door on 127.0.0.1 after the door's per-start secret and the relay's PROXY header. The private keys are never sent to the relay. Certificates are ordered by ACME DNS-01 (instant-acme, behind an Issuer trait so tests use an in-process authority) for the wildcard under the app's name, from the relay's authority list in its order (a not-usable one is skipped, a failing one falls to the next), stored, reused across restarts, and renewed at the time the authority's renewal information suggests, else two thirds through the life. New dependencies: instant-acme 0.8 (Apache-2.0; ring, hyper-rustls, time and x509-parser features, no aws-lc-rs), x509-parser 0.18 and webpki-root-certs 1 (already in the tree), time and async-trait for tests. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 64 ++ Cargo.toml | 2 +- crates/ledger-link/Cargo.toml | 51 ++ crates/ledger-link/src/acme.rs | 290 ++++++++ crates/ledger-link/src/certs.rs | 356 ++++++++++ crates/ledger-link/src/identity.rs | 329 +++++++++ crates/ledger-link/src/lib.rs | 59 ++ crates/ledger-link/src/line.rs | 351 ++++++++++ crates/ledger-link/src/link.rs | 893 ++++++++++++++++++++++++ crates/ledger-link/src/private.rs | 88 +++ crates/ledger-link/src/status.rs | 248 +++++++ crates/ledger-link/tests/link.rs | 594 ++++++++++++++++ crates/ledger-link/tests/support/mod.rs | 527 ++++++++++++++ justfile | 2 +- 14 files changed, 3852 insertions(+), 2 deletions(-) create mode 100644 crates/ledger-link/Cargo.toml create mode 100644 crates/ledger-link/src/acme.rs create mode 100644 crates/ledger-link/src/certs.rs create mode 100644 crates/ledger-link/src/identity.rs create mode 100644 crates/ledger-link/src/lib.rs create mode 100644 crates/ledger-link/src/line.rs create mode 100644 crates/ledger-link/src/link.rs create mode 100644 crates/ledger-link/src/private.rs create mode 100644 crates/ledger-link/src/status.rs create mode 100644 crates/ledger-link/tests/link.rs create mode 100644 crates/ledger-link/tests/support/mod.rs 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 From 0f9420aa30140c4ca65f3b3fc9d31db7c6015214 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 12:59:46 -0700 Subject: [PATCH 02/11] test(link): the ACME client against an in-process authority (P15 B3) The real instant-acme client speaks RFC 8555 to a small authority written in the test: account, order, DNS-01 proof read from the relay's own DNS, finalize with the client's CSR, download, an account binding when the relay gave one and none when it did not, a renewal that names the certificate it replaces, the authority's renewal window, and a refusal in the authority's own words. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-link/Cargo.toml | 3 +- crates/ledger-link/tests/acme.rs | 522 +++++++++++++++++++++++++++++++ 2 files changed, 524 insertions(+), 1 deletion(-) create mode 100644 crates/ledger-link/tests/acme.rs diff --git a/crates/ledger-link/Cargo.toml b/crates/ledger-link/Cargo.toml index b63f40d8..7597dcd3 100644 --- a/crates/ledger-link/Cargo.toml +++ b/crates/ledger-link/Cargo.toml @@ -36,13 +36,14 @@ ledger-store = { path = "../ledger-store" } [dev-dependencies] tempfile = "3" -rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] } +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" +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } sha2 = "0.10" time = "0.3" tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } diff --git a/crates/ledger-link/tests/acme.rs b/crates/ledger-link/tests/acme.rs new file mode 100644 index 00000000..2bd070a5 --- /dev/null +++ b/crates/ledger-link/tests/acme.rs @@ -0,0 +1,522 @@ +//! The ACME client against an in-process authority: the real +//! `instant-acme` client speaks RFC 8555 to a small authority written +//! here (it checks the proof in the relay's own DNS, signs the CSR it is +//! given with a CA of its own, and offers renewal information). No +//! network beyond 127.0.0.1: the "HTTP" is a function call. +#![allow(missing_docs)] + +mod support; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; +use bytes::Bytes; +use futures::future::BoxFuture; +use http_body_util::BodyExt; +use instant_acme::{BodyWrapper, BytesResponse, Error, HttpClient}; +use ledger_link::certs::{DnsProof, Issuer, OrderRequest, inspect, leaf_der}; +use ledger_link::{AcmeIssuer, certs}; +use rcgen::{CertificateSigningRequestParams, CertifiedIssuer, KeyPair}; +use relay::proto::{Authority, Binding}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use support::common::{self, DOMAIN, n}; + +const BASE: &str = "https://acme.test"; + +#[derive(Default)] +struct Server { + nonce: u64, + accounts: HashMap, // kid -> thumbprint + new_accounts: Vec, + orders: Vec, + ari_gets: u32, + refuse_orders: bool, +} + +struct Order { + identifier: String, + replaces: Option, + thumbprint: String, + token: String, + authz_valid: bool, + done: bool, +} + +struct FakeAcme { + ca: CertifiedIssuer<'static, KeyPair>, + dns: std::net::SocketAddr, + state: Mutex, + window: (i64, i64), +} + +fn jws(body: &[u8]) -> (serde_json::Value, serde_json::Value) { + let v: serde_json::Value = serde_json::from_slice(body).unwrap(); + let protected: serde_json::Value = + serde_json::from_slice(&B64.decode(v["protected"].as_str().unwrap()).unwrap()).unwrap(); + let payload = match v["payload"].as_str().unwrap() { + "" => serde_json::Value::Null, + p => serde_json::from_slice(&B64.decode(p).unwrap()).unwrap(), + }; + (protected, payload) +} + +fn thumbprint(jwk: &serde_json::Value) -> String { + let canon = format!( + r#"{{"crv":{},"kty":{},"x":{},"y":{}}}"#, + jwk["crv"], jwk["kty"], jwk["x"], jwk["y"] + ); + B64.encode(Sha256::digest(canon.as_bytes())) +} + +type Reply = (u16, Vec<(&'static str, String)>, Bytes); + +fn json(status: u16, extra: Vec<(&'static str, String)>, v: serde_json::Value) -> Reply { + let mut h = vec![("content-type", "application/json".to_string())]; + h.extend(extra); + (status, h, Bytes::from(v.to_string())) +} + +impl FakeAcme { + async fn handle(&self, method: &str, path: &str, body: &[u8]) -> Reply { + let nonce = { + let mut s = self.state.lock().unwrap(); + s.nonce += 1; + format!("nonce-{}", s.nonce) + }; + let with_nonce = |mut r: Reply| { + r.1.push(("replay-nonce", nonce.clone())); + r + }; + match (method, path) { + ("GET", "/dir") => with_nonce(json( + 200, + vec![], + serde_json::json!({ + "newNonce": format!("{BASE}/nonce"), + "newAccount": format!("{BASE}/acct"), + "newOrder": format!("{BASE}/order"), + "renewalInfo": format!("{BASE}/ari"), + "meta": {} + }), + )), + (_, "/nonce") => with_nonce((200, vec![], Bytes::new())), + ("POST", "/acct") => { + let (protected, payload) = jws(body); + let kid = format!("{BASE}/acct/1"); + let mut s = self.state.lock().unwrap(); + s.accounts + .insert(kid.clone(), thumbprint(&protected["jwk"])); + s.new_accounts.push(payload); + with_nonce(json( + 201, + vec![("location", kid)], + serde_json::json!({"status":"valid"}), + )) + } + ("POST", "/order") => { + let (protected, payload) = jws(body); + let mut s = self.state.lock().unwrap(); + if s.refuse_orders { + return with_nonce(json( + 429, + vec![], + serde_json::json!({"type":"urn:ietf:params:acme:error:rateLimited","detail":"too many certificates already issued"}), + )); + } + let thumb = s.accounts[protected["kid"].as_str().unwrap()].clone(); + let identifier = payload["identifiers"][0]["value"] + .as_str() + .unwrap() + .to_owned(); + let replaces = payload["replaces"].as_str().map(str::to_owned); + let id = s.orders.len() + 1; + s.orders.push(Order { + identifier, + replaces: replaces.clone(), + thumbprint: thumb, + token: format!("token-{id}"), + authz_valid: false, + done: false, + }); + let mut order = serde_json::json!({ + "status":"pending", + "identifiers": payload["identifiers"], + "authorizations":[format!("{BASE}/authz/{id}")], + "finalize": format!("{BASE}/finalize/{id}"), + }); + if let Some(r) = replaces { + order["replaces"] = r.into(); + } + with_nonce(json(201, vec![("location", format!("{BASE}/order/{id}"))], order)) + } + ("POST", p) if p.starts_with("/authz/") => { + let id: usize = p[7..].parse().unwrap(); + let s = self.state.lock().unwrap(); + let o = &s.orders[id - 1]; + let ident = o.identifier.trim_start_matches("*."); + with_nonce(json( + 200, + vec![], + serde_json::json!({ + "status": if o.authz_valid {"valid"} else {"pending"}, + "identifier": {"type":"dns","value": ident}, + "wildcard": o.identifier.starts_with("*."), + "challenges":[{"type":"dns-01","url":format!("{BASE}/chall/{id}"), + "token":o.token,"status":"pending"}] + }), + )) + } + ("POST", p) if p.starts_with("/chall/") => { + let id: usize = p[7..].parse().unwrap(); + let (ident, expected) = { + let s = self.state.lock().unwrap(); + let o = &s.orders[id - 1]; + let ka = format!("{}.{}", o.token, o.thumbprint); + ( + o.identifier.trim_start_matches("*.").to_owned(), + B64.encode(Sha256::digest(ka.as_bytes())), + ) + }; + let seen = + support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await; + let ok = seen.contains(&expected); + self.state.lock().unwrap().orders[id - 1].authz_valid = ok; + with_nonce(json( + 200, + vec![], + serde_json::json!({"type":"dns-01","url":format!("{BASE}/chall/{id}"), + "token":format!("token-{id}"),"status": if ok {"valid"} else {"invalid"}}), + )) + } + ("POST", p) if p.starts_with("/order/") => { + let id: usize = p[7..].parse().unwrap(); + let s = self.state.lock().unwrap(); + let o = &s.orders[id - 1]; + let mut order = serde_json::json!({ + "status": if o.done {"valid"} else if o.authz_valid {"ready"} else {"pending"}, + "identifiers":[{"type":"dns","value":o.identifier}], + "authorizations":[format!("{BASE}/authz/{id}")], + "finalize": format!("{BASE}/finalize/{id}"), + }); + if o.done { + order["certificate"] = format!("{BASE}/cert/{id}").into(); + } + if let Some(r) = &o.replaces { + order["replaces"] = r.clone().into(); + } + with_nonce(json(200, vec![], order)) + } + ("POST", p) if p.starts_with("/finalize/") => { + let id: usize = p[10..].parse().unwrap(); + let (_, payload) = jws(body); + let csr = B64.decode(payload["csr"].as_str().unwrap()).unwrap(); + let der = rustls::pki_types::CertificateSigningRequestDer::from(csr); + let mut params = CertificateSigningRequestParams::from_der(&der).unwrap(); + let now = time::OffsetDateTime::now_utc(); + params.params.not_before = now - time::Duration::hours(1); + params.params.not_after = now + time::Duration::days(60); + params.params.use_authority_key_identifier_extension = true; + let cert = params.signed_by(&self.ca).unwrap(); + let mut s = self.state.lock().unwrap(); + s.orders[id - 1].done = true; + CERTS.lock().unwrap().insert(id, format!("{}{}", cert.pem(), self.ca.pem())); + let o = &s.orders[id - 1]; + with_nonce(json( + 200, + vec![], + serde_json::json!({ + "status":"valid", + "identifiers":[{"type":"dns","value":o.identifier}], + "authorizations":[format!("{BASE}/authz/{id}")], + "finalize": format!("{BASE}/finalize/{id}"), + "certificate": format!("{BASE}/cert/{id}"), + "replaces": o.replaces, + }), + )) + } + ("POST", p) if p.starts_with("/cert/") => { + let id: usize = p[6..].parse().unwrap(); + let pem = CERTS.lock().unwrap()[&id].clone(); + with_nonce(( + 200, + vec![("content-type", "application/pem-certificate-chain".into())], + Bytes::from(pem), + )) + } + ("GET", p) if p.starts_with("/ari/") => { + self.state.lock().unwrap().ari_gets += 1; + let now = time::OffsetDateTime::now_utc(); + let at = |secs: i64| { + (now + time::Duration::seconds(secs)) + .format(&time::format_description::well_known::Rfc3339) + .unwrap() + }; + json( + 200, + vec![("retry-after", "3600".into())], + serde_json::json!({"suggestedWindow":{"start":at(self.window.0),"end":at(self.window.1)}}), + ) + } + _ => json(404, vec![], serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"})), + } + } +} + +static CERTS: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + +struct Http(Arc); + +impl HttpClient for Http { + fn request( + &self, + req: http::Request>, + ) -> Pin> + Send>> { + let fake = self.0.clone(); + Box::pin(async move { + let (parts, body) = req.into_parts(); + let bytes = body.collect().await.map_err(|e| Error::Other(e.into()))?.to_bytes(); + let path = parts.uri.path().to_owned(); + assert_eq!(parts.uri.host(), Some("acme.test")); + let (status, headers, out) = fake.handle(parts.method.as_str(), &path, &bytes).await; + let mut b = http::Response::builder().status(status); + for (k, v) in headers { + b = b.header(k, v); + } + let (parts, _) = b.body(()).unwrap().into_parts(); + Ok(BytesResponse { + parts, + body: Box::new(out), + }) + }) + } +} + +struct Proof(relay::client::LineHandle); + +impl DnsProof for Proof { + fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let r = self.0.publish_txt(value).await.map_err(|e| e.to_string())?; + if r.ok { Ok(()) } else { Err(r.error.unwrap_or_default()) } + }) + } + fn clear(&self) -> BoxFuture<'_, ()> { + Box::pin(async move { + let _ = self.0.request(relay::proto::Request::ClearTxt).await; + }) + } +} + +struct Rig { + env: common::Env, + acme: Arc, + issuer: AcmeIssuer, + line: relay::client::Line, + dir: tempfile::TempDir, + name: relay::names::Name, +} + +async fn rig(window: (i64, i64)) -> Rig { + let env = common::start(common::quick_limits()).await; + let mut params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign]; + let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap(); + let acme = Arc::new(FakeAcme { + ca, + dns: env.relay.dns_udp_addr(), + state: Mutex::new(Server::default()), + window, + }); + 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 (key, _) = relay::proto::AppKey::generate(); + let name = n("ledger-accrual-tally-mint"); + let line = env.connect(name, &key, true).await.unwrap(); + Rig { + env, + acme, + issuer, + line, + dir, + name, + } +} + +fn authority(binding: bool) -> Authority { + Authority { + id: "fake".into(), + directory: format!("{BASE}/dir"), + needs_binding: binding, + usable: true, + binding: binding.then(|| Binding { + kid: "kid-1".into(), + hmac_key: B64.encode(b"0123456789abcdef0123456789abcdef"), + }), + } +} + +/// WB-link-4: account, order, the DNS proof through the relay, finalize +/// and download, in the real client; the key is made here; the account is +/// kept privately; the relay's DNS is left clean. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_order_goes_through_account_proof_finalize_and_download() { + let r = rig((60, 120)).await; + let proof = Proof(r.line.handle()); + let a = authority(false); + let ident = format!("*.{}.{DOMAIN}", r.name); + let issued = r + .issuer + .issue(OrderRequest { + authority: &a, + identifier: ident.clone(), + replaces: None, + dns: &proof, + }) + .await + .unwrap(); + let der = leaf_der(&issued.chain_pem).unwrap(); + let (nb, na, names) = inspect(&der).unwrap(); + assert_eq!(names, [ident.clone()]); + assert!(nb < certs::now() && na > certs::now()); + 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()); + + // The account is kept in a private file, with no contact in it. + let file = r.dir.path().join("acme/fake.json"); + assert!(file.exists()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); + } + let st = r.acme.state.lock().unwrap(); + assert_eq!(st.new_accounts.len(), 1); + assert!(st.new_accounts[0]["contact"].as_array().is_none_or(|c| c.is_empty())); + assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true); + drop(st); + // The relay holds no proof once the order is done. + let left = support::dns_txt( + r.env.relay.dns_udp_addr(), + &format!("_acme-challenge.{}.{DOMAIN}.", r.name), + ) + .await; + assert!(left.is_empty(), "{left:?}"); +} + +/// WB-link-4: a second order reuses the account, a renewal names the +/// certificate it replaces, and the authority's renewal window is read. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_window() { + let r = rig((600, 900)).await; + let proof = Proof(r.line.handle()); + let a = authority(false); + let ident = format!("*.{}.{DOMAIN}", r.name); + let first = r + .issuer + .issue(OrderRequest { + authority: &a, + identifier: ident.clone(), + replaces: None, + dns: &proof, + }) + .await + .unwrap(); + let second = r + .issuer + .issue(OrderRequest { + authority: &a, + identifier: ident.clone(), + replaces: leaf_der(&first.chain_pem), + dns: &proof, + }) + .await + .unwrap(); + assert_ne!(first.chain_pem, second.chain_pem); + assert_ne!(*first.key_pem, *second.key_pem, "a fresh key for each certificate"); + { + let st = r.acme.state.lock().unwrap(); + assert_eq!(st.new_accounts.len(), 1, "the account was reused"); + assert!(st.orders[0].replaces.is_none()); + let id = st.orders[1].replaces.clone().unwrap(); + assert!(id.contains('.'), "an ARI certificate id: {id}"); + } + let (s, e) = r + .issuer + .renewal_window(&a, &first.chain_pem) + .await + .expect("the authority offers a window"); + let now = certs::now(); + assert!((now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e), "{s} {e} {now}"); + assert_eq!(r.acme.state.lock().unwrap().ari_gets, 1); +} + +/// WB-link-4: an authority that needs an account binding gets the one the +/// relay gave, and without one nothing is asked of it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_binding_is_sent_when_there_is_one_and_never_invented() { + let r = rig((60, 120)).await; + let proof = Proof(r.line.handle()); + let ident = format!("*.{}.{DOMAIN}", r.name); + let mut no = authority(true); + no.binding = None; + no.usable = false; + let err = r + .issuer + .issue(OrderRequest { + authority: &no, + identifier: ident.clone(), + replaces: None, + dns: &proof, + }) + .await + .err() + .unwrap(); + assert!(err.contains("needs an account binding"), "{err}"); + assert!(r.acme.state.lock().unwrap().new_accounts.is_empty()); + + let yes = authority(true); + r.issuer + .issue(OrderRequest { + authority: &yes, + identifier: ident, + replaces: None, + dns: &proof, + }) + .await + .unwrap(); + let st = r.acme.state.lock().unwrap(); + let eab = &st.new_accounts[0]["externalAccountBinding"]; + assert!(eab.is_object(), "{:?}", st.new_accounts); + let protected: serde_json::Value = + serde_json::from_slice(&B64.decode(eab["protected"].as_str().unwrap()).unwrap()).unwrap(); + assert_eq!(protected["kid"], "kid-1"); +} + +/// WB-link-4: an authority's refusal comes back in its own words. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_refusal_comes_back_in_the_authoritys_words() { + let r = rig((60, 120)).await; + r.acme.state.lock().unwrap().refuse_orders = true; + 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.contains("too many certificates"), "{err}"); +} From 861ed57d82f993af5bcad1b17eb65048ce4d2577 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 13:40:00 -0700 Subject: [PATCH 03/11] feat(host): web assistants per company, joined to the remote door (P15 B3) WebAssistants is the switch per company: turning one on makes the link's address, starts the books server's remote door at it (the door listens on 127.0.0.1 and gives the app its per-start secret), offers the company, and hands the link the door; turning off withdraws the company and, with none left, closes the line first and then the door. A new address stops the door, makes a new label, and restarts the door at the new issuer, so every token made at the old address is refused. The switches are kept in a private file and put back for the companies that are open at the next start. Nothing is half-on after a failed step. The line runs in the window's process (the viewer owner holds it), so it ends with the window and never outlives the books it offers. THIRD-PARTY-NOTICES.txt is regenerated with scripts/notices.sh: the app now links instant-acme, the relay crate's client side and hickory-proto. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 14 + THIRD-PARTY-NOTICES.txt | 1513 ++++++++++++++++++++++++++++++ crates/ledger-cli/Cargo.toml | 19 +- crates/ledger-cli/src/main.rs | 56 +- crates/ledger-host/Cargo.toml | 1 + crates/ledger-host/src/lib.rs | 1 + crates/ledger-host/src/web.rs | 434 +++++++++ crates/ledger-link/tests/acme.rs | 73 +- 8 files changed, 2085 insertions(+), 26 deletions(-) create mode 100644 crates/ledger-host/src/web.rs diff --git a/Cargo.lock b/Cargo.lock index 73ecfbfd..4508742f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4006,13 +4006,19 @@ name = "ledger-cli" version = "0.1.0" dependencies = [ "base64 0.22.1", + "bytes", "chrono", + "futures", + "http-body-util", + "hyper", + "hyper-util", "jsonschema", "ledger-config", "ledger-core", "ledger-gui", "ledger-host", "ledger-import", + "ledger-link", "ledger-mcp", "ledger-package", "ledger-store", @@ -4020,14 +4026,20 @@ dependencies = [ "libc", "minisign", "proptest", + "rcgen", + "relay", "reqwest", "rmcp", "rusqlite", "rust_decimal", + "rustls", "serde_json", "sha2 0.10.9", "tempfile", + "time", "tokio", + "tokio-rustls", + "zeroize", "zip", ] @@ -4085,6 +4097,7 @@ dependencies = [ "ledger-config", "ledger-core", "ledger-import", + "ledger-link", "ledger-package", "ledger-store", "ledger-vault", @@ -4105,6 +4118,7 @@ version = "0.1.0" dependencies = [ "base64 0.22.1", "ledger-core", + "ledger-link", "ledger-mcp", "ledger-store", "libc", diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 05616714..20f44d12 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -23,6 +23,287 @@ Permission to use, copy, modify, and/or distribute this software for any purpose THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +================================================================================ +Apache License 2.0 +================================================================================ + +Used by: + ring 0.17.14 + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +Licenses for support code +------------------------- + +Parts of the TLS test suite are under the Go license. This code is not included +in BoringSSL (i.e. libcrypto and libssl) when compiled, however, so +distributing code linked against BoringSSL does not trigger this license: + +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +BoringSSL uses the Chromium test infrastructure to run a continuous build, +trybots etc. The scripts which manage this, and the script for generating build +metadata, are under the Chromium license. Distributing code linked against +BoringSSL does not trigger this license. + +Copyright 2015 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ================================================================================ Apache License 2.0 ================================================================================ @@ -874,6 +1155,7 @@ Used by: ciborium-ll 0.2.2 ciborium 0.2.2 codespan-reporting 0.13.1 + instant-acme 0.8.5 self_cell 1.3.0 Apache License @@ -1505,6 +1787,7 @@ Apache License 2.0 Used by: gethostname 1.1.0 + ring 0.17.14 Apache License Version 2.0, January 2004 @@ -3068,6 +3351,160 @@ For these and/or other purposes and motivations, and without any expectation of d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. +================================================================================ +Community Data License Agreement Permissive 2.0 +================================================================================ + +Used by: + webpki-root-certs 1.0.11 + +# Community Data License Agreement - Permissive - Version 2.0 + +This is the Community Data License Agreement - Permissive, Version +2.0 (the "agreement"). Data Provider(s) and Data Recipient(s) agree +as follows: + +## 1. Provision of the Data + +1.1. A Data Recipient may use, modify, and share the Data made +available by Data Provider(s) under this agreement if that Data +Recipient follows the terms of this agreement. + +1.2. This agreement does not impose any restriction on a Data +Recipient's use, modification, or sharing of any portions of the +Data that are in the public domain or that may be used, modified, +or shared under any other legal exception or limitation. + +## 2. Conditions for Sharing Data + +2.1. A Data Recipient may share Data, with or without modifications, so +long as the Data Recipient makes available the text of this agreement +with the shared Data. + +## 3. No Restrictions on Results + +3.1. This agreement does not impose any restriction or obligations +with respect to the use, modification, or sharing of Results. + +## 4. No Warranty; Limitation of Liability + +4.1. All Data Recipients receive the Data subject to the following +terms: + +THE DATA IS PROVIDED ON AN "AS IS" BASIS, WITHOUT REPRESENTATIONS, +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED +INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + +NO DATA PROVIDER SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE DATA OR RESULTS, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 5. Definitions + +5.1. "Data" means the material received by a Data Recipient under +this agreement. + +5.2. "Data Provider" means any person who is the source of Data +provided under this agreement and in reliance on a Data Recipient's +agreement to its terms. + +5.3. "Data Recipient" means any person who receives Data directly +or indirectly from a Data Provider and agrees to the terms of this +agreement. + +5.4. "Results" means any outcome obtained by computational analysis +of Data, including for example machine learning models and models' +insights. + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +/* Copyright (c) 2014, Intel Corporation. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ + +#ifndef OPENSSL_HEADER_EC_ECP_NISTZ384_H +#define OPENSSL_HEADER_EC_ECP_NISTZ384_H + +#include "../../limbs/limbs.h" + +#define P384_LIMBS (384u / LIMB_BITS) + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; + Limb Z[P384_LIMBS]; +} P384_POINT; + +typedef struct { + Limb X[P384_LIMBS]; + Limb Y[P384_LIMBS]; +} P384_POINT_AFFINE; + + +#endif // OPENSSL_HEADER_EC_ECP_NISTZ384_H + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2015-2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! EdDSA Signatures. + +use super::ops::ELEM_LEN; +use crate::digest; + +pub mod signing; +pub mod verification; + +/// The length of an Ed25519 public key. +pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN; + +pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest { + let mut ctx = digest::Context::new(&digest::SHA512); + ctx.update(signature_r); + ctx.update(public_key); + ctx.update(msg); + ctx.finish() +} + + ================================================================================ ISC License ================================================================================ @@ -3090,6 +3527,622 @@ Used by: // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2015-2022 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::limb::Limb; + +#[derive(Clone, Copy)] +#[repr(transparent)] +pub struct N0([Limb; 2]); + +impl N0 { + #[cfg(feature = "alloc")] + pub(super) const LIMBS_USED: usize = 64 / crate::limb::LIMB_BITS; + + #[inline] + pub const fn precalculated(n0: u64) -> Self { + #[cfg(target_pointer_width = "64")] + { + Self([n0, 0]) + } + + #[cfg(target_pointer_width = "32")] + { + Self([n0 as Limb, (n0 >> crate::limb::LIMB_BITS) as Limb]) + } + } +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2015-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#[cfg(target_pointer_width = "64")] +type CompilerWord = u64; + +#[cfg(target_pointer_width = "32")] +type CompilerWord = u32; + +/// A native word that isn't secret. +/// +/// `LeakyWord` supports `as` conversions to/from native types. +/// +/// XXX: This isn't the native word size on targets where a pointer isn't the +/// same size as a native word. TODO: Fix this. +pub(crate) type LeakyWord = CompilerWord; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2015-2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::{bb, error}; + +#[deprecated( + note = "To be removed. Internal function not intended for external use with no promises regarding side channels." +)] +pub fn verify_slices_are_equal(a: &[u8], b: &[u8]) -> Result<(), error::Unspecified> { + bb::verify_slices_are_equal(a, b) +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2016 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Elliptic curve operations and schemes using Curve25519. + +pub mod ed25519; + +pub mod x25519; + +mod ops; +mod scalar; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2016-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::error::{KeyRejected, Unspecified}; + +impl From for Unspecified { + fn from(source: untrusted::EndOfInput) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: core::array::TryFromSliceError) -> Self { + super::erase(source) + } +} + +impl From for Unspecified { + fn from(source: KeyRejected) -> Self { + super::erase(source) + } +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2018 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#[cfg(target_arch = "x86")] +pub fn shift_full_blocks( + in_out: super::overlapping::Overlapping<'_, u8>, + mut transform: impl FnMut(&[u8; BLOCK_LEN]) -> [u8; BLOCK_LEN], +) { + let (in_out, src) = in_out.into_slice_src_mut(); + let in_out_len = in_out[src.clone()].len(); + + for i in (0..in_out_len).step_by(BLOCK_LEN) { + let block = { + let input = + <&[u8; BLOCK_LEN]>::try_from(&in_out[(src.start + i)..][..BLOCK_LEN]).unwrap(); + transform(input) + }; + let output = <&mut [u8; BLOCK_LEN]>::try_from(&mut in_out[i..][..BLOCK_LEN]).unwrap(); + *output = block; + } +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2018 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Serialization and deserialization. + +#[doc(hidden)] +pub mod der; + +#[cfg(feature = "alloc")] +mod writer; + +#[cfg(feature = "alloc")] +pub(crate) mod der_writer; + +pub(crate) mod positive; + +pub use self::positive::Positive; + +#[cfg(feature = "alloc")] +pub(crate) use self::writer::TooLongError; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2019-2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use super::BlockLen; + +pub(super) use self::{ + sha2_32::{block_data_order_32, State32, SHA256_BLOCK_LEN}, + sha2_64::{block_data_order_64, State64, SHA512_BLOCK_LEN}, +}; + +pub(super) const CHAINING_WORDS: usize = 8; + +#[cfg(any( + all(target_arch = "aarch64", target_endian = "little"), + all(target_arch = "arm", target_endian = "little"), + target_arch = "x86_64" +))] +#[macro_use] +mod ffi; + +pub(super) mod fallback; +mod sha2_32; +mod sha2_64; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2022 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +/// Polyfill for `Option::unwrap()` as a const fn; feature `const_option`. +/// https://github.com/rust-lang/rust/issues/67441. +/// TODO(MSRV): Replace this with `x.unwrap()`. +/// +/// `T: Copy` avoids "constant functions cannot evaluate destructors." +pub const fn unwrap_const(x: Option) -> T +where + T: Copy, +{ + if let Some(x) = x { + x + } else { + panic!("unwrap_const on `None`"); + } +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +// TODO(MSRV 1.76): Replace with `core::ptr::from_mut`. +#[allow(dead_code)] +#[inline(always)] +pub fn from_mut(r: &mut T) -> *mut T { + r +} + +// TODO(MSRV 1.76): Replace with `core::ptr::from_ref`. +#[allow(dead_code)] +#[inline(always)] +pub const fn from_ref(r: &T) -> *const T { + r +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Integration tests for non-public APIs. + +mod bits_tests; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +//! Utilities to make dealing with slices less tediuous. + +/// Replaces the first N elements of `a` with the first N elements of `b`, where +/// N is `core::cmp::min(a.len(), b.len())`, leaving the rest unchanged. +pub fn overwrite_at_start(a: &mut [T], b: &[T]) { + a.iter_mut().zip(b).for_each(|(a, b)| { + *a = *b; + }); +} + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub use self::{ + array::Array, + base::{IndexError, Overlapping}, + partial_block::PartialBlock, +}; + +mod array; +mod base; +mod partial_block; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2024 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +use crate::testutil; +use core::{marker::PhantomData, mem::size_of}; + +/// A ZST that can be added to any type to make the type `!Send`. +#[derive(Clone, Copy)] +pub struct NotSend(PhantomData<*mut ()>); + +impl NotSend { + pub const VALUE: Self = Self(PhantomData); +} + +#[allow(deprecated)] +const _: () = testutil::compile_time_assert_clone::(); +#[allow(deprecated)] +const _: () = testutil::compile_time_assert_copy::(); +const _: () = assert!(size_of::() == 0); + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(all(target_arch = "aarch64", target_endian = "little"))] + +pub(in super::super) mod mont; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +#![cfg(target_arch = "x86_64")] + +pub(in super::super::super) mod mont; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +mod storage; + +pub(super) use self::storage::{AlignedStorage, LIMBS_PER_CHUNK}; + + +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +// Copyright 2025 Brian Smith. +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice appear in all copies. +// +// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +pub(super) mod aarch64; +pub(super) mod x86_64; + + ================================================================================ ISC License ================================================================================ @@ -3133,6 +4186,28 @@ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +================================================================================ +ISC License +================================================================================ + +Used by: + ring 0.17.14 + +Copyright 2015-2025 Brian Smith. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + ================================================================================ ISC License ================================================================================ @@ -3888,6 +4963,35 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + nom 7.1.3 + +Copyright (c) 2014-2019 Geoffroy Couprie + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -4174,6 +5278,35 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + hickory-proto 0.26.3 + +Copyright (c) 2015 The Hickory DNS Developers +Copyright (c) 2017 Google LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -4654,6 +5787,22 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + yasna 0.6.0 + +Copyright (c) 2016 Masaki Hara + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -5115,6 +6264,45 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + asn1-rs-derive 0.6.0 + asn1-rs 0.7.2 + der-parser 10.0.0 + oid-registry 0.8.1 + rusticata-macros 4.1.0 + x509-parser 0.18.1 + +Copyright (c) 2017 Pierre Chifflier + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -7116,6 +8304,40 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + critical-section 1.2.0 + +Copyright (c) 2022 The critical-section authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -7890,6 +9112,7 @@ MIT License ================================================================================ Used by: + synstructure 0.13.2 synstructure 0.14.0 Copyright 2016 Nika Layzell @@ -9200,6 +10423,7 @@ MIT License Used by: accesskit 0.24.1 + asn1-rs-impl 0.2.0 block2 0.5.1 block2 0.6.2 brotli-decompressor 5.0.3 @@ -9234,6 +10458,7 @@ Used by: objc2 0.6.5 palette_math 0.7.7 profiling 1.0.18 + rcgen 0.14.10 rust_xlsxwriter 0.102.0 type-map 0.5.1 wasmi 1.1.0 @@ -9263,6 +10488,7 @@ Used by: windows_x86_64_gnu 0.53.1 windows_x86_64_msvc 0.52.6 windows_x86_64_msvc 0.53.1 + yamux 0.14.1 MIT License @@ -9771,12 +10997,16 @@ Used by: home 0.5.12 itoa 1.0.18 khronos-egl 6.0.0 + lazy_static 1.5.1 linux-raw-sys 0.12.1 linux-raw-sys 0.4.15 + minimal-lexical 0.2.1 once_cell 1.21.4 paste 1.0.15 pastey 0.2.3 + pin-project-internal 1.1.13 pin-project-lite 0.2.17 + pin-project 1.1.13 piper 0.2.5 polling 3.11.0 portable-atomic 1.15.0 @@ -10502,6 +11732,37 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + data-encoding 2.11.1 + +The MIT License (MIT) + +Copyright (c) 2015-2020 Julien Cretin +Copyright (c) 2017-2020 Google Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -10565,6 +11826,36 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================================ +MIT License +================================================================================ + +Used by: + pem 4.0.0 + +The MIT License (MIT) + +Copyright (c) 2016 Jonathan Creekmore + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + ================================================================================ MIT License ================================================================================ @@ -13416,6 +14707,226 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------- +Packaged with: + rcgen 0.14.10 (LICENSE) +-------------------------------------------------------------------------------- + +Copyright (c) 2019-2026 est31 and contributors + +Licensed under MIT or Apache License 2.0, +at your option. + +The full list of contributors can be obtained by looking +at the VCS log (originally, this crate was git versioned, +there you can do "git shortlog -sn" for this task). + +MIT License +----------- + +The MIT License (MIT) + +Copyright (c) 2019-2026 est31 and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + + +Apache License, version 2.0 +--------------------------- + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + -------------------------------------------------------------------------------- Packaged with: rust_xlsxwriter 0.102.0 (LICENSE_Apache2.0) @@ -14457,6 +15968,7 @@ Their copyright notices are in their source repositories: accesskit 0.24.1 https://github.com/AccessKit/accesskit alloc-stdlib 0.2.4 https://github.com/dropbox/rust-alloc-no-stdlib + asn1-rs-impl 0.2.0 https://github.com/rusticata/asn1-rs.git block2 0.5.1 https://github.com/madsmtm/objc2 block2 0.6.2 https://github.com/madsmtm/objc2 comemo-macros 0.5.1 https://github.com/typst/comemo @@ -14490,6 +16002,7 @@ Their copyright notices are in their source repositories: wasmi_core 1.1.0 https://github.com/wasmi-labs/wasmi wasmi_ir 1.1.0 https://github.com/wasmi-labs/wasmi wasmparser 0.239.0 https://github.com/bytecodealliance/wasm-tools/tree/main/crates/wasmparser + yamux 0.14.1 https://github.com/paritytech/yamux ================================================================================ FONTS diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index a51a1126..a99d2b3c 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -15,10 +15,11 @@ path = "src/main.rs" default = ["gui"] # The viewer. Off in the server-only build for another machine (plan # D-22, P9), so a headless machine carries no window libraries. -gui = ["dep:ledger-gui"] +gui = ["dep:ledger-gui", "dep:ledger-link"] [dependencies] ledger-host = { path = "../ledger-host" } +ledger-link = { path = "../ledger-link", optional = true } ledger-mcp = { path = "../ledger-mcp" } ledger-store = { path = "../ledger-store" } ledger-gui = { path = "../ledger-gui", optional = true } @@ -36,7 +37,21 @@ reqwest = "0.13" rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] } rust_decimal = "1" rmcp = { version = "3", features = ["client", "transport-streamable-http-client-reqwest"] } -tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "net", "io-util"] } +# The web link end to end (tests/web_link.rs): an in-process relay and +# certificate authority, and a web caller that speaks HTTP/1.1 and HTTP/2. +relay = { path = "../relay" } +ledger-link = { path = "../ledger-link" } +rcgen = { version = "0.14", default-features = false, features = ["ring", "pem"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } +hyper = { version = "1", features = ["client", "http2"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" +bytes = "1" +futures = "0.3" +zeroize = "1" +time = "0.3" ledger-config = { path = "../ledger-config" } ledger-core = { path = "../ledger-core" } ledger-package = { path = "../ledger-package" } diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index a2e24137..69e68251 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -76,13 +76,22 @@ struct ViewerOwner { /// 3.1): started with the window, closed with it. All of what is done /// with it is `AppHost`'s, which the tests drive. server: ledger_host::app_server::AppHost, + /// Web assistants: the switch per company, the address and the line to + /// the relay (ledger-host web.rs), in this window's process: the line + /// ends with the window. + web: ledger_host::web::WebAssistants, } #[cfg(feature = "gui")] impl ViewerOwner { fn new(common: ledger_host::commands::Common) -> Self { let server = ledger_host::app_server::AppHost::new(common.root.clone()); - Self { common, server } + let web = ledger_host::web::WebAssistants::new(common.root.clone()); + Self { + common, + server, + web, + } } } @@ -93,7 +102,11 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn serve_start(&self, open: &[String]) -> Result<(), String> { - self.server.start(open) + self.server.start(open)?; + // What was on when the window closed is on again, for the + // companies that are open. + self.web.restore(&self.server, open); + Ok(()) } fn serve_host_holds(&self) -> bool { @@ -105,7 +118,9 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn serve_open(&self, book: &str) -> Result, String> { - self.server.open_book(book) + let opened = self.server.open_book(book)?; + self.web.restore(&self.server, &[book.to_string()]); + Ok(opened) } fn serve_close(&self, book: &str) -> Result, String> { @@ -117,6 +132,8 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn serve_stop(&self) -> Result, String> { + // The line closes first: nothing arrives for books that are closing. + self.web.shutdown(); self.server.stop(ledger_host::app_server::STOP_WAIT) } @@ -207,6 +224,39 @@ impl ledger_gui::owner::Owner for ViewerOwner { self.server.web_set_post(approval, post) } + fn web_state(&self, book: &str) -> Option { + use ledger_gui::owner::WebStep; + let s = self.web.state(book); + Some(ledger_gui::owner::WebConnect { + on: s.on, + step: match s.step { + ledger_link::Step::Off => WebStep::Off, + ledger_link::Step::GettingAddress => WebStep::GettingAddress, + ledger_link::Step::Connecting => WebStep::Connecting, + ledger_link::Step::GettingCertificate => WebStep::GettingCertificate, + ledger_link::Step::Connected => WebStep::Connected, + }, + address: s.address, + connector: s.connector, + words: s.words, + problem: s.problem, + needs_person: s.needs_person, + kept: s.kept, + }) + } + + fn web_turn_on(&self, book: &str) -> Result { + self.web.turn_on(&self.server, book) + } + + fn web_turn_off(&self, book: &str) -> Result { + self.web.turn_off(&self.server, book) + } + + fn web_new_address(&self, _book: &str) -> Result { + self.web.new_address(&self.server) + } + fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result { self.server.revoke_token(book, name, id) } diff --git a/crates/ledger-host/Cargo.toml b/crates/ledger-host/Cargo.toml index 5ca81669..b3eedc39 100644 --- a/crates/ledger-host/Cargo.toml +++ b/crates/ledger-host/Cargo.toml @@ -11,6 +11,7 @@ description = "wanderbooks: the books open while something holds them (the host, ledger-core = { path = "../ledger-core" } ledger-mcp = { path = "../ledger-mcp" } ledger-store = { path = "../ledger-store" } +ledger-link = { path = "../ledger-link" } serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "io-std", "sync", "net", "signal", "time", "process"] } diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index bd6bfb2a..43d4cad2 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -28,6 +28,7 @@ mod start; pub mod tokens; #[cfg(unix)] pub mod update; +pub mod web; /// How a mode stops when it can't go on: the reason is already printed, /// and the number is the process's exit code. diff --git a/crates/ledger-host/src/web.rs b/crates/ledger-host/src/web.rs new file mode 100644 index 00000000..96578c07 --- /dev/null +++ b/crates/ledger-host/src/web.rs @@ -0,0 +1,434 @@ +//! Web assistants, from the app's side: the switch per company, the one +//! address, and the line to the relay, joined to the books server's remote +//! door (plan P15 unit B3; WB-link-6). +//! +//! ```text +//! GOAL: a person turns "Allow web assistants" on for a company and the +//! app offers that company at one durable public address, through +//! the relay, with the sign-in the books server's remote door gives; +//! turned off, the company is no longer offered, and when no company +//! is offered the line and the door are closed; and what was on when +//! the app closed is on again when it opens, once the books are. +//! SOURCE: plan/p15-app-and-relay.md 3.3 (a switch per company, off by +//! default; the address with Copy; "Turning it off closes the line +//! and the door; the name is kept"), 5 (one name per installation, +//! each company a path under it), D-80, D-84, WB-link-6. +//! INVARIANTS: +//! 1. Off by default, and per company: nothing is dialled, listened on +//! or offered until a person turns a company on, and only that +//! company is offered. +//! 2. The order is the door first, then the line when turning on (the +//! door listens on 127.0.0.1 only and wants the secret), and the line +//! first, then the door, when turning off: nothing arrives for a door +//! that is gone, and no door is open to a line that is gone. +//! 3. One address for every company: the address's path names the +//! company (`/b//mcp`), and a new address replaces the +//! secret label, restarts the door at the new issuer (so every token +//! and sign-in made at the old address is refused) and keeps the name. +//! 4. The switches are kept in a private file in the link folder, so +//! they are still on at the next start; a company that is not open +//! yet waits for its tab. +//! 5. The state is read from memory and never waits on the network or +//! the server: the window asks it every frame. +//! 6. A failure at any step leaves nothing half-on: the company is not +//! offered, and if it was the only one the line and the door are +//! closed again; the error is in words. +//! SCENARIOS: +//! 1. See `crates/ledger-cli/tests/web_link.rs`: on, a web assistant +//! signs in through the relay and reads the books, off, on again at +//! the same address, a new address, a restart. +//! ``` + +use crate::app_server::AppHost; +use ledger_link::{DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble}; +use ledger_mcp::admin::{Request, Response}; +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +/// The relay's domain and its own host name. +pub const DOMAIN: &str = "wanderbooks.link"; +/// The relay's host, which its certificate is for. +pub const RELAY_HOST: &str = "relay.wanderbooks.link"; + +const SWITCHES: &str = "web.json"; +const ADMIN_WAIT: Duration = Duration::from_secs(30); + +/// What the Connect page shows of the web assistants of one company. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WebState { + /// The switch for this company. + pub on: bool, + /// Where it has got to. + pub step: Step, + /// The address, while on. + pub address: Option, + /// The address an assistant is given for this company. + pub connector: Option, + /// A line of progress in words. + pub words: String, + /// What is wrong, in words. + pub problem: Option, + /// Whether the problem needs the person (and is not just waiting). + pub needs_person: bool, + /// An address is kept for when it is turned on again. + pub kept: bool, +} + +impl WebState { + fn off(kept: bool) -> Self { + WebState { + on: false, + step: Step::Off, + address: None, + connector: None, + words: "Web assistants are off.".into(), + problem: None, + needs_person: false, + kept, + } + } +} + +/// How the app reaches the books server's admin requests. +pub trait Admin: Send + Sync { + /// One admin request. + fn admin(&self, request: Request) -> Result; +} + +impl Admin for AppHost { + fn admin(&self, request: Request) -> Result { + self.running()?.call(request, Some(ADMIN_WAIT)) + } +} + +/// How the link is made (tests give it a relay of their own). +pub type Maker = Box Result + Send + Sync>; + +/// Web assistants for this window. +pub struct WebAssistants { + root: Option, + make: Maker, + link: OnceLock, String>>, + on: Mutex>, + /// An error from putting the switches back at the start. + restore_error: Mutex>, + // One change at a time. + busy: Mutex<()>, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The program's own relay. +pub fn production(dir: PathBuf) -> Result { + Ok(LinkConfig { + issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)), + dir, + domain: DOMAIN.into(), + relay_host: RELAY_HOST.into(), + dial: ledger_link::Dial::Host(RELAY_HOST.into(), 443), + relay_tls: ledger_link::public_relay_tls().map_err(|e| e.to_string())?, + timing: ledger_link::Timing::default(), + }) +} + +impl WebAssistants { + /// Web assistants for the data root `root` (else this account's). + pub fn new(root: Option) -> Self { + Self::with_maker(root, Box::new(production)) + } + + /// With a link made another way (tests). + pub fn with_maker(root: Option, make: Maker) -> Self { + WebAssistants { + root, + make, + link: OnceLock::new(), + on: Mutex::new(BTreeSet::new()), + restore_error: Mutex::new(None), + busy: Mutex::new(()), + } + } + + fn dir(&self) -> Result { + let root = + ledger_store::root::Root::find(self.root.as_deref()).map_err(|e| e.to_string())?; + Ok(root.path().join("link")) + } + + fn link(&self) -> Result<&Arc, String> { + self.link + .get_or_init(|| { + let cfg = (self.make)(self.dir()?)?; + Link::start(cfg).map(Arc::new) + }) + .as_ref() + .map_err(Clone::clone) + } + + fn save(&self, set: &BTreeSet) -> Result<(), String> { + let dir = self.dir()?; + let text = serde_json::to_vec(&serde_json::json!({ "books": set })) + .map_err(|_| "can't keep the switches".to_string())?; + ledger_link::private::make_dir(&dir) + .map_err(|e| format!("can't keep the switches ({})", e.kind()))?; + ledger_link::private::write(&dir.join(SWITCHES), &text) + .map_err(|e| format!("can't keep the switches ({})", e.kind())) + } + + fn load(&self) -> BTreeSet { + let Ok(dir) = self.dir() else { + return BTreeSet::new(); + }; + std::fs::read(dir.join(SWITCHES)) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| { + v["books"].as_array().map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() + }) + }) + .unwrap_or_default() + } + + /// The state of one company's web assistants (INVARIANT 5). + pub fn state(&self, book: &str) -> WebState { + let on = lock(&self.on).contains(book); + let Some(Ok(link)) = self.link.get() else { + // The link was never made: nothing is on, and whether an address + // is kept is read lazily from the folder. + let kept = self + .dir() + .map(|d| d.join("identity.json").exists()) + .unwrap_or(false); + let mut s = WebState::off(kept); + if on { + s.on = true; + s.step = Step::GettingAddress; + s.words = "Getting an address…".into(); + } + return s; + }; + let st = link.status(); + let kept = link.kept_address().is_some(); + if !on { + return WebState::off(kept); + } + Self::describe(book, &st, kept, lock(&self.restore_error).clone()) + } + + fn describe(book: &str, st: &LinkStatus, kept: bool, restore: Option) -> WebState { + let address = st.address.clone(); + let needs_person = st + .trouble + .as_ref() + .is_some_and(|t: &Trouble| !t.mends_itself()); + WebState { + on: true, + step: st.step(), + connector: address.as_ref().map(|a| format!("{a}/b/{book}/mcp")), + address, + words: st.words(), + problem: st.problem().or(restore), + needs_person, + kept, + } + } + + /// Turn web assistants on for `book` (INVARIANTS 1, 2, 6): its words + /// say what happens next. + pub fn turn_on(&self, admin: &dyn Admin, book: &str) -> Result { + let _one = lock(&self.busy); + let link = self.link()?.clone(); + let was = lock(&self.on).clone(); + let door = self.start_door(admin, &link)?; + let offered = admin.admin(Request::RemoteAllow { + book: book.into(), + allowed: true, + }); + match offered { + Ok(Response::Remote(_)) => {} + Ok(Response::Refused(why)) | Err(why) => { + self.unwind(admin, &link, &was); + return Err(why); + } + Ok(other) => { + self.unwind(admin, &link, &was); + return Err(format!("the books server answered oddly: {other:?}")); + } + } + let mut now = was.clone(); + now.insert(book.to_owned()); + if let Err(why) = self.save(&now) { + let _ = admin.admin(Request::RemoteAllow { + book: book.into(), + allowed: false, + }); + self.unwind(admin, &link, &was); + return Err(why); + } + *lock(&self.on) = now; + *lock(&self.restore_error) = None; + link.set_door(Some(door)); + Ok("Web assistants are on. Getting an address and a certificate takes a moment.".into()) + } + + /// The door first (it listens on this computer only), then the line: + /// the line is turned on, so the address is known, and the door is + /// started as that address. + fn start_door(&self, admin: &dyn Admin, link: &Arc) -> Result { + link.turn_on().map_err(|e| e.to_string())?; + let address = link + .status() + .address + .ok_or("Wanderbooks has no address for this yet")?; + let info = match admin.admin(Request::RemoteStart { + public_url: address, + port: None, + }) { + Ok(Response::Remote(info)) => info, + Ok(Response::Refused(why)) | Err(why) => { + if lock(&self.on).is_empty() { + link.turn_off(); + } + return Err(why); + } + Ok(other) => { + if lock(&self.on).is_empty() { + link.turn_off(); + } + return Err(format!("the books server answered oddly: {other:?}")); + } + }; + let listening = info + .listening + .ok_or("the books server's door isn't listening")? + .parse() + .map_err(|_| "the books server's door has an odd address".to_string())?; + let secret = info + .proxy_secret + .ok_or("the books server gave no secret for its door")?; + DoorTarget::new(listening, &secret.0) + } + + /// Put things back as they were `before` a failed change (INVARIANT 6). + fn unwind(&self, admin: &dyn Admin, link: &Arc, before: &BTreeSet) { + if before.is_empty() { + link.turn_off(); + link.set_door(None); + let _ = admin.admin(Request::RemoteStop); + } + } + + /// Turn web assistants off for `book` (INVARIANT 2): with no company + /// left offered, the line closes first, then the door. + pub fn turn_off(&self, admin: &dyn Admin, book: &str) -> Result { + let _one = lock(&self.busy); + let mut now = lock(&self.on).clone(); + now.remove(book); + // Withdraw the company first: nothing new reaches its books. + let withdrawn = admin.admin(Request::RemoteAllow { + book: book.into(), + allowed: false, + }); + let mut note = None; + if let Err(why) = withdrawn { + // The server may be gone already (the books closed); what must + // still happen is the line closing. + note = Some(why); + } + if now.is_empty() + && let Some(Ok(link)) = self.link.get() + { + link.turn_off(); + link.set_door(None); + let _ = admin.admin(Request::RemoteStop); + } + self.save(&now)?; + *lock(&self.on) = now; + Ok(match note { + Some(_) => "Web assistants are off.".into(), + None => "Web assistants are off for this company. Its address is kept for when you turn them on again.".into(), + }) + } + + /// A new address (INVARIANT 3): the one the web assistants use for + /// every company changes; the old one stops working. + pub fn new_address(&self, admin: &dyn Admin) -> Result { + let _one = lock(&self.busy); + let link = self.link()?.clone(); + let on = !lock(&self.on).is_empty(); + if on { + // The old door goes first: nothing signs in at the old address + // while the new one is made. + let _ = admin.admin(Request::RemoteStop); + link.set_door(None); + } + let new = link.new_address().map_err(|e| e.to_string())?; + if on { + let door = self.start_door(admin, &link)?; + let allowed: Vec = lock(&self.on).iter().cloned().collect(); + for book in allowed { + let _ = admin.admin(Request::RemoteAllow { + book, + allowed: true, + }); + } + link.set_door(Some(door)); + } + Ok(format!( + "Your new address is ready ({new}). The old one has stopped working: connect your assistants again with the new one." + )) + } + + /// Put the switches back as they were when the app closed, for the + /// companies that are open (INVARIANT 4). + pub fn restore(&self, admin: &dyn Admin, open: &[String]) { + let kept = self.load(); + for book in open { + if kept.contains(book) + && !lock(&self.on).contains(book) + && let Err(why) = self.turn_on(admin, book) + { + *lock(&self.restore_error) = Some(format!( + "Web assistants could not be turned back on for {book}: {why}" + )); + } + } + } + + /// The window is closing: nothing is dialled or listened on after + /// this. The switches stay as they are on disk. + pub fn shutdown(&self) { + if let Some(Ok(link)) = self.link.get() { + link.turn_off(); + link.set_door(None); + } + } + + /// The network may have changed (a laptop woke): dial again now. + pub fn nudge(&self) { + if let Some(Ok(link)) = self.link.get() { + link.nudge(); + } + } + + /// The link's own status (tests). + pub fn link_status(&self) -> Option { + self.link + .get() + .and_then(|l| l.as_ref().ok()) + .map(|l| l.status()) + } +} + +impl Drop for WebAssistants { + fn drop(&mut self) { + self.shutdown(); + } +} diff --git a/crates/ledger-link/tests/acme.rs b/crates/ledger-link/tests/acme.rs index 2bd070a5..10693695 100644 --- a/crates/ledger-link/tests/acme.rs +++ b/crates/ledger-link/tests/acme.rs @@ -34,6 +34,7 @@ struct Server { orders: Vec, ari_gets: u32, refuse_orders: bool, + certs: HashMap, } struct Order { @@ -150,7 +151,11 @@ impl FakeAcme { if let Some(r) = replaces { order["replaces"] = r.into(); } - with_nonce(json(201, vec![("location", format!("{BASE}/order/{id}"))], order)) + with_nonce(json( + 201, + vec![("location", format!("{BASE}/order/{id}"))], + order, + )) } ("POST", p) if p.starts_with("/authz/") => { let id: usize = p[7..].parse().unwrap(); @@ -180,8 +185,7 @@ impl FakeAcme { B64.encode(Sha256::digest(ka.as_bytes())), ) }; - let seen = - support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await; + let seen = support::dns_txt(self.dns, &format!("_acme-challenge.{ident}.")).await; let ok = seen.contains(&expected); self.state.lock().unwrap().orders[id - 1].authz_valid = ok; with_nonce(json( @@ -222,7 +226,8 @@ impl FakeAcme { let cert = params.signed_by(&self.ca).unwrap(); let mut s = self.state.lock().unwrap(); s.orders[id - 1].done = true; - CERTS.lock().unwrap().insert(id, format!("{}{}", cert.pem(), self.ca.pem())); + s.certs + .insert(id, format!("{}{}", cert.pem(), self.ca.pem())); let o = &s.orders[id - 1]; with_nonce(json( 200, @@ -239,7 +244,7 @@ impl FakeAcme { } ("POST", p) if p.starts_with("/cert/") => { let id: usize = p[6..].parse().unwrap(); - let pem = CERTS.lock().unwrap()[&id].clone(); + let pem = self.state.lock().unwrap().certs[&id].clone(); with_nonce(( 200, vec![("content-type", "application/pem-certificate-chain".into())], @@ -260,14 +265,15 @@ impl FakeAcme { serde_json::json!({"suggestedWindow":{"start":at(self.window.0),"end":at(self.window.1)}}), ) } - _ => json(404, vec![], serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"})), + _ => json( + 404, + vec![], + serde_json::json!({"type":"urn:ietf:params:acme:error:malformed","detail":"no such path"}), + ), } } } -static CERTS: std::sync::LazyLock>> = - std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); - struct Http(Arc); impl HttpClient for Http { @@ -278,7 +284,11 @@ impl HttpClient for Http { let fake = self.0.clone(); Box::pin(async move { let (parts, body) = req.into_parts(); - let bytes = body.collect().await.map_err(|e| Error::Other(e.into()))?.to_bytes(); + let bytes = body + .collect() + .await + .map_err(|e| Error::Other(e.into()))? + .to_bytes(); let path = parts.uri.path().to_owned(); assert_eq!(parts.uri.host(), Some("acme.test")); let (status, headers, out) = fake.handle(parts.method.as_str(), &path, &bytes).await; @@ -301,7 +311,11 @@ impl DnsProof for Proof { fn publish<'a>(&'a self, value: &'a str) -> BoxFuture<'a, Result<(), String>> { Box::pin(async move { let r = self.0.publish_txt(value).await.map_err(|e| e.to_string())?; - if r.ok { Ok(()) } else { Err(r.error.unwrap_or_default()) } + if r.ok { + Ok(()) + } else { + Err(r.error.unwrap_or_default()) + } }) } fn clear(&self) -> BoxFuture<'_, ()> { @@ -384,11 +398,13 @@ async fn an_order_goes_through_account_proof_finalize_and_download() { .unwrap(); let der = leaf_der(&issued.chain_pem).unwrap(); let (nb, na, names) = inspect(&der).unwrap(); - assert_eq!(names, [ident.clone()]); + assert_eq!(names, std::slice::from_ref(&ident)); assert!(nb < certs::now() && na > certs::now()); 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()); + assert!( + certs::StoredCert::new("ledger-accrual-tally-mint", "fake", &issued, &ident, None).is_ok() + ); // The account is kept in a private file, with no contact in it. let file = r.dir.path().join("acme/fake.json"); @@ -396,13 +412,22 @@ async fn an_order_goes_through_account_proof_finalize_and_download() { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!( + std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + { + let st = r.acme.state.lock().unwrap(); + + assert_eq!(st.new_accounts.len(), 1); + assert!( + st.new_accounts[0]["contact"] + .as_array() + .is_none_or(|c| c.is_empty()) + ); + assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true); } - let st = r.acme.state.lock().unwrap(); - assert_eq!(st.new_accounts.len(), 1); - assert!(st.new_accounts[0]["contact"].as_array().is_none_or(|c| c.is_empty())); - assert_eq!(st.new_accounts[0]["termsOfServiceAgreed"], true); - drop(st); // The relay holds no proof once the order is done. let left = support::dns_txt( r.env.relay.dns_udp_addr(), @@ -441,7 +466,10 @@ async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_windo .await .unwrap(); assert_ne!(first.chain_pem, second.chain_pem); - assert_ne!(*first.key_pem, *second.key_pem, "a fresh key for each certificate"); + assert_ne!( + *first.key_pem, *second.key_pem, + "a fresh key for each certificate" + ); { let st = r.acme.state.lock().unwrap(); assert_eq!(st.new_accounts.len(), 1, "the account was reused"); @@ -455,7 +483,10 @@ async fn a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_windo .await .expect("the authority offers a window"); let now = certs::now(); - assert!((now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e), "{s} {e} {now}"); + assert!( + (now + 590..=now + 610).contains(&s) && (now + 890..=now + 910).contains(&e), + "{s} {e} {now}" + ); assert_eq!(r.acme.state.lock().unwrap().ari_gets, 1); } From 13a3f1b51953ad95b7232ffb7b5197e37a408975 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 13:40:00 -0700 Subject: [PATCH 04/11] feat(gui): the web half of the Connect page and the first run (P15 B3) The Connect page gets "On the web": a switch "Allow web assistants" per company, off by default; three lines of progress in plain words (getting an address, getting a certificate, connected) with a spinner on the one under way; once it works, the address for the company with Copy; the three steps for Claude on the web that the plan stands behind (Settings, Connectors, Add custom connector, paste, sign in and match the code); and, for ChatGPT and any other assistant, "we haven't tested this yet" rather than steps nobody tried. What goes wrong is in words and says whether the window and the assistants on this computer are affected. A new address is asked for twice. The first time a company is open and the server says no assistant was ever connected, the Connect page opens by itself, once, remembered per installation. The owner trait gains web_state, web_turn_on, web_turn_off and web_new_address; an owner that does not offer them shows no switch. The tabs tests start with the first run already done, since they are about tabs. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/Cargo.toml | 1 + crates/ledger-gui/src/app.rs | 53 +++ crates/ledger-gui/src/company.rs | 5 + crates/ledger-gui/src/connect.rs | 332 +++++++++++++- crates/ledger-gui/src/owner.rs | 57 +++ crates/ledger-gui/tests/tabs.rs | 13 +- crates/ledger-gui/tests/web_connect.rs | 577 +++++++++++++++++++++++++ 7 files changed, 1026 insertions(+), 12 deletions(-) create mode 100644 crates/ledger-gui/tests/web_connect.rs diff --git a/crates/ledger-gui/Cargo.toml b/crates/ledger-gui/Cargo.toml index 3040b7a9..1b95eec0 100644 --- a/crates/ledger-gui/Cargo.toml +++ b/crates/ledger-gui/Cargo.toml @@ -50,6 +50,7 @@ chrono = "0.4" egui_kittest = { version = "0.36", features = ["wgpu", "snapshot", "eframe"] } proptest = "1" tempfile = "3" +ledger-link = { path = "../ledger-link" } zip = "9.0.1" [lints] diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 2c92c98f..211c5fb5 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -188,6 +188,10 @@ pub struct App { assistants_ok: bool, /// "Now" for "10 seconds ago", fixed (tests, screenshots) or not. fixed_now: Option>, + /// The Connect page has been opened by itself once, or an assistant has + /// been connected: kept per installation, and never again after that + /// (WB-app-6). + first_connect_done: bool, } /// The warning about assistants that is up (INVARIANT 10). @@ -206,6 +210,9 @@ enum Warn { /// for a moment does not make an assistant that was connected seem gone. const WARN_AGE: std::time::Duration = std::time::Duration::from_secs(60); +/// The kept preference that says the Connect page has opened by itself. +const FIRST_CONNECT_KEY: &str = "first_connect_done"; + /// What a window is called when no company is in front. const TITLE: &str = "wanderbooks"; @@ -334,9 +341,50 @@ impl App { let schemes = SchemeMenu::restored(get, ctx.global_style().visuals.dark_mode); let mut app = Self::bare(ctx, schemes); app.dock_prefs = (get("dock_open"), get("dock_agent")); + app.first_connect_done = get(FIRST_CONNECT_KEY).is_some(); app } + /// The first time a company is open and no assistant has ever been + /// connected, the Connect page opens by itself, once (WB-app-6): a + /// person who installs, starts the app and makes or opens their first + /// company sees the way to connect an assistant without looking for it. + /// "Never connected" is the server's own answer for the whole + /// installation: no key, no session, no web approval. It is asked after + /// the answer is known (never from a guess), it is remembered per + /// installation, and it is not asked again once an assistant exists. + fn first_connect(&mut self, statuses: &[Status]) { + if self.first_connect_done { + return; + } + let Some(roster) = self.connections.roster() else { + return; // not known yet: not a guess + }; + let any = !roster.tokens.is_empty() + || !roster.assistants.is_empty() + || !roster.web_approvals.is_empty() + || !roster.web_pending.is_empty(); + if any { + self.first_connect_done = true; + return; + } + let ready = statuses + .get(self.active) + .is_some_and(|s| s.serves && !s.down && s.link != Link::Unknown); + if !ready { + return; + } + if let Some(v) = self.views.get_mut(self.active) { + v.open_connect(); + self.first_connect_done = true; + } + } + + /// Whether the Connect page has opened by itself already (tests). + pub fn first_connect_done(&self) -> bool { + self.first_connect_done + } + /// The first-run page, if it is up (tests). pub fn welcome(&self) -> Option<&crate::welcome::Welcome> { self.welcome.as_ref() @@ -381,6 +429,7 @@ impl App { warn: Warn::Off, assistants_ok: false, fixed_now: None, + first_connect_done: false, } } @@ -1233,6 +1282,7 @@ impl eframe::App for App { for (v, s) in self.views.iter_mut().zip(&statuses) { v.set_assist(s.clone()); } + self.first_connect(&statuses); let tabs: Vec = self .views .iter() @@ -1280,6 +1330,9 @@ impl eframe::App for App { fn save(&mut self, storage: &mut dyn eframe::Storage) { self.schemes.keep(&mut |k, v| storage.set_string(k, v)); + if self.first_connect_done { + storage.set_string(FIRST_CONNECT_KEY, "1".to_string()); + } // The dock, as the front tab has it, else as it was kept. match self.active_view() { Some(v) => v.dock_ref().keep(&mut |k, v| storage.set_string(k, v)), diff --git a/crates/ledger-gui/src/company.rs b/crates/ledger-gui/src/company.rs index 0757b15d..e81df1c5 100644 --- a/crates/ledger-gui/src/company.rs +++ b/crates/ledger-gui/src/company.rs @@ -228,6 +228,11 @@ impl CompanyView { self.assist = status; } + /// Open the Connect page (the first run does, once: app.rs). + pub fn open_connect(&mut self) { + self.nav.go(Route::Connect); + } + /// What this view was last given of its assistants (tests). pub fn assist(&self) -> &crate::connections::Status { &self.assist diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 00adcbdd..750d687f 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -14,7 +14,8 @@ //! sentence; Connect is a page per company: on this computer, a row //! per tool, and the connections with Revoke); D-77 (bookkeeping is //! through an assistant, the window reads); WB-assist-1, -//! WB-assist-3, WB-assist-4. +//! WB-assist-3, WB-assist-4, WB-assist-6 (the web half), WB-app-6 +//! (the first run). //! INVARIANTS: //! 1. One place per fact: a tab carries the state as a shape (the same //! three shapes everywhere: plugs apart, plugs together, a turning @@ -43,8 +44,9 @@ //! 6. Nothing here blocks the frame: every request of the server runs //! off the UI thread; what is shown while it is not known is "not //! known", never a guess. -//! 7. The web half of the page (the switch, the address, the steps for -//! Claude and ChatGPT) is unit B3's. Unit B1's part of it is here: a +//! 7. The web half of the page (the switch, the progress, the address and +//! the steps) is WB-assist-6's (`State::web_switch`, `web_progress`, +//! `claude_steps`). Unit B1's part of it is here: a //! web assistant that asks to connect is shown to the person, in //! words, as a card that says who is asking, where it is sent back //! to, the address it asked from and what it will be able to do, with @@ -418,6 +420,10 @@ pub struct State { /// The waiting web assistants the person has ticked "let it post /// entries too" for. post_asked: std::collections::BTreeSet, + /// "Get a new address" was clicked once: the second click does it. + new_address_asked: bool, + /// The address was just copied (the time, for the word "Copied"). + copied_at: Option, } /// The two lines an assistant set up by hand needs. @@ -458,16 +464,27 @@ impl State { &mut self, ui: &mut Ui, status: &Status, + book: &str, owner: &Option>, jobs: &crate::jobs::Spawner, ) { - if status.web_pending.is_empty() && status.web_approvals.is_empty() { + let web = owner.as_ref().and_then(|o| o.web_state(book)); + if web.is_none() && status.web_pending.is_empty() && status.web_approvals.is_empty() { return; } let p = pal(ui.ctx()); ui.add_space(24.0); - section(ui, "Assistants on the web"); + section(ui, "On the web"); let mut want: Want = None; + if let Some(web) = &web { + if let Some(w) = self.web_switch(ui, status, book, web, owner) { + want = Some(w); + } + ui.add_space(10.0); + } + if !(status.web_pending.is_empty() && status.web_approvals.is_empty()) { + section(ui, "Assistants on the web"); + } let (shown, more) = newest_waiting(&status.web_pending); for request in shown { if let Some(w) = self.pending_card(ui, status, request, owner) { @@ -819,7 +836,7 @@ impl State { ), }; } - self.web_section(ui, status, &owner, jobs); + self.web_section(ui, status, book, &owner, jobs); ui.add_space(24.0); self.connections(ui, status, book, &owner, jobs); }); @@ -1220,3 +1237,306 @@ fn connection_row( ); } } + +// ---- the web half of the page (plan P15 unit B3) ------------------------------ + +/// The exact steps for Claude on the web, for the address `connector`. +/// Only what the plan can stand behind (plan/served.md 3 and the Connect +/// card there: Settings, Connectors, Add custom connector, paste the +/// address, sign in); the sign-in is this window's (D-83, D-90). +pub fn claude_steps() -> [&'static str; 3] { + [ + "In Claude on the web, open Settings, then Connectors.", + "Choose \u{201c}Add custom connector\u{201d} and paste the address above.", + "Claude opens a sign-in page that shows a code. Come back to this window, check that the code is the same, and choose Allow.", + ] +} + +/// What the page says for ChatGPT: no steps are given, because none were +/// tried (plan 7: "ChatGPT Plus and write tools: OpenAI's two pages +/// disagree"). +pub const CHATGPT_NOTE: &str = "We haven't tested this yet, so there are no steps to give. If you add the address above to ChatGPT as a connector, the sign-in comes to this window the same way."; + +/// What the page says for any other assistant. +pub const OTHER_NOTE: &str = "Other assistants (Gemini, Grok, muse.ai and the like): we haven't tested these yet. The same address may work; the sign-in comes to this window the same way."; + +/// Words for the steps of turning web assistants on: what is done, what is +/// being done, what waits. `current` is the one in progress (none once it +/// is connected). +pub fn web_progress(step: crate::owner::WebStep) -> [(&'static str, Progress); 3] { + use crate::owner::WebStep as S; + let first = match step { + S::Off | S::GettingAddress | S::Connecting => Progress::Now, + _ => Progress::Done, + }; + let second = match step { + S::GettingCertificate => Progress::Now, + S::Connected => Progress::Done, + _ => Progress::Waiting, + }; + let third = match step { + S::Connected => Progress::Done, + _ => Progress::Waiting, + }; + [ + ("Getting an address", first), + ("Getting a certificate", second), + ("Connected", third), + ] +} + +/// Where one of the steps stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Progress { + /// Done. + Done, + /// Being done now. + Now, + /// Not started. + Waiting, +} + +/// A switch: a pill that is on or off, with its label, as one control. +/// The label is its accessible name, so it is found as "Allow web +/// assistants". +fn switch(ui: &mut Ui, on: bool, enabled: bool, label: &str) -> egui::Response { + let p = pal(ui.ctx()); + let size = vec2(40.0, 22.0); + let (rect, resp) = ui.allocate_exact_size( + size, + if enabled { + Sense::click() + } else { + Sense::hover() + }, + ); + if ui.is_rect_visible(rect) { + let t = ui.ctx().animate_bool(resp.id, on); + let fill = if on { p.accent } else { p.border }; + ui.painter().rect_filled( + rect, + CornerRadius::same(11), + fill.gamma_multiply(if enabled { 1.0 } else { 0.5 }), + ); + let r = rect.height() / 2.0 - 3.0; + let x = egui::lerp((rect.left() + r + 3.0)..=(rect.right() - r - 3.0), t); + ui.painter() + .circle_filled(egui::pos2(x, rect.center().y), r, p.surface); + } + let name = label.to_string(); + resp.widget_info(move || { + egui::WidgetInfo::selected(egui::WidgetType::Checkbox, enabled, on, name.clone()) + }); + resp +} + +impl State { + /// The switch, the progress, the address with Copy and the steps + /// (plan 3.3). What the person asks for, if anything. + fn web_switch( + &mut self, + ui: &mut Ui, + status: &Status, + book: &str, + web: &crate::owner::WebConnect, + owner: &Option>, + ) -> Want { + let p = pal(ui.ctx()); + let mut want: Want = None; + let can = owner.is_some() && self.job.is_none(); + ui.horizontal(|ui| { + let resp = switch(ui, web.on, can, "Allow web assistants"); + ui.label(RichText::new("Allow web assistants").font(theme::semibold(14.0))); + if resp.clicked() + && let Some(o) = owner.clone() + { + let b = book.to_string(); + self.new_address_asked = false; + want = Some(if web.on { + ( + "Turning web assistants off".to_string(), + "Turning web assistants off".to_string(), + Box::new(move || o.web_turn_off(&b)) as Box Outcome + Send>, + ) + } else { + ( + "Turning web assistants on".to_string(), + "Turning web assistants on".to_string(), + Box::new(move || o.web_turn_on(&b)) as Box Outcome + Send>, + ) + }); + } + }); + ui.label( + RichText::new(format!( + "Claude and ChatGPT on the web can only reach {} if you give them an address on the internet. Turn this on to get one. Wanderbooks keeps it private to you, and nobody can read what passes through. An assistant on the web still has to be allowed here, by you, each time it connects.", + status.company + )) + .font(theme::regular(13.0)) + .color(p.muted), + ); + if !web.on { + ui.add_space(4.0); + ui.label( + RichText::new(if web.kept { + "Off. Nothing on this computer can be reached from the internet. Turning it on again gives the same address as before." + } else { + "Off. Nothing on this computer can be reached from the internet." + }) + .font(theme::regular(13.0)) + .color(p.muted), + ); + return want; + } + ui.add_space(8.0); + // Progress, in words. + for (words, progress) in web_progress(web.step) { + ui.horizontal(|ui| match progress { + Progress::Done => { + ui.label(RichText::new(icon::CHECK_CIRCLE).color(p.accent)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now if web.problem.is_some() => { + ui.label(RichText::new(icon::WARNING).color(p.warning)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now => { + ui.spinner(); + ui.label(RichText::new(format!("{words}\u{2026}")).font(theme::regular(13.5))); + } + Progress::Waiting => { + ui.label(RichText::new(icon::CIRCLE).color(p.muted)); + ui.label( + RichText::new(words) + .font(theme::regular(13.5)) + .color(p.muted), + ); + } + }); + } + if web.step != crate::owner::WebStep::Connected || web.problem.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } + if let Some(problem) = &web.problem { + ui.add_space(4.0); + ui.label( + RichText::new(problem) + .font(theme::regular(13.0)) + .color(p.warning), + ); + if !web.needs_person { + ui.label( + RichText::new( + "Your assistants on this computer, and this window, are not affected.", + ) + .font(theme::regular(12.5)) + .color(p.muted), + ); + } + } + // The address is shown once it works (or while the page says why it + // does not): not before, so nobody pastes one that cannot answer yet. + if let Some(connector) = web + .connector + .as_ref() + .filter(|_| web.step == crate::owner::WebStep::Connected || web.problem.is_some()) + { + ui.add_space(10.0); + ui.label(RichText::new("The address to give an assistant").font(theme::semibold(13.5))); + ui.horizontal(|ui| { + Frame::new() + .fill(p.surface) + .stroke(Stroke::new(1.0, p.border)) + .corner_radius(CornerRadius::same(6)) + .inner_margin(Margin::symmetric(8, 5)) + .show(ui, |ui| { + ui.add( + egui::Label::new( + RichText::new(connector).font(egui::FontId::monospace(12.5)), + ) + .selectable(true), + ); + }); + let copy = ui.button(format!("{} Copy", icon::COPY)); + if copy.clicked() { + ui.ctx().copy_text(connector.clone()); + self.copied_at = Some(ui.input(|i| i.time)); + } + copy.widget_info(|| { + egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Copy the address") + }); + if let Some(at) = self.copied_at { + if ui.input(|i| i.time) - at < 3.0 { + ui.label( + RichText::new("Copied") + .font(theme::regular(12.5)) + .color(p.muted), + ); + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } else { + self.copied_at = None; + } + } + }); + ui.label( + RichText::new("Keep this address to yourself: anyone who has it can ask to connect (you would still be asked first).") + .font(theme::regular(12.5)) + .color(p.muted), + ); + ui.add_space(10.0); + ui.label(RichText::new("Claude on the web").font(theme::semibold(13.5))); + for (i, step) in claude_steps().iter().enumerate() { + ui.label(RichText::new(format!("{}. {step}", i + 1)).font(theme::regular(13.0))); + } + ui.add_space(8.0); + ui.label(RichText::new("ChatGPT").font(theme::semibold(13.5))); + ui.label( + RichText::new(CHATGPT_NOTE) + .font(theme::regular(13.0)) + .color(p.muted), + ); + ui.add_space(8.0); + ui.label(RichText::new("Another assistant").font(theme::semibold(13.5))); + ui.label( + RichText::new(OTHER_NOTE) + .font(theme::regular(13.0)) + .color(p.muted), + ); + } + // A new address, behind a confirmation. + ui.add_space(12.0); + if self.new_address_asked { + ui.label( + RichText::new("The old address stops working at once. Every assistant connected through it has to be connected again with the new one.") + .font(theme::regular(13.0)) + .color(p.warning), + ); + ui.horizontal(|ui| { + if ui + .add_enabled(can, egui::Button::new("Get a new address")) + .clicked() + && let Some(o) = owner.clone() + { + let b = book.to_string(); + self.new_address_asked = false; + want = Some(( + "Getting a new address".to_string(), + "Getting a new address".to_string(), + Box::new(move || o.web_new_address(&b)), + )); + } + if ui.button("Keep the old one").clicked() { + self.new_address_asked = false; + } + }); + } else if ui + .add_enabled(can, egui::Button::new("Get a new address\u{2026}")) + .clicked() + { + self.new_address_asked = true; + } + want + } +} diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index ccac21cd..a10aaa4f 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -253,6 +253,44 @@ pub struct WebApproval { pub last_used: Option, } +/// How far web assistants have got for a company (plan P15 B3): the steps +/// the page tells in words. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WebStep { + /// Off. + Off, + /// Getting an address. + GettingAddress, + /// Making the line to the relay. + Connecting, + /// The line is up; the certificate is being got. + GettingCertificate, + /// A web assistant can reach the company now. + Connected, +} + +/// What the Connect page shows of one company's web assistants. Read from +/// memory by the owner, every frame, never a wait. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WebConnect { + /// The switch. + pub on: bool, + /// How far it has got. + pub step: WebStep, + /// The address for the whole installation, while on. + pub address: Option, + /// The address an assistant is given for this company. + pub connector: Option, + /// A line of progress, in words. + pub words: String, + /// What is wrong, in words. + pub problem: Option, + /// The problem needs the person (it will not mend itself). + pub needs_person: bool, + /// An address is kept for when web assistants are turned on again. + pub kept: bool, +} + /// Who is connected and who may connect, across the open companies. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Roster { @@ -349,6 +387,25 @@ pub trait Owner: Send + Sync { fn web_set_post(&self, _approval: &str, _post: bool) -> Result { Err("not here".into()) } + /// The company's web assistants as they stand: `None` when this window + /// has no way to offer them (the switch is not drawn). Reads memory; + /// never waits. + fn web_state(&self, _book: &str) -> Option { + None + } + /// Turn web assistants on for the company: `Ok` says what happens next + /// in words. Blocks (a request or two of the server). + fn web_turn_on(&self, _book: &str) -> Result { + Err("not here".into()) + } + /// Turn them off for the company. Blocks. + fn web_turn_off(&self, _book: &str) -> Result { + Err("not here".into()) + } + /// A new address for web assistants: the old one stops working. Blocks. + fn web_new_address(&self, _book: &str) -> Result { + Err("not here".into()) + } /// This program run with `words`, as a line to type in a terminal (the /// program's own path, the words, the data root if one was named): what /// the Connect page shows for an assistant it has no button for. diff --git a/crates/ledger-gui/tests/tabs.rs b/crates/ledger-gui/tests/tabs.rs index 515176a8..d2e6f193 100644 --- a/crates/ledger-gui/tests/tabs.rs +++ b/crates/ledger-gui/tests/tabs.rs @@ -225,12 +225,13 @@ impl eframe::Storage for Prefs { } fn prefs(pairs: &[(&str, &str)]) -> Prefs { - Prefs( - pairs - .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect(), - ) + // The Connect page opens by itself once, in a window whose server says + // no assistant was ever connected (WB-app-6); these tests are about + // tabs, so that has happened already. + let mut kept: std::collections::BTreeMap = + [("first_connect_done".to_string(), "1".to_string())].into(); + kept.extend(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string()))); + Prefs(kept.into_iter().collect()) } /// The app as it starts from `kept`, over `world`'s data root, its first diff --git a/crates/ledger-gui/tests/web_connect.rs b/crates/ledger-gui/tests/web_connect.rs new file mode 100644 index 00000000..fe9c66a0 --- /dev/null +++ b/crates/ledger-gui/tests/web_connect.rs @@ -0,0 +1,577 @@ +//! The web half of the Connect page (plan P15 unit B3; WB-assist-6, +//! WB-app-6): the switch, the progress in plain words, the address with +//! Copy, the steps, every state the page can be in, and the page opening +//! by itself, once, for a person who has never connected an assistant. +//! +//! ```text +//! GOAL: a person with no technical background turns web assistants on, +//! watches it get an address and a certificate in words, copies the +//! address, follows steps that were tried (and is told plainly where +//! none were), sees what is wrong in words with nothing lost +//! locally, turns it off, and can get a new address after being +//! asked; and a first run shows the Connect page once. +//! SOURCE: plan/p15-app-and-relay.md 3.3 ("Allow web assistants" per +//! company, off by default; the address with Copy; the exact steps +//! for Claude and for ChatGPT; the relay unreachable in words, with +//! nothing lost locally; turning off keeps the name; a new address +//! behind a confirmation), 5 (the plan's research: ChatGPT's two +//! pages disagree, so no steps are written); WB-assist-6, +//! WB-app-6. +//! INVARIANTS: +//! 1. Off by default: the switch is shown off, with no address and no +//! steps, and an owner with no web assistants (`web_state` none) +//! shows no switch at all. +//! 2. The switch calls the owner and nothing else; the state is the +//! owner's, read every frame. +//! 3. The steps for Claude are exactly the three in `claude_steps`; +//! ChatGPT and any other assistant are told "we haven't tested this +//! yet", never given steps nobody tried. +//! 4. A problem that mends itself says the window and the local +//! assistants are not affected; one that needs the person does not +//! say that and says what to do. +//! 5. A new address is asked for twice: the first click only asks. +//! 6. The Connect page opens by itself once, when the window's server +//! says no assistant was ever connected, and never again; with any +//! key, session, approval or waiting request it does not open. +//! SCENARIOS: +//! 1. See the tests below; `web_screenshots` (SHOT_DIR) draws each state +//! light and dark. +//! ``` + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use ledger_core::{AccountType, Currency}; +use ledger_gui::connect::{CHATGPT_NOTE, OTHER_NOTE, Progress, claude_steps, web_progress}; +use ledger_gui::data::Source; +use ledger_gui::nav::Route; +use ledger_gui::owner::{Owner, RestorePlan, Roster, TokenRow, WebConnect, WebStep}; +use ledger_gui::{App, Start}; +use ledger_store::root::{BookId, Root}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +const CONNECTOR: &str = + "https://k3j9x0q7m2z8c5v1b4n6a9s2d.ledger-accrual-tally-mint.wanderbooks.link/b/alpha/mcp"; + +struct World { + _dir: tempfile::TempDir, + root: PathBuf, +} + +impl World { + fn new(companies: &[(&str, &str)]) -> World { + let dir = tempfile::Builder::new() + .prefix("wb-gui-web-") + .tempdir() + .unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + Root::setup(&home, Some(&root), None).unwrap(); + let found = Root::find(Some(&root)).unwrap(); + for (id, name) in companies { + let mut s = found + .create_book(&BookId::parse(id).unwrap(), Currency::USD) + .unwrap(); + s.add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + s.change_settings( + &[ledger_core::settings::Change { + key: "company.name".into(), + value: Some(serde_json::json!(name)), + }], + &ledger_core::settings::Source { + decided_by: "Test".into(), + decided_on: chrono::NaiveDate::from_ymd_opt(2026, 10, 15).unwrap(), + citation: None, + note: None, + }, + ) + .unwrap(); + drop(s); + } + World { _dir: dir, root } + } + + fn source(&self, id: &str) -> Source { + Source { + data_dir: self.root.join("books").join(id), + today: chrono::NaiveDate::from_ymd_opt(2026, 10, 15), + } + } +} + +/// An owner that serves, has web assistants in whatever state a test sets, +/// and says what it was asked. +struct Web { + state: Mutex>, + roster: Mutex, + log: Mutex>, +} + +impl Web { + fn new(state: Option) -> Arc { + Arc::new(Web { + state: Mutex::new(state), + roster: Mutex::new(Roster::default()), + log: Mutex::new(vec![]), + }) + } + + fn set(&self, s: WebConnect) { + *self.state.lock().unwrap() = Some(s); + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } +} + +impl Owner for Web { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + Ok(()) + } + fn serve_open(&self, _book: &str) -> Result, String> { + Ok(None) + } + fn serve_close(&self, _book: &str) -> Result, String> { + Ok(None) + } + fn serve_stop(&self) -> Result, String> { + Ok(None) + } + fn serve_roster(&self) -> Result { + Ok(self.roster.lock().unwrap().clone()) + } + fn command_line(&self, words: &[&str]) -> Result { + Ok(format!("wanderbooks {}", words.join(" "))) + } + fn web_state(&self, _book: &str) -> Option { + self.state.lock().unwrap().clone() + } + fn web_turn_on(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("on {book}")); + Ok("Web assistants are on.".into()) + } + fn web_turn_off(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("off {book}")); + Ok("Web assistants are off.".into()) + } + fn web_new_address(&self, book: &str) -> Result { + self.log.lock().unwrap().push(format!("new {book}")); + Ok("Your new address is ready.".into()) + } + fn new_books(&self, _id: &str, _currency: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _book: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore( + &self, + _source: &str, + _id: Option, + _replace: bool, + ) -> Result { + Err("not here".into()) + } + fn restore(&self, _plan: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + fn connect( + &self, + _agent: ledger_gui::owner::Agent, + _book: &str, + ) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _book: &str, _passphrase: &str) -> Result, String> { + Err("not here".into()) + } +} + +fn off() -> WebConnect { + WebConnect { + on: false, + step: WebStep::Off, + address: None, + connector: None, + words: "Web assistants are off.".into(), + problem: None, + needs_person: false, + kept: false, + } +} + +fn on(step: WebStep) -> WebConnect { + WebConnect { + on: true, + step, + address: Some(CONNECTOR.trim_end_matches("/b/alpha/mcp").into()), + connector: Some(CONNECTOR.into()), + words: String::new(), + problem: None, + needs_person: false, + kept: true, + } +} + +fn token() -> TokenRow { + TokenRow { + id: "t1".into(), + book: "alpha".into(), + name: "agent".into(), + scopes: vec!["read".into()], + created: "2026-11-01T09:00:00Z".into(), + } +} + +fn start(w: &World, owner: &Arc, kept: &[(&str, &str)], dark: bool) -> Harness<'static, App> { + let mut map: HashMap = kept + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + map.insert(ledger_gui::app::open_key(&w.root), "alpha".into()); + map.insert("dark".into(), dark.to_string()); + let (root, fallback) = (w.root.clone(), w.source("alpha")); + let for_app: Arc = owner.clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(1280.0, 1900.0)) + .build_eframe(move |cc| { + let mut app = App::start_with_owner( + &cc.egui_ctx, + &|k| map.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ); + app.set_now("2026-11-21T10:30:00Z".parse().unwrap()); + app + }); + let o: Arc = owner.clone(); + h.state_mut().view_mut(0).unwrap().set_owner(o); + until(&mut h, "the books load", |a| { + a.views().iter().all(|v| v.books().is_some()) + }); + h +} + +fn until(h: &mut Harness<'static, App>, what: &str, ok: impl Fn(&App) -> bool) { + let end = Instant::now() + Duration::from_secs(30); + loop { + h.run_steps(2); + if ok(h.state()) { + return; + } + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// The Connect page, in front, with the server's answer read. +fn connect_page(w: &World, owner: &Arc, dark: bool) -> Harness<'static, App> { + let mut h = start(w, owner, &[("first_connect_done", "1")], dark); + h.state_mut().view_mut(0).unwrap().open_connect(); + h.state().connections().forget(); + h.run_steps(2); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(4); + h +} + +fn texts(h: &Harness<'_, App>) -> String { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut all = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, &mut all); + } + all.join("\n") +} + +fn has(h: &Harness<'_, App>, text: &str) -> bool { + texts(h).contains(text) +} + +fn copied(h: &Harness<'_, App>) -> Vec { + h.output() + .platform_output + .commands + .iter() + .filter_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) + .collect() +} + +/// WB-assist-6 INVARIANT 1: off by default, nothing but the switch and +/// words; and no switch at all when the window cannot offer them. +#[test] +fn the_switch_is_off_by_default_and_an_owner_without_web_assistants_has_none() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let h = connect_page(&w, &owner, false); + let switch = h.get_by_role_and_label(Role::CheckBox, "Allow web assistants"); + assert_eq!( + switch.accesskit_node().toggled(), + Some(egui::accesskit::Toggled::False) + ); + assert!(has( + &h, + "Off. Nothing on this computer can be reached from the internet." + )); + assert!(!has(&h, "The address to give an assistant")); + assert!(!has(&h, "Claude on the web")); + assert!(owner.said().is_empty(), "looking asks nothing of the owner"); + + let none = Web::new(None); + let h = connect_page(&w, &none, false); + assert!( + h.query_by_role_and_label(Role::CheckBox, "Allow web assistants") + .is_none() + ); +} + +/// WB-assist-6 INVARIANTS 2, 3: turned on, the progress in plain words, +/// then the address with Copy, the three steps for Claude, and for ChatGPT +/// and the rest the plain "we haven't tested this yet". +#[test] +fn turning_it_on_shows_progress_then_the_address_the_steps_and_what_was_not_tried() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let mut h = connect_page(&w, &owner, false); + h.get_by_role_and_label(Role::CheckBox, "Allow web assistants") + .click(); + until(&mut h, "the owner was asked", |_| !owner.said().is_empty()); + assert_eq!(owner.said(), ["on alpha"]); + + owner.set(on(WebStep::GettingAddress)); + h.run_steps(4); + assert!(has(&h, "Getting an address\u{2026}")); + assert!(has(&h, "Getting a certificate")); + assert!( + !has(&h, "Add custom connector"), + "no steps before there is an address that works" + ); + + owner.set(on(WebStep::GettingCertificate)); + h.run_steps(4); + assert!(has(&h, "Getting a certificate\u{2026}")); + + owner.set(on(WebStep::Connected)); + h.run_steps(4); + assert!(has(&h, "Connected")); + assert!(has(&h, CONNECTOR)); + for (i, step) in claude_steps().iter().enumerate() { + assert!(has(&h, &format!("{}. {step}", i + 1)), "{step}"); + } + assert!(has(&h, CHATGPT_NOTE) && CHATGPT_NOTE.contains("We haven't tested this yet")); + assert!(has(&h, OTHER_NOTE) && OTHER_NOTE.contains("we haven't tested these yet")); + // The word MCP is nowhere. + assert!(!texts(&h).contains("MCP")); + // Copy puts the address for this company on the clipboard. + h.get_by_role_and_label(Role::Button, "Copy the address") + .click(); + h.step(); + assert_eq!(copied(&h), [CONNECTOR]); + h.run_steps(2); + assert!(has(&h, "Copied")); +} + +/// The progress words are one function: what is done, what is under way, +/// what waits. +#[test] +fn the_progress_steps_are_in_order() { + use Progress::*; + let p = |s| web_progress(s).map(|(_, p)| p); + assert_eq!(p(WebStep::GettingAddress), [Now, Waiting, Waiting]); + assert_eq!(p(WebStep::Connecting), [Now, Waiting, Waiting]); + assert_eq!(p(WebStep::GettingCertificate), [Done, Now, Waiting]); + assert_eq!(p(WebStep::Connected), [Done, Done, Done]); + let words: Vec<_> = web_progress(WebStep::Connected).map(|(w, _)| w).to_vec(); + assert_eq!( + words, + ["Getting an address", "Getting a certificate", "Connected"] + ); +} + +/// WB-assist-6 INVARIANT 4: the relay cannot be reached (nothing is lost, +/// the window and the local assistants work), the clock is wrong (it needs +/// the person), the certificate is waited for. +#[test] +fn what_goes_wrong_is_in_words_and_says_what_is_not_affected() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(WebConnect { + problem: Some("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()), + ..on(WebStep::Connecting) + })); + let h = connect_page(&w, &owner, false); + assert!(has(&h, "This computer can't reach the internet.")); + assert!(has( + &h, + "Your assistants on this computer, and this window, are not affected." + )); + // The local rows are there, above, untouched. + assert!(has(&h, "On this computer")); + + owner.set(WebConnect { + problem: Some("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()), + needs_person: true, + ..on(WebStep::Connecting) + }); + let mut h = h; + h.run_steps(4); + assert!(has(&h, "clock looks wrong")); + assert!(!has(&h, "are not affected")); + + owner.set(WebConnect { + problem: Some( + "Wanderbooks could not get a certificate yet: the authority says no. It keeps trying." + .into(), + ), + ..on(WebStep::GettingCertificate) + }); + h.run_steps(4); + assert!(has(&h, "could not get a certificate yet")); +} + +/// WB-assist-6: off calls the owner; a new address is asked for twice. +#[test] +fn off_and_a_new_address_go_through_the_owner_and_a_new_one_is_asked_twice() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(on(WebStep::Connected))); + let mut h = connect_page(&w, &owner, false); + // The first click only asks. + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + assert!(has(&h, "The old address stops working at once.")); + assert!(owner.said().is_empty()); + // Keeping the old one does nothing. + h.get_by_label("Keep the old one").click(); + h.run_steps(3); + assert!(!has(&h, "The old address stops working at once.")); + assert!(owner.said().is_empty()); + // The second click does it. + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + h.get_by_label("Get a new address").click(); + until(&mut h, "the owner was asked", |_| !owner.said().is_empty()); + assert_eq!(owner.said(), ["new alpha"]); + + h.get_by_role_and_label(Role::CheckBox, "Allow web assistants") + .click(); + until(&mut h, "off", |_| owner.said().len() == 2); + assert_eq!(owner.said()[1], "off alpha"); +} + +/// WB-app-6: the first time a company is open and no assistant was ever +/// connected, the Connect page opens by itself, once. +#[test] +fn the_connect_page_opens_by_itself_once_for_a_first_run() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let mut h = start(&w, &owner, &[], false); + until(&mut h, "the page opens", |a| a.first_connect_done()); + h.run_steps(3); + assert_eq!(h.state().route(), &Route::Connect); + // Local rows first, the web below. + assert!(has(&h, "On this computer") && has(&h, "On the web")); + // The person goes elsewhere: it does not open again. + h.state_mut().view_mut(0).unwrap().goto(Route::Company); + h.run_steps(6); + assert_ne!(h.state().route(), &Route::Connect); +} + +/// WB-app-6: it is remembered per installation, and not for a person who +/// has connected an assistant, or has one waiting. +#[test] +fn the_connect_page_does_not_open_when_it_was_shown_or_an_assistant_exists() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + // Shown before (kept preference). + let owner = Web::new(Some(off())); + let mut h = start(&w, &owner, &[("first_connect_done", "1")], false); + h.run_steps(8); + assert_ne!(h.state().route(), &Route::Connect); + // A key exists. + let owner = Web::new(Some(off())); + owner.roster.lock().unwrap().tokens.push(token()); + let mut h = start(&w, &owner, &[], false); + h.state().connections().forget(); + h.run_steps(6); + assert!(h.state().connections().wait_idle(Duration::from_secs(10))); + h.run_steps(6); + assert_ne!(h.state().route(), &Route::Connect); + assert!( + h.state().first_connect_done(), + "an existing assistant ends the first run for good" + ); +} + +/// Pictures for eyes: set `SHOT_DIR`. Each state of the web half, light and +/// dark. +#[test] +fn web_screenshots() { + let Ok(out) = std::env::var("SHOT_DIR") else { + return; + }; + let out = PathBuf::from(out); + std::fs::create_dir_all(&out).unwrap(); + let w = World::new(&[("alpha", "Wanderland Labs")]); + let states: Vec<(&str, WebConnect, bool)> = vec![ + ("1-off", off(), false), + ("2-getting-an-address", on(WebStep::GettingAddress), false), + ( + "3-getting-a-certificate", + on(WebStep::GettingCertificate), + false, + ), + ("4-connected", on(WebStep::Connected), false), + ( + "5-no-internet", + WebConnect { + problem: Some(ledger_link::Trouble::NoInternet.words()), + ..on(WebStep::Connecting) + }, + false, + ), + ( + "6-clock-wrong", + WebConnect { + problem: Some(ledger_link::Trouble::ClockWrong.words()), + needs_person: true, + ..on(WebStep::Connecting) + }, + false, + ), + ("7-new-address", on(WebStep::Connected), true), + ]; + for dark in [false, true] { + for (name, state, ask) in &states { + let owner = Web::new(Some(state.clone())); + let mut h = connect_page(&w, &owner, dark); + if *ask { + h.get_by_label_contains("Get a new address").click(); + h.run_steps(3); + } + h.run_steps(3); + h.render() + .unwrap() + .save(out.join(format!( + "{name}-{}.png", + if dark { "dark" } else { "light" } + ))) + .unwrap(); + } + } +} From db953c7b5b4aec64cdd6a1f89290c71a21c5005d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 13:40:00 -0700 Subject: [PATCH 05/11] test(cli): web assistants end to end through an in-process relay (P15 B3) The real books server (a child process on a temp root), its remote door and sign-in, the app's link, the relay crate's own in-process relay and an in-process certificate authority: a web caller's TLS through the relay is ended with the app's certificate, signs in with the person's answer made through the admin socket, and reads the books; HTTP/2 reaches the door by its authority; the door drops a connection without the secret; off closes the line and the door and on again is the same address with the same certificate; a new address refuses the old tokens; the switches are put back at the next start. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/web_link.rs | 707 ++++++++++++++++++++++++++++ 1 file changed, 707 insertions(+) create mode 100644 crates/ledger-cli/tests/web_link.rs diff --git a/crates/ledger-cli/tests/web_link.rs b/crates/ledger-cli/tests/web_link.rs new file mode 100644 index 00000000..0d49ddaf --- /dev/null +++ b/crates/ledger-cli/tests/web_link.rs @@ -0,0 +1,707 @@ +//! Web assistants end to end (plan P15 unit B3; WB-link-3, WB-link-6): +//! the real books server (a child process of the test, on a data root of +//! its own), the real remote door and its sign-in, the app's link +//! (`ledger-host` `web.rs` over `ledger-link`), an in-process relay (the +//! relay crate's own) and an in-process certificate authority. A web +//! caller's TLS connection goes through the relay to the app, which ends +//! it with its own certificate and hands it to the door; the caller signs +//! in (the person's answer is made as the window makes it, through the +//! admin socket) and reads the books. Nothing leaves 127.0.0.1. +//! +//! ```text +//! GOAL: a person turns web assistants on for a company; a web assistant +//! reaches the books through the relay at one durable address, +//! signs in with the person's approval and reads them; turning it +//! off closes the line and the door; a new address refuses what the +//! old one signed in; what was on is on again at the next start. +//! SOURCE: plan/p15-app-and-relay.md 3.3, 4, 5; WB-link-3, WB-link-6, +//! WB-remote-1 to WB-remote-6. +//! INVARIANTS: +//! 1. The caller's TLS ends in the app: the certificate it is shown is +//! the app's own, from the authority, never the relay's. +//! 2. The door is on 127.0.0.1 and every connection to it begins with +//! its per-start secret: a connection made straight to it without +//! the secret is dropped; one through the relay is served. +//! 3. The sign-in is the door's own: nothing is approved but by the +//! person's answer, and the address of the caller the door records is +//! the one the relay saw. +//! 4. Off closes the line and the door; the address is kept and the same +//! on again; a new address refuses every token of the old one. +//! SCENARIOS: +//! 1. See the tests below. +//! ``` + +mod common; +#[path = "../../relay/tests/common/mod.rs"] +mod relay_common; + +use base64::Engine as _; +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_mcp::admin::{Request, Response}; +use rcgen::{CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose}; +use relay::proto::Authority; +use rustls::pki_types::ServerName; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::net::SocketAddr; +use std::path::Path; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio_rustls::TlsConnector; +use zeroize::Zeroizing; + +const CLAUDE_CB: &str = "https://claude.ai/api/mcp/auth_callback"; + +fn exe() -> &'static Path { + Path::new(env!("CARGO_BIN_EXE_wanderbooks")) +} + +/// An in-process certificate authority: it takes the proof (which goes to +/// the relay, as a real one's would), and signs for the name asked. +struct Authority_ { + ca: CertifiedIssuer<'static, KeyPair>, + orders: std::sync::atomic::AtomicUsize, +} + +impl Authority_ { + fn new() -> Arc { + let mut params = CertificateParams::new(Vec::::new()).unwrap(); + params.is_ca = IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign]; + let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap(); + Arc::new(Authority_ { + ca, + orders: Default::default(), + }) + } + + fn roots(&self) -> rustls::RootCertStore { + let mut r = rustls::RootCertStore::empty(); + r.add(self.ca.der().clone()).unwrap(); + r + } +} + +impl Issuer for Authority_ { + fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.orders + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + req.dns.publish(&"A".repeat(43)).await?; + req.dns.clear().await; + 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::days(60); + 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, + _a: &'a Authority, + _c: &'a str, + ) -> BoxFuture<'a, Option<(i64, i64)>> { + Box::pin(async { None }) + } +} + +/// The server, as the window talks to it. +struct Srv<'a>(&'a AppServer); + +impl Admin for Srv<'_> { + fn admin(&self, request: Request) -> Result { + self.0.call(request, Some(Duration::from_secs(30))) + } +} + +struct Rig { + home: Home, + server: AppServer, + env: relay_common::Env, + ca: Arc, + web: WebAssistants, +} + +fn start_server(home: &Home) -> AppServer { + let dir = home.dir.path().to_path_buf(); + let server = AppServer::start_in( + exe(), + Some(&home.root()), + &[], + move |c: &mut std::process::Command| { + clean_env(c, &dir); + c.env("XDG_CONFIG_HOME", dir.join(".config")); + }, + ) + .unwrap_or_else(|why| panic!("{why}")); + server.wait_ready(Duration::from_secs(60)).unwrap(); + server +} + +fn web_for(home: &Home, env: &relay_common::Env, ca: &Arc) -> WebAssistants { + let (relay_tls, router, issuer) = (env.line_tls(), env.router(), ca.clone()); + WebAssistants::with_maker( + Some(home.root()), + Box::new(move |dir| { + Ok(LinkConfig { + dir, + domain: relay_common::DOMAIN.into(), + relay_host: relay_common::RELAY_HOST.into(), + dial: Dial::Addr(router), + relay_tls: relay_tls.clone(), + issuer: issuer.clone(), + timing: Timing { + ping_every: Duration::from_millis(500), + backoff_min: Duration::from_millis(50), + backoff_max: Duration::from_millis(400), + ..Timing::default() + }, + }) + }), + ) +} + +async fn rig(tag: &str) -> Rig { + let home = Home::new(tag); + let server = start_server(&home); + home.create(BOOK, "USD"); + server.open_book(BOOK).unwrap(); + let env = relay_common::start_with( + relay_common::quick_limits(), + relay::authorities::AuthorityList::from_toml( + "[[authority]]\nid = \"test\"\ndirectory = \"https://ca.example/dir\"\ncaa_domain = \"ca.example\"\n", + ) + .unwrap(), + ) + .await; + let ca = Authority_::new(); + let web = web_for(&home, &env, &ca); + Rig { + home, + server, + env, + ca, + web, + } +} + +fn wait_connected(r: &Rig) -> ledger_host::web::WebState { + let end = Instant::now() + Duration::from_secs(40); + loop { + let s = r.web.state(BOOK); + if s.step == Step::Connected { + return s; + } + assert!( + Instant::now() < end, + "never connected: {:?} {:?}", + s.step, + s.problem + ); + std::thread::sleep(Duration::from_millis(50)); + } +} + +fn host_of(connector: &str) -> String { + connector + .trim_start_matches("https://") + .split('/') + .next() + .unwrap() + .to_owned() +} + +struct Resp { + status: u16, + headers: Vec<(String, String)>, + body: String, +} + +impl Resp { + fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + + fn json(&self) -> Value { + serde_json::from_str(&self.body).unwrap_or_else(|_| panic!("not JSON: {}", self.body)) + } +} + +fn parse(raw: &[u8]) -> Resp { + let split = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .unwrap_or_else(|| panic!("no response: {:?}", String::from_utf8_lossy(raw))); + let head = String::from_utf8_lossy(&raw[..split]).to_string(); + let mut lines = head.lines(); + let status = lines + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); + let headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':')) + .map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + .collect(); + let rest = &raw[split + 4..]; + let chunked = headers + .iter() + .any(|(k, v)| k.eq_ignore_ascii_case("transfer-encoding") && v.contains("chunked")); + let body = if chunked { + let (mut out, mut body) = (Vec::new(), rest); + while let Some(at) = body.windows(2).position(|w| w == b"\r\n") { + let size = usize::from_str_radix(std::str::from_utf8(&body[..at]).unwrap().trim(), 16) + .unwrap_or(0); + if size == 0 { + break; + } + out.extend_from_slice(&body[at + 2..at + 2 + size]); + body = &body[at + 2 + size + 2..]; + } + out + } else { + rest.to_vec() + }; + Resp { + status, + headers, + body: String::from_utf8_lossy(&body).to_string(), + } +} + +fn tls(roots: rustls::RootCertStore, alpn: &[&[u8]]) -> TlsConnector { + let mut cfg = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + cfg.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect(); + TlsConnector::from(Arc::new(cfg)) +} + +/// One HTTP/1.1 request, as a web assistant's vendor would send it: TLS to +/// the relay's address with the app's host name, the whole answer. +async fn https( + r: &Rig, + host: &str, + method: &str, + path: &str, + extra: &[(&str, &str)], + body: &str, +) -> std::io::Result { + let tcp = TcpStream::connect(r.env.router()).await?; + let mut t = tokio::time::timeout( + Duration::from_secs(10), + tls(r.ca.roots(), &[b"http/1.1"]) + .connect(ServerName::try_from(host.to_owned()).unwrap(), tcp), + ) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "no handshake"))??; + let mut text = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); + for (k, v) in extra { + text.push_str(&format!("{k}: {v}\r\n")); + } + text.push_str(&format!("Content-Length: {}\r\n\r\n{body}", body.len())); + t.write_all(text.as_bytes()).await?; + let mut out = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(20), t.read_to_end(&mut out)).await; + Ok(parse(&out)) +} + +fn pct(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + char::from(b).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} + +fn form(pairs: &[(&str, &str)]) -> String { + pairs + .iter() + .map(|(k, v)| format!("{}={}", pct(k), pct(v))) + .collect::>() + .join("&") +} + +fn pkce(n: u32) -> (String, String) { + let verifier = format!("verifier-{n}-{}", "x".repeat(40)); + let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD + .encode(Sha256::digest(verifier.as_bytes())); + (verifier, challenge) +} + +/// The whole sign-in of a Claude-like client at `host`, the person's +/// answer made through the admin socket: the access token. The address +/// the door recorded for the request is returned too. +async fn sign_in(r: &Rig, host: &str, n: u32) -> (String, String) { + let reg = https( + r, + host, + "POST", + "/register", + &[("Content-Type", "application/json")], + &json!({"client_name": "Claude", "redirect_uris": [CLAUDE_CB]}).to_string(), + ) + .await + .unwrap(); + assert_eq!(reg.status, 201, "{}", reg.body); + let client = reg.json()["client_id"].as_str().unwrap().to_owned(); + let (verifier, challenge) = pkce(n); + let resource = format!("https://{host}/b/{BOOK}/mcp"); + let path = format!( + "/authorize?{}", + form(&[ + ("response_type", "code"), + ("client_id", &client), + ("redirect_uri", CLAUDE_CB), + ("code_challenge", &challenge), + ("code_challenge_method", "S256"), + ("state", "st-123"), + ("resource", &resource), + ("scope", "books:read books:write"), + ]) + ); + let page = https(r, host, "GET", &path, &[], "").await.unwrap(); + assert_eq!(page.status, 200, "{}", page.body); + let at = page + .body + .find("url=/authorize/wait/") + .expect("a waiting page"); + let rest = &page.body[at + 4..]; + let wait = rest[..rest.find('"').unwrap()].to_string(); + // The person, in the window: the request is listed with the caller's + // address, and allowed. + let pending = match r + .server + .call(Request::RemotePending, Some(Duration::from_secs(30))) + .unwrap() + { + Response::RemotePending(p) => p, + other => panic!("{other:?}"), + }; + assert_eq!(pending.len(), 1, "{pending:?}"); + let from = pending[0].from.clone(); + match r + .server + .call( + Request::RemoteDecide { + id: pending[0].id.clone(), + approve: true, + post: false, + }, + Some(Duration::from_secs(30)), + ) + .unwrap() + { + Response::RemoteDecided { .. } => {} + other => panic!("{other:?}"), + } + let back = https(r, host, "GET", &wait, &[], "").await.unwrap(); + assert_eq!(back.status, 302, "{}", back.body); + let location = back.header("location").unwrap().to_owned(); + let code = location + .split(['?', '&']) + .find_map(|p| p.strip_prefix("code=")) + .unwrap() + .to_owned(); + let token = https( + r, + host, + "POST", + "/token", + &[("Content-Type", "application/x-www-form-urlencoded")], + &form(&[ + ("grant_type", "authorization_code"), + ("client_id", &client), + ("code", &code), + ("code_verifier", &verifier), + ("redirect_uri", CLAUDE_CB), + ]), + ) + .await + .unwrap(); + assert_eq!(token.status, 200, "{}", token.body); + ( + token.json()["access_token"].as_str().unwrap().to_owned(), + from, + ) +} + +async fn mcp(r: &Rig, host: &str, token: Option<&str>, body: Value) -> Resp { + let bearer = token.map(|t| format!("Bearer {t}")); + let mut extra = vec![ + ("Content-Type", "application/json"), + ("Accept", "application/json, text/event-stream"), + ("MCP-Protocol-Version", "2025-06-18"), + ]; + if let Some(b) = &bearer { + extra.push(("Authorization", b)); + } + https( + r, + host, + "POST", + &format!("/b/{BOOK}/mcp"), + &extra, + &body.to_string(), + ) + .await + .unwrap() +} + +fn initialize() -> Value { + json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{}, + "clientInfo":{"name":"claude-web-test","version":"1"}}}) +} + +fn on(r: &Rig) -> ledger_host::web::WebState { + r.web.turn_on(&Srv(&r.server), BOOK).unwrap(); + wait_connected(r) +} + +/// INVARIANTS 1 to 3: a web assistant signs in through the relay and reads +/// the books; the certificate it was shown is the app's; the door refuses a +/// connection that comes straight to it without the secret. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_web_assistant_signs_in_through_the_relay_and_reads_the_books() { + let r = rig("web-e2e").await; + let s = on(&r); + let connector = s.connector.clone().unwrap(); + let host = host_of(&connector); + assert!(connector.ends_with(&format!("/b/{BOOK}/mcp"))); + // Off by default, then on: one order for the certificate. + assert_eq!(r.ca.orders.load(std::sync::atomic::Ordering::SeqCst), 1); + + // Unsigned: the door says where to sign in (a 401), through the relay. + let unsigned = mcp(&r, &host, None, initialize()).await; + assert_eq!(unsigned.status, 401, "{}", unsigned.body); + assert!(unsigned.header("www-authenticate").unwrap().contains(&host)); + + // Signed in, with the person's answer, the books are read. + let (token, from) = sign_in(&r, &host, 1).await; + assert!( + from.starts_with("127.0.0.1"), + "the door records the address the relay saw: {from}" + ); + let init = mcp(&r, &host, Some(&token), initialize()).await; + assert_eq!(init.status, 200, "{}", init.body); + let start = mcp( + &r, + &host, + Some(&token), + json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"books.start","arguments":{}}}), + ) + .await; + assert_eq!(start.status, 200, "{}", start.body); + let text = start.json()["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default() + .to_owned(); + assert!(text.contains(BOOK) || !text.is_empty(), "{}", start.body); + + // The relay's own certificate is not the one the caller was shown: a + // caller that trusts only the relay's CA cannot talk to the app. + let tcp = TcpStream::connect(r.env.router()).await.unwrap(); + let wrong = tls(r.env.relay_ca.roots(), &[b"http/1.1"]) + .connect(ServerName::try_from(host.clone()).unwrap(), tcp) + .await; + assert!(wrong.is_err(), "the relay holds no certificate for the app"); + + // The door, reached straight on 127.0.0.1 without the secret, drops the + // connection before it says anything. + let door: SocketAddr = match r + .server + .call(Request::RemoteStatus, Some(Duration::from_secs(30))) + .unwrap() + { + Response::Remote(info) => info.listening.unwrap().parse().unwrap(), + other => panic!("{other:?}"), + }; + let mut straight = TcpStream::connect(door).await.unwrap(); + let _ = straight + .write_all(b"GET /b/acme/mcp HTTP/1.1\r\nHost: x\r\n\r\n") + .await; + let mut got = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(10), straight.read_to_end(&mut got)).await; + assert!(got.is_empty(), "no answer without the secret: {got:?}"); +} + +/// INVARIANT 2, HTTP/2: the same connection over h2, which has no Host +/// header but an authority, reaches the door too. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_door_answers_http2_by_its_authority() { + let r = rig("web-h2").await; + let host = host_of(&on(&r).connector.unwrap()); + let tcp = TcpStream::connect(r.env.router()).await.unwrap(); + let t = tls(r.ca.roots(), &[b"h2"]) + .connect(ServerName::try_from(host.clone()).unwrap(), tcp) + .await + .unwrap(); + assert_eq!(t.get_ref().1.alpn_protocol(), Some(&b"h2"[..])); + let (mut send, conn) = + hyper::client::conn::http2::handshake::<_, _, http_body_util::Empty>( + hyper_util::rt::TokioExecutor::new(), + hyper_util::rt::TokioIo::new(t), + ) + .await + .unwrap(); + tokio::spawn(conn); + let req = hyper::Request::builder() + .method("GET") + .uri(format!("https://{host}/b/{BOOK}/mcp")) + .body(http_body_util::Empty::new()) + .unwrap(); + let resp = tokio::time::timeout(Duration::from_secs(10), send.send_request(req)) + .await + .unwrap() + .unwrap(); + assert_eq!(resp.status(), 401); + assert!( + resp.headers()["www-authenticate"] + .to_str() + .unwrap() + .contains(&host) + ); +} + +/// INVARIANT 4: off closes the line and the door and keeps the address; on +/// again is the same address and signs in again. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn off_closes_the_line_and_the_door_and_on_again_is_the_same_address() { + let r = rig("web-off").await; + let before = on(&r); + let host = host_of(&before.connector.clone().unwrap()); + assert_eq!(r.env.relay.shared().lines.len(), 1); + + let said = r.web.turn_off(&Srv(&r.server), BOOK).unwrap(); + assert!(said.contains("kept"), "{said}"); + let s = r.web.state(BOOK); + assert!(!s.on && s.step == Step::Off && s.kept); + // The line is gone at the relay, and the door no longer listens. + let end = Instant::now() + Duration::from_secs(10); + while !r.env.relay.shared().lines.is_empty() { + assert!(Instant::now() < end, "the relay still has the line"); + tokio::time::sleep(Duration::from_millis(25)).await; + } + match r + .server + .call(Request::RemoteStatus, Some(Duration::from_secs(30))) + .unwrap() + { + Response::Remote(info) => { + assert!( + info.listening.is_none() && info.public_url.is_none(), + "{info:?}" + ); + } + other => panic!("{other:?}"), + } + assert!( + tokio::time::timeout(Duration::from_secs(10), async { + let tcp = TcpStream::connect(r.env.router()).await.unwrap(); + tls(r.ca.roots(), &[b"http/1.1"]) + .connect(ServerName::try_from(host.clone()).unwrap(), tcp) + .await + }) + .await + .unwrap() + .is_err(), + "no line, no TLS" + ); + + // On again: the same address, and the sign-in works. + let after = on(&r); + assert_eq!(after.connector, before.connector); + assert_eq!( + r.ca.orders.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the certificate was kept" + ); + let (token, _) = sign_in(&r, &host, 2).await; + assert_eq!(mcp(&r, &host, Some(&token), initialize()).await.status, 200); +} + +/// INVARIANT 4: a new address stops the old one, and every token made at +/// the old address is refused at the new. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_new_address_refuses_what_the_old_one_signed_in() { + let r = rig("web-new").await; + let old_connector = on(&r).connector.unwrap(); + let old = host_of(&old_connector); + let (token, _) = sign_in(&r, &old, 3).await; + assert_eq!(mcp(&r, &old, Some(&token), initialize()).await.status, 200); + + let said = r.web.new_address(&Srv(&r.server)).unwrap(); + assert!(said.contains("old one has stopped working"), "{said}"); + let new_connector = wait_connected(&r).connector.unwrap(); + assert_ne!(new_connector, old_connector); + let new = host_of(&new_connector); + // The old address gets no TLS at all. + let tcp = TcpStream::connect(r.env.router()).await.unwrap(); + assert!( + tls(r.ca.roots(), &[b"http/1.1"]) + .connect(ServerName::try_from(old.clone()).unwrap(), tcp) + .await + .is_err() + ); + // The old token at the new address is refused; a new sign-in works. + assert_eq!(mcp(&r, &new, Some(&token), initialize()).await.status, 401); + let (fresh, _) = sign_in(&r, &new, 4).await; + assert_eq!(mcp(&r, &new, Some(&fresh), initialize()).await.status, 200); + assert_eq!( + r.ca.orders.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the wildcard certificate serves the new label" + ); +} + +/// INVARIANT 4 (WB-link-6): what was on when the app closed is on again at +/// the next start, for the company that is open, at the same address. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_switches_are_put_back_at_the_next_start() { + let mut r = rig("web-restore").await; + let before = on(&r).connector.unwrap(); + // The app closes: the line ends with it, the switch stays on disk. + r.web.shutdown(); + drop(std::mem::replace( + &mut r.web, + web_for(&r.home, &r.env, &r.ca), + )); + assert!( + !r.web.state(BOOK).on, + "a new start begins off, until put back" + ); + r.web.restore(&Srv(&r.server), &[BOOK.to_string()]); + let after = wait_connected(&r).connector.unwrap(); + assert_eq!(after, before); + assert_eq!(r.ca.orders.load(std::sync::atomic::Ordering::SeqCst), 1); + // A company that is not open waits for its tab: nothing is put back. + let r2 = rig("web-restore-none").await; + r2.web.restore(&Srv(&r2.server), &[BOOK.to_string()]); + assert!(!r2.web.state(BOOK).on, "never turned on, never put back"); +} From 14c1a26bfc471680868de789f99376bcc5fa026a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 13:40:00 -0700 Subject: [PATCH 06/11] docs(spec): WB-link-1 to 6, WB-assist-6, WB-app-6 for the app's side of the relay (P15 B3) The claims for the identity, the line, TLS at the app, certificates, the states in words and the per-company switch, the Connect page's web half and the first run; parity.md, the architecture table and the plan's follow-ups (what B3 left out and why: certificate-log watching, steps for products nobody tried, the key for key-only products, a real relay and authority). Co-Authored-By: Claude Fable 5.2 --- docs/architecture.md | 4 +- docs/parity.md | 3 +- docs/spec/claims/app.md | 14 +++ docs/spec/claims/assistants.md | 31 ++++- docs/spec/claims/link.md | 215 +++++++++++++++++++++++++++++++++ plan/p15-app-and-relay.md | 29 ++++- 6 files changed, 292 insertions(+), 4 deletions(-) create mode 100644 docs/spec/claims/link.md diff --git a/docs/architecture.md b/docs/architecture.md index afee12cb..c9cd1871 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,7 +36,9 @@ the specification in `bookspec/` (which never depends on the engine). | `ledger-import` | formats: QuickBooks CSV in; IIF, XLSX, Typst PDFs (statements, the invoice, labels, the audit workpaper) out | `ledger-core`, `ledger-reader` | | `ledger-package` | the shared read-only view over `Store` or `Snapshot` (`PackageBooks`): the CPA package, the 1099 worksheet, the invoice document, Needs attention | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-vault` | | `ledger-mcp` | the books server: the MCP tools (122), resources, the handbook, scopes, the door and the access log, backups' scheduling | all of the above | -| `ledger-host` | the app's books server as the window's child (`app_server`, P15), the headless host and its leases (`serve` alone starts one), the agent bridge (`wanderbooks mcp`, a line to whatever runs), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config` | +| `relay` | the relay for `wanderbooks.link` (P15 B2): routes a web caller's TLS by name down the app's line, and is the domain's DNS; its `proto`, `names`, `mux` and `client` modules are the app's side of the wire too | none of ours | +| `ledger-link` | the app's side of the relay (P15 B3): the durable address (key, four-word name, secret label), the one outbound line with backoff and pings, TLS ended in the app, the app's own certificate by ACME DNS-01 (the authority is the relay's list, behind an `Issuer` trait) and its renewals; runs in the window's process | `relay` (and `ledger-store`, Windows only, for the owner-only file helper) | +| `ledger-host` | the app's books server as the window's child (`app_server`, P15), the headless host and its leases (`serve` alone starts one), the agent bridge (`wanderbooks mcp`, a line to whatever runs), tokens in 0600 files under the data root (D-63), the owner's commands, uploads and downloads, `update` and `rollback` (P11a), books homes and how to start an agent in one (P11b) | `ledger-store`, `ledger-mcp`, `ledger-config`, `ledger-link` | | `ledger-gui` | the viewer: read-only, live, egui, one window with a tab per open company (P15); the Books menu hands work to the server; the agent dock and the first-run page (P11b) | `ledger-core`, `ledger-store`, `ledger-config`, `ledger-import`, `ledger-package`, `ledger-vault`, `ledger-host` | | `ledger-cli` | `wanderbooks`, the one executable: every mode (`serve`, `server`, `host`, `mcp`, `gui`, `setup`, `books`, `token`, `connect`, `doctor`, `licenses`, …) and the over-the-wire test suites | everything | | `bookspec/checker`, `bookspec/runner` | the example schema and parser, the rule catalogue, the `Engine` trait; the per-rule runner | nothing of ours (the adapter in `ledger-core`'s tests depends on them) | diff --git a/docs/parity.md b/docs/parity.md index f1ee845e..74dc44b6 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -270,7 +270,8 @@ product's own sign-in has been tried against it yet. | Area | Counterpart (a cross-check, not the spec) | Status | Notes | |---|---|---|---| -| Web assistants reach a company over HTTPS and sign in with OAuth 2.1, approved by the person in the app's window; read and draft by default, posting per connection | QBO's and Xero's "connected apps" consent screens are a cross-check only | partial | WB-remote-1 to WB-remote-10, WB-assist-5; `ledger-mcp` unit tests in `src/local/remote/` (`tests.rs`, `proxy.rs`, `cimd.rs`, `pages.rs`), `ledger-gui` `tests/assistants.rs`; open: reached through the relay (B3), tried with Claude and ChatGPT on the web, uploads and downloads over this door | +| Web assistants reach a company over HTTPS and sign in with OAuth 2.1, approved by the person in the app's window; read and draft by default, posting per connection | QBO's and Xero's "connected apps" consent screens are a cross-check only | partial | WB-remote-1 to WB-remote-10, WB-assist-5; `ledger-mcp` unit tests in `src/local/remote/` (`tests.rs`, `proxy.rs`, `cimd.rs`, `pages.rs`), `ledger-gui` `tests/assistants.rs`; open: tried with Claude and ChatGPT on the web, uploads and downloads over this door | +| Web assistants are turned on per company in the app (off by default), reached through the relay at one durable private address with the app's own certificate, and the page says in plain words how far it has got and what is wrong | Tailscale Funnel and Home Assistant Cloud do the same (a cross-check only) | partial | WB-link-1 to WB-link-6, WB-assist-6, WB-app-6; `ledger-link` `tests/link.rs` and `tests/acme.rs`, `ledger-cli` `tests/web_link.rs`, `ledger-gui` `tests/web_connect.rs`; open: the relay and a certificate authority are only tried in-process (never a real relay or authority), steps for ChatGPT and others (none written: untested), a key for products that take only a key, watching the certificate logs for a certificate the app did not ask for | ## P15 T1: every write is one transaction, exactly once (2026-11-21, D-88, D-89) diff --git a/docs/spec/claims/app.md b/docs/spec/claims/app.md index 98bd9e1e..791afacb 100644 --- a/docs/spec/claims/app.md +++ b/docs/spec/claims/app.md @@ -235,3 +235,17 @@ and its test that a list with nothing running says which books wait for an upgra `a_command_racing_the_apps_start_joins_the_app`, `two_commands_at_once_with_nothing_running_both_do_their_work`, `a_bridge_that_held_a_host_follows_the_app_that_takes_its_place`). + +**WB-app-6 A first run opens the Connect page once.** After a person makes or +opens their first company, and the window's server says no assistant was ever +connected (no key, no session, no web approval, none waiting, for any +company), the window opens the Connect page by itself, once, with the tools on +this computer first and the web below. It is remembered for the installation +and never happens again, whatever is connected or revoked later; an +installation that has an assistant never sees it. It is asked only after the +server has answered, never from a guess, and not in a window that has no +server. +*Enforced:* `ledger_gui::app::App::first_connect`. +*Checked:* `ledger-gui` `tests/web_connect.rs` +(`the_connect_page_opens_by_itself_once_for_a_first_run`, +`the_connect_page_does_not_open_when_it_was_shown_or_an_assistant_exists`). diff --git a/docs/spec/claims/assistants.md b/docs/spec/claims/assistants.md index 6d600d86..1693c7f3 100644 --- a/docs/spec/claims/assistants.md +++ b/docs/spec/claims/assistants.md @@ -88,7 +88,7 @@ when it connected and last acted, and "Revoke", asked once, which calls what `wanderbooks token revoke` calls (the server ends the key and the sessions on it; its copy in the token file is removed). The window writes no books. The web half of the page (the switch, the address, the steps for Claude and -ChatGPT) is plan unit B3's, and the "Claude desktop app" row (a one-click +ChatGPT) is WB-assist-6's (plan unit B3), and the "Claude desktop app" row (a one-click extension) is unit C1's. What unit B1 puts in `connect::State::web_section` is the question to the person when a web assistant asks to connect (WB-remote-5): a card that says who is asking, where it is sent back to, the address it asked @@ -126,3 +126,32 @@ SCENARIOS: *Enforced:* `first_tools_lead`, `connect_text`, `list_tools` (the server's `BooksServer`). *Checked:* `ledger-mcp` unit test `the_company_and_the_entry_point_are_in_the_first_tools_too`. + +**WB-assist-6 The Connect page's web half turns web assistants on and says, in +plain words, how far it has got and what to do.** Under "On the web" the page +has a switch "Allow web assistants" for the company, off by default; off, it +says nothing on this computer can be reached from the internet, and that +turning it on again gives the same address if one was kept. On, it tells the +progress in three lines (getting an address, getting a certificate, connected) +with a spinner on the one under way, then the address an assistant is given +for this company with a Copy button, and the steps. The steps for Claude on the +web are three, the ones the plan stands behind (Settings, then Connectors; Add +custom connector, paste the address; sign in, and match the code in this +window before choosing Allow). For ChatGPT, and for any other assistant, the +page says "we haven't tested this yet" and gives no steps: the plan records +that OpenAI's two pages disagree, and a step nobody tried is not written. A +problem is in words: one that mends itself (no internet, the relay down or +busy, a certificate not yet got) says the window and the assistants on this +computer are not affected and that it keeps trying; one that needs the person +(a wrong clock, a lost address) says what to do. "Get a new address" asks +first: the old address stops working at once and every assistant connected +through it has to be connected again. The switch is the owner's: the page +only asks it. The word "MCP" is nowhere on the page. +*Enforced:* `ledger_gui::connect::State::web_section`, `claude_steps`, +`web_progress`, `web_state`. +*Checked:* `ledger-gui` `tests/web_connect.rs` +(`the_switch_is_off_by_default_and_an_owner_without_web_assistants_has_none`, +`turning_it_on_shows_progress_then_the_address_the_steps_and_what_was_not_tried`, +`the_progress_steps_are_in_order`, +`what_goes_wrong_is_in_words_and_says_what_is_not_affected`, +`off_and_a_new_address_go_through_the_owner_and_a_new_one_is_asked_twice`). diff --git a/docs/spec/claims/link.md b/docs/spec/claims/link.md new file mode 100644 index 00000000..c31ac90e --- /dev/null +++ b/docs/spec/claims/link.md @@ -0,0 +1,215 @@ +# Claims: the link + +The product rules of the app's side of the relay (plan P15, unit B3; +decisions D-80, D-82, D-85, D-87 in `plan/p15-app-and-relay.md`). No authority +states them: they are wanderbooks' own (`WB-link-`). The code is the crate +`crates/ledger-link` (the app's identity, line and TLS and certificates) and, +joining it to the books server's remote door, `crates/ledger-host/src/web.rs`. +The relay itself is `crates/relay` (`relay.md`); the remote door and its +sign-in are `remote.md`. + +Rules: none from bookspec. + +--- + +## Product rules + +**WB-link-1** An installation has one durable address, `https://..wanderbooks.link`, and its key never leaves the machine. + +```text +GOAL: a person has one address that is the same every time web assistants + are turned on, that nobody can list or guess, and a key the relay is + only ever sent the public half of; and can have a new address, after + which the old one stops working. +SOURCE: D-82, D-85, D-87 in 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); the relay's own rule (WB-relay-3: + a label is 25 to 63 characters of a-z and 0-9). +INVARIANTS: + 1. The name is four words from the relay's list, picked by the app and + kept; the relay claims it for the app's key at the first line. + 2. The secret label is 32 random characters of a-z and 0-9, about 165 + bits (128 are needed), made by rejection sampling. + 3. The key (Ed25519), the label and the certificate's key are in the + data root's private link folder: owner-only files (0600 on Unix, the + owner-only access list the token files use on Windows), written whole + or not at all. + 4. A new address replaces the label at once and the old host name is no + longer given a certificate; if the relay has lost the name, a whole new + identity is made. + 5. No key, label or token is in a log, an error, a status's debug text or + a test's output. +SCENARIOS: + 1. The first turn-on makes an address; off and on again, and a restart of + the app, give the same one, and the name is claimed once. + 2. A new address differs in its label only; the old one gets no TLS. + 3. A damaged identity file is an error in words and is never overwritten. +``` + +*Enforced:* `Identity::load_or_create`, `Identity::new_label`, `Identity::reset`, `new_label`, `write` (module `private`, crate `ledger-link`). +*Checked:* `ledger-link` `tests/link.rs` (`the_key_the_certificate_and_the_label_are_private`, `a_new_address_stops_the_old_one`, `off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart`, `a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on`) and unit tests in `src/identity.rs` and `src/private.rs`. + +**WB-link-2** The app holds one outbound line to the relay and keeps it, by itself, through anything. + +```text +GOAL: the line comes back after the network drops, the relay restarts, the + relay is down for a while or the computer sleeps and wakes on another + network, never spins hot against a relay that is down, and ends when + it is told to or when the app does. +SOURCE: plan/p15-app-and-relay.md section 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; WB-relay-2 (the proof + that is signed for each session). +INVARIANTS: + 1. The line is yamux over TLS 1.3 to the relay, proved with the app's key + over that session (the relay crate's own client); the line runs in the + app's own process and ends with it, so it can never keep a door open for + books that closed. + 2. A failed dial waits a growing, jittered time (at most five minutes); + a nudge or a held line starts it again. + 3. The line is pinged every 30 seconds and a ping not answered in 15 + ends it and a new one is made. + 4. A wall-clock step much longer than the time that passed (a sleep) ends + the line and dials again at once. + 5. The line offers the relay more streams than the relay's limits need. +SCENARIOS: + 1. The relay drops the line; the app dials again and the same name is + served, with no new claim. + 2. An idle line, pinged, outlives several of the relay's silence limits; + without pings the relay drops it and the app dials again. + 3. A relay that is not there is dialled with a backoff, not in a loop. +``` + +*Enforced:* `Backoff`, `WakeDetector`, `Timing` (module `line`) and `Inner::hold` and `Inner::line_loop` (module `link`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`the_line_comes_back_after_the_relay_drops_it`, `pings_keep_an_idle_line_and_silence_loses_it`, `an_unreachable_relay_says_so_in_words_and_recovers_by_itself`) and unit tests in `src/line.rs` (`the_backoff_grows_stays_under_its_ceiling_and_resets`, `a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep`). + +**WB-link-3** The app ends the web caller's TLS itself, with its own certificate, and hands the plain stream to the remote door after the secret and the relay's header. + +```text +GOAL: what the relay forwards is TLS it cannot read; the app decrypts it + with a key that never left the machine, for the app's own host name + only; and the remote door can tell the connection came from the app's + line and whose address the caller has. +SOURCE: D-80 (encrypted end to end), plan/p15-app-and-relay.md section 4 + rule 8 (the per-start secret, then the PROXY header); WB-remote-1; + WB-relay-6. +INVARIANTS: + 1. TLS (1.3 and 1.2, with HTTP/2 or HTTP/1.1 by ALPN) is ended with the + certificate the app holds, and only for the exact host name of its + address: any other name, the apex and a stranger's guess get no + certificate. + 2. The first 64 bytes of every connection to the door are the door's + per-start secret as given, then the relay's PROXY version 2 header, + then the caller's plain bytes; the door is on 127.0.0.1 only. + 3. At most 16 callers are served at once, and a caller whose handshake + does not finish in time is dropped; with no door, a caller is turned + away at once. + 4. Nothing the relay could use to read traffic leaves the machine. +SCENARIOS: + 1. A caller's TLS through the relay reaches a stand-in door, which is + given the secret first, then the caller's address as the relay saw + it, then plain HTTP; what crossed the relay holds neither the + request, the reply, the secret nor any key. + 2. With no door the caller's connection ends; with it back, it works. +``` + +*Enforced:* `Resolver`, `server_config` (module `certs`) and `Inner::serve_caller` (module `link`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`a_caller_through_the_relay_reaches_the_door_and_the_relay_sees_only_ciphertext`, `a_stalled_handshake_is_dropped_and_no_door_means_no_service`) and `ledger-cli` `tests/web_link.rs` (`a_web_assistant_signs_in_through_the_relay_and_reads_the_books`). + +**WB-link-4** The app's certificate is its own, from the authority the relay lists, kept across restarts and renewed ahead of expiry. + +```text +GOAL: a certificate for the app's own name, ordered with a key made here, + kept so a restart orders nothing, renewed when the authority says (or + two thirds through its life), from whichever authority the relay lists + so a swap needs no release. +SOURCE: D-87, plan/p15-app-and-relay.md section 5 ("Authorities are data, + not code"; the proof record is published by the relay for the app's + own name); RFC 8555 (ACME, DNS-01, external account binding); + RFC 9773 (renewal information). +INVARIANTS: + 1. The order is for the wildcard under the app's name; the proof goes to + the relay over the app's own line and is cleared afterwards; the app + gives an authority no contact. + 2. The authorities are the relay's list, in its order; one marked not + usable is skipped; a failure falls to the next; all failing is a + state in words, retried with a growing, jittered wait while the line + stays up. + 3. The certificate and its key are kept in one private file and read at + start; a certificate for another name, or one that does not parse, is + ordered again. + 4. Renewal is at the time the authority's renewal information suggests + (asked again from time to time), else two thirds through the life, + naming the certificate it replaces; the certificate in use serves + until it ends if a renewal fails. + 5. An account binding is sent only when the relay gave one for this app. +SCENARIOS: + 1. Order, store, reuse across a restart: one order in all. + 2. The renewal window opens: a second order names the first. + 3. The first authority fails and the second issues; one needing a binding + the relay has none for is never asked. + 4. Every authority failing says so in words and mends when one works. +``` + +*Enforced:* `StoredCert`, `CertStore`, `default_renewal` (module `certs`), `AcmeIssuer` (module `acme`), `Inner::cert_loop` and `Inner::order` (module `link`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`the_first_authority_fails_and_the_second_issues`, `an_authority_that_is_not_usable_is_skipped`, `every_authority_failing_is_said_and_retried_until_one_works`, `the_certificate_is_renewed_at_the_authoritys_suggested_time`, `without_renewal_information_it_renews_two_thirds_through`) and `tests/acme.rs` (`an_order_goes_through_account_proof_finalize_and_download`, `a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_window`, `a_binding_is_sent_when_there_is_one_and_never_invented`, `a_refusal_comes_back_in_the_authoritys_words`). + +**WB-link-5** Every state of the link ends in plain words and mends by itself. + +```text +GOAL: no network, a relay that is down or busy, an authority that is + rate-limited, a clock that is wrong, a laptop that slept: each is said + in words a person can use, says what is not affected, and recovers + without the person unless it needs them. +SOURCE: 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. One place makes the words (`Trouble::words`, `LinkStatus::words`); a + trouble that mends itself says it keeps trying and that the local + assistants still work; one that needs the person says what to do. + 2. A relay certificate that has ended or not begun is a wrong clock, not + a relay that is down. + 3. A name that does not resolve is no internet; an unanswered relay is + the relay down; a relay that does not know the name is the name lost, + and a new address makes a new identity. + 4. The link's state is read from memory and never waits; the window and + the local assistants never depend on the network. +SCENARIOS: + 1. Each trouble has words; the mending ones say so. + 2. A relay that is not there is "can't reach its relay ... keeps + trying", and the link connects when it is. + 3. A name that cannot be resolved is no internet; an expired relay + certificate is a wrong clock. +``` + +*Enforced:* `Trouble`, `LinkStatus`, `Step` (module `status`), `trouble_of_io`, `trouble_of_refusal` (module `line`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`an_unreachable_relay_says_so_in_words_and_recovers_by_itself`, `no_internet_is_said_as_that`, `a_wrong_clock_is_said_as_that`) and unit tests in `src/status.rs` and `src/line.rs` (`errors_read_as_the_right_trouble`). + +**WB-link-6** Web assistants are on per company, off by default, and the line and the door are open only while some company is on. + +```text +GOAL: nothing is dialled, listened on or offered until a person turns a + company on; turning it off closes the line and the door and keeps the + address; what was on when the app closed is on again at the next + start. +SOURCE: plan/p15-app-and-relay.md 3.3 ("Allow web assistants" per company, + off by default; "Turning it off closes the line and the door; the + name is kept"), section 5 (one name per installation); D-84. +INVARIANTS: + 1. Turning on starts the door (127.0.0.1) as the app's one address and + offers the company; turning off withdraws the company and, with none + left, closes the line and then the door. + 2. A new address restarts the door at the new address: every token and + sign-in made at the old one is refused. + 3. The switches are kept in a private file and put back for the + companies that are open; a failure at any step leaves nothing + half-on. +SCENARIOS: + 1. On, a web assistant signs in through the relay and reads the books; + off, the line and the door are gone and the address is kept; on again, + the same address; a new address, and the old one is refused. +``` + +*Enforced:* `WebAssistants` (`turn_on`, `turn_off`, `new_address`, `restore`) in `crates/ledger-host/src/web.rs`. +*Checked:* `ledger-cli` `tests/web_link.rs` (`a_web_assistant_signs_in_through_the_relay_and_reads_the_books`, `off_closes_the_line_and_the_door_and_on_again_is_the_same_address`, `a_new_address_refuses_what_the_old_one_signed_in`, `the_switches_are_put_back_at_the_next_start`). diff --git a/plan/p15-app-and-relay.md b/plan/p15-app-and-relay.md index 7232ed3c..d74731ef 100644 --- a/plan/p15-app-and-relay.md +++ b/plan/p15-app-and-relay.md @@ -470,7 +470,34 @@ From the review of unit B2 (the relay service): - The 100,000-line soak has not been run; 20,000 is the largest. - Unit B3's duties: ping at least every 60 s (a line silent for 180 s is dropped); a secret label of 25 or more random base36 characters; a - yamux stream limit at least the relay's. + yamux stream limit at least the relay's. Done in `crates/ledger-link` + (ping every 30 s, a 32-character label, 64 streams). + +From unit B3 (the app's side of the relay), left out on purpose: + +- Certificate transparency watching is not built. Section 5 says the app + watches the public certificate logs for its own name and warns of a + certificate it did not ask for; it names no log service, API or timing, + and the unit's brief left it for later if the plan left it open. It needs + a log monitor choice (crt.sh and the like are third-party services the + app would call with the app's name), so it waits for the owner's word. +- The steps for ChatGPT, Gemini, Grok and muse.ai are not written: the plan + has none it stands behind (section 7: OpenAI's two pages disagree), so + the page says "we haven't tested this yet". The steps for Claude on the + web are the ones in `plan/served.md` (Settings, Connectors, Add custom + connector, paste, sign in); nobody has tried them on the live product. +- "Other assistant": a key made on the spot for products that take only a + key (section 3.3 and `remote_make_key`) is not reached from the page yet. +- The line has no way to learn that the books server's door is gone while + the window is still open (the server exited): callers are turned away, + and the window's own notice says the server is down. +- ACME against a real authority, and a real relay, are untried: the tests + run the real `instant-acme` client against an authority written in the + test, and the link against the relay crate in-process. +- Several companies share one address; a new address ends the sign-ins of + all of them (one issuer), and the approvals listed under "Who can reach + these books" for the old address stay listed until revoked. +- A first run for the window with no server asks nothing and opens nothing. From the review of unit A2 (the app starts and stops the server), left for unit A5 or later: From b90df7158a1d711fbc96702a997291838c81d873 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 14:59:57 -0700 Subject: [PATCH 07/11] fix(link): the app believes only public authorities, only their hosts, and only while a certificate lasts The review of P15 B3 found the relay could steer three things it must not. - A certificate is now checked against the public roots the program ships, for the app's wildcard, when it is issued and every time it is read from disk; a lifetime over 100 days is refused (no public authority issues one), and the renewal is planned no later than two thirds of the life or 60 days. A kept certificate that fails is ignored and ordered again. Only a test builds a CertTrust of its own roots. - The ACME client sends a request only to a directory on a host compiled into the app (Let's Encrypt production and staging, Google Trust Services, ZeroSSL, Buypass, SSL.com): the relay still picks which and in what order, but cannot name a new host. A kept account is used only if its directory is on the list too. http is a direct dependency now (it was a dev-dependency, and already in the tree): the host is read with the parser the ACME library uses. - The resolver refuses a certificate at its end, sleeps stop at it, and the state stops saying "Connected" when it has ended. - The certificate work waits for the line, so it is for the name the relay accepted (a first claim that finds the name taken picks another); web.rs starts the door only once the name is settled. - A line that held under 60 s does not reset the backoff; one that held is redialled after 0 to 30 s, so a relay restart is not met by every app in the same second. - What the relay and the authority say is shown as a short quoted detail with control and invisible characters removed, in the app's own words. - The kept address is read once, not from the key file every frame; the folder is synced after a private file is renamed into place. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/web_link.rs | 4 +- crates/ledger-link/Cargo.toml | 2 +- crates/ledger-link/src/acme.rs | 283 +++++++++++++++++--- crates/ledger-link/src/certs.rs | 336 ++++++++++++++++++++++-- crates/ledger-link/src/lib.rs | 3 +- crates/ledger-link/src/line.rs | 106 +++++++- crates/ledger-link/src/link.rs | 283 ++++++++++++++++---- crates/ledger-link/src/private.rs | 45 +++- crates/ledger-link/src/text.rs | 128 +++++++++ crates/ledger-link/tests/acme.rs | 151 ++++++++++- crates/ledger-link/tests/link.rs | 195 +++++++++++++- crates/ledger-link/tests/support/mod.rs | 32 ++- 12 files changed, 1440 insertions(+), 128 deletions(-) create mode 100644 crates/ledger-link/src/text.rs 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); From f9caf713a7eb76f2b9e4c6e223976e4c783b6ef8 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 14:59:57 -0700 Subject: [PATCH 08/11] fix(host): turning a company off is only off when the books server said so turn_off sent RemoteAllow{false} and ignored any reply but an error, so a refusal left the company reachable while the window said off, and with another company on the line and the door stayed up. Now anything but the server's success keeps the company shown as on, with the reason in words; a server that cannot be reached at all closes the whole line and door (the safe side) and says so. The door is also started only once the relay has accepted the name (the settled address), and production uses the public roots as its certificate trust. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-host/src/web.rs | 283 ++++++++++++++++++++++++++++++++-- 1 file changed, 269 insertions(+), 14 deletions(-) diff --git a/crates/ledger-host/src/web.rs b/crates/ledger-host/src/web.rs index 96578c07..2f01f137 100644 --- a/crates/ledger-host/src/web.rs +++ b/crates/ledger-host/src/web.rs @@ -33,14 +33,25 @@ //! 6. A failure at any step leaves nothing half-on: the company is not //! offered, and if it was the only one the line and the door are //! closed again; the error is in words. +//! 7. Off is only off when the books server said so: a refusal or any +//! reply but its success leaves the company shown as on, with the +//! error in words; a server that cannot be reached at all closes the +//! whole line and the door (every company), and says so. A company is +//! never shown off while it can still be reached. +//! 8. The door is started as the address the relay has accepted: the +//! name is claimed and settled first (a name taken picks another), so +//! the address given to the door is the one the line and the +//! certificate carry. //! SCENARIOS: //! 1. See `crates/ledger-cli/tests/web_link.rs`: on, a web assistant //! signs in through the relay and reads the books, off, on again at -//! the same address, a new address, a restart. +//! the same address, a new address, a restart; and the tests below +//! (a books server that refuses or cannot be reached when a company +//! is turned off). //! ``` use crate::app_server::AppHost; -use ledger_link::{DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble}; +use ledger_link::{CertTrust, DoorTarget, Link, LinkConfig, LinkStatus, Step, Trouble}; use ledger_mcp::admin::{Request, Response}; use std::collections::BTreeSet; use std::path::PathBuf; @@ -54,6 +65,9 @@ pub const RELAY_HOST: &str = "relay.wanderbooks.link"; const SWITCHES: &str = "web.json"; const ADMIN_WAIT: Duration = Duration::from_secs(30); +/// How long to wait for the relay to accept the name before the door is +/// started as that address (INVARIANT 8). +const CLAIM_WAIT: Duration = Duration::from_secs(30); /// What the Connect page shows of the web assistants of one company. #[derive(Clone, Debug, PartialEq, Eq)] @@ -114,6 +128,7 @@ pub struct WebAssistants { on: Mutex>, /// An error from putting the switches back at the start. restore_error: Mutex>, + claim_wait: Duration, // One change at a time. busy: Mutex<()>, } @@ -126,6 +141,7 @@ fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { pub fn production(dir: PathBuf) -> Result { Ok(LinkConfig { issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)), + trust: CertTrust::public()?, dir, domain: DOMAIN.into(), relay_host: RELAY_HOST.into(), @@ -149,10 +165,17 @@ impl WebAssistants { link: OnceLock::new(), on: Mutex::new(BTreeSet::new()), restore_error: Mutex::new(None), + claim_wait: CLAIM_WAIT, busy: Mutex::new(()), } } + /// Wait this long for the relay to accept the name (tests). + pub fn with_claim_wait(mut self, wait: Duration) -> Self { + self.claim_wait = wait; + self + } + fn dir(&self) -> Result { let root = ledger_store::root::Root::find(self.root.as_deref()).map_err(|e| e.to_string())?; @@ -283,6 +306,14 @@ impl WebAssistants { /// started as that address. fn start_door(&self, admin: &dyn Admin, link: &Arc) -> Result { link.turn_on().map_err(|e| e.to_string())?; + // The name is settled before the door is started as it (INVARIANT + // 8): the first claim may find it taken and pick another. + if let Err(why) = link.wait_settled(self.claim_wait) { + if lock(&self.on).is_empty() { + link.turn_off(); + } + return Err(why); + } let address = link .status() .address @@ -325,8 +356,8 @@ impl WebAssistants { } } - /// Turn web assistants off for `book` (INVARIANT 2): with no company - /// left offered, the line closes first, then the door. + /// Turn web assistants off for `book` (INVARIANTS 2 and 7): with no + /// company left offered, the line closes first, then the door. pub fn turn_off(&self, admin: &dyn Admin, book: &str) -> Result { let _one = lock(&self.busy); let mut now = lock(&self.on).clone(); @@ -336,24 +367,41 @@ impl WebAssistants { book: book.into(), allowed: false, }); - let mut note = None; - if let Err(why) = withdrawn { - // The server may be gone already (the books closed); what must - // still happen is the line closing. - note = Some(why); + let mut closed_all = false; + match withdrawn { + Ok(Response::Remote(_)) => {} + // The server answered, and did not withdraw the company: it can + // still be reached, so it stays shown as on, with the reason. + Ok(Response::Refused(why)) => { + return Err(format!( + "Web assistants are still on for this company: the books server would not turn them off ({why})." + )); + } + Ok(other) => { + return Err(format!( + "Web assistants are still on for this company: the books server answered in a way Wanderbooks did not expect ({other:?})." + )); + } + // The server cannot be reached at all, so nothing can be told + // about what it still offers: the safe side is to close the + // line and the door for every company. + Err(_) => closed_all = true, } - if now.is_empty() + if (now.is_empty() || closed_all) && let Some(Ok(link)) = self.link.get() { link.turn_off(); link.set_door(None); let _ = admin.admin(Request::RemoteStop); } + // What the person asked to be on stays on disk, so it is on again + // at the next start; what is open now is what is still offered. self.save(&now)?; - *lock(&self.on) = now; - Ok(match note { - Some(_) => "Web assistants are off.".into(), - None => "Web assistants are off for this company. Its address is kept for when you turn them on again.".into(), + *lock(&self.on) = if closed_all { BTreeSet::new() } else { now }; + Ok(if closed_all { + "Wanderbooks could not reach its books server to turn this off one company at a time, so it closed the connection to the internet for every company. Turn web assistants on again for the others if you want them.".into() + } else { + "Web assistants are off for this company. Its address is kept for when you turn them on again.".into() }) } @@ -432,3 +480,210 @@ impl Drop for WebAssistants { self.shutdown(); } } + +#[cfg(test)] +mod tests { + use super::*; + use ledger_mcp::admin::{RemoteInfo, TokenText}; + use std::sync::atomic::{AtomicU8, Ordering}; + + const SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + /// What the books server does when a company is withdrawn. + const OK: u8 = 0; + const REFUSES: u8 = 1; + const UNREACHABLE: u8 = 2; + + /// A stand-in for the books server's admin socket: it keeps the set of + /// companies it offers and says what it was asked. + struct Server { + withdraw: AtomicU8, + offered: Mutex>, + asked: Mutex>, + door: Mutex, + } + + impl Server { + fn new() -> Server { + Server { + withdraw: AtomicU8::new(OK), + offered: Mutex::new(BTreeSet::new()), + asked: Mutex::new(vec![]), + door: Mutex::new(false), + } + } + + fn info(&self) -> RemoteInfo { + RemoteInfo { + listening: Some("127.0.0.1:9".into()), + public_url: None, + allowed: lock(&self.offered).iter().cloned().collect(), + proxy_secret: Some(TokenText(SECRET.into())), + } + } + + fn said(&self, what: &str) -> usize { + lock(&self.asked).iter().filter(|a| *a == what).count() + } + } + + impl Admin for Server { + fn admin(&self, request: Request) -> Result { + match request { + Request::RemoteStart { .. } => { + *lock(&self.door) = true; + Ok(Response::Remote(self.info())) + } + Request::RemoteStop => { + lock(&self.asked).push("stop".into()); + *lock(&self.door) = false; + lock(&self.offered).clear(); + Ok(Response::Remote(self.info())) + } + Request::RemoteAllow { + book, + allowed: true, + } => { + lock(&self.offered).insert(book); + Ok(Response::Remote(self.info())) + } + Request::RemoteAllow { + book, + allowed: false, + } => { + lock(&self.asked).push(format!("withdraw {book}")); + match self.withdraw.load(Ordering::SeqCst) { + REFUSES => Ok(Response::Refused("not today".into())), + UNREACHABLE => Err("the books server is not there".into()), + _ => { + lock(&self.offered).remove(&book); + Ok(Response::Remote(self.info())) + } + } + } + other => Err(format!("not asked in these tests: {other:?}")), + } + } + } + + /// Web assistants over a data root of their own, with a name the relay + /// already accepted (so the address is settled) and a relay that is + /// not there: the line cannot come up, which these tests do not need. + fn web() -> (tempfile::TempDir, WebAssistants) { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + ledger_store::root::Root::setup(&home, Some(&root), None).unwrap(); + let found = ledger_store::root::Root::find(Some(&root)).unwrap(); + let link = found.path().join("link"); + let mut id = ledger_link::identity::Identity::load_or_create(&link).unwrap(); + id.set_claimed().unwrap(); + let web = WebAssistants::with_maker( + Some(root), + Box::new(|dir| { + Ok(LinkConfig { + domain: DOMAIN.into(), + relay_host: RELAY_HOST.into(), + dial: ledger_link::Dial::Addr("127.0.0.1:1".parse().unwrap()), + relay_tls: ledger_link::public_relay_tls().map_err(|e| e.to_string())?, + // Never reached: the line cannot come up, so nothing is + // ordered. + issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)), + trust: CertTrust::public()?, + timing: ledger_link::Timing::default(), + dir, + }) + }), + ); + (dir, web) + } + + fn link_on(web: &WebAssistants) -> bool { + web.link_status().is_some_and(|s| s.on) + } + + /// The plain case: with another company still on, turning one off makes + /// it unreachable at once and the other keeps working. + #[test] + fn one_company_off_is_unreachable_at_once_while_another_still_works() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + assert_eq!(lock(&server.offered).len(), 2); + + let said = web.turn_off(&server, "alpha").unwrap(); + assert!(said.contains("off for this company"), "{said}"); + assert!(!web.state("alpha").on); + assert!(web.state("beta").on); + let offered = lock(&server.offered).clone(); + assert!( + !offered.contains("alpha"), + "alpha is not offered by the server" + ); + assert!(offered.contains("beta"), "beta still is"); + assert!(link_on(&web), "the line stays up for beta"); + assert!(*lock(&server.door), "and so does the door"); + assert_eq!(server.said("stop"), 0); + // The company left off stays off at the next start. + assert_eq!(web.load(), BTreeSet::from(["beta".to_string()])); + } + + /// The server refuses to withdraw the company: it is still reachable, + /// so it is still shown as on, with the reason in words; nothing else + /// changes. + #[test] + fn a_refusal_leaves_the_company_shown_as_on_with_the_reason() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + + server.withdraw.store(REFUSES, Ordering::SeqCst); + let err = web.turn_off(&server, "alpha").unwrap_err(); + assert!(err.contains("still on for this company"), "{err}"); + assert!(err.contains("not today"), "{err}"); + assert!(web.state("alpha").on, "alpha is reachable, so shown on"); + assert!(web.state("beta").on); + assert!(lock(&server.offered).contains("alpha")); + assert!(link_on(&web)); + assert_eq!(server.said("stop"), 0, "the door was not closed"); + // Nothing was saved off either. + assert_eq!( + web.load(), + BTreeSet::from(["alpha".to_string(), "beta".to_string()]) + ); + + // And once the server is willing, it works. + server.withdraw.store(OK, Ordering::SeqCst); + web.turn_off(&server, "alpha").unwrap(); + assert!(!web.state("alpha").on); + } + + /// The server cannot be reached at all: the safe side is the whole line + /// and door closed, and the person is told. + #[test] + fn an_unreachable_server_closes_the_whole_line_and_door_and_says_so() { + let (_dir, web) = web(); + let server = Server::new(); + web.turn_on(&server, "alpha").unwrap(); + web.turn_on(&server, "beta").unwrap(); + + server.withdraw.store(UNREACHABLE, Ordering::SeqCst); + let said = web.turn_off(&server, "alpha").unwrap(); + assert!( + said.contains("closed the connection to the internet for every company"), + "{said}" + ); + assert!(!link_on(&web), "the line is closed"); + assert!(!web.state("alpha").on); + assert!( + !web.state("beta").on, + "beta is not reachable either, so not shown on" + ); + assert_eq!(server.said("stop"), 1, "the door was told to close"); + // What the person had on is still wanted at the next start. + assert_eq!(web.load(), BTreeSet::from(["beta".to_string()])); + } +} From 1b1d86622a271d22da1a7b330f20eba19decf3cf Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:01:41 -0700 Subject: [PATCH 09/11] fix(gui): one line when connected, and the Connect page says who can read what Once web assistants are connected the three progress lines (address, certificate, connected) collapse to a green dot and "Connected"; they are shown while connecting and when a step is the trouble. The page no longer says nobody can read what passes through, which was not true: the relay that carries the connection cannot, but the assistant's own company reads what it is sent. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/connect.rs | 59 +++++++++++++++----------- crates/ledger-gui/tests/web_connect.rs | 54 +++++++++++++++++++++++ 2 files changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/ledger-gui/src/connect.rs b/crates/ledger-gui/src/connect.rs index 750d687f..7ae8d23e 100644 --- a/crates/ledger-gui/src/connect.rs +++ b/crates/ledger-gui/src/connect.rs @@ -1369,7 +1369,7 @@ impl State { }); ui.label( RichText::new(format!( - "Claude and ChatGPT on the web can only reach {} if you give them an address on the internet. Turn this on to get one. Wanderbooks keeps it private to you, and nobody can read what passes through. An assistant on the web still has to be allowed here, by you, each time it connects.", + "Claude and ChatGPT on the web can only reach {} if you give them an address on the internet. Turn this on to get one. The relay that carries the connection can't read it. The assistant's maker (for example Anthropic or OpenAI) sees what you let that assistant read. An assistant on the web still has to be allowed here, by you, each time it connects.", status.company )) .font(theme::regular(13.0)) @@ -1389,30 +1389,41 @@ impl State { return want; } ui.add_space(8.0); - // Progress, in words. - for (words, progress) in web_progress(web.step) { - ui.horizontal(|ui| match progress { - Progress::Done => { - ui.label(RichText::new(icon::CHECK_CIRCLE).color(p.accent)); - ui.label(RichText::new(words).font(theme::regular(13.5))); - } - Progress::Now if web.problem.is_some() => { - ui.label(RichText::new(icon::WARNING).color(p.warning)); - ui.label(RichText::new(words).font(theme::regular(13.5))); - } - Progress::Now => { - ui.spinner(); - ui.label(RichText::new(format!("{words}\u{2026}")).font(theme::regular(13.5))); - } - Progress::Waiting => { - ui.label(RichText::new(icon::CIRCLE).color(p.muted)); - ui.label( - RichText::new(words) - .font(theme::regular(13.5)) - .color(p.muted), - ); - } + // Progress, in words: the three steps while it is being made, or + // when one of them is the trouble; once it works, one line. + if web.step == crate::owner::WebStep::Connected && web.problem.is_none() { + ui.horizontal(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); + ui.painter().circle_filled(rect.center(), 5.0, p.positive); + ui.label(RichText::new("Connected").font(theme::regular(13.5))); }); + } else { + for (words, progress) in web_progress(web.step) { + ui.horizontal(|ui| match progress { + Progress::Done => { + ui.label(RichText::new(icon::CHECK_CIRCLE).color(p.accent)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now if web.problem.is_some() => { + ui.label(RichText::new(icon::WARNING).color(p.warning)); + ui.label(RichText::new(words).font(theme::regular(13.5))); + } + Progress::Now => { + ui.spinner(); + ui.label( + RichText::new(format!("{words}\u{2026}")).font(theme::regular(13.5)), + ); + } + Progress::Waiting => { + ui.label(RichText::new(icon::CIRCLE).color(p.muted)); + ui.label( + RichText::new(words) + .font(theme::regular(13.5)) + .color(p.muted), + ); + } + }); + } } if web.step != crate::owner::WebStep::Connected || web.problem.is_some() { ui.ctx() diff --git a/crates/ledger-gui/tests/web_connect.rs b/crates/ledger-gui/tests/web_connect.rs index fe9c66a0..1d036781 100644 --- a/crates/ledger-gui/tests/web_connect.rs +++ b/crates/ledger-gui/tests/web_connect.rs @@ -33,6 +33,11 @@ //! 6. The Connect page opens by itself once, when the window's server //! says no assistant was ever connected, and never again; with any //! key, session, approval or waiting request it does not open. +//! 7. Once it is connected, the three progress steps are one line, +//! "Connected"; they are shown while connecting and when one is the +//! trouble. The page does not say that nobody can read the traffic: +//! the relay cannot, the assistant's own company reads what it is +//! sent. //! SCENARIOS: //! 1. See the tests below; `web_screenshots` (SHOT_DIR) draws each state //! light and dark. @@ -372,6 +377,9 @@ fn turning_it_on_shows_progress_then_the_address_the_steps_and_what_was_not_trie owner.set(on(WebStep::Connected)); h.run_steps(4); assert!(has(&h, "Connected")); + // Once it works the three steps are one line: "Connected". + assert!(!has(&h, "Getting an address")); + assert!(!has(&h, "Getting a certificate")); assert!(has(&h, CONNECTOR)); for (i, step) in claude_steps().iter().enumerate() { assert!(has(&h, &format!("{}. {step}", i + 1)), "{step}"); @@ -389,6 +397,52 @@ fn turning_it_on_shows_progress_then_the_address_the_steps_and_what_was_not_trie assert!(has(&h, "Copied")); } +/// The three steps are shown while connecting, and when a step is the +/// trouble even though the address works; a clean connection is one line. +#[test] +fn the_steps_collapse_to_one_line_when_connected_and_return_with_a_trouble() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(on(WebStep::Connected))); + let mut h = connect_page(&w, &owner, false); + h.run_steps(4); + assert!(has(&h, "Connected")); + assert!(!has(&h, "Getting an address")); + assert!(!has(&h, "Getting a certificate")); + // The certificate could not be renewed: the steps are back, with the + // trouble. + owner.set(WebConnect { + problem: Some("The certificate could not be renewed yet.".into()), + ..on(WebStep::Connected) + }); + h.run_steps(4); + assert!(has(&h, "Getting an address")); + assert!(has(&h, "Getting a certificate")); + assert!(has(&h, "The certificate could not be renewed yet.")); + // Connecting again shows them as well. + owner.set(on(WebStep::Connecting)); + h.run_steps(4); + assert!(has(&h, "Getting an address")); +} + +/// The words of the switch are true about who can read what (plan 5): the +/// relay cannot; the assistant's own company reads what it is sent. +#[test] +fn the_page_says_who_can_read_what_and_not_that_nobody_can() { + let w = World::new(&[("alpha", "Wanderland Labs")]); + let owner = Web::new(Some(off())); + let mut h = connect_page(&w, &owner, false); + h.run_steps(3); + let all = texts(&h); + assert!(!all.contains("nobody can read")); + assert!(all.contains("The relay that carries the connection can't read it.")); + assert!(all.contains( + "The assistant's maker (for example Anthropic or OpenAI) sees what you let that assistant read." + )); + assert!(all.contains( + "An assistant on the web still has to be allowed here, by you, each time it connects." + )); +} + /// The progress words are one function: what is done, what is under way, /// what waits. #[test] From 703b4f97c2a26f0d6653c5ad97613e712afbae9a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:03:48 -0700 Subject: [PATCH 10/11] docs(host): a doc comment linked to a private item, which the docs lint refuses Co-Authored-By: Claude Fable 5.2 --- crates/ledger-host/src/app_server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index 1c9815e5..f63e9997 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -467,7 +467,7 @@ impl AppServer { /// is not ready, a host or another server holds them (a command racing /// the app's start, or `serve`'s), this one has lost the race and the /// caller is to join what runs (commands.rs `reach`). Seen for as long - /// as [`BEATEN_AFTER`], so the moment between this server taking the + /// as `BEATEN_AFTER`, so the moment between this server taking the /// lock and saying so is not taken for losing. pub fn wait_ready_unless_beaten(&self, within: Duration) -> Result { let deadline = Instant::now() + within; From b0fe3decdc16a7fde33d60c30b267f843be9203c Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 15:03:48 -0700 Subject: [PATCH 11/11] docs(spec): the claims and the plan say what the B3 review changed Adding a brand-new certificate authority needs a release of the app: it contacts only directory hosts compiled into it, and believes only certificates that chain to the public roots it ships, because a relay that could name any host or authority could make every app send requests where it likes. The secret label is seen by the relay, the vendor's resolvers and the network path (the sign-in is the lock); the relay cannot read the traffic, the assistant's own company reads what it is sent. Certificate log watching is still not built, so a relay misusing its DNS control to get a certificate for a name would not be detected. Co-Authored-By: Claude Fable 5.2 --- docs/spec/claims/link.md | 83 ++++++++++++++++++++++++++++++++++----- plan/p15-app-and-relay.md | 28 ++++++++++++- 2 files changed, 99 insertions(+), 12 deletions(-) diff --git a/docs/spec/claims/link.md b/docs/spec/claims/link.md index c31ac90e..ba470557 100644 --- a/docs/spec/claims/link.md +++ b/docs/spec/claims/link.md @@ -39,6 +39,13 @@ INVARIANTS: identity is made. 5. No key, label or token is in a log, an error, a status's debug text or a test's output. + 6. The label is not a secret from the network. It travels in the caller's + TLS hello (the server name) and in the DNS queries that find the + address, so the relay, the vendor's resolvers and the path in between + all see it. The sign-in is the lock; the label only stops listing and + guessing. Nothing here says otherwise to the person. + 7. The address kept is read from the folder once and held: the window + asks every frame, and the key beside it is read only where it signs. SCENARIOS: 1. The first turn-on makes an address; off and on again, and a restart of the app, give the same one, and the name is claimed once. @@ -47,7 +54,7 @@ SCENARIOS: ``` *Enforced:* `Identity::load_or_create`, `Identity::new_label`, `Identity::reset`, `new_label`, `write` (module `private`, crate `ledger-link`). -*Checked:* `ledger-link` `tests/link.rs` (`the_key_the_certificate_and_the_label_are_private`, `a_new_address_stops_the_old_one`, `off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart`, `a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on`) and unit tests in `src/identity.rs` and `src/private.rs`. +*Checked:* `ledger-link` `tests/link.rs` (`the_key_the_certificate_and_the_label_are_private`, `a_new_address_stops_the_old_one`, `off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart`, `a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on`, `the_kept_address_is_read_once_not_every_frame`) and unit tests in `src/identity.rs` and `src/private.rs`. **WB-link-2** The app holds one outbound line to the relay and keeps it, by itself, through anything. @@ -66,7 +73,12 @@ INVARIANTS: app's own process and ends with it, so it can never keep a door open for books that closed. 2. A failed dial waits a growing, jittered time (at most five minutes); - a nudge or a held line starts it again. + a nudge starts it again. A line that held for a minute is redialled + after a wait spread over 0 to 30 seconds, and only then does the + backoff start over; a line that ended sooner (a relay that accepts and + drops) waits as a failed dial does. So a relay that restarts is not + met by every app in the same second, and one that misbehaves is not + redialled at a steady rate for ever. 3. The line is pinged every 30 seconds and a ping not answered in 15 ends it and a new one is made. 4. A wall-clock step much longer than the time that passed (a sleep) ends @@ -80,8 +92,8 @@ SCENARIOS: 3. A relay that is not there is dialled with a backoff, not in a loop. ``` -*Enforced:* `Backoff`, `WakeDetector`, `Timing` (module `line`) and `Inner::hold` and `Inner::line_loop` (module `link`), crate `ledger-link`. -*Checked:* `ledger-link` `tests/link.rs` (`the_line_comes_back_after_the_relay_drops_it`, `pings_keep_an_idle_line_and_silence_loses_it`, `an_unreachable_relay_says_so_in_words_and_recovers_by_itself`) and unit tests in `src/line.rs` (`the_backoff_grows_stays_under_its_ceiling_and_resets`, `a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep`). +*Enforced:* `Backoff`, `Redial`, `WakeDetector`, `Timing` (module `line`) and `Inner::hold` and `Inner::line_loop` (module `link`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`the_line_comes_back_after_the_relay_drops_it`, `pings_keep_an_idle_line_and_silence_loses_it`, `an_unreachable_relay_says_so_in_words_and_recovers_by_itself`) and unit tests in `src/line.rs` (`the_backoff_grows_stays_under_its_ceiling_and_resets`, `a_wall_clock_jump_with_no_monotonic_jump_is_a_sleep`, `a_line_that_ends_young_keeps_the_backoff_and_one_that_held_is_spread`). **WB-link-3** The app ends the web caller's TLS itself, with its own certificate, and hands the plain stream to the remote door after the secret and the relay's header. @@ -105,6 +117,12 @@ INVARIANTS: does not finish in time is dropped; with no door, a caller is turned away at once. 4. Nothing the relay could use to read traffic leaves the machine. + 5. Who can read what, said plainly: the relay that carries the + connection cannot read it. The assistant's maker (for example + Anthropic or OpenAI) reads what the person lets that assistant read, + which is what it is sent. "Nobody can read what passes through" is + not true and is not said; the Connect page says the two sentences + above. SCENARIOS: 1. A caller's TLS through the relay reaches a stand-in door, which is given the secret first, then the caller's address as the relay saw @@ -121,8 +139,11 @@ SCENARIOS: ```text GOAL: a certificate for the app's own name, ordered with a key made here, kept so a restart orders nothing, renewed when the authority says (or - two thirds through its life), from whichever authority the relay lists - so a swap needs no release. + two thirds through its life), from whichever of a fixed set of public + authorities the relay lists, so a swap among them needs no release; + and nothing the relay says can make the app believe a certificate + from an authority it made up, or send a request to a server it + named. SOURCE: D-87, plan/p15-app-and-relay.md section 5 ("Authorities are data, not code"; the proof record is published by the relay for the app's own name); RFC 8555 (ACME, DNS-01, external account binding); @@ -143,16 +164,46 @@ INVARIANTS: naming the certificate it replaces; the certificate in use serves until it ends if a renewal fails. 5. An account binding is sent only when the relay gave one for this app. + 6. A certificate is believed only if its chain ends at one of the public + roots the program ships, for the app's wildcard, at issue and at every + load (`CertTrust`; only a test builds one of its own roots, and + nothing at run time can). A lifetime over 100 days is refused, and a + renewal is planned no later than two thirds of the life or 60 days, + whichever is sooner. A kept certificate that fails any of this is + ignored and ordered again. The same name keeps a good wildcard across + "Get a new address"; a name that is given up (a lost one, a first claim + that found it taken) has none carried over. + 7. A certificate is never served at or after its end, however far off + the next renewal try is: the resolver refuses it, no wait runs past it, + and the state stops saying it is in place. + 8. The app sends a request only to an authority's directory on a host + compiled into it (`DIRECTORY_HOSTS`: Let's Encrypt production and + staging, Google Trust Services, ZeroSSL, Buypass and SSL.com, each + from its own documentation), over https and with no port or name in + the address. The relay still chooses which of them and in what order; + one on any other host is skipped and said so. A kept account is used + only if its directory is on the list too. Adding a brand-new + authority therefore takes a release of the app: that is the price of + the relay not being trusted with where the app sends its requests. + 9. The certificate work starts when the line is up, so it is for the name + the relay accepted; a first claim that finds the name taken picks + another before any certificate is ordered, and the door is started as + the address that was settled (`Link::wait_settled`). SCENARIOS: 1. Order, store, reuse across a restart: one order in all. 2. The renewal window opens: a second order names the first. 3. The first authority fails and the second issues; one needing a binding the relay has none for is never asked. 4. Every authority failing says so in words and mends when one works. + 5. A certificate from an authority the relay made up, or that lives over + 100 days, is refused and never stored or served; one on disk is + discarded; one that has ended is not served; a directory on another + host is not contacted; a name taken on the first claim is replaced + before any order. ``` -*Enforced:* `StoredCert`, `CertStore`, `default_renewal` (module `certs`), `AcmeIssuer` (module `acme`), `Inner::cert_loop` and `Inner::order` (module `link`), crate `ledger-link`. -*Checked:* `ledger-link` `tests/link.rs` (`the_first_authority_fails_and_the_second_issues`, `an_authority_that_is_not_usable_is_skipped`, `every_authority_failing_is_said_and_retried_until_one_works`, `the_certificate_is_renewed_at_the_authoritys_suggested_time`, `without_renewal_information_it_renews_two_thirds_through`) and `tests/acme.rs` (`an_order_goes_through_account_proof_finalize_and_download`, `a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_window`, `a_binding_is_sent_when_there_is_one_and_never_invented`, `a_refusal_comes_back_in_the_authoritys_words`). +*Enforced:* `StoredCert`, `CertStore`, `CertTrust`, `Resolver`, `renewal_cap` (module `certs`), `AcmeIssuer`, `DIRECTORY_HOSTS` (module `acme`), `Link::wait_settled`, `Inner::cert_loop` and `Inner::order` (module `link`), crate `ledger-link`. +*Checked:* `ledger-link` `tests/link.rs` (`the_first_authority_fails_and_the_second_issues`, `an_authority_that_is_not_usable_is_skipped`, `every_authority_failing_is_said_and_retried_until_one_works`, `the_certificate_is_renewed_at_the_authoritys_suggested_time`, `without_renewal_information_it_renews_two_thirds_through`) and `tests/acme.rs` (`an_order_goes_through_account_proof_finalize_and_download`, `a_renewal_reuses_the_account_names_what_it_replaces_and_reads_the_window`, `a_binding_is_sent_when_there_is_one_and_never_invented`, `a_refusal_comes_back_in_the_authoritys_words`, `a_directory_on_a_host_the_app_does_not_know_is_refused_before_any_request`, `a_kept_account_for_an_unlisted_directory_is_not_used`) and `tests/link.rs` (`a_certificate_from_an_authority_the_relay_made_up_is_never_stored_or_served`, `a_stored_certificate_from_a_made_up_authority_is_discarded_and_ordered_again`, `a_name_taken_on_the_first_claim_settles_before_the_certificate_and_the_address`, `an_expired_certificate_is_not_served_and_the_state_says_so`) and unit tests in `src/certs.rs` (`a_certificate_from_an_authority_the_relay_made_up_is_refused`, `a_lifetime_over_the_cap_is_refused`, `renewal_is_never_later_than_two_thirds_or_sixty_days`, `a_stored_certificate_that_fails_is_ignored_when_read`, `the_resolver_serves_only_its_host_and_only_until_the_certificate_ends`) and `src/acme.rs` (`every_listed_host_is_accepted_at_its_directory_and_no_other_is`). **WB-link-5** Every state of the link ends in plain words and mends by itself. @@ -175,6 +226,11 @@ INVARIANTS: and a new address makes a new identity. 4. The link's state is read from memory and never waits; the window and the local assistants never depend on the network. + 5. The window's words are the app's own, chosen from the kind of + failure. What the relay or an authority said is shown only as a short + quoted detail: control and invisible characters removed, white space + made single spaces, cut to about 120 characters, and the whole text + of failures bounded (`detail`, `clean`). SCENARIOS: 1. Each trouble has words; the mending ones say so. 2. A relay that is not there is "can't reach its relay ... keeps @@ -184,7 +240,7 @@ SCENARIOS: ``` *Enforced:* `Trouble`, `LinkStatus`, `Step` (module `status`), `trouble_of_io`, `trouble_of_refusal` (module `line`), crate `ledger-link`. -*Checked:* `ledger-link` `tests/link.rs` (`an_unreachable_relay_says_so_in_words_and_recovers_by_itself`, `no_internet_is_said_as_that`, `a_wrong_clock_is_said_as_that`) and unit tests in `src/status.rs` and `src/line.rs` (`errors_read_as_the_right_trouble`). +*Checked:* `ledger-link` `tests/link.rs` (`an_unreachable_relay_says_so_in_words_and_recovers_by_itself`, `no_internet_is_said_as_that`, `a_wrong_clock_is_said_as_that`, `an_authority_that_shouts_is_shown_short_and_plain`) and `tests/acme.rs` (`what_the_authority_says_is_short_plain_and_quoted`) and unit tests in `src/status.rs`, `src/text.rs` (`long_text_with_tricks_comes_out_short_and_plain`) and `src/line.rs` (`errors_read_as_the_right_trouble`). **WB-link-6** Web assistants are on per company, off by default, and the line and the door are open only while some company is on. @@ -205,6 +261,13 @@ INVARIANTS: 3. The switches are kept in a private file and put back for the companies that are open; a failure at any step leaves nothing half-on. + 4. Off is only off when the books server said so. A refusal, or any + reply but its success, leaves the company shown as on, with the error + in words (it is still reachable by anyone holding a token); a server + that cannot be reached at all closes the whole line and the door, for + every company, and says so. + 5. The door is started as the address the relay has accepted: the name is + claimed and settled first. SCENARIOS: 1. On, a web assistant signs in through the relay and reads the books; off, the line and the door are gone and the address is kept; on again, @@ -212,4 +275,4 @@ SCENARIOS: ``` *Enforced:* `WebAssistants` (`turn_on`, `turn_off`, `new_address`, `restore`) in `crates/ledger-host/src/web.rs`. -*Checked:* `ledger-cli` `tests/web_link.rs` (`a_web_assistant_signs_in_through_the_relay_and_reads_the_books`, `off_closes_the_line_and_the_door_and_on_again_is_the_same_address`, `a_new_address_refuses_what_the_old_one_signed_in`, `the_switches_are_put_back_at_the_next_start`). +*Checked:* `ledger-cli` `tests/web_link.rs` (`a_web_assistant_signs_in_through_the_relay_and_reads_the_books`, `off_closes_the_line_and_the_door_and_on_again_is_the_same_address`, `a_new_address_refuses_what_the_old_one_signed_in`, `the_switches_are_put_back_at_the_next_start`) and unit tests in `crates/ledger-host/src/web.rs` (`one_company_off_is_unreachable_at_once_while_another_still_works`, `a_refusal_leaves_the_company_shown_as_on_with_the_reason`, `an_unreachable_server_closes_the_whole_line_and_door_and_says_so`). diff --git a/plan/p15-app-and-relay.md b/plan/p15-app-and-relay.md index d74731ef..25decbf1 100644 --- a/plan/p15-app-and-relay.md +++ b/plan/p15-app-and-relay.md @@ -367,8 +367,19 @@ app's certificate code knows that protocol and nothing about any one authority. At each issuance it asks the relay service for the list to try, in order: for each authority its directory address, whether it needs an account binding, and if so a binding credential the relay -service obtained for this app. Changing or adding an authority is a -change to that list on our server, with no new release of the app. What +service obtained for this app. Choosing among the authorities the app +knows, and their order, is a change to that list on our server, with no +new release of the app. **Adding a brand-new authority needs a release** +(B3 review, 2026-11-21): the app sends requests only to directory hosts +compiled into it (Let's Encrypt production and staging, Google Trust +Services, ZeroSSL, Buypass, SSL.com: `DIRECTORY_HOSTS` in +`crates/ledger-link/src/acme.rs`, each host from the authority's own +documentation), because a relay that could name any host in the list +could make every app send requests to a server of its choice. For the +same reason the app believes a certificate only if it chains to the +public roots it ships, for its own wildcard, and lives no longer than +100 days; the relay's list can choose among authorities but cannot make +the app trust a new one. What differs between authorities beyond the protocol (renewal information, lifetimes, limits) sits behind one small trait. The tests issue from a local test authority configured two ways, one with an account binding @@ -382,6 +393,17 @@ then show only the wildcard. The words are for recognition; the secret label stops listing and guessing; the sign-in is the lock. One name per installation; each company is a path under it. +**What the label does not hide, and who can read what** (B3 review, +2026-11-21). The secret label is in the caller's TLS hello (the server +name) and in the DNS queries that find the address, so the relay, the +vendor's resolvers and the network path all see it. It is not a secret +from them; it stops listing and guessing, and the sign-in is the lock. +The relay cannot read the traffic (its certificate is not there to read +it with). The assistant's own company (Anthropic, OpenAI and the like) +reads what it is sent, which is what the person lets that assistant read. +The Connect page says these two things and not "nobody can read what +passes through". + **State (D-85).** Durable: name, public key, created, blocked. In memory: name to open line. Transient: proof records, minutes each. @@ -481,6 +503,8 @@ From unit B3 (the app's side of the relay), left out on purpose: and the unit's brief left it for later if the plan left it open. It needs a log monitor choice (crt.sh and the like are third-party services the app would call with the app's name), so it waits for the owner's word. + Until it is built, a relay that misuses its DNS control to get a + certificate for a user's name would not be detected. - The steps for ChatGPT, Gemini, Grok and muse.ai are not written: the plan has none it stands behind (section 7: OpenAI's two pages disagree), so the page says "we haven't tested this yet". The steps for Claude on the