[relay] F23: quotas (507), a NixOS module behind Caddy with TLS and no logs, and a VM test that no address is kept

This commit is contained in:
2026-11-16 11:39:18 +01:00
parent 2a8daa7570
commit dd576f9feb
11 changed files with 773 additions and 11 deletions
+1
View File
@@ -59,6 +59,7 @@ impl From<Refused> for Status {
Refused::Exists => StatusCode::CONFLICT,
Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR,
Refused::Full => StatusCode::INSUFFICIENT_STORAGE,
})
}
}
+16 -3
View File
@@ -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 <addr:port>`, `--db <path>`. Anything else is refused with a usage line.
/// `--listen <addr:port>`, `--db <path>`, 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<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
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<String>| -> Result<i64, String> {
v.and_then(|v| v.parse::<i64>().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<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
_ => return Err(usage.to_string()),
}
}
Ok(Args { listen, db })
Ok(Args { listen, db, limits })
}
+3 -2
View File
@@ -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!(
+80 -5
View File
@@ -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<rusqlite::Error> for Refused {
@@ -58,6 +88,7 @@ impl From<rusqlite::Error> for Refused {
pub struct Store {
conn: Mutex<Connection>,
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, rusqlite::Error> {
Self::init(Connection::open(path)?)
Self::init(Connection::open(path)?, Limits::default())
}
pub fn open_with(path: &Path, limits: Limits) -> Result<Self, rusqlite::Error> {
Self::init(Connection::open(path)?, limits)
}
pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
Self::init(Connection::open_in_memory()?)
Self::init(Connection::open_in_memory()?, Limits::default())
}
fn init(conn: Connection) -> Result<Self, rusqlite::Error> {
pub fn open_in_memory_with(limits: Limits) -> Result<Self, rusqlite::Error> {
Self::init(Connection::open_in_memory()?, limits)
}
fn init(conn: Connection, limits: Limits) -> Result<Self, rusqlite::Error> {
// 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<i64, Refused> {
Ok(conn
.query_row(sql, args, |r| r.get::<_, Option<i64>>(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<i64>) = 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()[..],
+292
View File
@@ -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<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 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<u8>,
) -> 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");
}