Files
Amicitia-Tabellarius/crates/relay/tests/relay.rs
T
mnovak 3a0944ebff
ci / check (pull_request) Has been cancelled
[relay] Files: a file route for same-size encrypted chunks with its own quotas; the client seals chunks in STREAM and sends a file payload inside MLS
The relay stores files (id, upload and fetch token hashes, chunk count, uploaded hour) and chunks
(file id, index, ciphertext): every chunk is 256 000 bytes, so it learns the size rounded up to
250 KiB and nothing finer, and it keeps no fetch count. Only the uploader's token puts or deletes,
only the fetch token gets, a chunk never changes; per-file and relay-wide quotas answer 507; files
go after 30 days, incomplete ones after 24 hours. The client pads a file to whole chunks and seals
each with ChaCha20-Poly1305 in the aead crate's STREAM, under a key made for that file; the key,
name, type, size and thumbnail travel only in the new `file` payload, which shares `seq` with text.
Also: every route now answers a bare 413 (axum's own carried a text). PROTOCOL.md §1, §4, §5, §7, §8.
2026-11-22 19:29:37 +01:00

876 lines
28 KiB
Rust

//! 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<const N: usize>() -> [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<Store>,
now: Arc<AtomicI64>,
}
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::new(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<u8>,
) -> (StatusCode, Vec<u8>) {
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<FetchedBlob>) {
let (s, body) = self
.call(Method::GET, &m.blobs_path(), Some(token), vec![])
.await;
let blobs = if s == StatusCode::OK {
serde_json::from_slice::<FetchedBlobs>(&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<String>)> = vec![
(
"blobs".into(),
vec![
"mailbox_id".into(),
"ciphertext".into(),
"size".into(),
"received_hour".into(),
],
),
// Files (`.agents/features/files.md` §2.3): every chunk is the same size, so no size column.
(
"chunks".into(),
vec!["file_id".into(), "idx".into(), "ciphertext".into()],
),
(
"files".into(),
vec![
"id".into(),
"upload_hash".into(),
"fetch_hash".into(),
"chunks".into(),
"uploaded_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(),
],
),
// Wake-up (`.agents/features/wake-up.md` §2.3), only for a mailbox whose owner opted in.
("push".into(), vec!["mailbox_id".into(), "endpoint".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<_>>(),
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
);
// Over a route's limit, axum's own refusal carries a text; the relay's is bare (§8).
let (s, body) = relay
.call(
Method::POST,
&m.blobs_path(),
Some(&m.post),
vec![1; MAX_BLOB_BYTES + 1],
)
.await;
assert_eq!((s, body.len()), (StatusCode::PAYLOAD_TOO_LARGE, 0));
let (s, body) = relay
.call(Method::POST, "/v0/mailboxes", None, vec![b' '; 64 * 1024])
.await;
assert_eq!((s, body.len()), (StatusCode::PAYLOAD_TOO_LARGE, 0));
}
#[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<u8> {
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<u8>)> = 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<u8> = b"DELETED-BLOB-MARKER-"
.iter()
.copied()
.chain(random::<16>())
.collect();
let aged: Vec<u8> = 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::<String>::new()).expect("defaults");
assert_eq!(args.listen.to_string(), DEFAULT_LISTEN);
assert!(args.listen.ip().is_loopback());
assert!(
!args.push_loopback,
"loopback push endpoints only when asked for"
);
assert!(
parse_args(["--push-loopback".to_string()])
.expect("flag")
.push_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:<port>\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);
}
}
/// `GET /join` (PROTOCOL.md §8, 2026-11-18): a static page that hands the fragment to the app. It
/// must load nothing from elsewhere, run nothing but its own script, and keep nothing.
#[tokio::test]
async fn the_join_page_is_static_and_loads_nothing_from_elsewhere() {
use tower::ServiceExt;
let relay = Relay::in_memory();
let response = relay
.app
.clone()
.oneshot(Request::get("/join").body(Body::empty()).expect("request"))
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let h = response.headers().clone();
let get = |name: &str| {
h.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_string()
};
assert_eq!(get("content-type"), "text/html; charset=utf-8");
assert_eq!(get("cache-control"), "no-store");
assert_eq!(get("referrer-policy"), "no-referrer");
assert_eq!(get("x-content-type-options"), "nosniff");
assert!(h.get("set-cookie").is_none());
let csp = get("content-security-policy");
assert!(
csp.starts_with("default-src 'none'; script-src 'sha256-"),
"{csp}"
);
for part in [
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
] {
assert!(csp.contains(part), "{csp} lacks {part}");
}
let body = String::from_utf8(
response
.into_body()
.collect()
.await
.expect("body")
.to_bytes()
.to_vec(),
)
.expect("utf-8");
// Nothing loaded from anywhere, and nothing the script could send the fragment with or leave
// the page by on its own (a custom scheme must wait for the person's tap).
for banned in [
"http://",
"https://",
" src=",
"<link",
"<img",
"<iframe",
"@import",
"url(",
"fetch(",
"XMLHttpRequest",
"sendBeacon",
"WebSocket",
"location.href",
"location.assign",
"location.replace",
"window.open",
] {
assert!(!body.contains(banned), "the page contains {banned:?}");
}
// One script and one style, both named by the policy's hashes; the invite goes to the app.
assert_eq!(body.matches("<script>").count(), 1);
assert_eq!(body.matches("<style>").count(), 1);
assert!(body.contains("\"amicitia://invite?relay=\" + location.origin + \"#\" + invite"));
assert!(body.contains("location.hash"));
}
#[test]
fn the_join_page_policy_hashes_its_own_script_and_style() {
use base64::Engine;
use sha2::{Digest, Sha256};
let page = tabellarius_relay::join::PAGE;
let between = |open: &str, close: &str| {
let s = page.find(open).expect("the tag opens") + open.len();
&page[s..page[s..].find(close).expect("the tag closes") + s]
};
let csp = tabellarius_relay::join::CONTENT_SECURITY_POLICY.as_str();
for text in [
between("<script>", "</script>"),
between("<style>", "</style>"),
] {
let b64 = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(text.as_bytes()));
assert!(csp.contains(&format!("'sha256-{b64}'")), "{csp}");
}
}