[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
ci / check (pull_request) Has been cancelled

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.
This commit is contained in:
2026-11-22 19:29:37 +01:00
parent 4d0dac0591
commit 3a0944ebff
20 changed files with 2352 additions and 42 deletions
+98 -7
View File
@@ -4,6 +4,7 @@
use crate::store::{Refused, Store};
use crate::wake::Waker;
use axum::body::Bytes;
use axum::extract::rejection::BytesRejection;
use axum::extract::{DefaultBodyLimit, Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
@@ -12,8 +13,9 @@ use axum::{Json, Router};
use serde::de::DeserializeOwned;
use std::sync::Arc;
use tabellarius_protocol::{
CreateInvite, CreateMailbox, FetchedBlobs, InviteId, MailboxId, RotatePostToken, SetPush,
Sha256Hash, Token, VersionInfo, MAX_BLOB_BYTES, VERSION,
CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId,
RotatePostToken, SetPush, Sha256Hash, Token, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES,
VERSION,
};
/// Unix seconds. The server passes the system clock; tests pass their own.
@@ -49,17 +51,27 @@ 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));
// A chunk is exactly FILE_CHUNK_BYTES; one byte more is refused before it is read.
let chunk_routes = Router::new()
.route(
"/v0/files/{id}/chunks/{index}",
put(put_chunk).get(get_chunk),
)
.layer(DefaultBodyLimit::max(FILE_CHUNK_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/mailboxes/{id}/push", put(set_push).delete(clear_push))
.route("/v0/files", post(create_file))
.route("/v0/files/{id}", delete(delete_file))
.route("/v0/invites", post(create_invite))
.route("/v0/invites/{id}", get(claim_invite))
.route("/version", get(version))
.route("/join", get(crate::join::page))
.layer(DefaultBodyLimit::max(MAX_JSON_BYTES))
.merge(blob_routes)
.merge(chunk_routes)
.with_state(state)
}
@@ -84,6 +96,11 @@ impl From<Refused> for Status {
}
}
/// A body over the route's limit is axum's rejection, which carries a text: a bare 413 instead.
fn bare(body: Result<Bytes, BytesRejection>) -> Result<Bytes, Status> {
body.map_err(|_| Status(StatusCode::PAYLOAD_TOO_LARGE))
}
/// Parses a JSON body with the protocol's strict types; any failure is a plain 400.
fn json<T: DeserializeOwned>(body: &Bytes) -> Result<T, Status> {
serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST))
@@ -103,7 +120,11 @@ fn bearer(headers: &HeaderMap) -> Result<Token, Status> {
.ok_or(Status(StatusCode::NOT_FOUND))
}
async fn create_mailbox(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
async fn create_mailbox(
State(s): State<AppState>,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let req: CreateMailbox = json(&body)?;
s.store.create_mailbox(&req, (s.clock)())?;
Ok(StatusCode::CREATED)
@@ -113,8 +134,9 @@ async fn post_blob(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let now = (s.clock)();
@@ -153,8 +175,9 @@ async fn rotate_post_token(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let req: RotatePostToken = json(&body)?;
@@ -167,8 +190,9 @@ async fn set_push(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let id = mailbox(&id)?;
let token = bearer(&headers)?;
let req: SetPush = json(&body)?;
@@ -190,7 +214,74 @@ async fn clear_push(
Ok(StatusCode::NO_CONTENT)
}
async fn create_invite(State(s): State<AppState>, body: Bytes) -> Result<StatusCode, Status> {
/// A malformed file id in the path is treated like an unknown one.
fn file(id: &str) -> Result<FileId, Status> {
FileId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND))
}
/// A chunk index: decimal digits of a `u32`, no sign, no leading zero. Anything else is a 404.
fn chunk_index(text: &str) -> Result<u32, Status> {
let canonical = !text.is_empty()
&& text.bytes().all(|b| b.is_ascii_digit())
&& (text == "0" || !text.starts_with('0'));
text.parse::<u32>()
.ok()
.filter(|_| canonical)
.ok_or(Status(StatusCode::NOT_FOUND))
}
async fn create_file(
State(s): State<AppState>,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let req: CreateFile = json(&body)?;
s.store.create_file(&req, (s.clock)())?;
Ok(StatusCode::CREATED)
}
async fn put_chunk(
State(s): State<AppState>,
Path((id, index)): Path<(String, String)>,
headers: HeaderMap,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let id = file(&id)?;
let index = chunk_index(&index)?;
let token = bearer(&headers)?;
s.store.put_chunk(&id, &token, index, &body)?;
Ok(StatusCode::CREATED)
}
async fn get_chunk(
State(s): State<AppState>,
Path((id, index)): Path<(String, String)>,
headers: HeaderMap,
) -> Result<Response, Status> {
let id = file(&id)?;
let index = chunk_index(&index)?;
let token = bearer(&headers)?;
let bytes = s.store.get_chunk(&id, &token, index)?;
Ok(([(header::CONTENT_TYPE, "application/octet-stream")], bytes).into_response())
}
async fn delete_file(
State(s): State<AppState>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Result<StatusCode, Status> {
let id = file(&id)?;
let token = bearer(&headers)?;
s.store.delete_file(&id, &token)?;
Ok(StatusCode::NO_CONTENT)
}
async fn create_invite(
State(s): State<AppState>,
body: Result<Bytes, BytesRejection>,
) -> Result<StatusCode, Status> {
let body = bare(body)?;
let req: CreateInvite = json(&body)?;
s.store.create_invite(&req, (s.clock)())?;
Ok(StatusCode::CREATED)
+6 -4
View File
@@ -22,12 +22,12 @@ pub struct Args {
pub push_loopback: bool,
}
/// `--listen <addr:port>`, `--db <path>`, and the relay-wide quotas `--max-bytes`,
/// `--max-mailboxes`, `--max-invites` (positive integers), and `--push-loopback` (tests). Anything else is refused with a usage
/// line.
/// `--listen <addr:port>`, `--db <path>`, the relay-wide quotas `--max-bytes`, `--max-mailboxes`,
/// `--max-invites`, `--max-files`, `--max-file-bytes` (positive integers), and `--push-loopback`
/// (tests). 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] \
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--push-loopback]";
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback]";
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();
@@ -43,6 +43,8 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
"--max-bytes" => limits.total_bytes = positive(it.next())?,
"--max-mailboxes" => limits.mailboxes = positive(it.next())?,
"--max-invites" => limits.invites = positive(it.next())?,
"--max-files" => limits.files = positive(it.next())?,
"--max-file-bytes" => limits.file_bytes = positive(it.next())?,
"--push-loopback" => push_loopback = true,
"--listen" => {
listen = it
+3 -2
View File
@@ -1,5 +1,5 @@
//! `tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] [--max-bytes N]
//! [--max-mailboxes N] [--max-invites N] [--push-loopback]`
//! [--max-mailboxes N] [--max-invites N] [--max-files N] [--max-file-bytes N] [--push-loopback]`
//!
//! Prints one line at start (version and address) and nothing per request.
@@ -53,7 +53,8 @@ async fn main() {
tabellarius_protocol::VERSION
);
// Purge at start and every hour: blobs after 30 days, invites after their expiry.
// Purge at start and every hour: blobs and files after 30 days, files not complete after a
// day, invites after their expiry.
let purger = Arc::clone(&store);
tokio::spawn(async move {
let mut every_hour = tokio::time::interval(Duration::from_secs(3600));
+172 -9
View File
@@ -1,6 +1,6 @@
//! Every rule of the relay, over SQLite, with the clock passed in.
//!
//! The database holds exactly `docs/PROTOCOL.md` §5: four tables, and nothing about who connected.
//! The database holds exactly `docs/PROTOCOL.md` §5: six 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.
@@ -9,9 +9,10 @@ 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, PushEndpoint, Sha256Hash, Token, BLOB_TTL_SECS,
INVITE_TTL_SECS, MAX_BLOBS_PER_FETCH, MAX_BLOB_BYTES,
blob_hash, day_of, hour_of, BlobBytes, ClaimedInvite, CreateFile, CreateInvite, CreateMailbox,
FetchedBlob, FileId, InviteId, KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token,
BLOB_TTL_SECS, FILE_CHUNK_BYTES, INCOMPLETE_FILE_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.
@@ -39,6 +40,19 @@ CREATE TABLE IF NOT EXISTS push (
mailbox_id BLOB PRIMARY KEY NOT NULL,
endpoint TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS files (
id BLOB PRIMARY KEY NOT NULL,
upload_hash BLOB NOT NULL,
fetch_hash BLOB NOT NULL,
chunks INTEGER NOT NULL,
uploaded_hour INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS chunks (
file_id BLOB NOT NULL,
idx INTEGER NOT NULL,
ciphertext BLOB NOT NULL,
PRIMARY KEY (file_id, idx)
);
";
/// Why a request was refused. Deliberately coarse: it says nothing about which part was wrong.
@@ -65,6 +79,10 @@ pub struct Limits {
pub total_bytes: i64,
pub mailboxes: i64,
pub invites: i64,
/// Files on the relay, complete or not (`.agents/features/files.md` §2.3).
pub files: i64,
/// Bytes reserved by files: each counts as its chunks times `FILE_CHUNK_BYTES` from creation.
pub file_bytes: i64,
}
/// Waiting blobs in one mailbox (`PROTOCOL.md` §8).
@@ -80,6 +98,8 @@ impl Default for Limits {
total_bytes: 1024 * 1024 * 1024,
mailboxes: 100_000,
invites: 10_000,
files: 10_000,
file_bytes: 4 * 1024 * 1024 * 1024,
}
}
}
@@ -100,6 +120,8 @@ pub struct Store {
pub struct Purged {
pub blobs: usize,
pub invites: usize,
/// Files removed with their chunks: older than 30 days, or incomplete after 24 hours.
pub files: usize,
}
fn same_hash(stored: &[u8], presented: &Sha256Hash) -> bool {
@@ -399,14 +421,153 @@ impl Store {
Ok(())
}
/// Deletes blobs older than 30 days and invites past their expiry.
/// Deletes blobs older than 30 days, invites past their expiry, and files older than 30 days
/// or still incomplete 24 hours after they were created, with their chunks.
pub fn purge(&self, now: i64) -> Result<Purged, Refused> {
let conn = self.conn();
let mut 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 })
let oldest_incomplete = hour_of(now - INCOMPLETE_FILE_TTL_SECS);
let tx = conn.transaction()?;
let blobs = tx.execute("DELETE FROM blobs WHERE received_hour < ?1", [oldest_kept])?;
let invites = tx.execute("DELETE FROM invites WHERE expiry <= ?1", [now])?;
let files = tx.execute(
"DELETE FROM files WHERE uploaded_hour < ?1
OR (uploaded_hour < ?2
AND chunks > (SELECT count(*) FROM chunks WHERE chunks.file_id = files.id))",
params![oldest_kept, oldest_incomplete],
)?;
tx.execute(
"DELETE FROM chunks WHERE file_id NOT IN (SELECT id FROM files)",
[],
)?;
tx.commit()?;
Ok(Purged {
blobs,
invites,
files,
})
}
/// A new file (`.agents/features/files.md` §2.3): its id, the hashes of the two tokens its
/// uploader made, and how many chunks it will have. It counts against the relay's file quota
/// at its full size from now on, so an upload under way is never cut off by another.
pub fn create_file(&self, req: &CreateFile, now: i64) -> Result<(), Refused> {
let conn = self.conn();
let (files, chunks): (i64, Option<i64>) =
conn.query_row("SELECT count(*), sum(chunks) FROM files", [], |r| {
Ok((r.get(0)?, r.get(1)?))
})?;
let reserved =
(chunks.unwrap_or(0) + i64::from(req.chunks.get())) * FILE_CHUNK_BYTES as i64;
if files >= self.limits.files || reserved > self.limits.file_bytes {
return Err(Refused::Full);
}
let changed = conn.execute(
"INSERT OR IGNORE INTO files (id, upload_hash, fetch_hash, chunks, uploaded_hour)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
&req.id.as_bytes()[..],
&req.upload_token_hash.as_bytes()[..],
&req.fetch_token_hash.as_bytes()[..],
i64::from(req.chunks.get()),
hour_of(now)
],
)?;
if changed == 0 {
return Err(Refused::Exists);
}
Ok(())
}
/// Checks a token against a file's upload or fetch hash; returns its chunk count.
fn authorize_file(
conn: &Connection,
id: &FileId,
token: &Token,
column: Column,
) -> Result<i64, Refused> {
let sql = match column {
Column::Post => "SELECT upload_hash, chunks FROM files WHERE id = ?1",
Column::Fetch => "SELECT fetch_hash, chunks FROM files WHERE id = ?1",
};
let stored: Option<(Vec<u8>, i64)> = conn
.query_row(sql, [&id.as_bytes()[..]], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?;
// As for mailboxes: an unknown file takes the same path as a wrong token.
let (stored, chunks) = stored.unwrap_or_else(|| (vec![0; 32], 0));
let known = !stored.iter().all(|b| *b == 0);
if known & same_hash(&stored, &token.hash()) {
Ok(chunks)
} else {
Err(Refused::NotFound)
}
}
/// Stores chunk `index` of a file, with the upload token. The same bytes again are accepted (an
/// upload resumed after a crash); other bytes are [`Refused::Exists`]: a chunk never changes.
/// An index at or past the file's chunk count is [`Refused::Full`], after the token.
pub fn put_chunk(
&self,
id: &FileId,
token: &Token,
index: u32,
chunk: &[u8],
) -> Result<(), Refused> {
if chunk.len() != FILE_CHUNK_BYTES {
return Err(Refused::TooLarge);
}
let mut conn = self.conn();
let chunks = Self::authorize_file(&conn, id, token, Column::Post)?;
if i64::from(index) >= chunks {
return Err(Refused::Full);
}
let tx = conn.transaction()?;
let held: Option<Vec<u8>> = tx
.query_row(
"SELECT ciphertext FROM chunks WHERE file_id = ?1 AND idx = ?2",
params![&id.as_bytes()[..], i64::from(index)],
|r| r.get(0),
)
.optional()?;
match held {
Some(bytes) if bytes == chunk => return Ok(()),
Some(_) => return Err(Refused::Exists),
None => {}
}
tx.execute(
"INSERT INTO chunks (file_id, idx, ciphertext) VALUES (?1, ?2, ?3)",
params![&id.as_bytes()[..], i64::from(index), chunk],
)?;
tx.commit()?;
Ok(())
}
/// Chunk `index` of a file, with the fetch token. Not there (yet) = [`Refused::NotFound`].
pub fn get_chunk(&self, id: &FileId, token: &Token, index: u32) -> Result<Vec<u8>, Refused> {
let conn = self.conn();
Self::authorize_file(&conn, id, token, Column::Fetch)?;
conn.query_row(
"SELECT ciphertext FROM chunks WHERE file_id = ?1 AND idx = ?2",
params![&id.as_bytes()[..], i64::from(index)],
|r| r.get(0),
)
.optional()?
.ok_or(Refused::NotFound)
}
/// The uploader deletes a file and its chunks early, with the upload token.
pub fn delete_file(&self, id: &FileId, token: &Token) -> Result<(), Refused> {
let mut conn = self.conn();
Self::authorize_file(&conn, id, token, Column::Post)?;
let tx = conn.transaction()?;
tx.execute(
"DELETE FROM chunks WHERE file_id = ?1",
[&id.as_bytes()[..]],
)?;
tx.execute("DELETE FROM files WHERE id = ?1", [&id.as_bytes()[..]])?;
tx.commit()?;
Ok(())
}
/// The live schema: (table, columns) for every table, in name order. For the §5 test.
@@ -429,6 +590,8 @@ impl Store {
}
}
/// Which of a mailbox's (or a file's) two hashes a token is checked against: the one that lets it
/// post (or upload), or the one that lets it fetch.
#[derive(Clone, Copy)]
enum Column {
Post,
+403
View File
@@ -0,0 +1,403 @@
//! Files (`.agents/features/files.md` §2.3, `PROTOCOL.md` §8): create, put, get, delete; only the
//! upload token puts and deletes, only the fetch token gets; every chunk is the same size; a
//! per-file and a relay-wide quota (507); files go after 30 days, incomplete ones after a day.
use axum::body::Body;
use axum::http::{header, Method, Request, StatusCode};
use http_body_util::BodyExt;
use std::sync::atomic::{AtomicI64, Ordering};
use std::sync::Arc;
use tabellarius_protocol::*;
use tabellarius_relay::http::{router, AppState, Clock};
use tabellarius_relay::store::{Limits, Purged, Store};
use tower::ServiceExt;
const T0: i64 = 1_794_000_000;
const HOUR: i64 = 3600;
const DAY: i64 = 24 * HOUR;
fn random<const N: usize>() -> [u8; N] {
let mut b = [0u8; N];
getrandom::fill(&mut b).expect("system randomness");
b
}
struct File {
id: FileId,
upload: Token,
fetch: Token,
chunks: u32,
}
impl File {
fn new(chunks: u32) -> Self {
Self {
id: FileId::from_bytes(random()),
upload: Token::from_bytes(random()),
fetch: Token::from_bytes(random()),
chunks,
}
}
fn chunk_path(&self, index: u32) -> String {
format!("/v0/files/{}/chunks/{index}", self.id.to_wire())
}
}
fn chunk(fill: u8) -> Vec<u8> {
vec![fill; FILE_CHUNK_BYTES]
}
struct Relay {
app: axum::Router,
store: Arc<Store>,
now: Arc<AtomicI64>,
}
impl Relay {
fn with(limits: Limits) -> Self {
let store = Arc::new(Store::open_in_memory_with(limits).expect("store"));
let now = Arc::new(AtomicI64::new(T0));
let n = Arc::clone(&now);
let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst));
Relay {
app: router(AppState::new(Arc::clone(&store), clock)),
store,
now,
}
}
fn new() -> Self {
Self::with(Limits::default())
}
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 body = resp.into_body().collect().await.expect("body").to_bytes();
if !status.is_success() {
assert!(body.is_empty(), "a refusal has no body");
}
(status, body.to_vec())
}
async fn create(&self, f: &File) -> StatusCode {
self.create_json(serde_json::json!({
"id": f.id,
"uploadTokenHash": f.upload.hash(),
"fetchTokenHash": f.fetch.hash(),
"chunks": f.chunks,
}))
.await
}
async fn create_json(&self, body: serde_json::Value) -> StatusCode {
let body = serde_json::to_vec(&body).expect("json");
self.call(Method::POST, "/v0/files", None, body).await.0
}
async fn put(&self, f: &File, index: u32, token: &Token, bytes: Vec<u8>) -> StatusCode {
self.call(Method::PUT, &f.chunk_path(index), Some(token), bytes)
.await
.0
}
async fn get(&self, f: &File, index: u32, token: &Token) -> (StatusCode, Vec<u8>) {
self.call(Method::GET, &f.chunk_path(index), Some(token), Vec::new())
.await
}
async fn delete(&self, f: &File, token: &Token) -> StatusCode {
let path = format!("/v0/files/{}", f.id.to_wire());
self.call(Method::DELETE, &path, Some(token), Vec::new())
.await
.0
}
}
#[tokio::test]
async fn a_file_is_created_put_fetched_and_deleted() {
let relay = Relay::new();
let f = File::new(2);
assert_eq!(relay.create(&f).await, StatusCode::CREATED);
assert_eq!(relay.create(&f).await, StatusCode::CONFLICT);
assert_eq!(
relay.put(&f, 0, &f.upload, chunk(1)).await,
StatusCode::CREATED
);
assert_eq!(
relay.get(&f, 1, &f.fetch).await.0,
StatusCode::NOT_FOUND,
"not up yet"
);
assert_eq!(
relay.put(&f, 1, &f.upload, chunk(2)).await,
StatusCode::CREATED
);
let (status, bytes) = relay.get(&f, 1, &f.fetch).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes, chunk(2));
// Fetching deletes nothing, and is not counted anywhere.
assert_eq!(relay.get(&f, 1, &f.fetch).await.0, StatusCode::OK);
assert_eq!(relay.delete(&f, &f.upload).await, StatusCode::NO_CONTENT);
assert_eq!(relay.get(&f, 0, &f.fetch).await.0, StatusCode::NOT_FOUND);
assert_eq!(relay.delete(&f, &f.upload).await, StatusCode::NOT_FOUND);
assert_eq!(relay.store.purge(T0).expect("purge"), Purged::default());
}
#[tokio::test]
async fn only_the_upload_token_puts_and_deletes_and_only_the_fetch_token_gets() {
let relay = Relay::new();
let f = File::new(1);
let other = File::new(1);
relay.create(&f).await;
relay.create(&other).await;
let stranger = Token::from_bytes(random());
for token in [&stranger, &f.fetch, &other.upload] {
assert_eq!(
relay.put(&f, 0, token, chunk(1)).await,
StatusCode::NOT_FOUND
);
assert_eq!(relay.delete(&f, token).await, StatusCode::NOT_FOUND);
}
let (s, _) = relay
.call(Method::PUT, &f.chunk_path(0), None, chunk(1))
.await;
assert_eq!(s, StatusCode::NOT_FOUND, "no token at all");
assert_eq!(
relay.put(&f, 0, &f.upload, chunk(1)).await,
StatusCode::CREATED
);
for token in [&stranger, &f.upload, &other.fetch] {
assert_eq!(relay.get(&f, 0, token).await.0, StatusCode::NOT_FOUND);
}
assert_eq!(relay.get(&f, 0, &f.fetch).await.0, StatusCode::OK);
}
#[tokio::test]
async fn a_chunk_is_exactly_the_chunk_size_and_never_changes() {
let relay = Relay::new();
let f = File::new(1);
relay.create(&f).await;
for size in [0, 1, FILE_CHUNK_BYTES - 1] {
assert_eq!(
relay.put(&f, 0, &f.upload, vec![1; size]).await,
StatusCode::PAYLOAD_TOO_LARGE,
"{size}"
);
}
assert_eq!(
relay
.put(&f, 0, &f.upload, vec![1; FILE_CHUNK_BYTES + 1])
.await,
StatusCode::PAYLOAD_TOO_LARGE
);
assert_eq!(
relay.put(&f, 0, &f.upload, chunk(1)).await,
StatusCode::CREATED
);
assert_eq!(
relay.put(&f, 0, &f.upload, chunk(1)).await,
StatusCode::CREATED,
"the same bytes again: an upload resumed"
);
assert_eq!(
relay.put(&f, 0, &f.upload, chunk(2)).await,
StatusCode::CONFLICT,
"other bytes: refused"
);
assert_eq!(relay.get(&f, 0, &f.fetch).await.1, chunk(1));
}
#[tokio::test]
async fn a_file_holds_only_its_declared_chunks_and_at_most_the_protocols() {
let relay = Relay::new();
let f = File::new(2);
relay.create(&f).await;
assert_eq!(
relay.put(&f, 2, &f.upload, chunk(1)).await,
StatusCode::INSUFFICIENT_STORAGE,
"the file's quota"
);
assert_eq!(
relay
.put(&f, 2, &Token::from_bytes(random()), chunk(1))
.await,
StatusCode::NOT_FOUND,
"a stranger learns nothing about the file from a 507"
);
for chunks in [0, MAX_FILE_CHUNKS + 1] {
assert_eq!(
relay.create(&File::new(chunks)).await,
StatusCode::BAD_REQUEST,
"{chunks}"
);
}
assert_eq!(
relay.create(&File::new(MAX_FILE_CHUNKS)).await,
StatusCode::CREATED
);
let extra = serde_json::json!({
"id": FileId::from_bytes(random()),
"uploadTokenHash": Token::from_bytes(random()).hash(),
"fetchTokenHash": Token::from_bytes(random()).hash(),
"chunks": 1,
"name": "Menu.jpg",
});
assert_eq!(
relay.create_json(extra).await,
StatusCode::BAD_REQUEST,
"no field beyond the four: the relay takes no name"
);
}
#[tokio::test]
async fn a_malformed_id_or_index_is_a_bare_404() {
let relay = Relay::new();
let f = File::new(3);
relay.create(&f).await;
relay.put(&f, 0, &f.upload, chunk(1)).await;
let id = f.id.to_wire();
for path in [
format!("/v0/files/{id}/chunks/00"),
format!("/v0/files/{id}/chunks/+0"),
format!("/v0/files/{id}/chunks/-1"),
format!("/v0/files/{id}/chunks/x"),
format!("/v0/files/{id}/chunks/4294967296"),
format!("/v0/files/{id}A/chunks/0"),
"/v0/files/AAAA/chunks/0".to_string(),
] {
let (s, _) = relay
.call(Method::GET, &path, Some(&f.fetch), Vec::new())
.await;
assert_eq!(s, StatusCode::NOT_FOUND, "{path}");
}
}
#[tokio::test]
async fn the_relay_wide_file_quota_counts_each_file_at_full_size_from_its_creation() {
let relay = Relay::with(Limits {
files: 3,
file_bytes: 5 * FILE_CHUNK_BYTES as i64,
..Limits::default()
});
let a = File::new(3);
assert_eq!(relay.create(&a).await, StatusCode::CREATED);
assert_eq!(
relay.create(&File::new(3)).await,
StatusCode::INSUFFICIENT_STORAGE,
"a's three chunks are reserved though none is up"
);
let b = File::new(2);
assert_eq!(relay.create(&b).await, StatusCode::CREATED);
// a's upload is never cut off by b.
for i in 0..3 {
assert_eq!(
relay.put(&a, i, &a.upload, chunk(1)).await,
StatusCode::CREATED
);
}
assert_eq!(relay.delete(&b, &b.upload).await, StatusCode::NO_CONTENT);
assert_eq!(relay.create(&File::new(1)).await, StatusCode::CREATED);
assert_eq!(relay.create(&File::new(1)).await, StatusCode::CREATED);
assert_eq!(
relay.create(&File::new(1)).await,
StatusCode::INSUFFICIENT_STORAGE,
"the file count"
);
}
#[tokio::test]
async fn files_go_after_30_days_and_incomplete_ones_after_a_day() {
let relay = Relay::new();
let complete = File::new(1);
let incomplete = File::new(2);
relay.create(&complete).await;
relay.create(&incomplete).await;
relay.put(&complete, 0, &complete.upload, chunk(1)).await;
relay
.put(&incomplete, 0, &incomplete.upload, chunk(2))
.await;
let p = relay.store.purge(T0 + DAY - HOUR).expect("purge");
assert_eq!(p.files, 0, "under a day: an upload may still be under way");
let p = relay.store.purge(T0 + DAY + HOUR).expect("purge");
assert_eq!(p.files, 1);
assert_eq!(
relay.get(&incomplete, 0, &incomplete.fetch).await.0,
StatusCode::NOT_FOUND
);
assert_eq!(
relay
.put(&incomplete, 1, &incomplete.upload, chunk(2))
.await,
StatusCode::NOT_FOUND,
"and cannot be finished"
);
assert_eq!(
relay.get(&complete, 0, &complete.fetch).await.0,
StatusCode::OK
);
let p = relay.store.purge(T0 + 30 * DAY - HOUR).expect("purge");
assert_eq!(p.files, 0, "the complete file within its 30 days");
let p = relay.store.purge(T0 + 30 * DAY + HOUR).expect("purge");
assert_eq!(p.files, 1);
assert_eq!(
relay.get(&complete, 0, &complete.fetch).await.0,
StatusCode::NOT_FOUND
);
relay.now.store(T0 + 31 * DAY, Ordering::SeqCst);
assert_eq!(
relay.create(&complete).await,
StatusCode::CREATED,
"the id is free again"
);
}
#[test]
fn nothing_of_a_file_is_left_after_it_is_deleted_or_purged() {
let dir = tempfile::tempdir().expect("dir");
let path = dir.path().join("relay.db");
let store = Store::open(&path).expect("store");
let count = || -> (i64, i64) {
let conn = rusqlite::Connection::open(&path).expect("open");
let n = |t: &str| {
conn.query_row(&format!("SELECT count(*) FROM {t}"), [], |r| r.get(0))
.expect("count")
};
(n("files"), n("chunks"))
};
let deleted = File::new(2);
let abandoned = File::new(2);
for f in [&deleted, &abandoned] {
store
.create_file(
&CreateFile {
id: f.id,
upload_token_hash: f.upload.hash(),
fetch_token_hash: f.fetch.hash(),
chunks: ChunkCount::new(f.chunks).expect("count"),
},
T0,
)
.expect("create");
store
.put_chunk(&f.id, &f.upload, 0, &chunk(3))
.expect("chunk");
}
assert_eq!(count(), (2, 2));
store
.delete_file(&deleted.id, &deleted.upload)
.expect("delete");
assert_eq!(count(), (1, 1), "the deleted file's chunks went with it");
store.purge(T0 + DAY + HOUR).expect("purge");
assert_eq!(count(), (0, 0), "the abandoned one's too");
}
+10 -2
View File
@@ -242,6 +242,10 @@ fn the_operator_sets_the_relay_wide_caps() {
"7",
"--max-invites",
"9",
"--max-files",
"11",
"--max-file-bytes",
"13",
]
.map(String::from),
)
@@ -250,9 +254,11 @@ fn the_operator_sets_the_relay_wide_caps() {
(
args.limits.total_bytes,
args.limits.mailboxes,
args.limits.invites
args.limits.invites,
args.limits.files,
args.limits.file_bytes
),
(5000, 7, 9)
(5000, 7, 9, 11, 13)
);
assert_eq!(
args.limits.mailbox_blobs, MAILBOX_BLOBS,
@@ -264,6 +270,8 @@ fn the_operator_sets_the_relay_wide_caps() {
vec!["--max-bytes", "-5"],
vec!["--max-mailboxes", "many"],
vec!["--max-invites", "1.5"],
vec!["--max-files", "0"],
vec!["--max-file-bytes", "-1"],
] {
assert!(
parse_args(bad.iter().map(|s| s.to_string())).is_err(),
+29
View File
@@ -147,6 +147,21 @@ fn schema_is_exactly_protocol_section_5() {
"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![
@@ -355,6 +370,20 @@ async fn a_blob_over_256_kib_is_refused() {
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]