Compare commits

..
3 Commits
Author SHA1 Message Date
swaitsandClaude Fable 5.2 045211e212 fix(host): a start that loses to a live app server says so; the window's close keeps one 90 s deadline
two-user / two-user (push) Canceled after 0s
portable-macos / portable (macos-latest) (push) Canceled after 0s
portable-windows / portable (windows-latest) (push) Canceled after 0s
check / check (cli) (push) Canceled after 0s
check / check (gui-tests) (push) Canceled after 0s
check / check (gui-unit) (push) Canceled after 0s
check / check (lint) (push) Canceled after 0s
check / check (rest) (push) Canceled after 0s
Two copies of the app started at once left the loser showing
'starting' for ever: its server waited on the other's lock. The wait
now gives up when another app's live server has held the books for
two seconds, stops its own child, and says another program has them.
A server that is closing is still waited for, and a missing info file
never counts, so the app's own server cannot be taken for another.
The window's close passes what remains of its 90 seconds to each step
(it could reach about 185), and a close that panics leaves a notice.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 17:20:56 -07:00
swaitsandClaude Fable 5.2 ce306a13c7 fix(deps): url 2.5.9 for RUSTSEC-2026-0592
A stack overflow in Url::origin on nested blob URLs. url reaches the
books only through typst's citation library; the upgrade is offered,
so it is taken instead of an ignore.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 17:20:55 -07:00
swaitsandClaude Fable 5.2 975a4d0452 feat(relay): a setup kit for a real machine; the relay's own name answers CAA so its certificate can renew
The apex CAA set allows issuance by DNS-01 only, and the relay
publishes challenge records only for apps' names, so no authority
could issue or renew the relay's own certificate. The relay now
answers CAA at its own host name with the same authorities and no
method restriction; every other name still climbs to the apex.
deploy/relay holds the service unit, settings and certbot hook, and
docs/relay-deploy.md the steps.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 09:47:50 -07:00
12 changed files with 852 additions and 27 deletions

No files matched your search

