Merge branch 't3/p15-b3-web-assistants': the app's side of the relay (P15 B3)

Buypass is left out of the compiled-in directory hosts: its directory
could not be confirmed from its own documentation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 15:05:16 -07:00
commit 0759089790
37 files changed
+10182 -26

No files matched your search

Generated
+78
View File
@@ -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"
@@ -3973,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",
@@ -3987,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",
]
@@ -4052,6 +4097,7 @@ dependencies = [
"ledger-config",
"ledger-core",
"ledger-import",
"ledger-link",
"ledger-package",
"ledger-store",
"ledger-vault",
@@ -4072,6 +4118,7 @@ version = "0.1.0"
dependencies = [
"base64 0.22.1",
"ledger-core",
"ledger-link",
"ledger-mcp",
"ledger-store",
"libc",
@@ -4111,6 +4158,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"
+1 -1
View File
@@ -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"
File diff suppressed because it is too large. Load diff
+17 -2
View File
@@ -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" }
+53 -3
View File
@@ -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<Option<String>, 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<Option<String>, String> {
@@ -117,6 +132,8 @@ impl ledger_gui::owner::Owner for ViewerOwner {
}
fn serve_stop(&self) -> Result<Option<String>, 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<ledger_gui::owner::WebConnect> {
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<String, String> {
self.web.turn_on(&self.server, book)
}
fn web_turn_off(&self, book: &str) -> Result<String, String> {
self.web.turn_off(&self.server, book)
}
fn web_new_address(&self, _book: &str) -> Result<String, String> {
self.web.new_address(&self.server)
}
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.server.revoke_token(book, name, id)
}
+709
View File
@@ -0,0 +1,709 @@
//! 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::{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;
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<Self> {
let mut params = CertificateParams::new(Vec::<String>::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<Issued, String>> {
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<Response, String> {
self.0.call(request, Some(Duration::from_secs(30)))
}
}
struct Rig {
home: Home,
server: AppServer,
env: relay_common::Env,
ca: Arc<Authority_>,
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<Authority_>) -> 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| {
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(),
trust: CertTrust::for_tests(roots.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<Resp> {
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::<Vec<_>>()
.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<bytes::Bytes>>(
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");
}
+1
View File
@@ -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]
+53
View File
@@ -188,6 +188,10 @@ pub struct App {
assistants_ok: bool,
/// "Now" for "10 seconds ago", fixed (tests, screenshots) or not.
fixed_now: Option<chrono::DateTime<chrono::Utc>>,
/// 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<Tab> = 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)),
+5
View File
@@ -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
+337 -6
View File
@@ -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<String>,
/// "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<f64>,
}
/// 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<Arc<dyn Owner>>,
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,317 @@ 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<Arc<dyn Owner>>,
) -> 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<dyn FnOnce() -> 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<dyn FnOnce() -> 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. 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))
.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: 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()
.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
}
}
+57
View File
@@ -253,6 +253,44 @@ pub struct WebApproval {
pub last_used: Option<i64>,
}
/// 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<String>,
/// The address an assistant is given for this company.
pub connector: Option<String>,
/// A line of progress, in words.
pub words: String,
/// What is wrong, in words.
pub problem: Option<String>,
/// 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<String, String> {
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<WebConnect> {
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<String, String> {
Err("not here".into())
}
/// Turn them off for the company. Blocks.
fn web_turn_off(&self, _book: &str) -> Result<String, String> {
Err("not here".into())
}
/// A new address for web assistants: the old one stops working. Blocks.
fn web_new_address(&self, _book: &str) -> Result<String, String> {
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.
+7 -6
View File
@@ -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<String, String> =
[("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
+631
View File
@@ -0,0 +1,631 @@
//! 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.
//! 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.
//! ```
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<Option<WebConnect>>,
roster: Mutex<Roster>,
log: Mutex<Vec<String>>,
}
impl Web {
fn new(state: Option<WebConnect>) -> Arc<Web> {
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<String> {
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<Option<String>, String> {
Ok(None)
}
fn serve_close(&self, _book: &str) -> Result<Option<String>, String> {
Ok(None)
}
fn serve_stop(&self) -> Result<Option<String>, String> {
Ok(None)
}
fn serve_roster(&self) -> Result<Roster, String> {
Ok(self.roster.lock().unwrap().clone())
}
fn command_line(&self, words: &[&str]) -> Result<String, String> {
Ok(format!("wanderbooks {}", words.join(" ")))
}
fn web_state(&self, _book: &str) -> Option<WebConnect> {
self.state.lock().unwrap().clone()
}
fn web_turn_on(&self, book: &str) -> Result<String, String> {
self.log.lock().unwrap().push(format!("on {book}"));
Ok("Web assistants are on.".into())
}
fn web_turn_off(&self, book: &str) -> Result<String, String> {
self.log.lock().unwrap().push(format!("off {book}"));
Ok("Web assistants are off.".into())
}
fn web_new_address(&self, book: &str) -> Result<String, String> {
self.log.lock().unwrap().push(format!("new {book}"));
Ok("Your new address is ready.".into())
}
fn new_books(&self, _id: &str, _currency: &str) -> Result<String, String> {
Err("not here".into())
}
fn back_up_now(&self, _book: &str) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn plan_restore(
&self,
_source: &str,
_id: Option<String>,
_replace: bool,
) -> Result<RestorePlan, String> {
Err("not here".into())
}
fn restore(&self, _plan: &RestorePlan) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn connect(
&self,
_agent: ledger_gui::owner::Agent,
_book: &str,
) -> Result<Vec<String>, String> {
Err("not here".into())
}
fn upgrade_format(&self, _book: &str, _passphrase: &str) -> Result<Vec<String>, 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<Web>, kept: &[(&str, &str)], dark: bool) -> Harness<'static, App> {
let mut map: HashMap<String, String> = 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<dyn Owner> = 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<dyn Owner> = 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<Web>, 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<String>) {
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<String> {
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"));
// 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}");
}
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 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]
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();
}
}
}
+1
View File
@@ -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"] }
+1 -1
View File
@@ -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<Waited, String> {
let deadline = Instant::now() + within;
+1
View File
@@ -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.
+689
View File
@@ -0,0 +1,689 @@
//! 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/<company>/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.
//! 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; 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::{CertTrust, 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);
/// 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)]
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<String>,
/// The address an assistant is given for this company.
pub connector: Option<String>,
/// A line of progress in words.
pub words: String,
/// What is wrong, in words.
pub problem: Option<String>,
/// 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<Response, String>;
}
impl Admin for AppHost {
fn admin(&self, request: Request) -> Result<Response, String> {
self.running()?.call(request, Some(ADMIN_WAIT))
}
}
/// How the link is made (tests give it a relay of their own).
pub type Maker = Box<dyn Fn(PathBuf) -> Result<LinkConfig, String> + Send + Sync>;
/// Web assistants for this window.
pub struct WebAssistants {
root: Option<PathBuf>,
make: Maker,
link: OnceLock<Result<Arc<Link>, String>>,
on: Mutex<BTreeSet<String>>,
/// An error from putting the switches back at the start.
restore_error: Mutex<Option<String>>,
claim_wait: Duration,
// One change at a time.
busy: Mutex<()>,
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// The program's own relay.
pub fn production(dir: PathBuf) -> Result<LinkConfig, String> {
Ok(LinkConfig {
issuer: Arc::new(ledger_link::AcmeIssuer::new(&dir)),
trust: CertTrust::public()?,
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<PathBuf>) -> Self {
Self::with_maker(root, Box::new(production))
}
/// With a link made another way (tests).
pub fn with_maker(root: Option<PathBuf>, make: Maker) -> Self {
WebAssistants {
root,
make,
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<PathBuf, String> {
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<Link>, 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<String>) -> 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<String> {
let Ok(dir) = self.dir() else {
return BTreeSet::new();
};
std::fs::read(dir.join(SWITCHES))
.ok()
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&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<String>) -> 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<String, String> {
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<Link>) -> Result<DoorTarget, String> {
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
.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<Link>, before: &BTreeSet<String>) {
if before.is_empty() {
link.turn_off();
link.set_door(None);
let _ = admin.admin(Request::RemoteStop);
}
}
/// 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<String, String> {
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 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() || 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) = 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()
})
}
/// 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<String, String> {
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<String> = 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<LinkStatus> {
self.link
.get()
.and_then(|l| l.as_ref().ok())
.map(|l| l.status())
}
}
impl Drop for WebAssistants {
fn drop(&mut self) {
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<BTreeSet<String>>,
asked: Mutex<Vec<String>>,
door: Mutex<bool>,
}
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<Response, String> {
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()]));
}
}
+52
View File
@@ -0,0 +1,52 @@
[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"
http = "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", "x509-parser"] }
hickory-proto = { version = "0.26", default-features = false, features = ["std"] }
tokio = { version = "1", features = ["test-util"] }
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"] }
[lints]
workspace = true
+487
View File
@@ -0,0 +1,487 @@
//! 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 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::{
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<dyn Fn() -> Option<Box<dyn HttpClient>> + 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://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<String>,
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"),
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;
self
}
/// Wait this long for an order (tests).
pub fn with_patience(mut self, patience: Duration) -> Self {
self.patience = patience;
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<instant_acme::AccountBuilder, String> {
match (self.http)() {
Some(http) => Ok(Account::builder_with_http(http)),
None => Account::builder().map_err(|e| words(Kind::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<Account, String> {
self.directory_allowed(&authority.directory)?;
let file = self.file(authority);
if let Ok(bytes) = std::fs::read(&file) {
let bytes = Zeroizing::new(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::<serde_json::Value>(&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::<AccountCredentials>(&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(Kind::Unreachable, &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(Kind::NewAccount, &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(_)
)
}
/// 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 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())
}
}
}
}
impl Issuer for AcmeIssuer {
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
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(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(Kind::Proof, &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. It said {}.",
detail(&why)
)
})?;
published = true;
challenge
.set_ready()
.await
.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(Kind::Finish, &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(Kind::Issue, &e))?);
let chain_pem = order
.poll_certificate(&policy)
.await
.map_err(|e| words(Kind::Download, &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) {}
#[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",
"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}'));
}
}
+652
View File
@@ -0,0 +1,652 @@
//! 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 (`<secret>.<name>.<domain>`):
//! 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.
//! 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.
//! 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, 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::{Duration, 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.<name>`.
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: `*.<four-words>.<domain>`.
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<Vec<u8>>,
/// 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<String>,
}
/// 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<Issued, String>>;
/// 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 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<WebPkiServerVerifier>,
}
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<Self, String> {
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<Self, String> {
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` (`*.<name>.<domain>`).
pub fn check(&self, chain_pem: &str, identifier: &str, t: i64) -> Result<(), String> {
let chain: Vec<CertificateDer<'static>> =
CertificateDer::pem_slice_iter(chain_pem.as_bytes())
.collect::<Result<_, _>>()
.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)]
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<Vec<u8>> {
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<String>)> {
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, 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<i64>,
trust: &CertTrust,
) -> Result<Self, String> {
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());
}
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(cap).min(cap);
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,
})
}
/// 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<Self> {
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<Arc<CertifiedKey>> {
certified(&self.chain_pem, &self.key_pem)
}
/// The certificate's DER (for renewal information).
pub fn der(&self) -> Option<Vec<u8>> {
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
}
/// 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<Arc<CertifiedKey>> {
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(chain_pem.as_bytes())
.collect::<Result<_, _>>()
.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
/// (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<StoredCert> {
let bytes = std::fs::read(&self.path).ok()?;
let c: StoredCert = serde_json::from_slice(&bytes).ok()?;
c.vetted(name, identifier, trust)
}
/// 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), and never at or after its end
/// (INVARIANT 9).
pub struct Resolver {
host: RwLock<String>,
key: RwLock<Option<(Arc<CertifiedKey>, i64)>>,
}
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<Self> {
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, with when it ends (unix seconds), or none.
pub fn set_cert(&self, cert: Option<(Arc<CertifiedKey>, 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<Arc<CertifiedKey>> {
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<Arc<CertifiedKey>> {
self.pick(hello.server_name()?, now())
}
}
/// 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<Resolver>) -> Arc<rustls::ServerConfig> {
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::*;
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::<String>::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());
}
}
+329
View File
@@ -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://<secret>.<four-words>.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<Vec<u8>>,
}
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<Self, IdentityError> {
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<Option<Self>, 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<Self, IdentityError> {
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<Self, IdentityError> {
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://<secret>.<four-words>.<domain>`.
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, IdentityError> {
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));
}
}
+60
View File
@@ -0,0 +1,60 @@
//! 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://<secret>.<four-words>.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 mod text;
pub use acme::AcmeIssuer;
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};
/// 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<std::sync::Arc<rustls::ClientConfig>, 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)
}
+451
View File
@@ -0,0 +1,451 @@
//! 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 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.
//! 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; 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
//! 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,
/// 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 {
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),
line_stable: Duration::from_secs(60),
redial_spread: 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)
}
}
/// 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,
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::<rustls::Error>() {
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<u128> = (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_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<Duration> = (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));
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);
}
}
File diff suppressed because it is too large. Load diff
+127
View File
@@ -0,0 +1,127 @@
//! 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, 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; on Windows the file and its folder are owner-only
//! (`ledger_store::winsec::is_private`).
//! ```
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)?;
sync_folder(path)
})();
if result.is_err() {
let _ = std::fs::remove_file(&tmp);
}
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::*;
#[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);
}
/// 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());
}
}
+248
View File
@@ -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<String>,
/// 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<i64>,
/// Why the line is not up.
pub trouble: Option<Trouble>,
/// Why the certificate is not in place (or not renewed), in words.
pub cert_trouble: Option<String>,
/// 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<String> {
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"));
}
}
+128
View File
@@ -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");
}
}
+694
View File
@@ -0,0 +1,694 @@
//! 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<String, String>, // kid -> thumbprint
new_accounts: Vec<serde_json::Value>,
orders: Vec<Order>,
ari_gets: u32,
refuse_orders: bool,
/// What a refusal says in its detail (else a short one).
detail: Option<String>,
certs: HashMap<usize, String>,
}
struct Order {
identifier: String,
replaces: Option<String>,
thumbprint: String,
token: String,
authz_valid: bool,
done: bool,
}
struct FakeAcme {
ca: CertifiedIssuer<'static, KeyPair>,
dns: std::net::SocketAddr,
state: Mutex<Server>,
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 {
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();
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":s.detail.clone().unwrap_or_else(|| "too many certificates already issued".into())}),
));
}
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;
s.certs
.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 = self.state.lock().unwrap().certs[&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"}),
),
}
}
}
struct Http(Arc<FakeAcme>);
impl HttpClient for Http {
fn request(
&self,
req: http::Request<BodyWrapper<Bytes>>,
) -> Pin<Box<dyn Future<Output = Result<BytesResponse, Error>> + 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<FakeAcme>,
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::<String>::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_directory_hosts_for_tests(&["acme.test"])
.with_http(Arc::new(move || {
Some(Box::new(Http(a2.clone())) as Box<dyn HttpClient>)
}));
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, 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,
&certs::CertTrust::for_tests(r.acme.roots())
)
.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);
}
// 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}");
}
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<dyn HttpClient>)
}));
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}");
}
+787
View File
@@ -0,0 +1,787 @@
//! 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::{CertTrust, Dial, Step, Trouble};
use std::sync::atomic::Ordering;
use std::time::Duration;
use support::*;
fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
/// WB-link-1 to WB-link-3: claim, prove, line up, certificate; then a web
/// caller's TLS connection through the relay is ended at the app and the
/// door is given the secret, the caller's address and plain HTTP; and
/// what crossed the relay was ciphertext.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_caller_through_the_relay_reaches_the_door_and_the_relay_sees_only_ciphertext() {
let w = world(LIST, |_| {}).await;
assert_eq!(w.link.status().step(), Step::Off);
w.link.turn_on().unwrap();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.claimed && s.line_up && s.cert_expires.is_some());
assert_eq!(w.env.relay.shared().lines.len(), 1);
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
let host = w.host();
// The address is `<secret>.<four words>.<domain>`, the secret 25 or
// more characters of a-z and 0-9.
let parts: Vec<&str> = host.split('.').collect();
assert_eq!(parts.len(), 4, "{host}");
assert!(
parts[0].len() >= 25
&& parts[0]
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
);
assert_eq!(format!("{}.{}", parts[2], parts[3]), DOMAIN);
let reply = w
.assistant(&host)
.await
.expect("TLS completes with the app");
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
assert!(reply.ends_with(BODY));
// The door was given the secret first, then the caller's address as
// the relay saw it, then plain HTTP with no TLS in it.
let seen = w.door.seen.lock().unwrap().clone();
assert_eq!(seen.len(), 1);
assert!(seen[0].secret_ok);
let from_relay = w.caller_tap.source_ports.lock().unwrap().clone();
assert_eq!(seen[0].caller, from_relay.first().copied());
assert!(seen[0].request.starts_with("GET /ping HTTP/1.1\r\n"));
// What crossed the relay, both ways, is TLS: the request and the reply
// are not in it in the clear.
for crossed in [
w.caller_tap.seen_up(),
w.caller_tap.seen_down(),
w.tap.seen_up(),
w.tap.seen_down(),
] {
assert!(!crossed.is_empty());
assert!(!contains(&crossed, b"GET /ping"));
assert!(!contains(&crossed, BODY.as_bytes()));
assert!(!contains(&crossed, SECRET.as_bytes()));
}
// The caller's own bytes carried the name in the clear (the relay
// routes on it) and the app's certificate only inside TLS 1.3.
assert!(contains(&w.caller_tap.seen_up(), host.as_bytes()));
// Nothing private was sent to the relay: not the line's key, not the
// certificate's key, not the account.
let key = std::fs::read(w.dir.path().join("link/line.key")).unwrap();
let cert: serde_json::Value =
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
.unwrap();
let cert_key = cert["key_pem"].as_str().unwrap().to_owned();
for crossed in [w.tap.seen_up(), w.tap.seen_down(), w.caller_tap.seen_up()] {
assert!(!contains(&crossed, &key));
assert!(!contains(&crossed, cert_key.as_bytes()));
assert!(!contains(&crossed, b"PRIVATE KEY"));
}
}
/// WB-link-1: the key and certificate files are private, and the secret
/// label is in no status text.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_key_the_certificate_and_the_label_are_private() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let dir = w.dir.path().join("link");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode =
|p: std::path::PathBuf| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(dir.clone()), 0o700);
for f in ["identity.json", "line.key", "cert.json"] {
assert_eq!(mode(dir.join(f)), 0o600, "{f}");
}
}
let host = w.host();
let label = host.split('.').next().unwrap();
let status = format!("{:?} {}", w.link.status(), w.link.status().words());
assert!(!status.contains(label));
// The label is not the name's, nor guessable from the files' times.
assert!(!host.split('.').nth(1).unwrap().contains(label));
}
/// WB-link-1, 4: off means off (the line ends, the certificate stops being
/// served), the name is kept, on again is the same address, and a restart
/// of the app reuses the stored certificate: one order in all.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn off_closes_the_line_and_the_address_is_the_same_on_again_and_after_a_restart() {
let mut w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let host = w.host();
assert_eq!(w.fake.orders(), 1);
w.link.turn_off();
let s = w.link.status();
assert_eq!(s.step(), Step::Off);
assert!(s.address.is_none());
// The relay lost the line, and a caller is turned away.
eventually("the relay lost the line", || {
w.env.relay.shared().lines.is_empty()
})
.await;
assert!(w.assistant(&host).await.is_err());
// The name is kept.
assert_eq!(
w.link
.kept_address()
.unwrap()
.trim_start_matches("https://"),
host
);
w.link.turn_on().unwrap();
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
assert_eq!(w.host(), host);
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
assert_eq!(
w.fake.orders(),
1,
"a certificate already held is not ordered again"
);
// The name was claimed once.
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
// The app is closed and started again.
w.link.turn_off();
w.restart(|_| {});
w.link.turn_on().unwrap();
until(&w.link, "connected after a restart", |s| {
s.step() == Step::Connected
})
.await;
assert_eq!(w.host(), host);
assert_eq!(w.fake.orders(), 1, "a restart orders nothing");
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
}
/// WB-link-1: a new address replaces the secret label and the old one
/// stops working at once; the name, the key and the certificate stay.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_new_address_stops_the_old_one() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let old = w.host();
assert!(w.assistant(&old).await.is_ok());
let new = w.link.new_address().unwrap();
let new = new.trim_start_matches("https://").to_owned();
assert_ne!(new, old);
// Same name, a different label.
assert_eq!(
old.split_once('.').unwrap().1,
new.split_once('.').unwrap().1
);
until(&w.link, "connected again", |s| s.step() == Step::Connected).await;
assert_eq!(w.host(), new);
assert!(
w.assistant(&old).await.is_err(),
"the old address no longer gets a certificate"
);
assert!(w.assistant(&new).await.unwrap().ends_with(BODY));
assert_eq!(w.fake.orders(), 1, "the wildcard certificate still serves");
// The apex and a made-up label get nothing either.
let name = new.split_once('.').unwrap().1.to_owned();
assert!(w.assistant(&name).await.is_err());
assert!(
w.assistant(&format!("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.{name}"))
.await
.is_err()
);
}
/// WB-link-2: the relay drops the line, and the app dials again by itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_line_comes_back_after_the_relay_drops_it() {
let w = world(LIST, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let before = w.tap.accepted.load(Ordering::SeqCst);
let host = w.host();
w.tap.sever();
eventually("the app dialled again", || {
w.tap.accepted.load(Ordering::SeqCst) > before
})
.await;
until(&w.link, "connected again", |s| {
s.line_up && s.step() == Step::Connected
})
.await;
eventually("the relay has the line", || {
w.env.relay.shared().lines.len() == 1
})
.await;
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
// The name was not claimed again; the proof is the key.
assert_eq!(
w.env.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
}
/// WB-link-2: pings keep an idle line. The relay drops a line silent for
/// its idle limit; this one outlives several of them.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn pings_keep_an_idle_line_and_silence_loses_it() {
let mut limits = relay_limits();
limits.line_idle_ms = 700;
let w = world_with(limits, LIST, |t| {
t.ping_every = Duration::from_millis(150);
})
.await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let dialled = w.tap.accepted.load(Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(2500)).await;
assert_eq!(
w.tap.accepted.load(Ordering::SeqCst),
dialled,
"an idle but pinged line is never dropped and redialled"
);
assert!(w.link.status().line_up);
// Without pings the same relay drops it.
let silent = world_with(
{
let mut l = relay_limits();
l.line_idle_ms = 500;
l
},
LIST,
|t| t.ping_every = Duration::from_secs(3600),
)
.await;
silent.link.turn_on().unwrap();
until(&silent.link, "connected", |s| s.step() == Step::Connected).await;
let first = silent.tap.accepted.load(Ordering::SeqCst);
eventually("the silent line was dropped and dialled again", || {
silent.tap.accepted.load(Ordering::SeqCst) > first
})
.await;
}
fn relay_limits() -> relay::Limits {
support::common::quick_limits()
}
/// WB-link-5: with the relay unreachable the state says so in words and
/// mends itself; the people at the window lose nothing.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_unreachable_relay_says_so_in_words_and_recovers_by_itself() {
let w = world(LIST, |_| {}).await;
w.tap.refuse.store(true, Ordering::SeqCst);
w.link.turn_on().unwrap();
let s = until(&w.link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::RelayDown));
assert_eq!(s.step(), Step::GettingAddress);
assert!(s.problem().unwrap().contains("keeps trying"));
assert!(s.problem().unwrap().contains("on this computer still work"));
// Several failed dials, spaced by backoff: not a hot loop.
tokio::time::sleep(Duration::from_millis(800)).await;
assert!(w.tap.accepted.load(Ordering::SeqCst) < 25);
// The network comes back.
w.tap.refuse.store(false, Ordering::SeqCst);
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.trouble.is_none() && s.cert_trouble.is_none());
}
/// WB-link-5: no internet at all (the relay's name does not resolve) is
/// said as that.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn no_internet_is_said_as_that() {
let w = world(LIST, |_| {}).await;
// Rebuild the link with a dial that cannot resolve.
let mut cfg = config(&w);
cfg.dial = Dial::Host("relay.nonexistent.invalid".into(), 443);
cfg.dir = w.dir.path().join("link2");
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
link.turn_on().unwrap();
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::NoInternet));
assert!(s.problem().unwrap().contains("can't reach the internet"));
link.turn_off();
}
/// WB-link-5: a relay whose certificate is not valid yet or has ended
/// means this clock is wrong; it is said so, and the state keeps trying.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_wrong_clock_is_said_as_that() {
use rcgen::{CertificateParams, KeyPair};
let w = world(LIST, |_| {}).await;
// A TLS server with a certificate that ended yesterday.
let mut params = CertificateParams::new(vec![RELAY_HOST.to_string()]).unwrap();
let now = time::OffsetDateTime::now_utc();
params.not_before = now - time::Duration::days(30);
params.not_after = now - time::Duration::days(1);
let key = KeyPair::generate().unwrap();
let cert = params.self_signed(&key).unwrap();
let chain = vec![cert.der().clone()];
let pk = rustls::pki_types::PrivateKeyDer::Pkcs8(rustls::pki_types::PrivatePkcs8KeyDer::from(
key.serialize_der(),
));
let server = relay::tls::server_config(chain, pk).unwrap();
let acceptor = tokio_rustls::TlsAcceptor::from(server);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
loop {
let Ok((s, _)) = listener.accept().await else {
return;
};
let a = acceptor.clone();
tokio::spawn(async move {
let _ = a.accept(s).await;
});
}
});
let mut roots = rustls::RootCertStore::empty();
roots.add(cert.der().clone()).unwrap();
let mut cfg = config(&w);
cfg.dial = Dial::Addr(addr);
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
cfg.dir = w.dir.path().join("link3");
let link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
link.turn_on().unwrap();
let s = until(&link, "a trouble", |s| s.trouble.is_some()).await;
assert_eq!(s.trouble, Some(Trouble::ClockWrong));
assert!(s.problem().unwrap().contains("clock"));
assert!(Trouble::ClockWrong.mends_itself());
link.turn_off();
}
/// WB-link-1, 5: a relay that no longer knows the name says so in words,
/// and a new address (a whole new identity) claims a new name and carries on.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_relay_that_lost_the_name_says_so_and_a_new_address_carries_on() {
let mut w = world(LIST, |_| {}).await;
// A second relay, with an empty registry, whose certificate this app
// trusts too.
let fresh = support::common::start_with(
support::common::quick_limits(),
relay::authorities::AuthorityList::from_toml(LIST).unwrap(),
)
.await;
let mut roots = fresh.relay_ca.roots();
roots
.roots
.extend(w.env.relay_ca.roots().roots.iter().cloned());
let mut cfg = config(&w);
cfg.relay_tls = relay::tls::client_config(roots).unwrap();
w.link = ledger_link::Link::start_on(tokio::runtime::Handle::current(), cfg);
w.link.set_door(Some(w.door.target.clone()));
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let old = w.host();
*w.tap.upstream.lock().unwrap() = fresh.router();
w.tap.sever();
let s = until(&w.link, "the name is lost", |s| {
s.trouble == Some(Trouble::NameLost)
})
.await;
assert!(s.problem().unwrap().contains("Get a new address"));
let new = w.link.new_address().unwrap();
assert_ne!(new.trim_start_matches("https://"), old);
until(&w.link, "claimed a new name", |s| s.claimed && s.line_up).await;
assert_eq!(
fresh.relay.shared().metrics.claims.load(Ordering::Relaxed),
1
);
}
/// WB-link-4: the authorities are the relay's list, in its order; one
/// marked not usable is skipped; the first failing falls to the second;
/// the certificate is kept 0600 and reused; and the wildcard is for this
/// name and none other.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_first_authority_fails_and_the_second_issues() {
let w = world(LIST, |_| {}).await;
w.fake.state.lock().unwrap().fail.insert("first".into());
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let orders: Vec<String> = w
.fake
.state
.lock()
.unwrap()
.orders
.iter()
.map(|o| o.authority.clone())
.collect();
assert_eq!(orders, ["first", "second"]);
let host = w.host();
let name = host.split_once('.').unwrap().1;
let id = w.fake.state.lock().unwrap().orders[1].identifier.clone();
assert_eq!(id, format!("*.{name}"));
// The relay's DNS holds no proof once the order is done.
let proofs = dns_txt(
w.env.relay.dns_udp_addr(),
&format!("_acme-challenge.{name}."),
)
.await;
assert!(proofs.is_empty(), "{proofs:?}");
}
/// WB-link-4: an authority that needs a binding the relay has none for is
/// listed and not usable: it is skipped, and the next is used.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_authority_that_is_not_usable_is_skipped() {
const LIST_BINDING: &str = r#"
[[authority]]
id = "needs-binding"
directory = "https://fake.example/b"
caa_domain = "b.example"
needs_binding = true
[[authority]]
id = "plain"
directory = "https://fake.example/p"
caa_domain = "p.example"
"#;
let w = world(LIST_BINDING, |_| {}).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let orders: Vec<String> = w
.fake
.state
.lock()
.unwrap()
.orders
.iter()
.map(|o| o.authority.clone())
.collect();
assert_eq!(
orders,
["plain"],
"the one that is not usable was never asked"
);
}
/// WB-link-4: every authority failing is a state in words that is retried
/// and mends itself; the line stays up meanwhile.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn every_authority_failing_is_said_and_retried_until_one_works() {
let w = world(LIST, |_| {}).await;
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
}
w.link.turn_on().unwrap();
let s = until(&w.link, "a certificate trouble", |s| {
s.cert_trouble.is_some()
})
.await;
assert_eq!(s.step(), Step::GettingCertificate);
assert!(s.line_up);
let words = s.problem().unwrap();
assert!(
words.contains("could not get a certificate") && words.contains("keeps trying"),
"{words}"
);
// Retried, with a wait.
eventually("several tries", || w.fake.orders() >= 4).await;
// The authority comes back.
w.fake.state.lock().unwrap().fail.clear();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
assert!(s.cert_trouble.is_none());
}
/// WB-link-4: renewal ahead of expiry, at the time the authority's
/// renewal information suggests, naming the certificate it replaces; the
/// certificate that serves keeps serving while a renewal fails.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn the_certificate_is_renewed_at_the_authoritys_suggested_time() {
let w = world(LIST, |_| {}).await;
w.fake.state.lock().unwrap().window = Some((1, 2));
w.link.turn_on().unwrap();
let s = until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let first_end = s.cert_expires.unwrap();
assert_eq!(w.fake.orders(), 1);
eventually("a renewal", || w.fake.orders() >= 2).await;
{
let st = w.fake.state.lock().unwrap();
assert!(!st.orders[0].replaces);
assert!(
st.orders[1].replaces,
"a renewal names the certificate it replaces"
);
assert_eq!(st.orders[0].authority, st.orders[1].authority);
}
until(&w.link, "the new certificate serves", |s| {
s.cert_expires.is_some_and(|e| e >= first_end) && s.cert_trouble.is_none()
})
.await;
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
// A renewal that fails leaves the one in use serving.
{
let mut st = w.fake.state.lock().unwrap();
st.fail.insert("first".into());
st.fail.insert("second".into());
st.window = Some((1, 2));
}
let n = w.fake.orders();
eventually("a failed renewal try", || w.fake.orders() > n + 1).await;
let s = until(&w.link, "the renewal trouble", |s| s.cert_trouble.is_some()).await;
assert!(s.cert_expires.is_some());
assert!(
s.cert_trouble
.unwrap()
.contains("the one in use still works")
);
assert!(w.assistant(&w.host()).await.unwrap().ends_with(BODY));
}
/// WB-link-4: with no renewal information a certificate is renewed two
/// thirds of the way through its life.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn without_renewal_information_it_renews_two_thirds_through() {
let w = world(LIST, |_| {}).await;
// The authority's certificates are good for an hour from now and began
// an hour ago: two thirds of two hours is 20 minutes from now.
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let cert: serde_json::Value =
serde_json::from_slice(&std::fs::read(w.dir.path().join("link/cert.json")).unwrap())
.unwrap();
let (b, e, r) = (
cert["not_before"].as_i64().unwrap(),
cert["not_after"].as_i64().unwrap(),
cert["renew_at"].as_i64().unwrap(),
);
assert_eq!(r, b + (e - b) * 2 / 3);
assert_eq!(w.fake.orders(), 1);
}
/// WB-link-3: a caller that never finishes its handshake is dropped, and
/// a connection while the door is gone is closed, not held.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_stalled_handshake_is_dropped_and_no_door_means_no_service() {
let w = world(LIST, |t| t.handshake = Duration::from_millis(500)).await;
w.link.turn_on().unwrap();
until(&w.link, "connected", |s| s.step() == Step::Connected).await;
let host = w.host();
// No door: the caller's connection ends.
w.link.set_door(None);
let r = w.assistant(&host).await;
assert!(r.is_err() || r.unwrap().is_empty());
w.link.set_door(Some(w.door.target.clone()));
assert!(w.assistant(&host).await.unwrap().ends_with(BODY));
}
/// 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()));
}
+551
View File
@@ -0,0 +1,551 @@
//! 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::{CertTrust, Dial, DoorTarget, Link, LinkConfig, LinkStatus, Timing};
use rcgen::{BasicConstraints, CertificateParams, CertifiedIssuer, IsCa, KeyPair, KeyUsagePurpose};
use relay::proto::{Authority, Caller};
use rustls::RootCertStore;
use rustls::pki_types::ServerName;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::watch;
use tokio_rustls::TlsConnector;
use zeroize::Zeroizing;
pub use common::{DOMAIN, RELAY_HOST};
/// The words the fake authority speaks through.
pub struct Order {
pub authority: String,
pub identifier: String,
pub replaces: bool,
pub had_binding: bool,
}
pub struct FakeState {
pub orders: Vec<Order>,
/// Authority ids that refuse.
pub fail: std::collections::HashSet<String>,
/// Seconds the certificate lasts from now.
pub lifetime: i64,
/// What a refusal says, when it is not the fixed words.
pub say: Option<String>,
/// The renewal window the authority suggests, as seconds from now.
pub window: Option<(i64, i64)>,
}
/// An in-process certificate authority: it asks the relay's own DNS for
/// the proof, as a real one would, and signs with a CA of its own.
pub struct Fake {
ca: CertifiedIssuer<'static, KeyPair>,
dns: SocketAddr,
pub state: Mutex<FakeState>,
}
pub fn txt_at(m: &Message) -> Vec<String> {
m.answers
.iter()
.filter_map(|r| match &r.data {
RData::TXT(t) => Some(t.to_string()),
_ => None,
})
.collect()
}
pub async fn dns_txt(addr: SocketAddr, name: &str) -> Vec<String> {
let mut q = Message::query();
q.queries.push(Query::query(
DnsName::from_ascii(name).unwrap(),
RecordType::TXT,
));
let sock = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
sock.send_to(&q.to_vec().unwrap(), addr).await.unwrap();
let mut buf = [0u8; 2048];
let (len, _) = tokio::time::timeout(Duration::from_secs(5), sock.recv_from(&mut buf))
.await
.expect("an answer")
.unwrap();
txt_at(&Message::from_vec(&buf[..len]).unwrap())
}
impl Fake {
pub fn new(dns: SocketAddr) -> Arc<Self> {
let mut params = CertificateParams::new(Vec::<String>::new()).unwrap();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
params
.distinguished_name
.push(rcgen::DnType::CommonName, "fake authority");
let ca = CertifiedIssuer::self_signed(params, KeyPair::generate().unwrap()).unwrap();
Arc::new(Fake {
ca,
dns,
state: Mutex::new(FakeState {
orders: vec![],
fail: Default::default(),
lifetime: 3600,
say: None,
window: None,
}),
})
}
pub fn roots(&self) -> RootCertStore {
let mut roots = RootCertStore::empty();
roots.add(self.ca.der().clone()).unwrap();
roots
}
pub fn orders(&self) -> usize {
self.state.lock().unwrap().orders.len()
}
}
fn proof_value() -> String {
// 43 base64url characters, as a DNS-01 value is.
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let r = relay::proto::random32();
(0..43)
.map(|i| char::from(alphabet[usize::from(r[i % 32] % 64)]))
.collect()
}
impl Issuer for Fake {
fn issue<'a>(&'a self, req: OrderRequest<'a>) -> BoxFuture<'a, Result<Issued, String>> {
Box::pin(async move {
let (fails, lifetime, say) = {
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,
st.say.clone(),
)
};
if fails {
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.
let value = proof_value();
req.dns.publish(&value).await?;
let name = req.identifier.trim_start_matches("*.");
let seen = dns_txt(self.dns, &format!("_acme-challenge.{name}.")).await;
req.dns.clear().await;
if !seen.contains(&value) {
return Err("the proof of the name was not in the DNS".into());
}
let mut params = CertificateParams::new(vec![req.identifier.clone()]).unwrap();
let now = time::OffsetDateTime::now_utc();
params.not_before = now - time::Duration::hours(1);
params.not_after = now + time::Duration::seconds(lifetime);
let key = KeyPair::generate().unwrap();
let cert = params.signed_by(&key, &self.ca).unwrap();
Ok(Issued {
chain_pem: format!("{}{}", cert.pem(), self.ca.pem()),
key_pem: Zeroizing::new(key.serialize_pem()),
})
})
}
fn renewal_window<'a>(
&'a self,
_authority: &'a Authority,
_chain_pem: &'a str,
) -> BoxFuture<'a, Option<(i64, i64)>> {
Box::pin(async move {
let w = self.state.lock().unwrap().window;
let now = ledger_link::certs::now();
w.map(|(a, b)| (now + a, now + b))
})
}
}
/// What crosses between two ends, recorded, and cut on request.
pub struct Tap {
pub addr: SocketAddr,
pub upstream: Arc<Mutex<SocketAddr>>,
pub accepted: Arc<AtomicUsize>,
pub refuse: Arc<AtomicBool>,
pub to_upstream: Arc<Mutex<Vec<u8>>>,
pub from_upstream: Arc<Mutex<Vec<u8>>>,
cut: watch::Sender<u64>,
/// The address the relay sees connections from.
pub source_ports: Arc<Mutex<Vec<SocketAddr>>>,
}
impl Tap {
pub async fn new(upstream: SocketAddr) -> Tap {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let tap = Tap {
addr,
upstream: Arc::new(Mutex::new(upstream)),
accepted: Arc::new(AtomicUsize::new(0)),
refuse: Arc::new(AtomicBool::new(false)),
to_upstream: Arc::new(Mutex::new(vec![])),
from_upstream: Arc::new(Mutex::new(vec![])),
cut: watch::channel(0).0,
source_ports: Arc::new(Mutex::new(vec![])),
};
let (up, accepted, refuse, to, from, cut, ports) = (
tap.upstream.clone(),
tap.accepted.clone(),
tap.refuse.clone(),
tap.to_upstream.clone(),
tap.from_upstream.clone(),
tap.cut.clone(),
tap.source_ports.clone(),
);
tokio::spawn(async move {
loop {
let Ok((client, _)) = listener.accept().await else {
return;
};
accepted.fetch_add(1, Ordering::SeqCst);
if refuse.load(Ordering::SeqCst) {
continue; // dropped at once
}
let target = *up.lock().unwrap();
let (to, from, ports) = (to.clone(), from.clone(), ports.clone());
let mut watcher = cut.subscribe();
tokio::spawn(async move {
let Ok(server) = TcpStream::connect(target).await else {
return;
};
if let Ok(local) = server.local_addr() {
ports.lock().unwrap().push(local);
}
let (mut cr, mut cw) = client.into_split();
let (mut sr, mut sw) = server.into_split();
let a = async {
let mut buf = [0u8; 8192];
loop {
let n = cr.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
to.lock().unwrap().extend_from_slice(&buf[..n]);
if sw.write_all(&buf[..n]).await.is_err() {
break;
}
}
let _ = sw.shutdown().await;
};
let b = async {
let mut buf = [0u8; 8192];
loop {
let n = sr.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
from.lock().unwrap().extend_from_slice(&buf[..n]);
if cw.write_all(&buf[..n]).await.is_err() {
break;
}
}
let _ = cw.shutdown().await;
};
tokio::select! {
() = async { tokio::join!(a, b); } => {}
_ = watcher.changed() => {}
}
});
}
});
tap
}
/// Cut every connection now (the network dropped them).
pub fn sever(&self) {
self.cut.send_modify(|n| *n += 1);
}
pub fn seen_up(&self) -> Vec<u8> {
self.to_upstream.lock().unwrap().clone()
}
pub fn seen_down(&self) -> Vec<u8> {
self.from_upstream.lock().unwrap().clone()
}
}
/// What the stand-in door was given.
#[derive(Clone, Debug)]
pub struct Seen {
pub secret_ok: bool,
pub caller: Option<SocketAddr>,
pub request: String,
}
/// A stand-in for the remote door: it wants the secret, then the PROXY
/// header, then plain HTTP, and answers a fixed body.
pub struct Door {
pub target: DoorTarget,
pub seen: Arc<Mutex<Vec<Seen>>>,
}
pub const SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
pub const BODY: &str = "the door says hello";
impl Door {
pub async fn new() -> Door {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let seen = Arc::new(Mutex::new(vec![]));
let record = seen.clone();
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = listener.accept().await else {
return;
};
let record = record.clone();
tokio::spawn(async move {
let mut given = [0u8; 64];
if s.read_exact(&mut given).await.is_err() {
return;
}
let secret_ok = given.as_slice() == SECRET.as_bytes();
let caller = Caller::read(&mut s).await.ok().map(|c| c.source);
let mut req = Vec::new();
let mut buf = [0u8; 1024];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
let n = s.read(&mut buf).await.unwrap_or(0);
if n == 0 {
break;
}
req.extend_from_slice(&buf[..n]);
}
record.lock().unwrap().push(Seen {
secret_ok,
caller,
request: String::from_utf8_lossy(&req).into_owned(),
});
if secret_ok {
let _ = s
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{BODY}",
BODY.len()
)
.as_bytes(),
)
.await;
}
});
}
});
Door {
target: DoorTarget::new(addr, SECRET).unwrap(),
seen,
}
}
}
/// The timings the tests run at.
pub fn fast() -> Timing {
Timing {
ping_every: Duration::from_millis(200),
ping_timeout: Duration::from_secs(2),
tick: Duration::from_millis(100),
connect_timeout: Duration::from_secs(3),
backoff_min: Duration::from_millis(50),
backoff_max: Duration::from_millis(400),
handshake: Duration::from_secs(3),
cert_retry_min: Duration::from_millis(100),
cert_retry_max: Duration::from_millis(500),
order_timeout: Duration::from_secs(10),
ari_recheck: Duration::from_secs(1),
wake_gap: Duration::from_secs(30),
line_stable: Duration::from_millis(300),
redial_spread: Duration::from_millis(200),
}
}
pub const LIST: &str = r#"
[[authority]]
id = "first"
directory = "https://fake.example/first"
caa_domain = "first.example"
[[authority]]
id = "second"
directory = "https://fake.example/second"
caa_domain = "second.example"
"#;
pub struct World {
pub env: common::Env,
pub tap: Tap,
pub caller_tap: Tap,
pub door: Door,
pub fake: Arc<Fake>,
pub dir: tempfile::TempDir,
pub link: Link,
}
pub fn config(w: &World) -> LinkConfig {
LinkConfig {
dir: w.dir.path().join("link"),
domain: DOMAIN.into(),
relay_host: RELAY_HOST.into(),
dial: Dial::Addr(w.tap.addr),
relay_tls: w.env.line_tls(),
issuer: w.fake.clone(),
trust: CertTrust::for_tests(w.fake.roots()),
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(),
trust: CertTrust::for_tests(fake.roots()),
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 {
/// 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);
timing(&mut cfg.timing);
let old = std::mem::replace(
&mut self.link,
Link::start_on(tokio::runtime::Handle::current(), cfg),
);
drop(old);
self.link.set_door(Some(self.door.target.clone()));
}
/// An assistant: TLS to `host` through the tap, one GET, the whole
/// reply.
pub async fn assistant(&self, host: &str) -> std::io::Result<String> {
let tcp = TcpStream::connect(self.tap_for_callers()).await?;
let cfg = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(self.fake.roots())
.with_no_client_auth();
let mut tls = tokio::time::timeout(
Duration::from_secs(5),
TlsConnector::from(Arc::new(cfg))
.connect(ServerName::try_from(host.to_owned()).unwrap(), tcp),
)
.await
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::TimedOut, "the handshake never finished")
})??;
tls.write_all(
format!("GET /ping HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n").as_bytes(),
)
.await?;
let mut out = Vec::new();
let _ = tokio::time::timeout(Duration::from_secs(10), tls.read_to_end(&mut out)).await;
Ok(String::from_utf8_lossy(&out).into_owned())
}
fn tap_for_callers(&self) -> SocketAddr {
// Callers reach the relay's router the way the internet does: not
// through the app's tap, but through one of their own, which is
// also where what crosses is recorded.
self.caller_tap.addr
}
pub fn host(&self) -> String {
self.link
.status()
.address
.or_else(|| self.link.kept_address())
.unwrap()
.trim_start_matches("https://")
.to_owned()
}
}
pub async fn until(link: &Link, what: &str, mut ok: impl FnMut(&LinkStatus) -> bool) -> LinkStatus {
for _ in 0..400 {
let s = link.status();
if ok(&s) {
return s;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("never: {what}; last status {:?}", link.status());
}
pub async fn eventually(what: &str, mut ok: impl FnMut() -> bool) {
for _ in 0..400 {
if ok() {
return;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!("never: {what}");
}
+3 -1
View File
@@ -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) |
+2 -1
View File
@@ -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)
+14
View File
@@ -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`).
+30 -1
View File
@@ -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`).
+278
View File
@@ -0,0 +1,278 @@
# 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-<n>`). 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://<secret>.<four-words>.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.
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.
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`, `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.
```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 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
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`, `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.
```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.
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
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 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);
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.
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 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`, `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.
```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.
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
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`, `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.
```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.
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,
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`) 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`).
+1 -1
View File
@@ -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
+54 -3
View File
@@ -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, 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.
@@ -470,7 +492,36 @@ 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.
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
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: