From dd576f9feb34f45595beafbf877ee40271008522 Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 11:39:18 +0100 Subject: [PATCH] [relay] F23: quotas (507), a NixOS module behind Caddy with TLS and no logs, and a VM test that no address is kept --- .agents/features/home-relay.md | 83 ++++++++++ crates/relay/src/http.rs | 1 + crates/relay/src/lib.rs | 19 ++- crates/relay/src/main.rs | 5 +- crates/relay/src/store.rs | 85 +++++++++- crates/relay/tests/quotas.rs | 292 +++++++++++++++++++++++++++++++++ deploy/nixos/README.md | 60 +++++++ deploy/nixos/module.nix | 142 ++++++++++++++++ deploy/nixos/test.nix | 82 +++++++++ docs/PROTOCOL.md | 8 +- flake.nix | 7 + 11 files changed, 773 insertions(+), 11 deletions(-) create mode 100644 .agents/features/home-relay.md create mode 100644 crates/relay/tests/quotas.rs create mode 100644 deploy/nixos/README.md create mode 100644 deploy/nixos/module.nix create mode 100644 deploy/nixos/test.nix diff --git a/.agents/features/home-relay.md b/.agents/features/home-relay.md new file mode 100644 index 0000000..911b5a0 --- /dev/null +++ b/.agents/features/home-relay.md @@ -0,0 +1,83 @@ +# F23 — The relay on a home server: quotas, a NixOS module, TLS + +Analysis, 2026-11-16. Issues T#8 (deploy) and Amicitia #51. The container image of T#8 is left for later: the NixOS module is what the home server runs. It builds on F20 (the relay) and +`relay.md` §3–4, which put two things before any relay that faces the internet: **quotas**, and a +**reverse proxy that logs no IP address**. + +## 1. Why and what +Two people on two machines can only chat through a relay both can reach. Mark's home server is the +first one. After F23: +- the relay refuses to fill its disk: per-mailbox and relay-wide caps, answered with a bare **507**; +- `deploy/nixos/module.nix` runs it on NixOS, listening on loopback only, behind **Caddy** with TLS + from Let's Encrypt, and **no access log, no error log with an address in it**; +- a NixOS VM test boots that configuration, sends requests through the proxy from a known address, + and fails if that address appears anywhere in the journal or under `/var/log`; +- Amicitia accepts an `https://` relay address (its own PR). + +## 2. Design +```mermaid +flowchart LR + A[app] -->|TLS 443| C[Caddy: TLS, no logs] + C -->|HTTP 127.0.0.1:8470| R[tabellarius-relay: systemd, DynamicUser, loopback only] + R --> D[(SQLite: PROTOCOL.md section 5)] +``` +### Quotas *(protocol change, §8: a new status)* +| Limit | Default | Set by | +|:--|:--|:--| +| waiting blobs in one mailbox | 1 000 | the protocol | +| waiting bytes in one mailbox | 32 MiB | the protocol | +| waiting bytes on the relay | 1 GiB | `--max-bytes` | +| mailboxes on the relay | 100 000 | `--max-mailboxes` | +| unclaimed invites on the relay | 10 000 | `--max-invites` | + +- Over a limit, the relay answers **507 Insufficient Storage**, bare, like every refusal. The + per-mailbox caps are checked **after** the post token, so 507 tells nothing to someone without + the token. The relay-wide caps say only that the relay is full. +- **No identity is needed to count**: nothing new is stored; the counts come from §5's own columns + (`size`, the rows). No IP address is kept, not even in memory: rate limits by address would need + one. A flood can fill the relay up to its caps; then it refuses, and the operator sees it. +- The client already handles it: 507 is a failure, so the message waits in the outbox. +- **Mailboxes are never deleted yet** (`relay.md` §4): an abandoned mailbox counts against the + 100 000 until a protocol version can delete one. Stated. + +### The NixOS module (`deploy/nixos/module.nix`) +- `services.tabellarius.enable`, `.domain`, `.maxBytes`, `.maxMailboxes`, `.maxInvites`, `.package` + (the flake's own build). +- **The relay:** a systemd service with `DynamicUser`, `StateDirectory=tabellarius` (the database), + `--listen 127.0.0.1:8470`. Hardened: `ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`, + `PrivateDevices`, `NoNewPrivileges`, `MemoryDenyWriteExecute`, `RestrictAddressFamilies=AF_INET + AF_INET6`, `SystemCallFilter=@system-service`, and **`IPAddressDeny=any` with + `IPAddressAllow=localhost`**: even a bug cannot make it talk to anything but the proxy. +- **The proxy:** `services.caddy`, one virtual host, `reverse_proxy 127.0.0.1:8470`. The NixOS + module writes an access log per host by default; the host's `logFormat` is set to + `output discard`, and Caddy's default logger too. Caddy's own TLS-handshake and proxy errors can + name a client address, so no log is the rule; an operator who needs one turns it on and knows + why. Headers: none added. +- **journald:** the relay prints one line at start. Nothing per request. + +### The VM test (`deploy/nixos/test.nix`, `nix flake check`) +Two machines: `server` with the module (TLS from Caddy's internal CA instead of Let's Encrypt), and +`client` at a fixed address. The client creates a mailbox, posts, fetches, acknowledges, makes a +mistake (a wrong token, a malformed request), and fills a mailbox to its 507. Then the test greps +the server's whole journal and `/var/log` for the client's address and fails if it appears. + +**Not run here.** This machine has neither Nix nor WSL. The module and the test are written to be +run with `nix flake check` on Linux, and the PR says so. Mark's server is the first real run. + +## 3. Risks +- **Privacy:** the logs are the risk this feature exists to close. The VM test is its proof, once + it runs. The network layer (a router, the ISP) still sees addresses and timing (§1). +- **Abuse:** caps bound the disk; they do not stop someone from filling them. Proof of work or + invite-only mailbox creation is for a later protocol version. +- **Reproducibility:** the module uses the flake's package, so the relay that runs is the one built + from this commit (`docs/VERIFY.md`). + +## 4. Tests — written first +1. Each cap: the post or create that would cross it gets 507; one under it succeeds; after an + acknowledgement (or a purge) there is room again. +2. The per-mailbox cap answers 404, not 507, to a wrong token. +3. The CLI reads `--max-bytes`, `--max-mailboxes`, `--max-invites`; a bad value is refused. +4. The VM test (§2), on Linux. + +Planted bugs: the mailbox cap checked before the token; an acknowledgement not freeing space; the +global byte cap ignored; the invite cap counting claimed invites; the CLI option ignored. diff --git a/crates/relay/src/http.rs b/crates/relay/src/http.rs index 9965298..bba8c31 100644 --- a/crates/relay/src/http.rs +++ b/crates/relay/src/http.rs @@ -59,6 +59,7 @@ impl From for Status { Refused::Exists => StatusCode::CONFLICT, Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE, Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR, + Refused::Full => StatusCode::INSUFFICIENT_STORAGE, }) } } diff --git a/crates/relay/src/lib.rs b/crates/relay/src/lib.rs index 1e9756e..3c9c6e1 100644 --- a/crates/relay/src/lib.rs +++ b/crates/relay/src/lib.rs @@ -15,16 +15,29 @@ pub const DEFAULT_DB: &str = "tabellarius-relay.db"; pub struct Args { pub listen: SocketAddr, pub db: PathBuf, + pub limits: store::Limits, } -/// `--listen `, `--db `. Anything else is refused with a usage line. +/// `--listen `, `--db `, and the relay-wide quotas `--max-bytes`, +/// `--max-mailboxes`, `--max-invites` (positive integers). Anything else is refused with a usage +/// line. pub fn parse_args>(args: I) -> Result { - let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]"; + let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \ + [--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000]"; let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?; let mut db = PathBuf::from(DEFAULT_DB); + let mut limits = store::Limits::default(); let mut it = args.into_iter(); + let positive = |v: Option| -> Result { + v.and_then(|v| v.parse::().ok()) + .filter(|&n| n > 0) + .ok_or_else(|| usage.to_string()) + }; while let Some(arg) = it.next() { match arg.as_str() { + "--max-bytes" => limits.total_bytes = positive(it.next())?, + "--max-mailboxes" => limits.mailboxes = positive(it.next())?, + "--max-invites" => limits.invites = positive(it.next())?, "--listen" => { listen = it .next() @@ -40,5 +53,5 @@ pub fn parse_args>(args: I) -> Result return Err(usage.to_string()), } } - Ok(Args { listen, db }) + Ok(Args { listen, db, limits }) } diff --git a/crates/relay/src/main.rs b/crates/relay/src/main.rs index 78273ef..cd0ad18 100644 --- a/crates/relay/src/main.rs +++ b/crates/relay/src/main.rs @@ -1,4 +1,5 @@ -//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]` +//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N] +//! [--max-mailboxes N] [--max-invites N]` //! //! Prints one line at start (version and address) and nothing per request. @@ -24,7 +25,7 @@ async fn main() { std::process::exit(2); } }; - let store = match Store::open(&args.db) { + let store = match Store::open_with(&args.db, args.limits) { Ok(s) => Arc::new(s), Err(_) => { eprintln!( diff --git a/crates/relay/src/store.rs b/crates/relay/src/store.rs index 18bae43..bb753fe 100644 --- a/crates/relay/src/store.rs +++ b/crates/relay/src/store.rs @@ -48,6 +48,36 @@ pub enum Refused { TooLarge, /// The database failed; nothing about the request is in the error. Storage, + /// A quota is reached (`PROTOCOL.md` §8, 507): the mailbox's, after its token, or the relay's. + Full, +} + +/// How much the relay holds before it answers [`Refused::Full`]. The per-mailbox caps are the +/// protocol's; the relay-wide ones are the operator's (`.agents/features/home-relay.md` §2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + pub mailbox_blobs: i64, + pub mailbox_bytes: i64, + pub total_bytes: i64, + pub mailboxes: i64, + pub invites: i64, +} + +/// Waiting blobs in one mailbox (`PROTOCOL.md` §8). +pub const MAILBOX_BLOBS: i64 = 1_000; +/// Waiting bytes in one mailbox (`PROTOCOL.md` §8). +pub const MAILBOX_BYTES: i64 = 32 * 1024 * 1024; + +impl Default for Limits { + fn default() -> Self { + Limits { + mailbox_blobs: MAILBOX_BLOBS, + mailbox_bytes: MAILBOX_BYTES, + total_bytes: 1024 * 1024 * 1024, + mailboxes: 100_000, + invites: 10_000, + } + } } impl From for Refused { @@ -58,6 +88,7 @@ impl From for Refused { pub struct Store { conn: Mutex, + limits: Limits, } /// What a purge removed. @@ -73,23 +104,39 @@ fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool { impl Store { pub fn open(path: &Path) -> Result { - Self::init(Connection::open(path)?) + Self::init(Connection::open(path)?, Limits::default()) + } + + pub fn open_with(path: &Path, limits: Limits) -> Result { + Self::init(Connection::open(path)?, limits) } pub fn open_in_memory() -> Result { - Self::init(Connection::open_in_memory()?) + Self::init(Connection::open_in_memory()?, Limits::default()) } - fn init(conn: Connection) -> Result { + pub fn open_in_memory_with(limits: Limits) -> Result { + Self::init(Connection::open_in_memory()?, limits) + } + + fn init(conn: Connection, limits: Limits) -> Result { // Deleted rows are overwritten in the file, and there is no -wal copy of anything. conn.pragma_update(None, "secure_delete", "ON")?; conn.pragma_update(None, "journal_mode", "DELETE")?; conn.execute_batch(SCHEMA)?; Ok(Self { conn: Mutex::new(conn), + limits, }) } + /// One number from the database: a count or a sum, 0 for none. + fn number(conn: &Connection, sql: &str, args: impl rusqlite::Params) -> Result { + Ok(conn + .query_row(sql, args, |r| r.get::<_, Option>(0))? + .unwrap_or(0)) + } + fn conn(&self) -> std::sync::MutexGuard<'_, Connection> { // A panic while holding the lock leaves SQLite consistent (every write is one statement or // one transaction), so a poisoned lock is still safe to use. @@ -97,7 +144,11 @@ impl Store { } pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> { - let changed = self.conn().execute( + let conn = self.conn(); + if Self::number(&conn, "SELECT count(*) FROM mailboxes", [])? >= self.limits.mailboxes { + return Err(Refused::Full); + } + let changed = conn.execute( "INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day) VALUES (?1, ?2, ?3, ?4)", params![ @@ -150,6 +201,20 @@ impl Store { } let conn = self.conn(); Self::authorize(&conn, id, token, Column::Post)?; + // After the token: a stranger learns nothing about this mailbox from a 507. + let size = blob.len() as i64; + let (count, bytes): (i64, Option) = conn.query_row( + "SELECT count(*), sum(size) FROM blobs WHERE mailbox_id = ?1", + [&id.as_bytes()[..]], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + let total = Self::number(&conn, "SELECT sum(size) FROM blobs", [])?; + if count >= self.limits.mailbox_blobs + || bytes.unwrap_or(0) + size > self.limits.mailbox_bytes + || total + size > self.limits.total_bytes + { + return Err(Refused::Full); + } conn.execute( "INSERT INTO blobs (mailbox_id, ciphertext, size, received_hour) VALUES (?1, ?2, ?3, ?4)", params![&id.as_bytes()[..], blob, blob.len() as i64, hour_of(now)], @@ -231,7 +296,17 @@ impl Store { pub fn create_invite(&self, req: &CreateInvite, now: i64) -> Result<(), Refused> { // Expiry rounded up to the hour: the exact second the invite was made is not kept. let expiry = (hour_of(now + INVITE_TTL_SECS) + 1) * 3600; - let changed = self.conn().execute( + let conn = self.conn(); + // Expired invites wait for the hourly purge; they do not count against new ones. + let waiting = Self::number( + &conn, + "SELECT count(*) FROM invites WHERE expiry > ?1", + [now], + )?; + if waiting >= self.limits.invites { + return Err(Refused::Full); + } + let changed = conn.execute( "INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)", params![ &req.id.as_bytes()[..], diff --git a/crates/relay/tests/quotas.rs b/crates/relay/tests/quotas.rs new file mode 100644 index 0000000..b25c0c7 --- /dev/null +++ b/crates/relay/tests/quotas.rs @@ -0,0 +1,292 @@ +//! Quotas (`.agents/features/home-relay.md` §4, `PROTOCOL.md` §8): over a limit the relay answers a +//! bare 507; the per-mailbox caps only after the post token. Small limits, so the tests are quick. + +use axum::body::Body; +use axum::http::{header, Method, Request, StatusCode}; +use http_body_util::BodyExt; +use std::sync::Arc; +use tabellarius_protocol::*; +use tabellarius_relay::http::{router, AppState, Clock}; +use tabellarius_relay::parse_args; +use tabellarius_relay::store::{Limits, Store, MAILBOX_BLOBS, MAILBOX_BYTES}; +use tower::ServiceExt; + +const T0: i64 = 1_794_000_000; + +fn random() -> [u8; N] { + let mut b = [0u8; N]; + getrandom::fill(&mut b).expect("system randomness"); + b +} + +struct Mailbox { + id: MailboxId, + post: Token, + fetch: Token, +} + +impl Mailbox { + fn new() -> Self { + Self { + id: MailboxId::from_bytes(random()), + post: Token::from_bytes(random()), + fetch: Token::from_bytes(random()), + } + } + fn path(&self) -> String { + format!("/v0/mailboxes/{}/blobs", self.id.to_wire()) + } +} + +struct Relay(axum::Router); + +impl Relay { + fn with(limits: Limits) -> Self { + let store = Arc::new(Store::open_in_memory_with(limits).expect("store")); + let clock: Clock = Arc::new(|| T0); + Relay(router(AppState { store, clock })) + } + async fn call( + &self, + method: Method, + path: &str, + auth: Option<&Token>, + body: Vec, + ) -> StatusCode { + let mut req = Request::builder().method(method).uri(path); + if let Some(t) = auth { + req = req.header(header::AUTHORIZATION, t.to_bearer()); + } + let resp = self + .0 + .clone() + .oneshot(req.body(Body::from(body)).expect("request")) + .await + .expect("infallible"); + let status = resp.status(); + let body = resp.into_body().collect().await.expect("body").to_bytes(); + if !status.is_success() { + assert!(body.is_empty(), "a refusal has no body"); + } + status + } + async fn create(&self, m: &Mailbox) -> StatusCode { + let body = serde_json::to_vec(&CreateMailbox { + id: m.id, + post_token_hash: m.post.hash(), + fetch_token_hash: m.fetch.hash(), + }) + .expect("json"); + self.call(Method::POST, "/v0/mailboxes", None, body).await + } + async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode { + self.call(Method::POST, &m.path(), Some(token), blob.to_vec()) + .await + } + async fn ack(&self, m: &Mailbox, blob: &[u8]) -> StatusCode { + let path = format!("{}/{}", m.path(), blob_hash(blob).to_wire()); + self.call(Method::DELETE, &path, Some(&m.fetch), vec![]) + .await + } + async fn invite(&self) -> (StatusCode, InviteId, Token) { + let id = InviteId::from_bytes(random()); + let secret = Token::from_bytes(random()); + let body = serde_json::to_vec(&CreateInvite { + id, + secret_hash: secret.hash(), + key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"), + }) + .expect("json"); + ( + self.call(Method::POST, "/v0/invites", None, body).await, + id, + secret, + ) + } +} + +fn small(f: impl FnOnce(&mut Limits)) -> Limits { + let mut l = Limits::default(); + f(&mut l); + l +} + +#[test] +fn the_protocol_caps_are_the_documented_ones() { + assert_eq!(MAILBOX_BLOBS, 1_000); + assert_eq!(MAILBOX_BYTES, 32 * 1024 * 1024); + let l = Limits::default(); + assert_eq!( + (l.total_bytes, l.mailboxes, l.invites), + (1 << 30, 100_000, 10_000) + ); +} + +#[tokio::test] +async fn a_mailbox_holds_a_thousand_blobs_then_says_full_until_one_is_acknowledged() { + let relay = Relay::with(Limits::default()); + let m = Mailbox::new(); + assert_eq!(relay.create(&m).await, StatusCode::CREATED); + for i in 0..MAILBOX_BLOBS { + assert_eq!( + relay.post(&m, &m.post, &i.to_le_bytes()).await, + StatusCode::CREATED + ); + } + let one_more = b"one more"; + assert_eq!( + relay.post(&m, &m.post, one_more).await, + StatusCode::INSUFFICIENT_STORAGE + ); + // A stranger without the token learns nothing: 404, as for any wrong token. + let stranger = Token::from_bytes(random()); + assert_eq!( + relay.post(&m, &stranger, one_more).await, + StatusCode::NOT_FOUND + ); + assert_eq!( + relay.ack(&m, &0i64.to_le_bytes()).await, + StatusCode::NO_CONTENT + ); + assert_eq!(relay.post(&m, &m.post, one_more).await, StatusCode::CREATED); +} + +#[tokio::test] +async fn a_mailbox_holds_at_most_its_bytes() { + let relay = Relay::with(small(|l| l.mailbox_bytes = 1000)); + let m = Mailbox::new(); + relay.create(&m).await; + assert_eq!( + relay.post(&m, &m.post, &[1u8; 600]).await, + StatusCode::CREATED + ); + assert_eq!( + relay.post(&m, &m.post, &[2u8; 400]).await, + StatusCode::CREATED, + "exactly at the cap" + ); + assert_eq!( + relay.post(&m, &m.post, &[3u8; 1]).await, + StatusCode::INSUFFICIENT_STORAGE + ); + // Another mailbox is not affected. + let other = Mailbox::new(); + relay.create(&other).await; + assert_eq!( + relay.post(&other, &other.post, &[4u8; 600]).await, + StatusCode::CREATED + ); +} + +#[tokio::test] +async fn the_relay_holds_at_most_its_bytes_across_mailboxes() { + let relay = Relay::with(small(|l| l.total_bytes = 1000)); + let (a, b) = (Mailbox::new(), Mailbox::new()); + relay.create(&a).await; + relay.create(&b).await; + assert_eq!( + relay.post(&a, &a.post, &[1u8; 700]).await, + StatusCode::CREATED + ); + assert_eq!( + relay.post(&b, &b.post, &[2u8; 301]).await, + StatusCode::INSUFFICIENT_STORAGE + ); + assert_eq!( + relay.post(&b, &b.post, &[2u8; 300]).await, + StatusCode::CREATED + ); + assert_eq!(relay.ack(&a, &[1u8; 700]).await, StatusCode::NO_CONTENT); + assert_eq!( + relay.post(&b, &b.post, &[3u8; 700]).await, + StatusCode::CREATED, + "room again after an acknowledgement" + ); +} + +#[tokio::test] +async fn the_relay_holds_at_most_its_mailboxes() { + let relay = Relay::with(small(|l| l.mailboxes = 3)); + for _ in 0..3 { + assert_eq!(relay.create(&Mailbox::new()).await, StatusCode::CREATED); + } + assert_eq!( + relay.create(&Mailbox::new()).await, + StatusCode::INSUFFICIENT_STORAGE + ); +} + +#[tokio::test] +async fn the_relay_holds_at_most_its_unclaimed_invites() { + let relay = Relay::with(small(|l| l.invites = 2)); + let (s, id, secret) = relay.invite().await; + assert_eq!(s, StatusCode::CREATED); + assert_eq!(relay.invite().await.0, StatusCode::CREATED); + assert_eq!(relay.invite().await.0, StatusCode::INSUFFICIENT_STORAGE); + // A claimed invite is gone and makes room. + let path = format!("/v0/invites/{}", id.to_wire()); + assert_eq!( + relay.call(Method::GET, &path, Some(&secret), vec![]).await, + StatusCode::OK + ); + assert_eq!(relay.invite().await.0, StatusCode::CREATED); +} + +#[test] +fn the_operator_sets_the_relay_wide_caps() { + let args = parse_args( + [ + "--max-bytes", + "5000", + "--max-mailboxes", + "7", + "--max-invites", + "9", + ] + .map(String::from), + ) + .expect("args"); + assert_eq!( + ( + args.limits.total_bytes, + args.limits.mailboxes, + args.limits.invites + ), + (5000, 7, 9) + ); + assert_eq!( + args.limits.mailbox_blobs, MAILBOX_BLOBS, + "not the operator's" + ); + for bad in [ + vec!["--max-bytes"], + vec!["--max-bytes", "0"], + vec!["--max-bytes", "-5"], + vec!["--max-mailboxes", "many"], + vec!["--max-invites", "1.5"], + ] { + assert!( + parse_args(bad.iter().map(|s| s.to_string())).is_err(), + "{bad:?}" + ); + } +} + +#[test] +fn an_expired_invite_does_not_count_against_new_ones() { + let store = Store::open_in_memory_with(small(|l| l.invites = 1)).expect("store"); + let invite = || CreateInvite { + id: InviteId::from_bytes(random()), + secret_hash: Token::from_bytes(random()).hash(), + key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"), + }; + store.create_invite(&invite(), T0).expect("first"); + assert_eq!( + store.create_invite(&invite(), T0 + 3600), + Err(tabellarius_relay::store::Refused::Full) + ); + // Eight days on, the first has expired, though the hourly purge has not run yet. + store + .create_invite(&invite(), T0 + 8 * 24 * 3600) + .expect("room after the expiry"); +} diff --git a/deploy/nixos/README.md b/deploy/nixos/README.md new file mode 100644 index 0000000..19470f4 --- /dev/null +++ b/deploy/nixos/README.md @@ -0,0 +1,60 @@ +# Running the relay on NixOS + +The relay listens on `127.0.0.1` only. Caddy sits in front with TLS from Let's Encrypt, and writes +no log that holds an address (`.agents/features/home-relay.md`). + +## 1. Before +- A DNS name for the relay (an `A` and/or `AAAA` record) pointing at the machine. +- Ports **80** and **443** reachable from the internet. 80 is for Let's Encrypt's challenge; Caddy + redirects everything else on it to 443. + +## 2. The configuration +In the machine's flake: +```nix +{ + inputs.tabellarius.url = "git+https://gitea.marek-novak.cz/mnovak/Amicitia-Tabellarius?ref=main"; + + outputs = { nixpkgs, tabellarius, ... }: { + nixosConfigurations.home = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + modules = [ + tabellarius.nixosModules.default + { + services.tabellarius = { + enable = true; + domain = "relay.example.cz"; + # Optional, the defaults shown: + # maxBytes = 1073741824; maxMailboxes = 100000; maxInvites = 10000; + }; + } + ./configuration.nix + ]; + }; + }; +} +``` +Pin `tabellarius` in `flake.lock`, as for any input. Then `nixos-rebuild switch --flake .#home`. + +## 3. What it sets up +| Part | What it does | +|:--|:--| +| `tabellarius.service` | `--listen 127.0.0.1:8470`, its database in `/var/lib/private/tabellarius`, a dynamic user, and a systemd sandbox. It may talk to localhost only (`IPAddressAllow=localhost`) | +| Caddy | one virtual host, `reverse_proxy` to the relay. No access log, no error log. `X-Forwarded-For`, `X-Real-IP` and `Forwarded` are removed, so the relay never learns who connected | +| Firewall | 80 and 443 open. `logRefusedConnections` off by default: a relay that keeps no address keeps no stranger's either | + +## 4. Check it +- From another machine: `curl https://relay.example.cz/version` answers with the versions. +- On the server, after some use, the address of the machine you used must appear nowhere: + `journalctl -o verbose | grep -F ` and `grep -rF /var/log` find + nothing. +- The same check runs automatically in a VM: `nix flake check` in this repository (Linux, KVM). + +## 5. In the app +Settings → *Your message relay*: `https://relay.example.cz`. Until the app accepts `https://` +addresses (Amicitia F23), it takes a loopback address only. + +## 6. What the operator still sees +Caddy and the relay keep nothing, but the machine's network still carries the connections while +they happen. A router or ISP log, or `tcpdump` on the server, would show addresses and timing +(`docs/PROTOCOL.md` §1). Turning Caddy's log on, even for a while, writes addresses. Do it only +knowing that. diff --git a/deploy/nixos/module.nix b/deploy/nixos/module.nix new file mode 100644 index 0000000..c79e57b --- /dev/null +++ b/deploy/nixos/module.nix @@ -0,0 +1,142 @@ +# The Tabellarius relay on NixOS, behind Caddy with TLS, and no log that holds an address +# (.agents/features/home-relay.md). Import it from the flake: `tabellarius.nixosModules.default`. +# +# services.tabellarius = { +# enable = true; +# domain = "relay.example.cz"; # its DNS name points at this machine; ports 80 and 443 open +# }; +{ self }: +{ config, lib, pkgs, ... }: +let + cfg = config.services.tabellarius; + system = pkgs.stdenv.hostPlatform.system; +in +{ + options.services.tabellarius = { + enable = lib.mkEnableOption "the Tabellarius message relay, behind Caddy with TLS and no logs"; + + domain = lib.mkOption { + type = lib.types.str; + example = "relay.example.cz"; + description = "The relay's DNS name. Caddy gets its certificate from Let's Encrypt."; + }; + + package = lib.mkOption { + type = lib.types.package; + default = self.packages.${system}.default; + defaultText = lib.literalExpression "tabellarius.packages.\${system}.default"; + description = "The relay, built from this flake: the code that runs is the code published."; + }; + + port = lib.mkOption { + type = lib.types.port; + default = 8470; + description = "The loopback port between Caddy and the relay. Never exposed."; + }; + + maxBytes = lib.mkOption { + type = lib.types.ints.positive; + default = 1073741824; + description = "Waiting blobs the relay holds, in bytes, before it answers 507 (PROTOCOL.md section 8)."; + }; + + maxMailboxes = lib.mkOption { + type = lib.types.ints.positive; + default = 100000; + description = "Mailboxes the relay holds before it answers 507."; + }; + + maxInvites = lib.mkOption { + type = lib.types.ints.positive; + default = 10000; + description = "Unclaimed invites the relay holds before it answers 507."; + }; + + openFirewall = lib.mkOption { + type = lib.types.bool; + default = true; + description = "Open ports 80 (the ACME challenge, then a redirect) and 443."; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.tabellarius = { + description = "Tabellarius message relay (loopback only; Caddy in front)"; + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" ]; + serviceConfig = { + ExecStart = lib.escapeShellArgs [ + "${cfg.package}/bin/tabellarius-relay" + "--listen" "127.0.0.1:${toString cfg.port}" + "--db" "/var/lib/tabellarius/relay.db" + "--max-bytes" (toString cfg.maxBytes) + "--max-mailboxes" (toString cfg.maxMailboxes) + "--max-invites" (toString cfg.maxInvites) + ]; + Restart = "on-failure"; + DynamicUser = true; + StateDirectory = "tabellarius"; + StateDirectoryMode = "0700"; + UMask = "0077"; + + # It talks to Caddy on loopback and to nothing else, even if it had a bug. + IPAddressDeny = "any"; + IPAddressAllow = "localhost"; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ]; + + CapabilityBoundingSet = ""; + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + PrivateDevices = true; + PrivateUsers = true; + ProtectHostname = true; + ProtectClock = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectKernelLogs = true; + ProtectControlGroups = true; + ProtectProc = "invisible"; + ProcSubset = "pid"; + RestrictNamespaces = true; + RestrictRealtime = true; + RestrictSUIDSGID = true; + RemoveIPC = true; + LockPersonality = true; + MemoryDenyWriteExecute = true; + SystemCallArchitectures = "native"; + SystemCallFilter = [ "@system-service" "~@privileged" ]; + }; + }; + + services.caddy = { + enable = true; + # Caddy's own logger: errors about TLS handshakes or upstreams can name a client's address. + # No log is the rule; an operator who needs one turns it on for a while, knowing why. + logFormat = '' + output discard + ''; + virtualHosts.${cfg.domain} = { + # The NixOS module writes an access log per host by default; this one writes none. + logFormat = '' + output discard + ''; + extraConfig = '' + reverse_proxy 127.0.0.1:${toString cfg.port} { + # The relay never learns who connected: Caddy adds these by default. + header_up -X-Forwarded-For + header_up -X-Real-IP + header_up -Forwarded + } + ''; + }; + }; + + networking.firewall.allowedTCPPorts = lib.mkIf cfg.openFirewall [ 80 443 ]; + # NixOS logs every refused connection with its source address by default. Those are strangers, + # not users, but a relay that keeps no address should not keep theirs either. mkDefault: the + # machine's owner can turn it back on. + networking.firewall.logRefusedConnections = lib.mkDefault false; + }; +} diff --git a/deploy/nixos/test.nix b/deploy/nixos/test.nix new file mode 100644 index 0000000..4b93569 --- /dev/null +++ b/deploy/nixos/test.nix @@ -0,0 +1,82 @@ +# `nix flake check` (Linux, KVM): two machines. `server` runs the module; `client` talks to it +# through Caddy with TLS, does everything the protocol allows and some things it refuses, fills a +# mailbox cap to its 507, and then the test fails if the client's address appears anywhere in the +# server's journal or under /var/log, or in the relay's database (.agents/features/home-relay.md). +{ self, pkgs }: +pkgs.testers.runNixOSTest { + name = "tabellarius-relay-keeps-no-address"; + + nodes.server = { lib, ... }: { + imports = [ self.nixosModules.default ]; + services.tabellarius = { + enable = true; + domain = "relay.test"; + maxMailboxes = 3; + }; + # No Let's Encrypt inside a VM: Caddy's own CA instead. + services.caddy.virtualHosts."relay.test".extraConfig = lib.mkBefore "tls internal"; + }; + + nodes.client = { pkgs, ... }: { + environment.systemPackages = [ pkgs.curl pkgs.python3 ]; + }; + + testScript = '' + import base64, hashlib, json, os + + def b64(raw): + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + start_all() + server.wait_for_unit("tabellarius.service") + server.wait_for_unit("caddy.service") + server.wait_for_open_port(443) + client.wait_for_unit("multi-user.target") + + client_ip = client.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip() + server_ip = server.succeed("ip -4 -o addr show dev eth1 | awk '{print $4}' | cut -d/ -f1").strip() + assert client_ip and server_ip and client_ip != server_ip, (client_ip, server_ip) + + def call(method, path, token=None, body=None, json_body=False): + cmd = ["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}", + "--resolve", "relay.test:443:" + server_ip, "-X", method] + if token: + cmd += ["-H", "Authorization: Bearer " + token] + if body is not None: + client.succeed("cat > /tmp/body <<'EOF'\n" + body + "\nEOF") + client.succeed("truncate -s -1 /tmp/body") + cmd += ["--data-binary", "@/tmp/body"] + if json_body: + cmd += ["-H", "Content-Type: application/json"] + cmd.append("https://relay.test" + path) + return client.succeed(" ".join("'" + c + "'" for c in cmd)).strip() + + def mailbox(): + mid, post, fetch = os.urandom(16), os.urandom(32), os.urandom(32) + body = json.dumps({"id": b64(mid), "postTokenHash": b64(hashlib.sha256(post).digest()), + "fetchTokenHash": b64(hashlib.sha256(fetch).digest())}) + return b64(mid), b64(post), b64(fetch), body + + assert call("GET", "/version") == "200" + mid, post, fetch, body = mailbox() + assert call("POST", "/v0/mailboxes", body=body, json_body=True) == "201" + blob = "sealed-envelope-for-the-test" + assert call("POST", "/v0/mailboxes/" + mid + "/blobs", token=post, body=blob) == "201" + assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=fetch) == "200" + digest = b64(hashlib.sha256(blob.encode()).digest()) + assert call("DELETE", "/v0/mailboxes/" + mid + "/blobs/" + digest, token=fetch) == "204" + # Refusals: a wrong token, a malformed id, a body that is not JSON. + assert call("GET", "/v0/mailboxes/" + mid + "/blobs", token=b64(os.urandom(32))) == "404" + assert call("GET", "/v0/mailboxes/nonsense/blobs", token=fetch) == "404" + assert call("POST", "/v0/mailboxes", body="not json", json_body=True) == "400" + # The cap: three mailboxes, then 507. + for _ in range(2): + assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "201" + assert call("POST", "/v0/mailboxes", body=mailbox()[3], json_body=True) == "507" + + # Nowhere on the server: not in the journal, not under /var/log, not in the relay's data. + server.succeed("journalctl --sync") + server.fail("journalctl --no-pager -o verbose | grep -F '" + client_ip + "'") + server.fail("grep -rF '" + client_ip + "' /var/log /var/lib/private/tabellarius") + ''; +} diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 5298dfb..b3267dc 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -76,7 +76,7 @@ The platform facts above are Claude's understanding, to be verified in `.agents/ - Parsers are fuzzed (`cargo fuzz`) for every message type. - Every check in `VERIFY.md` §1 has a CI job or a documented manual procedure. -## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14 +## 8. The wire (v0) — approved 2026-11-08, routes added 2026-11-14, quotas 2026-11-16 HTTP/1.1 behind TLS (the reverse proxy, F23). Ids and tokens are unpadded base64url of a fixed length with one canonical spelling: ids are 16 bytes, and tokens and hashes are 32. JSON bodies refuse unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB. @@ -94,6 +94,12 @@ unknown fields. A blob is at most 256 KiB, and a KeyPackage at most 16 KiB. - A wrong token, an unknown id and a malformed id all give the same bare **404**, so nobody can probe what exists. +- **Quotas** *(added 2026-11-16, F23, so a relay can face the internet; `.agents/features/home-relay.md`)*: + a mailbox holds at most **1 000 waiting blobs** and **32 MiB**, and a relay at most what its + operator sets (by default 1 GiB of blobs, 100 000 mailboxes, 10 000 unclaimed invites). Over a + limit the answer is a bare **507**. The per-mailbox caps are checked only after the post token, + so a 507 tells a stranger nothing about a mailbox. Nothing new is stored to count: the counts + come from §5's own rows and `size`. A client treats 507 like any failure and tries again later. - A refusal has no body. - The relay prints no request. - Tests: `crates/relay/tests/relay.rs`, `crates/protocol/tests/wire.rs`. diff --git a/flake.nix b/flake.nix index 1064be9..a61010d 100644 --- a/flake.nix +++ b/flake.nix @@ -21,6 +21,13 @@ }; }); + # The relay on NixOS: loopback only, behind Caddy with TLS and no logs (deploy/nixos). + nixosModules.default = import ./deploy/nixos/module.nix { inherit self; }; + + # A VM test that the server keeps no client address anywhere (needs Linux and KVM). + checks.x86_64-linux.relay-keeps-no-address = + import ./deploy/nixos/test.nix { inherit self; pkgs = nixpkgs.legacyPackages.x86_64-linux; }; + devShells = forAll (pkgs: { default = pkgs.mkShell { packages = with pkgs; [ cargo rustc clippy rustfmt ];