Generated
+4 -4
View File
@@ -2383,9 +2383,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -8329,9 +8329,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
+2 -2
View File
@@ -4593,7 +4593,7 @@ MIT License
================================================================================
Used by:
form_urlencoded 1.2.2
form_urlencoded 1.2.3
Copyright (c) 2013-2016 The rust-url developers
@@ -4630,7 +4630,7 @@ Used by:
data-url 0.3.2
idna 1.1.0
percent-encoding 2.3.2
url 2.5.8
url 2.5.9
Copyright (c) 2013-2025 The rust-url developers
+94
View File
@@ -761,6 +761,100 @@ fn a_server_that_never_gets_ready_is_stopped_with_the_window_and_not_left_behind
until("the server's process is gone", || !alive(pid));
}
/// A start that loses the race (a second window, two starts at once)
/// does not wait on the other's lock for ever: it stops its own child and
/// says, in words, that another program has the books.
#[cfg(unix)]
#[test]
fn a_start_that_loses_the_race_says_another_has_the_books() {
let home = Home::new("host-lost-race");
// A child that never takes the lock, as one waiting behind another's
// would not have: alive until its input closes.
let waiting = script(
home.dir.path(),
"waiting",
"#!/bin/sh\ncat >/dev/null\nexit 0\n",
);
let loser = AppServer::start_in(&waiting, Some(&home.root()), &[], |_| {}).unwrap();
let pid = loser.pid();
// Another books server takes the books after the loser's look.
let other = Server::start_with(&home, &["--started-by", "app", "--open", "none"]);
let (said, heard) = mpsc::channel();
let waiter = std::thread::spawn(move || {
said.send(loser.wait_started(Duration::from_millis(100)))
.ok();
loser
});
let answer = heard
.recv_timeout(Duration::from_secs(30))
.expect("the loser stopped waiting");
assert_eq!(answer, Err(ANOTHER_HAS_THEM.to_string()));
let loser = waiter.join().unwrap();
until("the loser's child is gone", || !alive(pid));
assert!(loser.exited().is_some());
// The other one is untouched.
assert!(server_lock_held(&home.run()));
other.close();
}
/// A start while the books of the window just closed are still being
/// backed up is waited for, not told "another has them": the old server
/// says it is closing, and the new start goes on once it is gone.
#[cfg(unix)]
#[test]
fn a_start_behind_a_closing_server_waits_for_it() {
let home = Home::new("host-behind-closing");
let run = home.run();
let waiting = script(
home.dir.path(),
"waiting",
"#!/bin/sh\ncat >/dev/null\nexit 0\n",
);
let later = AppServer::start_in(&waiting, Some(&home.root()), &[], |_| {}).unwrap();
// The old server: the lock held, under another pid, saying it closes.
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(run.join("server.lock"))
.unwrap();
lock.lock().unwrap();
std::fs::write(
run.join("server.info"),
format!(
r#"{{"by":"app","pid":{},"closing":true}}"#,
std::process::id() + 1
),
)
.unwrap();
let later = std::sync::Arc::new(later);
let (said, heard) = mpsc::channel();
let waiter = std::thread::spawn({
let later = later.clone();
move || {
said.send(later.wait_started(Duration::from_millis(100)))
.ok()
}
});
// Well past the time a live holder would have beaten it.
assert!(
heard.recv_timeout(Duration::from_millis(3500)).is_err(),
"a closing server is waited for"
);
// The window ends the wait by stopping its own server: the start then
// ends because its server is gone, not because another had the books.
later.stop(Duration::from_secs(30));
let answer = heard
.recv_timeout(Duration::from_secs(30))
.expect("the wait ended");
assert!(
answer.as_ref().is_err_and(|why| why != ANOTHER_HAS_THEM),
"{answer:?}"
);
waiter.join().unwrap();
drop(lock);
}
/// The window closes after the child was spawned and before the start
/// stored it (finding: the window closed before the start thread stored
/// the child): the start stops it itself.
+74 -13
View File
@@ -123,6 +123,15 @@ pub const STOP_WAIT: Duration = Duration::from_secs(90);
/// taken them, is seen before this one is taken to have lost the race.
const BEATEN_AFTER: Duration = Duration::from_millis(300);
/// How long the same live program must hold the books, against a start
/// being waited for, before that start is taken to have lost: well past
/// the moment between a server taking the lock and saying what it is, or
/// a stale word of a server that crashed being replaced.
const LOST_AFTER: Duration = Duration::from_secs(2);
/// How often a start that is waited for is checked for having lost.
const BEATEN_LOOK: Duration = Duration::from_millis(50);
/// What [`AppServer::wait_ready_unless_beaten`] came to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Waited {
@@ -511,18 +520,65 @@ impl AppServer {
matches!(&*self.shared.phase(), Phase::Ready)
}
/// Whether the books are held by a program that is up and serving and
/// is not this server: a host (`wanderbooks serve`), or another app's
/// server that says so and is not closing. What is only finishing (a
/// server that has begun to close, a host's orphan, one a command is
/// running for the length of its work) is not that: it ends by itself,
/// and this server waits for it. Nor is a lock held with no word
/// readable, or with the word of one that is gone: that is the moment
/// before this server says what it is, or an earlier build's. Each is
/// waited for; none counts as another's.
fn another_serves(&self) -> Option<u32> {
if host_lock_held(&self.run) {
// A host's own pid is not known here: a changing holder is
// not told apart, and a host lock held does not come from
// this child, which takes only the server's.
return Some(0);
}
if !server_lock_held(&self.run) {
return None;
}
let info = ledger_mcp::local::read_server_info(&self.run)?;
(info.by == StartedBy::App && !info.closing && info.pid != self.pid).then_some(info.pid)
}
/// Wait for the server to be ready for as long as it lives: a server
/// still opening companies, or waiting for another server to finish
/// (local.rs INVARIANT 1), is waited for and not given up on; `Err`
/// only when it has exited (INVARIANT 8). `slice` is how long each
/// wait runs before the server is looked at again.
/// only when it has exited (INVARIANT 8), or when a host or another
/// live app server has held the books for [`LOST_AFTER`], the same
/// one all that time (the start lost the race: a second window, two
/// starts at once): this server is then stopped and the words are
/// [`ANOTHER_HAS_THEM`]. A server that is only finishing, a closing
/// backup of the window just closed included, is waited for. `slice`
/// is how long each wait runs before the server is looked at again.
pub fn wait_started(&self, slice: Duration) -> Result<(), String> {
let mut beaten: Option<(u32, Instant)> = None;
loop {
match self.wait_ready(slice) {
// Looked at often, whatever `slice` is: whether another
// program holds the books is read between the waits.
match self.wait_ready(slice.min(BEATEN_LOOK)) {
Ok(()) => return Ok(()),
Err(_) if self.exited().is_none() => {}
Err(why) => return Err(why),
}
match self.another_serves() {
Some(pid) => {
let (held, since) = beaten.get_or_insert((pid, Instant::now()));
if *held != pid {
(*held, *since) = (pid, Instant::now());
}
if since.elapsed() >= LOST_AFTER {
// This child only waits on the other's lock. Its
// input is closed, which ends it without touching
// anything.
self.stop(FAILED_START_STOP_WAIT);
return Err(ANOTHER_HAS_THEM.into());
}
}
None => beaten = None,
}
}
}
@@ -998,7 +1054,7 @@ impl AppHost {
/// Close the window's books (INVARIANT 9): each open company is closed
/// first, so its closing backup is reported if it was not whole; then
/// the server's input is closed and its exit waited for, the whole
/// taking about `within`. `Ok(None)` when all went whole; else the
/// taking at most `within` in all. `Ok(None)` when all went whole; else the
/// words, a line each (the companies whose backup was incomplete, a
/// server that exited badly or is still closing). Never kills.
pub fn stop(&self, within: Duration) -> Result<Option<String>, String> {
@@ -1007,10 +1063,13 @@ impl AppHost {
let Some(server) = self.slot().take() else {
return Ok(None);
};
let begun = Instant::now();
// One deadline for the whole close (WB-app-4): every step gets
// what is left of it.
let deadline = Instant::now() + within;
let remaining = || deadline.saturating_duration_since(Instant::now());
let mut said: Vec<String> = Vec::new();
if server.is_ready() && server.exited().is_none() {
match server.books(Some(within)) {
match server.books(Some(remaining())) {
Ok(books) => {
let open: Vec<String> =
books.into_iter().filter(|b| b.open).map(|b| b.id).collect();
@@ -1020,9 +1079,9 @@ impl AppHost {
let handles: Vec<_> = open
.iter()
.map(|id| {
let server = &server;
let (server, remaining) = (&server, &remaining);
scope.spawn(move || {
match server.close_book_within(id, Some(within)) {
match server.close_book_within(id, Some(remaining())) {
Ok(notice) => notice,
Err(why) => {
Some(format!("{id} could not be closed cleanly: {why}"))
@@ -1033,7 +1092,12 @@ impl AppHost {
.collect();
handles
.into_iter()
.map(|h| h.join().unwrap_or(None))
.zip(open.iter())
.map(|(h, id)| {
h.join().unwrap_or_else(|_| {
Some(format!("{id} could not be closed cleanly: the close stopped unexpectedly"))
})
})
.collect()
});
said.extend(notices.into_iter().flatten());
@@ -1043,10 +1107,7 @@ impl AppHost {
)),
}
}
let left = within
.saturating_sub(begun.elapsed())
.max(Duration::from_secs(5));
match server.stop(left) {
match server.stop(remaining()) {
Stopped::Closed => {}
Stopped::Failed(how) => said.push(format!(
"The books server ended badly ({how}). Its log is {SERVER_LOG} in the books' run folder; `wanderbooks doctor` says whether the books are whole."
+69 -6
View File
@@ -42,6 +42,10 @@
//! which sends a real resolver to TCP and sends a spoofed source
//! nothing larger than its query. All UDP answers together are
//! limited by a global rate; past it, silence.
//! 8. The relay's own host has its own CAA set, the same authorities with
//! no method restriction, so its certificate can be had by HTTP-01;
//! no other name below the apex has a CAA of its own, and with no
//! authority listed there is no CAA record anywhere.
//! 7. The CAA answer at the apex lists exactly the authority list's
//! issuer domains, each with `validationmethods=dns-01`; with no
//! authority listed there is no CAA record.
@@ -90,6 +94,8 @@ const QUERY_MAX: usize = 1232;
pub struct DnsService {
zone: Zone,
domain: DnsName,
/// The relay's own host, lower case, no trailing dot.
relay_host: String,
v4: Vec<Ipv4Addr>,
v6: Vec<Ipv6Addr>,
nameservers: Vec<(String, DnsName, Vec<IpAddr>)>,
@@ -127,6 +133,7 @@ impl DnsService {
Ok(DnsService {
zone,
domain,
relay_host: cfg.relay_host.trim_end_matches('.').to_ascii_lowercase(),
v4: cfg.address_v4.clone(),
v6: cfg.address_v6.clone(),
nameservers,
@@ -138,18 +145,32 @@ impl DnsService {
/// The CAA record set of the apex: one `issue` per listed authority,
/// DNS-01 only (RFC 8657).
fn caa(&self) -> Vec<Record> {
self.caa_set(&self.domain, true)
}
/// The CAA record set of the relay's own host: the same authorities,
/// with no method restriction, so the relay's own certificate can be
/// had by HTTP-01 (RFC 8555 section 8.3). A certificate authority uses
/// the closest record set, so this one replaces the apex's for this
/// one name and for no other.
fn caa_relay_host(&self, owner: &DnsName) -> Vec<Record> {
self.caa_set(owner, false)
}
fn caa_set(&self, owner: &DnsName, dns01_only: bool) -> Vec<Record> {
self.authorities
.caa_issuers()
.iter()
.filter_map(|issuer| {
let issuer = DnsName::from_ascii(issuer).ok()?;
let data = CAA::new_issue(
false,
Some(issuer),
vec![KeyValue::new("validationmethods", "dns-01")],
);
let params = if dns01_only {
vec![KeyValue::new("validationmethods", "dns-01")]
} else {
vec![]
};
let data = CAA::new_issue(false, Some(issuer), params);
Some(Record::from_rdata(
self.domain.clone(),
owner.clone(),
TTL_ADDR,
RData::CAA(data),
))
@@ -303,6 +324,9 @@ impl DnsService {
}
}
RecordType::CAA if apex => resp.answers = self.caa(),
RecordType::CAA if lower == self.relay_host => {
resp.answers = self.caa_relay_host(&owner);
}
RecordType::TXT => {
if let ["_acme-challenge", name] = labels.as_slice()
&& let Ok(name) = Name::parse(&name.to_ascii_lowercase())
@@ -737,6 +761,45 @@ mod tests {
assert_eq!(below.authorities.len(), 1);
}
#[test]
fn caa_at_the_relay_host_permits_the_listed_authorities_by_any_method() {
let (svc, _) = svc();
let m = ask(&svc, "relay.wanderbooks.link.", RecordType::CAA, true);
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
let shown: Vec<String> = m.answers.iter().map(|r| r.data.to_string()).collect();
assert_eq!(shown, [r#"0 issue "letsencrypt.org""#]);
assert!(!shown[0].contains("validationmethods"));
// The apex is what it was, and another host under the relay's
// label, or an app's name, still has none of its own.
let apex = ask(&svc, "wanderbooks.link.", RecordType::CAA, true);
let apex: Vec<String> = apex.answers.iter().map(|r| r.data.to_string()).collect();
assert_eq!(
apex,
[r#"0 issue "letsencrypt.org; validationmethods=dns-01""#]
);
for other in ["x.relay.wanderbooks.link.", "ns1.wanderbooks.link.", APP] {
let m = ask(&svc, other, RecordType::CAA, true);
assert!(m.answers.is_empty(), "{other}");
assert_eq!(m.authorities.len(), 1, "{other}");
}
}
#[test]
fn no_authority_list_means_no_caa_even_at_the_relay_host() {
let cfg = Config::default();
let txt = Arc::new(TxtStore::new(Duration::from_secs(60), 10, 4, 100));
let svc = DnsService::new(
Zone::new(&cfg.domain, &cfg.relay_host),
&cfg,
txt,
Arc::new(AuthorityList::empty()),
)
.unwrap();
for name in ["wanderbooks.link.", "relay.wanderbooks.link."] {
assert!(ask(&svc, name, RecordType::CAA, true).answers.is_empty());
}
}
#[test]
fn caa_is_made_from_the_list_and_follows_it() {
let dir = tempfile::tempdir().unwrap();
+24
View File
@@ -0,0 +1,24 @@
# The certificate authorities the relay offers to apps, in the order they
# are tried, and the source of the zone's CAA record. Installed as
# /etc/wanderbooks-relay/authorities.toml. The relay reads it again within
# half a minute of a change; a file with a mistake is refused and the old
# list stays in force. At most 16 entries.
#
# An app sends requests only to authorities compiled into it (Let's
# Encrypt, Google Trust Services, ZeroSSL, SSL.com), so a different
# authority here is only useful if the program already knows it.
#
# A binding secret (binding_kid, binding_hmac_key) is never put here: the
# relay refuses a file that has one. An authority that needs a binding
# (needs_binding = true) is offered as not usable, because no per-app
# source of bindings is built yet, so only authorities that need none work.
[[authority]]
# A short name for this authority, unique in the file.
id = "letsencrypt"
# Its ACME directory address (RFC 8555), https, from its own documentation.
directory = "https://acme-v02.api.letsencrypt.org/directory"
# The name this authority goes by in a CAA record (its "issuer domain
# name"). The relay publishes `issue "letsencrypt.org;
# validationmethods=dns-01"` at the domain's apex from this.
caa_domain = "letsencrypt.org"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# certbot runs this each time it gets or renews the relay's certificate
# (a "deploy hook"): it copies the new files to where the relay reads them
# and restarts the relay, which reads its certificate only when it starts.
# Installed as /etc/letsencrypt/renewal-hooks/deploy/wanderbooks-relay.sh,
# mode 0755. certbot sets RENEWED_LINEAGE to the certificate's folder.
set -eu
dest=/etc/wanderbooks-relay
install -o root -g wanderbooks-relay -m 0644 "$RENEWED_LINEAGE/fullchain.pem" "$dest/relay-cert.pem"
install -o root -g wanderbooks-relay -m 0640 "$RENEWED_LINEAGE/privkey.pem" "$dest/relay-key.pem"
systemctl restart wanderbooks-relay
+71
View File
@@ -0,0 +1,71 @@
# Settings for the relay (docs/relay-deploy.md). Every key here is a real
# key of `relay::Config`; a key the relay does not know stops it from
# starting, so a typo is caught at once. Installed as
# /etc/wanderbooks-relay/relay.toml.
#
# Replace each <placeholder> before starting. Times, in [limits], are in
# milliseconds.
# The domain the relay serves and is the DNS server of.
domain = "wanderbooks.link"
# The host an app's line dials. The program has this name built in, so
# leave it as it is.
relay_host = "relay.wanderbooks.link"
# Where the router listens: TCP 443. "[::]" is every IPv6 and IPv4
# address of the machine (Linux answers both on one socket). Use
# "0.0.0.0:443" for IPv4 only.
router_addr = "[::]:443"
# Where DNS listens: UDP and TCP, the same number. 53 in production.
dns_addr = "[::]:53"
# The registry: the one durable table, name to the app's public key.
# Back it up (docs/relay-deploy.md); losing it lets anyone claim a name
# someone else holds. The state folder is made by the service unit.
registry_path = "/var/lib/wanderbooks-relay/registry.sqlite3"
# The relay's own certificate for relay.wanderbooks.link, PEM, the whole
# chain, and its private key, PEM. The relay reads them once, when it
# starts: a new certificate needs a restart. These are not the apps'
# certificates; the relay holds none of those.
tls_cert = "/etc/wanderbooks-relay/relay-cert.pem"
tls_key = "/etc/wanderbooks-relay/relay-key.pem"
# The certificate authorities offered to apps, and the zone's CAA record
# is made from the same file (see authorities.toml). The file is read
# again within half a minute of a change. Keep this on: without a list
# the relay publishes no CAA record, and no app can get a certificate.
authorities_path = "/etc/wanderbooks-relay/authorities.toml"
# The addresses every name under the domain points at: this machine's
# public addresses. Leave address_v6 empty ([]) if the machine has none.
address_v4 = ["<server IPv4>"]
address_v6 = ["<server IPv6>"]
# The domain's name servers, as the DNS answers for them. They must be the
# same names, with the same addresses, as the host records and NS records
# at the registrar. Two names, because the registry of a domain wants at
# least two; both may be this one machine.
[[nameservers]]
name = "ns1.wanderbooks.link"
v4 = ["<server IPv4>"]
v6 = ["<server IPv6>"]
[[nameservers]]
name = "ns2.wanderbooks.link"
v4 = ["<server IPv4>"]
v6 = ["<server IPv6>"]
# Limits. Every one has a default (crates/relay/src/config.rs) sized for
# hundreds of thousands of apps on a large machine. Only the two that
# matter for memory are set here, for a 1 GB machine: an idle app costs
# about 15.4 KiB (the measurement in crates/relay/tests/memory.rs).
[limits]
# Apps connected at once. Past this a new app is turned away until one
# leaves. 20,000 idle lines is about 310 MiB.
max_lines = 20000
# Connections of every kind at once: apps' lines, assistants being
# spliced through, and connections still saying hello.
max_connections = 40000
+70
View File
@@ -0,0 +1,70 @@
# The relay for wanderbooks.link (plan P15, unit B2; docs/relay-deploy.md).
#
# One process, one account, two jobs: it routes an assistant's TLS
# connection down the line an app holds open (TCP 443), and it is the
# domain's DNS server (UDP and TCP 53). It runs as its own account with no
# shell, and the only file it writes is its registry, in its state folder.
#
# Install: the binary is /usr/local/bin/wanderbooks-relay (the `relay`
# program from `cargo build --release -p relay`), the settings are
# /etc/wanderbooks-relay/relay.toml and the certificate files that file
# names sit beside it. See docs/relay-deploy.md for every step.
[Unit]
Description=wanderbooks relay: routes web assistants to apps, and is the DNS of wanderbooks.link
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=wanderbooks-relay
Group=wanderbooks-relay
DynamicUser=no
# Makes /var/lib/wanderbooks-relay, owned by the account, and is the only
# writable place (the registry lives there).
StateDirectory=wanderbooks-relay
StateDirectoryMode=0700
WorkingDirectory=/var/lib/wanderbooks-relay
ExecStart=/usr/local/bin/wanderbooks-relay /etc/wanderbooks-relay/relay.toml
# The relay shuts down cleanly on SIGINT (Ctrl-C) and on nothing else: a
# SIGTERM would end it at once. So systemd stops it with SIGINT.
KillSignal=SIGINT
TimeoutStopSec=30
Restart=on-failure
RestartSec=2s
# The relay writes its log lines to standard error; the journal keeps them.
# One line a minute carries the counters (lines, routed, shed, ...).
StandardOutput=journal
StandardError=journal
# Ports 53 and 443 are below 1024. This one capability lets the account
# bind them and nothing more.
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
# Each idle app is one open socket, and each caller in flight is another.
# 262144 is far above what a small machine can hold in memory.
LimitNOFILE=262144
# The account and the filesystem.
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
LockPersonality=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
RestrictNamespaces=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
SystemCallArchitectures=native
UMask=0077
[Install]
WantedBy=multi-user.target
+2
View File
@@ -95,3 +95,5 @@ Columns: date | type (scout, run/verify, implement, refactor, debug, review) | p
- 2026-11-21 | impl-multi 3 | sonnet (high) | backups fix round (13 items: proof after each backup, drill on the newest only, repair, ahead vs diverged, lost key, no consolidation) | accepted on tests rerun after merge
- 2026-11-21 | debug 2 | sonnet (high) | a phone number refused as a tax id; the burst-close test | accepted: phones and ZIP+4 kept, the test's assumption fixed; rerun after merge
- 2026-11-21 | debug 3 | sonnet (high) | two Windows-only failures (authority list change detection; the assistant pictures) | accepted: rerun after merge; the Windows hash was reproduced on Linux with the dock held back
- 2026-11-22 | impl-multi 2 | sonnet | the relay's setup kit for a Vultr machine; CAA at the relay's own name so its certificate renews | accepted: hunk read, relay tests rerun
- 2026-11-22 | read 2 + impl 2 | sonnet | a late review of the app's server rechecked on main; the lost-race start, the 90 s close deadline, a panicked close's notice | accepted after one send-back: a closing holder is waited for, missing info never counts
+425
View File
@@ -0,0 +1,425 @@
# Running the relay on wanderbooks.link
This guide brings the relay up on a rented machine, step by step. The relay
is the program that lets a web assistant (Claude, ChatGPT) reach a tester's
desktop app. It has only ever run inside the test suite, so the first real
run is also its first test. The design is in `plan/p15-app-and-relay.md`
(section 5) and the rules in `docs/spec/claims/relay.md`.
Commands marked "desktop" are for your own Linux computer and work in fish.
Commands marked "server" are typed on the rented machine after `ssh`, where
the shell is bash.
## What the relay does, in one paragraph
One program does two jobs. It is the DNS server for `wanderbooks.link`: every
name under the domain points at the machine, so there is no zone file to
maintain. It also listens on port 443, reads the server name in the first
message of each connection, and passes the connection down the line the
right app holds open, without reading it. The only certificate the relay
holds is its own, for `relay.wanderbooks.link`: apps dial that name and check
it against the public roots. Apps get their own certificates; the relay holds
none of them.
## 1. What to rent on Vultr
Rent one machine:
- Product: Cloud Compute, the regular (shared CPU) type, the smallest plan:
1 vCPU, 1 GB of memory, about $5 to $6 a month. Check the price on the page.
- Operating system: Debian 13 (the current stable release). If the list does
not offer 13, take Debian 12. Why Debian: it ships with nothing listening
on port 53 (Ubuntu runs a small resolver there, and the relay needs the
port), it is plain and long supported, and it has the packages we use
(`certbot`, `ufw`, `unattended-upgrades`).
- Location: any region. Pick the one nearest the testers.
- Turn on IPv4 (it is on) and IPv6 ("Enable IPv6" in the deploy form). The
relay serves both.
- Add your SSH public key in the deploy form. You will log in as `root` with
the key, and the relay itself runs as an account with no powers.
How many testers fit: the relay measured 15.4 KiB of memory for each idle
app (`crates/relay/tests/memory.rs`). After the system's own share, a 1 GB
machine has room for tens of thousands of idle apps. The settings file
sets `max_lines = 20000` (about 310 MiB), which is hundreds of times more
than a test release needs. Memory is not the limit here; the certificate
authority's 50 new certificates a week is (see section 11).
When the machine is up, copy two things from the Vultr page: the IPv4
address and the IPv6 address. The rest of this guide calls them
`<server IPv4>` and `<server IPv6>`.
## 2. DNS: hand the domain to the relay
The relay answers all DNS for `wanderbooks.link` itself, so you do not add
an A record, a wildcard or a CAA record anywhere. You tell the registrar
where the domain's name servers are. The name servers are named inside the
domain (`ns1.wanderbooks.link`), so the registrar must also be told their
addresses. These are called glue or host records.
Where the domain is registered, add these. Remove any other name servers
and any DNSSEC (DS) record, because the relay does not sign its answers.
| What | Name | Type | Value |
|---|---|---|---|
| Host (glue) record | `ns1.wanderbooks.link` | A | `<server IPv4>` |
| Host (glue) record | `ns1.wanderbooks.link` | AAAA | `<server IPv6>` |
| Host (glue) record | `ns2.wanderbooks.link` | A | `<server IPv4>` |
| Host (glue) record | `ns2.wanderbooks.link` | AAAA | `<server IPv6>` |
| Name servers of the domain | `wanderbooks.link` | NS | `ns1.wanderbooks.link` |
| Name servers of the domain | `wanderbooks.link` | NS | `ns2.wanderbooks.link` |
Two names point at one machine because a domain registry wants two name
servers. Some registrars refuse two names with the same address. If yours
does, tell the person running the project before going on, and an extra
Vultr address can be added.
The relay then answers these, which you can see with `dig` in section 9. You
do not enter them anywhere:
| Name | Type | What the relay answers |
|---|---|---|
| `wanderbooks.link` and every name beneath it, including `relay.wanderbooks.link` and `*.<anything>.wanderbooks.link` | A, AAAA | `<server IPv4>`, `<server IPv6>` |
| `wanderbooks.link` | NS, SOA | the two name servers above |
| `wanderbooks.link` | CAA | `0 issue "letsencrypt.org; validationmethods=dns-01"` (made from `authorities.toml`) |
| `_acme-challenge.<four-words>.wanderbooks.link` | TXT | the proof value an app has just handed the relay, for a few minutes |
The CAA record matters for the relay's own certificate; section 7 explains.
## 3. First login and the machine's basics
Desktop:
```fish
ssh root@<server IPv4>
```
Server (bash), as root. Update, install what is needed, and turn on the
automatic security updates:
```bash
apt-get update && apt-get -y upgrade
apt-get -y install ufw unattended-upgrades certbot build-essential git curl sqlite3 dnsutils
printf 'APT::Periodic::Update-Package-Lists "1";\nAPT::Periodic::Unattended-Upgrade "1";\n' > /etc/apt/apt.conf.d/20auto-upgrades
```
The firewall. Port 22 is for you, 53 (both kinds) and 443 are the relay, and
80 is used only by certbot for the relay's certificate (section 7):
```bash
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 53/tcp
ufw allow 53/udp
ufw allow 80/tcp
ufw allow 443/tcp
ufw enable
```
Say `y` when it warns about ssh. Keep this terminal open, and in another
desktop terminal check `ssh root@<server IPv4>` still works before closing
it.
Turn off password logins (the key is the way in):
```bash
sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
systemctl reload ssh
```
A 1 GB machine can run out of memory while it compiles the relay, so add
some swap space:
```bash
fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
```
Nothing may already listen on port 53. This must print nothing:
```bash
ss -lunp | grep ':53 '
```
## 4. Getting the relay onto the machine
Recommended: build it on the server. The relay's program is called `relay`
and is built from this repository. Building on the server needs no
cross-compiler and cannot hit a mismatch between your desktop's system
libraries and the server's, which a program built on a newer Linux desktop
can (it then refuses to start with an error about `GLIBC`).
Copying a binary built on your desktop is possible for a statically linked
`x86_64-unknown-linux-musl` build. The relay's dependencies are pure Rust
apart from two that compile C (`ring` and bundled SQLite, and no OpenSSL), so
musl should work, but nobody has tried it here, and it needs the musl target
and `musl-gcc` on your desktop. This guide does not use it.
Server (bash). Install Rust, fetch the code and build. The build takes
several minutes on this machine:
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
. "$HOME/.cargo/env"
git clone https://github.com/swaits/wanderbooks /root/wanderbooks
cd /root/wanderbooks
cargo build --release --locked -p relay
```
When it ends, `/root/wanderbooks/target/release/relay` exists.
## 5. The account, the folders and the settings
Server (bash), from `/root/wanderbooks`:
```bash
cd /root/wanderbooks
useradd --system --home-dir /var/lib/wanderbooks-relay --no-create-home \
--shell /usr/sbin/nologin wanderbooks-relay
install -m 0755 target/release/relay /usr/local/bin/wanderbooks-relay
install -d -o root -g wanderbooks-relay -m 0750 /etc/wanderbooks-relay
install -o root -g wanderbooks-relay -m 0640 deploy/relay/relay.toml /etc/wanderbooks-relay/relay.toml
install -o root -g wanderbooks-relay -m 0640 deploy/relay/authorities.toml /etc/wanderbooks-relay/authorities.toml
install -m 0644 deploy/relay/wanderbooks-relay.service /etc/systemd/system/wanderbooks-relay.service
install -D -m 0755 deploy/relay/install-relay-cert.sh /etc/letsencrypt/renewal-hooks/deploy/wanderbooks-relay.sh
systemctl daemon-reload
```
Open the settings and replace the placeholders (`<server IPv4>` three times
and `<server IPv6>` three times, with the real addresses, no angle
brackets). If the machine has no IPv6, set `address_v6 = []` and delete the
`v6` lines:
```bash
nano /etc/wanderbooks-relay/relay.toml
```
Every setting is explained in that file. The state folder
`/var/lib/wanderbooks-relay` is made by the service unit; the registry (the
durable table of names and keys) lives there as `registry.sqlite3`.
## 6. The first start, with a stand-in certificate
The relay will not start without certificate files, and certbot can only
prove the name `relay.wanderbooks.link` once the relay is running and
answering DNS for it. So there is one first-start step: give the relay a
two-day self-signed stand-in so it can start. Certbot replaces it in the
next section.
Server (bash):
```bash
cd /etc/wanderbooks-relay
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
-days 2 -subj '/CN=relay.wanderbooks.link' \
-keyout relay-key.pem -out relay-cert.pem
chown root:wanderbooks-relay relay-key.pem relay-cert.pem
chmod 0640 relay-key.pem relay-cert.pem
systemctl enable --now wanderbooks-relay
journalctl -u wanderbooks-relay -n 20 --no-pager
```
The log should say `router on ... DNS on ... (udp) and ... (tcp)`. If it
says `could not start`, read the reason: a typo in `relay.toml`, or
something already on port 53 or 443.
Now check that the domain is delegated to it. Desktop (fish):
```fish
dig +short NS wanderbooks.link
dig +short A relay.wanderbooks.link
```
The first should print the two `ns` names and the second `<server IPv4>`.
Registrar changes can take from minutes to a day to reach everyone. Do not
go on until both answer.
## 7. The relay's own certificate
The relay needs a publicly trusted certificate for `relay.wanderbooks.link`,
because every app checks the relay against the public roots. The relay does
not obtain it; certbot does, with the HTTP method on port 80 (certbot
listens there itself for a moment; the relay does not use port 80). The
relay's DNS publishes a CAA record for this one name that lets Let's Encrypt
issue by any method, while every app's name still has the stricter
DNS-only rule from the apex. That is why the authority list is on from the
start.
Server (bash):
```bash
certbot certonly --standalone --preferred-challenges http \
-d relay.wanderbooks.link --agree-tos --register-unsafely-without-email \
--deploy-hook /etc/letsencrypt/renewal-hooks/deploy/wanderbooks-relay.sh
```
(Use `-m <your address>` in place of `--register-unsafely-without-email` if
you want expiry mail from Let's Encrypt.) The deploy hook copies the new
files over the stand-in and restarts the relay. Check the result:
```bash
journalctl -u wanderbooks-relay -n 20 --no-pager
certbot certificates
```
## 8. Renewal
Nothing to do. The `certbot` package runs its own timer twice a day and
renews the certificate when it is about 30 days from its end. The deploy
hook then copies the files and restarts the relay, because the relay reads
its certificate only when it starts. The restart drops every app's line
for a second or two. The apps redial by themselves, with a short random wait
that starts at one second (`crates/ledger-link`), so they come back without
anyone doing anything.
To see that renewal will work, without changing anything. Server (bash):
```bash
certbot renew --dry-run
```
Port 80 must stay open in the firewall for this to work.
## 9. Checking it works, from your desktop
None of this needs any wanderbooks program. Desktop (fish):
```fish
# The name servers and the delegation (what the registrar tells the world).
dig +short NS wanderbooks.link
# Any name under the domain is at the relay, including made-up ones.
dig +short A relay.wanderbooks.link
dig +short AAAA relay.wanderbooks.link
dig +short A anything.at-all.wanderbooks.link
# The relay's own answers, bypassing every cache.
dig @<server IPv4> CAA wanderbooks.link +noall +answer
dig @<server IPv4> +tcp A relay.wanderbooks.link +short
# It is not an open resolver: a name outside the domain is refused.
dig @<server IPv4> example.com +noall +comments | grep status
```
Expected: two `ns` names, `<server IPv4>` (and `<server IPv6>` for AAAA),
the CAA line `0 issue "letsencrypt.org; validationmethods=dns-01"`, and
`status: REFUSED` for `example.com`. Also check the relay's own name: `dig @<server IPv4> CAA relay.wanderbooks.link +noall +answer` should print
`0 issue "letsencrypt.org"`, with no `validationmethods`.
The TLS door. The first command should show a certificate for
`relay.wanderbooks.link` from Let's Encrypt and `Verify return code: 0 (ok)`.
The second, with a name nobody has claimed, should end at once with an
`unrecognized_name` alert:
```fish
openssl s_client -connect <server IPv4>:443 -servername relay.wanderbooks.link -tls1_3 </dev/null 2>&1 | grep -E 'subject=|issuer=|Verify return'
openssl s_client -connect <server IPv4>:443 -servername nothing.here.wanderbooks.link -tls1_3 </dev/null 2>&1 | grep -i -E 'alert|unrecognized'
```
The relay's log, which carries a line of counters every minute. Desktop:
```fish
ssh root@<server IPv4> journalctl -u wanderbooks-relay -n 50 --no-pager
ssh root@<server IPv4> journalctl -u wanderbooks-relay -f
```
A line like `lines 0 routed 0 unknown_or_offline 1 shed 0 hello_timeouts 0
bad_hello 0 claims 0` is healthy and idle. `lines` is apps connected now,
`claims` is names registered since the start, and `shed` counts connections
turned away because the relay was full.
Last, the real test: on a desktop with the app, turn on web assistants for a
company and watch `lines` become 1 in the log.
## 10. Looking after it
Restart, status and stop. Server (bash):
```bash
systemctl status wanderbooks-relay
systemctl restart wanderbooks-relay # drops every line; apps reconnect
```
Update to a new version of the relay. Server (bash):
```bash
cd /root/wanderbooks && git pull
. "$HOME/.cargo/env"
cargo build --release --locked -p relay
install -m 0755 target/release/relay /usr/local/bin/wanderbooks-relay
systemctl restart wanderbooks-relay
```
Changing the authority list needs no restart: edit
`/etc/wanderbooks-relay/authorities.toml` and the relay reads it within half
a minute. The settings file (`relay.toml`) and the certificate are read
only at start.
Block or unblock a name (a name is four words joined by hyphens). Server
(bash):
```bash
sudo -u wanderbooks-relay /usr/local/bin/wanderbooks-relay /etc/wanderbooks-relay/relay.toml block <four-word-name>
sudo -u wanderbooks-relay /usr/local/bin/wanderbooks-relay /etc/wanderbooks-relay/relay.toml unblock <four-word-name>
```
A block closes that app's line within about ten seconds.
Back up the registry. It is the one thing that cannot be rebuilt: it records
which key owns which name. If it is lost, every app's name is up for grabs.
Make a consistent copy while the relay runs, and bring it to your desktop.
Server (bash):
```bash
install -d -m 0700 /root/relay-backups
sqlite3 /var/lib/wanderbooks-relay/registry.sqlite3 ".backup /root/relay-backups/registry-$(date +%F).sqlite3"
```
Desktop (fish):
```fish
mkdir -p ~/relay-backups
scp 'root@<server IPv4>:/root/relay-backups/*' ~/relay-backups/
```
Do this after any day with new testers. To restore, stop the relay, put the
file back as `/var/lib/wanderbooks-relay/registry.sqlite3`, run
`chown wanderbooks-relay:wanderbooks-relay` on it, and start the relay. Also
consider Vultr's paid automatic backups for the whole machine.
## 11. What this does not do yet
Each item is checked against the code.
- **A renewal restarts the relay.** The relay reads its certificate only
when it starts (`crates/relay/src/tls.rs`), so each renewal, about every
60 days, drops every line for a moment. Apps redial on their own, so no
one has to act, but an assistant mid-call fails. Reloading the certificate
without a restart is not built.
- **No watching of the certificate logs.** The plan says the app should warn
the owner of a certificate issued for their name that they did not ask for.
Nothing in the code does this. A relay that misused its DNS to get a
certificate for a tester's name would not be noticed.
- **No higher Let's Encrypt limit.** Until Let's Encrypt grants a raised
limit, only 50 new apps a week can get certificates, and the relay enforces
that ceiling itself (`cert_publishes_per_window`). The request is a human
task, made for the registered domain by one account, and the plan says to
send it as soon as the relay runs. It has not been sent.
- **No monitoring.** The relay has no health page or metrics port. The only
signals are the minute counters in the log and the checks in section 9.
Nothing tells you if the machine is down. A free external uptime check on
`https://relay.wanderbooks.link` and on a `dig` of the domain would do.
- **One machine, one point of failure.** Both name servers are the same
machine. If it is down, the domain does not resolve (for five minutes after
its answers expire) and no assistant reaches any app.
- **Authorities that need an account binding do not work.** Only Let's
Encrypt is in the sample list. ZeroSSL and similar are listed as not
usable, because the per-app source of bindings is not built.
- **Untried against the real thing.** The relay has never run outside tests,
against a real certificate authority or a real assistant. The largest soak
was 20,000 lines; the 100,000-line soak has not been run.
- **IPv6 and DNSSEC.** The settings listen on `[::]` for both stacks, which
has been checked in the code and not on a live machine. The DNS does not
sign its answers, so the domain must have no DS record at the registrar.
- **No backup schedule.** Section 10 is a manual routine.
+6 -2
View File
@@ -221,7 +221,11 @@ INVARIANTS:
listed authority, `issue "<caa_domain>; validationmethods=dns-01"`
(RFC 8657), from each authority's `caa_domain` in the same list, so
swapping authorities is an edit to one file; with no authority
listed there is no CAA record.
listed there is no CAA record. The relay's own host alone has a set
of its own, the same authorities with no method restriction, so its
certificate can be had by HTTP-01 and renewed by certbot's timer; no
other name below the apex has one, so an app's name still climbs to
the apex and DNS-01.
SCENARIOS:
1. Two apps each publish; each name answers its own value and not the
other's; a bad value is refused; clearing removes only one's own.
@@ -239,7 +243,7 @@ SCENARIOS:
```
*Enforced:* `serve_control`, `TxtStore::publish`, `TxtStore::get`, `DnsService::answer`, `serve_udp`, `serve_tcp`, `AuthorityList::for_app`, `AuthorityList::caa_issuers`, `AuthorityList::reload`, `DnsService::truncated`, `is_proof_value`.
*Checked:* `relay` `tests/relay.rs` (`a_proof_record_is_published_for_ones_own_name_and_no_other`, `publishing_needs_a_proven_line`, `the_authority_list_is_served_and_follows_the_file`, `no_shared_binding_secret_is_ever_served`, `dns_over_udp_over_the_rate_is_answered_truncated`, `dns_over_udp_has_a_global_ceiling`, `dns_over_tcp_is_capped_and_times_out`); unit tests in `src/dns.rs` (`every_name_under_the_zone_is_at_the_relay_even_beneath_a_label_with_a_record`, `the_proof_record_is_answered_for_its_own_name_until_it_expires`, `outside_the_zone_is_refused_and_odd_queries_are_answered_plainly`, `garbage_never_panics_and_is_mostly_ignored`, `caa_at_the_apex_permits_the_listed_authorities_by_dns_01_only`, `caa_is_made_from_the_list_and_follows_it`, `the_truncated_answer_is_the_question_with_the_tc_bit_and_nothing_more`), `src/txt.rs` (`a_value_is_answered_until_its_ttl`, `only_proof_values_are_taken`, `values_per_name_and_names_in_all_are_bounded`, `publishes_are_counted_per_hour`) and `src/authorities.rs` (`the_list_is_served_in_order_and_a_binding_comes_only_from_a_source`, `a_list_file_that_carries_a_binding_secret_is_refused_in_words`, `a_bad_list_is_refused`, `an_edit_changes_what_is_served_and_a_bad_edit_does_not`, `a_binding_source_is_asked_only_for_authorities_that_need_one`).
*Checked:* `relay` `tests/relay.rs` (`a_proof_record_is_published_for_ones_own_name_and_no_other`, `publishing_needs_a_proven_line`, `the_authority_list_is_served_and_follows_the_file`, `no_shared_binding_secret_is_ever_served`, `dns_over_udp_over_the_rate_is_answered_truncated`, `dns_over_udp_has_a_global_ceiling`, `dns_over_tcp_is_capped_and_times_out`); unit tests in `src/dns.rs` (`every_name_under_the_zone_is_at_the_relay_even_beneath_a_label_with_a_record`, `the_proof_record_is_answered_for_its_own_name_until_it_expires`, `outside_the_zone_is_refused_and_odd_queries_are_answered_plainly`, `garbage_never_panics_and_is_mostly_ignored`, `caa_at_the_apex_permits_the_listed_authorities_by_dns_01_only`, `caa_at_the_relay_host_permits_the_listed_authorities_by_any_method`, `no_authority_list_means_no_caa_even_at_the_relay_host`, `caa_is_made_from_the_list_and_follows_it`, `the_truncated_answer_is_the_question_with_the_tc_bit_and_nothing_more`), `src/txt.rs` (`a_value_is_answered_until_its_ttl`, `only_proof_values_are_taken`, `values_per_name_and_names_in_all_are_bounded`, `publishes_are_counted_per_hour`) and `src/authorities.rs` (`the_list_is_served_in_order_and_a_binding_comes_only_from_a_source`, `a_list_file_that_carries_a_binding_secret_is_refused_in_words`, `a_bad_list_is_refused`, `an_edit_changes_what_is_served_and_a_bad_edit_does_not`, `a_binding_source_is_asked_only_for_authorities_that_need_one`).
**WB-relay-6** The app is told the caller's real address by the relay, first, in a header no caller can forge.