diff --git a/crates/relay/Cargo.toml b/crates/relay/Cargo.toml index d4d9da7..edcaf0a 100644 --- a/crates/relay/Cargo.toml +++ b/crates/relay/Cargo.toml @@ -8,6 +8,19 @@ publish.workspace = true [dependencies] tabellarius-protocol = { path = "../protocol" } +axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "signal"] } +# Plain SQLite: the relay holds only ciphertext and hashes; nothing in it is readable (PROTOCOL.md §5). +rusqlite = { version = "0.41", features = ["bundled"] } +serde = "1" +serde_json = "1" +subtle = "2" + +[dev-dependencies] +getrandom = "0.3" +http-body-util = "0.1" +tempfile = "3" +tower = { version = "0.5", features = ["util"] } [lints] workspace = true diff --git a/crates/relay/src/http.rs b/crates/relay/src/http.rs new file mode 100644 index 0000000..9965298 --- /dev/null +++ b/crates/relay/src/http.rs @@ -0,0 +1,162 @@ +//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's +//! address, and nothing here writes a request anywhere. + +use crate::store::{Refused, Store}; +use axum::body::Bytes; +use axum::extract::{DefaultBodyLimit, Path, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{delete, get, post, put}; +use axum::{Json, Router}; +use serde::de::DeserializeOwned; +use std::sync::Arc; +use tabellarius_protocol::{ + CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, Sha256Hash, + Token, VersionInfo, MAX_BLOB_BYTES, VERSION, +}; + +/// Unix seconds. The server passes the system clock; tests pass their own. +pub type Clock = Arc i64 + Send + Sync>; + +#[derive(Clone)] +pub struct AppState { + pub store: Arc, + pub clock: Clock, +} + +/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url. +const MAX_JSON_BYTES: usize = 32 * 1024; + +pub fn router(state: AppState) -> Router { + let blob_routes = Router::new() + .route("/v0/mailboxes/{id}/blobs", post(post_blob).get(fetch_blobs)) + .layer(DefaultBodyLimit::max(MAX_BLOB_BYTES)); + Router::new() + .route("/v0/mailboxes", post(create_mailbox)) + .route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge)) + .route("/v0/mailboxes/{id}/post-token", put(rotate_post_token)) + .route("/v0/invites", post(create_invite)) + .route("/v0/invites/{id}", get(claim_invite)) + .route("/version", get(version)) + .layer(DefaultBodyLimit::max(MAX_JSON_BYTES)) + .merge(blob_routes) + .with_state(state) +} + +/// Every refusal is a bare status code: no body that could echo the request back. +struct Status(StatusCode); + +impl IntoResponse for Status { + fn into_response(self) -> Response { + self.0.into_response() + } +} + +impl From for Status { + fn from(r: Refused) -> Self { + Status(match r { + Refused::NotFound => StatusCode::NOT_FOUND, + Refused::Exists => StatusCode::CONFLICT, + Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE, + Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR, + }) + } +} + +/// Parses a JSON body with the protocol's strict types; any failure is a plain 400. +fn json(body: &Bytes) -> Result { + serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST)) +} + +/// A malformed id in the path is treated like an unknown one. +fn mailbox(id: &str) -> Result { + MailboxId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND)) +} + +/// A missing or malformed bearer token is treated like a wrong one. +fn bearer(headers: &HeaderMap) -> Result { + headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| Token::from_bearer(v).ok()) + .ok_or(Status(StatusCode::NOT_FOUND)) +} + +async fn create_mailbox(State(s): State, body: Bytes) -> Result { + let req: CreateMailbox = json(&body)?; + s.store.create_mailbox(&req, (s.clock)())?; + Ok(StatusCode::CREATED) +} + +async fn post_blob( + State(s): State, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> Result { + let id = mailbox(&id)?; + let token = bearer(&headers)?; + s.store.post(&id, &token, &body, (s.clock)())?; + Ok(StatusCode::CREATED) +} + +async fn fetch_blobs( + State(s): State, + Path(id): Path, + headers: HeaderMap, +) -> Result, Status> { + let id = mailbox(&id)?; + let token = bearer(&headers)?; + let blobs = s.store.fetch(&id, &token)?; + Ok(Json(FetchedBlobs { blobs })) +} + +async fn acknowledge( + State(s): State, + Path((id, hash)): Path<(String, String)>, + headers: HeaderMap, +) -> Result { + let id = mailbox(&id)?; + let token = bearer(&headers)?; + let hash = Sha256Hash::parse(&hash).map_err(|_| Status(StatusCode::NOT_FOUND))?; + s.store.acknowledge(&id, &token, &hash)?; + Ok(StatusCode::NO_CONTENT) +} + +async fn rotate_post_token( + State(s): State, + Path(id): Path, + headers: HeaderMap, + body: Bytes, +) -> Result { + let id = mailbox(&id)?; + let token = bearer(&headers)?; + let req: RotatePostToken = json(&body)?; + s.store + .rotate_post_token(&id, &token, &req.post_token_hash)?; + Ok(StatusCode::NO_CONTENT) +} + +async fn create_invite(State(s): State, body: Bytes) -> Result { + let req: CreateInvite = json(&body)?; + s.store.create_invite(&req, (s.clock)())?; + Ok(StatusCode::CREATED) +} + +async fn claim_invite( + State(s): State, + Path(id): Path, + headers: HeaderMap, +) -> Result { + let id = InviteId::parse(&id).map_err(|_| Status(StatusCode::NOT_FOUND))?; + let secret = bearer(&headers)?; + let claimed = s.store.claim_invite(&id, &secret, (s.clock)())?; + Ok(Json(claimed).into_response()) +} + +async fn version() -> Json { + Json(VersionInfo { + protocol: VERSION.to_string(), + relay: env!("CARGO_PKG_VERSION").to_string(), + }) +} diff --git a/crates/relay/src/lib.rs b/crates/relay/src/lib.rs new file mode 100644 index 0000000..1e9756e --- /dev/null +++ b/crates/relay/src/lib.rs @@ -0,0 +1,44 @@ +//! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and +//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request. + +pub mod http; +pub mod store; + +use std::net::SocketAddr; +use std::path::PathBuf; + +/// Loopback unless told otherwise: a relay reachable from outside is a deliberate choice (F23). +pub const DEFAULT_LISTEN: &str = "127.0.0.1:8470"; +pub const DEFAULT_DB: &str = "tabellarius-relay.db"; + +#[derive(Debug, PartialEq, Eq)] +pub struct Args { + pub listen: SocketAddr, + pub db: PathBuf, +} + +/// `--listen `, `--db `. 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 mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?; + let mut db = PathBuf::from(DEFAULT_DB); + let mut it = args.into_iter(); + while let Some(arg) = it.next() { + match arg.as_str() { + "--listen" => { + listen = it + .next() + .and_then(|v| v.parse().ok()) + .ok_or_else(|| usage.to_string())?; + } + "--db" => { + db = it + .next() + .map(PathBuf::from) + .ok_or_else(|| usage.to_string())? + } + _ => return Err(usage.to_string()), + } + } + Ok(Args { listen, db }) +} diff --git a/crates/relay/src/main.rs b/crates/relay/src/main.rs index d4e327e..78273ef 100644 --- a/crates/relay/src/main.rs +++ b/crates/relay/src/main.rs @@ -1,10 +1,77 @@ -//! Placeholder: prints its version and exits. Opens no socket, stores nothing. -//! It exists so the reproducible build has an artefact to hash. The relay itself is written only -//! after the protocol review is approved. +//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db]` +//! +//! Prints one line at start (version and address) and nothing per request. -fn main() { - println!( - "tabellarius-relay {} (no relay yet: protocol under review)", - env!("CARGO_PKG_VERSION") - ); +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tabellarius_relay::http::{router, AppState, Clock}; +use tabellarius_relay::parse_args; +use tabellarius_relay::store::Store; + +fn now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +#[tokio::main] +async fn main() { + let args = match parse_args(std::env::args().skip(1)) { + Ok(a) => a, + Err(usage) => { + eprintln!("{usage}"); + std::process::exit(2); + } + }; + let store = match Store::open(&args.db) { + Ok(s) => Arc::new(s), + Err(_) => { + eprintln!( + "tabellarius-relay: cannot open the database {}", + args.db.display() + ); + std::process::exit(1); + } + }; + let listener = match tokio::net::TcpListener::bind(args.listen).await { + Ok(l) => l, + Err(_) => { + eprintln!("tabellarius-relay: cannot listen on {}", args.listen); + std::process::exit(1); + } + }; + let bound = listener + .local_addr() + .map(|a| a.to_string()) + .unwrap_or_default(); + println!( + "tabellarius-relay {} protocol {} listening on {bound}", + env!("CARGO_PKG_VERSION"), + tabellarius_protocol::VERSION + ); + + // Purge at start and every hour: blobs after 30 days, invites after their expiry. + let purger = Arc::clone(&store); + tokio::spawn(async move { + let mut every_hour = tokio::time::interval(Duration::from_secs(3600)); + loop { + every_hour.tick().await; + let _ = purger.purge(now()); + } + }); + + let clock: Clock = Arc::new(now); + let app = router(AppState { store, clock }); + let shutdown = async { + let _ = tokio::signal::ctrl_c().await; + }; + if axum::serve(listener, app) + .with_graceful_shutdown(shutdown) + .await + .is_err() + { + eprintln!("tabellarius-relay: the server stopped with an error"); + std::process::exit(1); + } } diff --git a/crates/relay/src/store.rs b/crates/relay/src/store.rs new file mode 100644 index 0000000..18bae43 --- /dev/null +++ b/crates/relay/src/store.rs @@ -0,0 +1,313 @@ +//! Every rule of the relay, over SQLite, with the clock passed in. +//! +//! The database holds exactly `docs/PROTOCOL.md` §5: three tables, and nothing about who connected. +//! A wrong token and an unknown id give the same [`Refused::NotFound`], so nobody can probe which +//! mailboxes or invites exist. + +use rusqlite::{params, Connection, OptionalExtension}; +use std::path::Path; +use std::sync::Mutex; +use subtle::ConstantTimeEq; +use tabellarius_protocol::{ + blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateInvite, CreateMailbox, FetchedBlob, + InviteId, KeyPackageBytes, MailboxId, Sha256Hash, Token, BLOB_TTL_SECS, INVITE_TTL_SECS, + MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES, +}; + +/// The schema, and nothing else (`PROTOCOL.md` §5). A column added here is a protocol change. +pub const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS mailboxes ( + id BLOB PRIMARY KEY NOT NULL, + post_hash BLOB NOT NULL, + fetch_hash BLOB NOT NULL, + created_day INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS blobs ( + mailbox_id BLOB NOT NULL, + ciphertext BLOB NOT NULL, + size INTEGER NOT NULL, + received_hour INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS blobs_by_mailbox ON blobs (mailbox_id); +CREATE TABLE IF NOT EXISTS invites ( + id BLOB PRIMARY KEY NOT NULL, + secret_hash BLOB NOT NULL, + key_package BLOB NOT NULL, + expiry INTEGER NOT NULL +); +"; + +/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong. +#[derive(Debug, PartialEq, Eq)] +pub enum Refused { + /// Unknown id, wrong token, or an expired invite: indistinguishable on purpose. + NotFound, + /// The id is already taken. + Exists, + /// Over a protocol limit. + TooLarge, + /// The database failed; nothing about the request is in the error. + Storage, +} + +impl From for Refused { + fn from(_: rusqlite::Error) -> Self { + Refused::Storage + } +} + +pub struct Store { + conn: Mutex, +} + +/// What a purge removed. +#[derive(Debug, PartialEq, Eq, Default)] +pub struct Purged { + pub blobs: usize, + pub invites: usize, +} + +fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool { + stored.len() == 32 && bool::from(stored.ct_eq(presented.as_bytes())) +} + +impl Store { + pub fn open(path: &Path) -> Result { + Self::init(Connection::open(path)?) + } + + pub fn open_in_memory() -> Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(conn: Connection) -> 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), + }) + } + + 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. + self.conn.lock().unwrap_or_else(|p| p.into_inner()) + } + + pub fn create_mailbox(&self, req: &CreateMailbox, now: i64) -> Result<(), Refused> { + let changed = self.conn().execute( + "INSERT OR IGNORE INTO mailboxes (id, post_hash, fetch_hash, created_day) + VALUES (?1, ?2, ?3, ?4)", + params![ + &req.id.as_bytes()[..], + &req.post_token_hash.as_bytes()[..], + &req.fetch_token_hash.as_bytes()[..], + day_of(now) + ], + )?; + if changed == 0 { + return Err(Refused::Exists); + } + Ok(()) + } + + /// Checks a token against the mailbox's stored hash (`post_hash` or `fetch_hash`). + fn authorize( + conn: &Connection, + id: &MailboxId, + token: &Token, + column: Column, + ) -> Result<(), Refused> { + let sql = match column { + Column::Post => "SELECT post_hash FROM mailboxes WHERE id = ?1", + Column::Fetch => "SELECT fetch_hash FROM mailboxes WHERE id = ?1", + }; + let stored: Option> = conn + .query_row(sql, [&id.as_bytes()[..]], |r| r.get(0)) + .optional()?; + let presented = token.hash(); + // Compare against something even when the mailbox is unknown, so both cases take the same path. + let stored = stored.unwrap_or_else(|| vec![0; 32]); + let known = !stored.iter().all(|b| *b == 0); + if known & same_hash(&stored, &presented) { + Ok(()) + } else { + Err(Refused::NotFound) + } + } + + pub fn post( + &self, + id: &MailboxId, + token: &Token, + blob: &[u8], + now: i64, + ) -> Result<(), Refused> { + if blob.len() > MAX_BLOB_BYTES { + return Err(Refused::TooLarge); + } + let conn = self.conn(); + Self::authorize(&conn, id, token, Column::Post)?; + 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)], + )?; + Ok(()) + } + + /// The waiting blobs, oldest first, at most [`MAX_BLOBS_PER_FETCH`]. Fetching deletes nothing: + /// a blob goes only when it is acknowledged, or at the TTL. + pub fn fetch(&self, id: &MailboxId, token: &Token) -> Result, Refused> { + let conn = self.conn(); + Self::authorize(&conn, id, token, Column::Fetch)?; + let mut stmt = conn.prepare( + "SELECT ciphertext, received_hour FROM blobs WHERE mailbox_id = ?1 + ORDER BY received_hour, rowid LIMIT ?2", + )?; + let rows = stmt.query_map( + params![&id.as_bytes()[..], MAX_BLOBS_PER_FETCH as i64], + |r| Ok((r.get::<_, Vec>(0)?, r.get::<_, i64>(1)?)), + )?; + let mut out = Vec::new(); + for row in rows { + let (bytes, received_hour) = row?; + let blob = BlobBytes::new(bytes).map_err(|_| Refused::Storage)?; + out.push(FetchedBlob { + blob, + received_hour, + }); + } + Ok(out) + } + + /// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`]. + pub fn acknowledge( + &self, + id: &MailboxId, + token: &Token, + hash: &Sha256Hash, + ) -> Result<(), Refused> { + let mut conn = self.conn(); + Self::authorize(&conn, id, token, Column::Fetch)?; + let tx = conn.transaction()?; + let rowid: Option = { + let mut stmt = + tx.prepare("SELECT rowid, ciphertext FROM blobs WHERE mailbox_id = ?1")?; + let mut rows = stmt.query([&id.as_bytes()[..]])?; + let mut found = None; + while let Some(row) = rows.next()? { + let bytes: Vec = row.get(1)?; + if blob_hash(&bytes) == *hash { + found = Some(row.get(0)?); + break; + } + } + found + }; + let rowid = rowid.ok_or(Refused::NotFound)?; + tx.execute("DELETE FROM blobs WHERE rowid = ?1", [rowid])?; + tx.commit()?; + Ok(()) + } + + /// Blocking: the owner (fetch token) gives the mailbox a new post token hash. + pub fn rotate_post_token( + &self, + id: &MailboxId, + fetch: &Token, + new_hash: &Sha256Hash, + ) -> Result<(), Refused> { + let conn = self.conn(); + Self::authorize(&conn, id, fetch, Column::Fetch)?; + conn.execute( + "UPDATE mailboxes SET post_hash = ?2 WHERE id = ?1", + params![&id.as_bytes()[..], &new_hash.as_bytes()[..]], + )?; + Ok(()) + } + + 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( + "INSERT OR IGNORE INTO invites (id, secret_hash, key_package, expiry) VALUES (?1, ?2, ?3, ?4)", + params![ + &req.id.as_bytes()[..], + &req.secret_hash.as_bytes()[..], + req.key_package.bytes(), + expiry + ], + )?; + if changed == 0 { + return Err(Refused::Exists); + } + Ok(()) + } + + /// Hands the KeyPackage out once and deletes the invite. Expired = not found. + pub fn claim_invite( + &self, + id: &InviteId, + secret: &Token, + now: i64, + ) -> Result { + let mut conn = self.conn(); + let tx = conn.transaction()?; + let row: Option<(Vec, Vec, i64)> = tx + .query_row( + "SELECT secret_hash, key_package, expiry FROM invites WHERE id = ?1", + [&id.as_bytes()[..]], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .optional()?; + let (stored, key_package, expiry) = + row.unwrap_or_else(|| (vec![0; 32], Vec::new(), i64::MIN)); + let ok = + same_hash(&stored, &secret.hash()) & (now < expiry) & !stored.iter().all(|b| *b == 0); + if !ok { + return Err(Refused::NotFound); + } + tx.execute("DELETE FROM invites WHERE id = ?1", [&id.as_bytes()[..]])?; + tx.commit()?; + Ok(ClaimedInvite { + key_package: KeyPackageBytes::new(key_package).map_err(|_| Refused::Storage)?, + }) + } + + /// Deletes blobs older than 30 days and invites past their expiry. + pub fn purge(&self, now: i64) -> Result { + let conn = self.conn(); + // A blob that arrived in hour h is gone once h is more than 30 days before now's hour. + let oldest_kept = hour_of(now - BLOB_TTL_SECS); + let blobs = conn.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?; + let invites = conn.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?; + Ok(Purged { blobs, invites }) + } + + /// The live schema: (table, columns) for every table, in name order. For the §5 test. + pub fn live_schema(&self) -> Result)>, rusqlite::Error> { + let conn = self.conn(); + let mut stmt = + conn.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")?; + let tables: Vec = stmt + .query_map([], |r| r.get(0))? + .collect::>()?; + let mut out = Vec::new(); + for table in tables { + let mut cols = conn.prepare(&format!("PRAGMA table_info(\"{table}\")"))?; + let names: Vec = cols + .query_map([], |r| r.get(1))? + .collect::>()?; + out.push((table, names)); + } + Ok(out) + } +} + +#[derive(Clone, Copy)] +enum Column { + Post, + Fetch, +} diff --git a/crates/relay/tests/relay.rs b/crates/relay/tests/relay.rs new file mode 100644 index 0000000..0558d53 --- /dev/null +++ b/crates/relay/tests/relay.rs @@ -0,0 +1,743 @@ +//! The relay against `docs/PROTOCOL.md` §5 and §7, through HTTP where the claim is about the wire. +//! Tokens and ids are generated per test (CLAUDE.md §2.5): no secret is in the repository. + +use axum::body::Body; +use axum::http::{header, Method, Request, StatusCode}; +use http_body_util::BodyExt; +use std::io::{Read, Write}; +use std::sync::atomic::{AtomicI64, Ordering}; +use std::sync::Arc; +use tabellarius_protocol::*; +use tabellarius_relay::http::{router, AppState, Clock}; +use tabellarius_relay::store::{Refused, Store}; +use tabellarius_relay::{parse_args, DEFAULT_LISTEN}; +use tower::ServiceExt; + +const T0: i64 = 1_794_000_000; // 2026-11-07, a fixed point; the clock moves only when a test moves it. + +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 create_body(&self) -> String { + serde_json::to_string(&CreateMailbox { + id: self.id, + post_token_hash: self.post.hash(), + fetch_token_hash: self.fetch.hash(), + }) + .expect("json") + } + fn blobs_path(&self) -> String { + format!("/v0/mailboxes/{}/blobs", self.id.to_wire()) + } +} + +struct Relay { + app: axum::Router, + store: Arc, + now: Arc, +} + +impl Relay { + fn in_memory() -> Self { + Self::with(Store::open_in_memory().expect("store")) + } + fn with(store: Store) -> Self { + let store = Arc::new(store); + let now = Arc::new(AtomicI64::new(T0)); + let n = Arc::clone(&now); + let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst)); + let app = router(AppState { + store: Arc::clone(&store), + clock, + }); + Self { app, store, now } + } + fn advance(&self, secs: i64) { + self.now.fetch_add(secs, Ordering::SeqCst); + } + async fn call( + &self, + method: Method, + path: &str, + auth: Option<&Token>, + body: Vec, + ) -> (StatusCode, Vec) { + 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 + .app + .clone() + .oneshot(req.body(Body::from(body)).expect("request")) + .await + .expect("infallible"); + let status = resp.status(); + let bytes = resp + .into_body() + .collect() + .await + .expect("body") + .to_bytes() + .to_vec(); + (status, bytes) + } + async fn create(&self, m: &Mailbox) -> StatusCode { + self.call( + Method::POST, + "/v0/mailboxes", + None, + m.create_body().into_bytes(), + ) + .await + .0 + } + async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode { + self.call(Method::POST, &m.blobs_path(), Some(token), blob.to_vec()) + .await + .0 + } + async fn fetch(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec) { + let (s, body) = self + .call(Method::GET, &m.blobs_path(), Some(token), vec![]) + .await; + let blobs = if s == StatusCode::OK { + serde_json::from_slice::(&body) + .expect("blobs") + .blobs + } else { + assert!(body.is_empty(), "a refusal has no body"); + vec![] + }; + (s, blobs) + } + async fn ack(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode { + let path = format!("{}/{}", m.blobs_path(), blob_hash(blob).to_wire()); + self.call(Method::DELETE, &path, Some(token), vec![]) + .await + .0 + } +} + +#[test] +fn schema_is_exactly_protocol_section_5() { + let store = Store::open_in_memory().expect("store"); + let live = store.live_schema().expect("schema"); + let expected: Vec<(String, Vec)> = vec![ + ( + "blobs".into(), + vec![ + "mailbox_id".into(), + "ciphertext".into(), + "size".into(), + "received_hour".into(), + ], + ), + ( + "invites".into(), + vec![ + "id".into(), + "secret_hash".into(), + "key_package".into(), + "expiry".into(), + ], + ), + ( + "mailboxes".into(), + vec![ + "id".into(), + "post_hash".into(), + "fetch_hash".into(), + "created_day".into(), + ], + ), + ]; + assert_eq!( + live, expected, + "a new table or column is a protocol change (CLAUDE.md §2.2)" + ); +} + +#[tokio::test] +async fn only_the_post_token_posts_and_only_the_fetch_token_fetches() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + assert_eq!(relay.create(&m).await, StatusCode::CREATED); + assert_eq!(relay.create(&m).await, StatusCode::CONFLICT); + + let stranger = Token::from_bytes(random()); + assert_eq!(relay.post(&m, &stranger, b"x").await, StatusCode::NOT_FOUND); + assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND); + let (s, _) = relay + .call(Method::POST, &m.blobs_path(), None, b"x".to_vec()) + .await; + assert_eq!(s, StatusCode::NOT_FOUND, "no token at all"); + assert_eq!(relay.post(&m, &m.post, b"hello").await, StatusCode::CREATED); + + assert_eq!(relay.fetch(&m, &m.post).await.0, StatusCode::NOT_FOUND); + assert_eq!(relay.fetch(&m, &stranger).await.0, StatusCode::NOT_FOUND); + let (s, blobs) = relay.fetch(&m, &m.fetch).await; + assert_eq!(s, StatusCode::OK); + assert_eq!(blobs.len(), 1); + assert_eq!(blobs[0].blob.bytes(), b"hello"); + assert_eq!(blobs[0].received_hour, hour_of(T0)); +} + +#[tokio::test] +async fn an_unknown_mailbox_looks_exactly_like_a_wrong_token() { + let relay = Relay::in_memory(); + let known = Mailbox::new(); + relay.create(&known).await; + let unknown = Mailbox::new(); + let wrong = relay + .call( + Method::POST, + &known.blobs_path(), + Some(&unknown.post), + b"x".to_vec(), + ) + .await; + let missing = relay + .call( + Method::POST, + &unknown.blobs_path(), + Some(&unknown.post), + b"x".to_vec(), + ) + .await; + let malformed = relay + .call( + Method::POST, + "/v0/mailboxes/not-an-id/blobs", + Some(&unknown.post), + b"x".to_vec(), + ) + .await; + assert_eq!(wrong, (StatusCode::NOT_FOUND, vec![])); + assert_eq!(missing, wrong); + assert_eq!(malformed, wrong); +} + +#[tokio::test] +async fn after_rotation_the_old_post_token_is_refused() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + relay.create(&m).await; + let new_post = Token::from_bytes(random()); + let body = serde_json::to_vec(&RotatePostToken { + post_token_hash: new_post.hash(), + }) + .expect("json"); + let path = format!("/v0/mailboxes/{}/post-token", m.id.to_wire()); + // Only the owner (fetch token) can rotate. + let (s, _) = relay + .call(Method::PUT, &path, Some(&m.post), body.clone()) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + let (s, _) = relay.call(Method::PUT, &path, Some(&m.fetch), body).await; + assert_eq!(s, StatusCode::NO_CONTENT); + assert_eq!( + relay.post(&m, &m.post, b"from the blocked person").await, + StatusCode::NOT_FOUND + ); + assert_eq!( + relay.post(&m, &new_post, b"from everyone else").await, + StatusCode::CREATED + ); + let (_, blobs) = relay.fetch(&m, &m.fetch).await; + assert_eq!(blobs.len(), 1); + assert_eq!(blobs[0].blob.bytes(), b"from everyone else"); +} + +#[tokio::test] +async fn an_acknowledged_blob_is_gone_and_no_other_is_touched() { + let relay = Relay::in_memory(); + let a = Mailbox::new(); + let b = Mailbox::new(); + relay.create(&a).await; + relay.create(&b).await; + relay.post(&a, &a.post, b"same bytes").await; + relay.post(&a, &a.post, b"second").await; + relay.post(&b, &b.post, b"same bytes").await; + + // b's owner cannot acknowledge a's blob, even with identical bytes. + let path = format!("{}/{}", a.blobs_path(), blob_hash(b"same bytes").to_wire()); + let (s, _) = relay + .call(Method::DELETE, &path, Some(&b.fetch), vec![]) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + + assert_eq!( + relay.ack(&a, &a.fetch, b"same bytes").await, + StatusCode::NO_CONTENT + ); + assert_eq!( + relay.ack(&a, &a.fetch, b"same bytes").await, + StatusCode::NOT_FOUND, + "already gone" + ); + let (_, left) = relay.fetch(&a, &a.fetch).await; + assert_eq!( + left.iter() + .map(|f| f.blob.bytes().to_vec()) + .collect::>(), + vec![b"second".to_vec()] + ); + let (_, other) = relay.fetch(&b, &b.fetch).await; + assert_eq!(other.len(), 1, "the other mailbox keeps its copy"); +} + +#[tokio::test] +async fn an_unacknowledged_blob_is_purged_after_30_days_not_before() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + relay.create(&m).await; + relay.post(&m, &m.post, b"waiting").await; + + relay.advance(BLOB_TTL_SECS - 3600); + let now = relay.now.load(Ordering::SeqCst); + assert_eq!(relay.store.purge(now).expect("purge").blobs, 0); + assert_eq!( + relay.fetch(&m, &m.fetch).await.1.len(), + 1, + "kept an hour before 30 days" + ); + + relay.advance(2 * 3600); + let now = relay.now.load(Ordering::SeqCst); + assert_eq!(relay.store.purge(now).expect("purge").blobs, 1); + assert!( + relay.fetch(&m, &m.fetch).await.1.is_empty(), + "gone an hour after 30 days" + ); +} + +#[tokio::test] +async fn a_fetch_returns_at_most_a_hundred_oldest_first() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + relay.create(&m).await; + for i in 0..105u8 { + relay.post(&m, &m.post, &[i]).await; + } + let (_, blobs) = relay.fetch(&m, &m.fetch).await; + assert_eq!(blobs.len(), MAX_BLOBS_PER_FETCH); + assert_eq!(blobs[0].blob.bytes(), &[0]); + assert_eq!(blobs[99].blob.bytes(), &[99]); +} + +#[tokio::test] +async fn a_blob_over_256_kib_is_refused() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + relay.create(&m).await; + assert_eq!( + relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES]).await, + StatusCode::CREATED + ); + assert_eq!( + relay.post(&m, &m.post, &vec![1; MAX_BLOB_BYTES + 1]).await, + StatusCode::PAYLOAD_TOO_LARGE + ); +} + +#[tokio::test] +async fn a_bad_body_is_a_bare_400() { + let relay = Relay::in_memory(); + let (s, body) = relay + .call( + Method::POST, + "/v0/mailboxes", + None, + br#"{"id":"Eva","name":"Eva"}"#.to_vec(), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); + assert!(body.is_empty(), "nothing of the request comes back"); +} + +fn invite_body(id: &InviteId, secret: &Token, kp: &[u8]) -> Vec { + serde_json::to_vec(&CreateInvite { + id: *id, + secret_hash: secret.hash(), + key_package: KeyPackageBytes::new(kp.to_vec()).expect("small"), + }) + .expect("json") +} + +#[tokio::test] +async fn an_invite_is_claimed_once_with_its_secret_only() { + let relay = Relay::in_memory(); + let id = InviteId::from_bytes(random()); + let secret = Token::from_bytes(random()); + let (s, _) = relay + .call( + Method::POST, + "/v0/invites", + None, + invite_body(&id, &secret, b"key package"), + ) + .await; + assert_eq!(s, StatusCode::CREATED); + let path = format!("/v0/invites/{}", id.to_wire()); + + let (s, _) = relay + .call( + Method::GET, + &path, + Some(&Token::from_bytes(random())), + vec![], + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND, "wrong secret"); + let (s, body) = relay.call(Method::GET, &path, Some(&secret), vec![]).await; + assert_eq!(s, StatusCode::OK); + let claimed: ClaimedInvite = serde_json::from_slice(&body).expect("invite"); + assert_eq!(claimed.key_package.bytes(), b"key package"); + let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await; + assert_eq!(s, StatusCode::NOT_FOUND, "one time only"); +} + +#[tokio::test] +async fn an_invite_expires_after_7_days() { + let relay = Relay::in_memory(); + let id = InviteId::from_bytes(random()); + let secret = Token::from_bytes(random()); + relay + .call( + Method::POST, + "/v0/invites", + None, + invite_body(&id, &secret, b"kp"), + ) + .await; + let path = format!("/v0/invites/{}", id.to_wire()); + + relay.advance(INVITE_TTL_SECS + 2 * 3600); + let (s, _) = relay.call(Method::GET, &path, Some(&secret), vec![]).await; + assert_eq!(s, StatusCode::NOT_FOUND, "expired, even before a purge"); + let now = relay.now.load(Ordering::SeqCst); + assert_eq!(relay.store.purge(now).expect("purge").invites, 1); +} + +#[test] +fn an_invite_is_still_good_just_before_7_days() { + let store = Store::open_in_memory().expect("store"); + let id = InviteId::from_bytes(random()); + let secret = Token::from_bytes(random()); + let req = CreateInvite { + id, + secret_hash: secret.hash(), + key_package: KeyPackageBytes::new(b"kp".to_vec()).expect("small"), + }; + store.create_invite(&req, T0).expect("created"); + assert!(store + .claim_invite(&id, &secret, T0 + INVITE_TTL_SECS - 1) + .is_ok()); + assert_eq!( + store + .claim_invite(&id, &secret, T0) + .expect_err("claimed already"), + Refused::NotFound, + "claimed already" + ); +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) +} + +/// Sends one raw HTTP/1.1 request over a real TCP connection from 127.0.0.1. +fn raw_http(addr: std::net::SocketAddr, request: &str, body: &[u8]) -> String { + let mut s = std::net::TcpStream::connect(addr).expect("connect"); + s.write_all(request.as_bytes()).expect("write"); + s.write_all(body).expect("write body"); + let mut out = String::new(); + s.read_to_string(&mut out).expect("read"); + out +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn no_token_secret_or_address_reaches_the_database() { + let dir = tempfile::tempdir().expect("tempdir"); + let db = dir.path().join("relay.db"); + let relay = Relay::with(Store::open(&db).expect("store")); + + // Over real TCP, so the server has a client address it could have stored. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let addr = listener.local_addr().expect("addr"); + let app = relay.app.clone(); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + + let m = Mailbox::new(); + let invite = InviteId::from_bytes(random()); + let secret = Token::from_bytes(random()); + let new_post = Token::from_bytes(random()); + let steps: Vec<(String, Vec)> = vec![ + ("POST /v0/mailboxes".into(), m.create_body().into_bytes()), + ( + format!("POST {} {}", m.blobs_path(), m.post.to_bearer()), + b"ciphertext".to_vec(), + ), + ( + format!("GET {} {}", m.blobs_path(), m.fetch.to_bearer()), + vec![], + ), + ( + format!( + "PUT /v0/mailboxes/{}/post-token {}", + m.id.to_wire(), + m.fetch.to_bearer() + ), + serde_json::to_vec(&RotatePostToken { + post_token_hash: new_post.hash(), + }) + .expect("json"), + ), + ( + "POST /v0/invites".into(), + invite_body(&invite, &secret, b"kp"), + ), + ]; + for (line, body) in steps { + let mut parts = line.splitn(3, ' '); + let (method, path, auth) = ( + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + parts.next(), + ); + let auth_header = auth + .map(|a| format!("Authorization: {a}\r\n")) + .unwrap_or_default(); + let req = format!( + "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUser-Agent: canary-agent/1.0\r\n{auth_header}Content-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + let resp = raw_http(addr, &req, &body); + assert!( + resp.starts_with("HTTP/1.1 2"), + "{method} {path}: {}", + resp.lines().next().unwrap_or("") + ); + } + server.abort(); + drop(relay); + + let bytes = std::fs::read(&db).expect("db file"); + for (what, needle) in [ + ("post token", m.post.as_bytes().to_vec()), + ("fetch token", m.fetch.as_bytes().to_vec()), + ("new post token", new_post.as_bytes().to_vec()), + ("invite secret", secret.as_bytes().to_vec()), + ("post token, base64url", m.post.to_wire().into_bytes()), + ("fetch token, base64url", m.fetch.to_wire().into_bytes()), + ("client address", b"127.0.0.1".to_vec()), + ( + "client address, binary", + vec![127, 0, 0, 1, (addr.port() >> 8) as u8], + ), + ("user agent", b"canary-agent".to_vec()), + ] { + assert!( + !contains(&bytes, &needle), + "{what} found in the database file" + ); + } + // What should be there is there: the hash, not the token. + assert!( + contains(&bytes, m.fetch.hash().as_bytes()), + "the fetch token's hash is stored" + ); + let others: Vec<_> = std::fs::read_dir(dir.path()) + .expect("dir") + .filter_map(|e| e.ok()) + .map(|e| e.file_name()) + .collect(); + assert_eq!( + others.len(), + 1, + "no -wal or -journal file left beside the database: {others:?}" + ); +} + +#[test] +fn a_deleted_blob_is_not_left_in_the_file() { + let dir = tempfile::tempdir().expect("tempdir"); + let db = dir.path().join("relay.db"); + let store = Store::open(&db).expect("store"); + let m = Mailbox::new(); + store + .create_mailbox( + &CreateMailbox { + id: m.id, + post_token_hash: m.post.hash(), + fetch_token_hash: m.fetch.hash(), + }, + T0, + ) + .expect("mailbox"); + let marker: Vec = b"DELETED-BLOB-MARKER-" + .iter() + .copied() + .chain(random::<16>()) + .collect(); + let aged: Vec = b"AGED-BLOB-MARKER-" + .iter() + .copied() + .chain(random::<16>()) + .collect(); + store.post(&m.id, &m.post, &marker, T0).expect("post"); + store.post(&m.id, &m.post, &aged, T0).expect("post"); + store + .acknowledge(&m.id, &m.fetch, &blob_hash(&marker)) + .expect("ack"); + store.purge(T0 + BLOB_TTL_SECS + 7200).expect("purge"); + drop(store); + let bytes = std::fs::read(&db).expect("db file"); + assert!( + !contains(&bytes, &marker), + "an acknowledged blob's bytes stay in the file" + ); + assert!( + !contains(&bytes, &aged), + "a purged blob's bytes stay in the file" + ); +} + +#[test] +fn the_relay_listens_on_loopback_unless_told_otherwise() { + let args = parse_args(Vec::::new()).expect("defaults"); + assert_eq!(args.listen.to_string(), DEFAULT_LISTEN); + assert!(args.listen.ip().is_loopback()); + assert!(parse_args(["--listen".to_string()]).is_err()); + assert!(parse_args(["--verbose".to_string()]).is_err()); +} + +#[test] +fn the_binary_serves_its_version_and_prints_no_request() { + let dir = tempfile::tempdir().expect("tempdir"); + let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_tabellarius-relay")) + .args(["--listen", "127.0.0.1:0", "--db"]) + .arg(dir.path().join("relay.db")) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn"); + let mut stdout = child.stdout.take().expect("stdout"); + // The one start line: "... listening on 127.0.0.1:\n" + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + while stdout.read(&mut byte).expect("read") == 1 && byte[0] != b'\n' { + line.push(byte[0]); + } + let line = String::from_utf8(line).expect("utf8"); + let addr: std::net::SocketAddr = line + .rsplit(' ') + .next() + .and_then(|a| a.parse().ok()) + .expect("address in the start line"); + assert!(addr.ip().is_loopback(), "{line}"); + + let resp = raw_http( + addr, + "GET /version HTTP/1.1\r\nHost: x\r\nUser-Agent: canary-agent/1.0\r\nConnection: close\r\n\r\n", + &[], + ); + assert!(resp.starts_with("HTTP/1.1 200"), "{resp}"); + assert!(resp.contains("\"protocol\":\"v0\""), "{resp}"); + + child.kill().expect("kill"); + let mut rest = String::new(); + stdout.read_to_string(&mut rest).expect("stdout"); + let mut err = String::new(); + child + .stderr + .take() + .expect("stderr") + .read_to_string(&mut err) + .expect("stderr"); + let _ = child.wait(); + assert!( + rest.is_empty() && err.is_empty(), + "the relay printed after start: {rest:?} {err:?}" + ); +} + +/// Random bodies, paths and headers at every route: a 4xx or a success, never a 500 or a panic. +#[tokio::test] +async fn no_random_request_breaks_the_relay() { + let relay = Relay::in_memory(); + let m = Mailbox::new(); + relay.create(&m).await; + let routes = [ + (Method::POST, "/v0/mailboxes".to_string()), + (Method::POST, m.blobs_path()), + (Method::GET, m.blobs_path()), + ( + Method::PUT, + format!("/v0/mailboxes/{}/post-token", m.id.to_wire()), + ), + (Method::POST, "/v0/invites".to_string()), + ( + Method::GET, + format!("/v0/invites/{}", InviteId::from_bytes(random()).to_wire()), + ), + ]; + for i in 0..3000usize { + let len = random::<1>()[0] as usize * (1 + i % 4); + let mut body = vec![0u8; len]; + getrandom::fill(&mut body).expect("randomness"); + if i % 3 == 0 { + // JSON-shaped noise reaches deeper into the parsers than raw bytes. + body = format!( + "{{\"id\":\"{}\",\"postTokenHash\":{},\"keyPackage\":\"{}\"}}", + String::from_utf8_lossy(&body[..len.min(30)]), + len, + "A".repeat(len) + ) + .into_bytes(); + } + let (method, path) = &routes[i % routes.len()]; + let token = if i % 2 == 0 { Some(&m.fetch) } else { None }; + let (status, _) = relay.call(method.clone(), path, token, body).await; + assert!( + !status.is_server_error(), + "{method} {path} answered {status}" + ); + } + // Garbage paths too. + for _ in 0..500 { + let id: String = random::<12>() + .iter() + .map(|b| (b'A' + b % 26) as char) + .collect(); + let (status, _) = relay + .call( + Method::GET, + &format!("/v0/mailboxes/{id}/blobs"), + Some(&m.fetch), + vec![], + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + } +}