[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
+320 -10
View File
@@ -19,6 +19,13 @@
pub mod transport;
mod files;
pub use files::{
chunks_for, FileRef, FileUpload, FILE_CHUNK_PLAIN, MAX_FILE_BYTES, MAX_FILE_NAME_CHARS,
MAX_MIME_BYTES, MAX_THUMB_BYTES,
};
pub use tabellarius_protocol::{FileId, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS};
mod snapshot;
pub use snapshot::SNAPSHOT_VERSION;
@@ -32,8 +39,8 @@ use sha2::Sha256;
use snapshot::Bytes;
use std::fmt;
use tabellarius_protocol::{
blob_hash, Author, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId,
PushEndpoint, Sha256Hash, Token, MAX_BLOB_BYTES,
blob_hash, Author, ChunkCount, CreateFile, CreateInvite, CreateMailbox, FileKey, InviteId,
KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token, MAX_BLOB_BYTES,
};
pub use transport::{MemoryTransport, Transport, TransportError};
@@ -53,7 +60,7 @@ pub const MAX_OPTION_CHARS: usize = 100;
/// The longest poll question, in characters.
pub const MAX_QUESTION_CHARS: usize = 300;
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
const KNOWN_KINDS: [&str; 8] = [
const KNOWN_KINDS: [&str; 9] = [
"hello",
"text",
"receipt",
@@ -62,6 +69,7 @@ const KNOWN_KINDS: [&str; 8] = [
"poll",
"vote",
"pollClose",
"file",
];
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
@@ -88,6 +96,13 @@ pub enum ClientError {
BadPoll,
/// A vote or a close for a poll that is already closed.
PollClosed,
/// A file that cannot be sent: empty or over [`MAX_FILE_BYTES`], a name or type outside the
/// wire's rules, a thumbnail that is not a small JPEG, or a chunk index or length that does not
/// fit the file.
BadFile,
/// A received file's chunk that does not open: tampered with, swapped, cut short, of the
/// wrong size, or with padding that is not zeros.
FileDamaged,
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
State,
}
@@ -169,6 +184,17 @@ pub enum Event {
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// A file (a message: `seq` names it, like a text's). `file` fetches and opens it
/// ([`Client::get_chunk`], [`Client::download`]); `thumb` is a small JPEG, checked to start
/// like one, or `None`.
File {
contact: ContactId,
seq: u64,
file: FileRef,
name: String,
mime: String,
thumb: Option<Vec<u8>>,
},
/// A message of a kind this client does not know (a newer app's). Show that something arrived
/// that needs an update; its `seq` counts like a text's.
Unsupported { contact: ContactId, seq: u64 },
@@ -336,6 +362,19 @@ enum Payload {
poll: MessageRef,
ballots: Vec<Ballot>,
},
/// A file on the relay: a message, sharing the sender's `seq` (`.agents/features/files.md`).
#[serde(rename_all = "camelCase")]
File {
seq: u64,
file: tabellarius_protocol::FileId,
fetch_token: Token,
key: FileKey,
name: String,
mime: String,
size: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
thumb: Option<Bytes>,
},
/// The receiver has saved our texts up to `upto`.
Receipt { upto: u64 },
/// A new post token for the mailbox the receiver already knows (unblock).
@@ -790,6 +829,132 @@ impl<T: Transport> Client<T> {
Ok(Outgoing::post(to, post, blob))
}
/// A file to send, staged (`.agents/features/files.md` §2.6): a new id, an upload token, a
/// fetch token and a key, all random. No network: keep it in the outbox, then
/// [`Client::upload`] (or [`Client::create_file`] and [`Client::put_chunk`]), then
/// [`Client::compose_file`].
pub fn start_upload(&self, size: u64) -> Result<FileUpload, ClientError> {
files::chunks_for(size).ok_or(ClientError::BadFile)?;
Ok(FileUpload {
id: tabellarius_protocol::FileId::from_bytes(self.random()?),
upload_token: Token::from_bytes(self.random()?),
fetch_token: Token::from_bytes(self.random()?),
key: FileKey::from_bytes(self.random()?),
size,
})
}
/// Creates the file on the relay. Again after a crash, the relay's 409 means it is there
/// already: the id is 16 random bytes that only this upload has.
pub fn create_file(&self, up: &FileUpload) -> Result<(), ClientError> {
let chunks = ChunkCount::new(up.chunks()).map_err(|_| ClientError::BadFile)?;
let req = CreateFile {
id: up.id,
upload_token_hash: up.upload_token.hash(),
fetch_token_hash: up.fetch_token.hash(),
chunks,
};
match self.transport.create_file(&req) {
Ok(()) | Err(TransportError::Conflict) => Ok(()),
Err(e) => Err(ClientError::Transport(e)),
}
}
/// Seals and puts chunk `index` ([`FileUpload::seal`]). Again with the same bytes, the relay
/// accepts it: an upload resumes chunk by chunk.
///
/// **The bytes must be the same on every try.** A chunk is sealed under the file's one key at
/// a nonce fixed by its index, so two different plaintexts for one index would reuse a nonce
/// (the relay refuses the second with 409, but it has seen both). An app keeps the file's bytes
/// with the [`FileUpload`] until the upload is done, rather than reading the source again.
pub fn put_chunk(&self, up: &FileUpload, index: u32, plain: &[u8]) -> Result<(), ClientError> {
let chunk = up.seal(index, plain)?;
Ok(self
.transport
.put_chunk(&up.id, &up.upload_token, index, &chunk)?)
}
/// Creates the file and puts every chunk of `bytes`, the whole file.
pub fn upload(&self, up: &FileUpload, bytes: &[u8]) -> Result<(), ClientError> {
if bytes.len() as u64 != up.size {
return Err(ClientError::BadFile);
}
self.create_file(up)?;
for index in 0..up.chunks() {
let part = up.part(bytes, index).ok_or(ClientError::BadFile)?;
self.put_chunk(up, index, part)?;
}
Ok(())
}
/// The sender deletes the file from the relay before its 30 days are up.
pub fn delete_file(&self, up: &FileUpload) -> Result<(), ClientError> {
Ok(self.transport.delete_file(&up.id, &up.upload_token)?)
}
/// A `file` message for a contact: a message, named by [`Client::sent_seq`] right after. Its
/// name, type and thumbnail are checked ([`ClientError::BadFile`]). Deliver it after the upload.
pub fn compose_file(
&mut self,
contact: ContactId,
up: &FileUpload,
name: &str,
mime: &str,
thumb: Option<&[u8]>,
) -> Result<Outgoing, ClientError> {
let thumb_bad = thumb.is_some_and(|t| !files::thumb_ok(t));
if files::chunks_for(up.size).is_none()
|| !files::name_ok(name)
|| !files::mime_ok(mime)
|| thumb_bad
{
return Err(ClientError::BadFile);
}
let index = self.index_of(contact)?;
let c = &mut self.contacts[index];
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
let seq = c.sent_seq + 1;
let blob = Self::seal(
&self.provider,
&self.signer,
&mut c.group,
&Payload::File {
seq,
file: up.id,
fetch_token: up.fetch_token,
key: up.key,
name: name.to_string(),
mime: mime.to_string(),
size: up.size,
thumb: thumb.map(|t| Bytes(t.to_vec())),
},
)?;
c.sent_seq = seq;
Ok(Outgoing::post(to, post, blob))
}
/// Fetches and opens chunk `index` of a received file: its plaintext, without padding. A chunk
/// not on the relay (yet) is `Transport(NotFound)`; one that does not open is
/// [`ClientError::FileDamaged`].
pub fn get_chunk(&self, file: &FileRef, index: u32) -> Result<Vec<u8>, ClientError> {
if index >= file.chunks() {
return Err(ClientError::BadFile);
}
let chunk = self
.transport
.get_chunk(&file.id, &file.fetch_token, index)?;
file.open(index, &chunk)
}
/// Fetches and opens every chunk: the whole file, exactly `size` bytes.
pub fn download(&self, file: &FileRef) -> Result<Vec<u8>, ClientError> {
let mut out = Vec::with_capacity(file.size as usize);
for index in 0..file.chunks() {
out.extend(self.get_chunk(file, index)?);
}
Ok(out)
}
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
pub fn author(&self) -> Author {
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
@@ -1243,6 +1408,45 @@ impl<T: Transport> Client<T> {
} => self.receive_poll(index, seq, question, options, multiple),
Payload::Vote { poll, choices } => self.receive_vote(index, poll, choices),
Payload::PollClose { poll, ballots } => self.receive_close(index, poll, ballots),
Payload::File {
seq,
file,
fetch_token,
key,
name,
mime,
size,
thumb,
} => {
let c = &mut self.contacts[index];
if c.name.is_none() {
return Err(ClientError::Mls);
}
if c.blocked
|| seq == 0
|| files::chunks_for(size).is_none()
|| !files::name_ok(&name)
|| !files::mime_ok(&mime)
{
return Ok(None);
}
c.received_seq = c.received_seq.max(seq);
// The file is real even when its thumbnail is not: the file stays, the picture goes.
let thumb = thumb.map(|t| t.0).filter(|t| files::thumb_ok(t));
Ok(Some(Event::File {
contact: c.id,
seq,
file: FileRef {
id: file,
fetch_token,
key,
size,
},
name,
mime,
thumb,
}))
}
Payload::Receipt { upto } => {
let c = &self.contacts[index];
if !self.receipts || c.name.is_none() || c.blocked {
@@ -1582,14 +1786,15 @@ mod tests {
#[test]
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
assert!(matches!(
parse_payload(br#"{"kind":"file","seq":4,"name":"?"}"#),
parse_payload(br#"{"kind":"sticker","seq":4,"name":"?"}"#),
Ok(Parsed::Unknown { seq: 4 })
));
for bad in [
&br#"{"kind":"file","name":"?"}"#[..],
br#"{"kind":"file","seq":0}"#,
br#"{"kind":"file","seq":-1}"#,
br#"{"kind":"file","seq":"4"}"#,
&br#"{"kind":"sticker","name":"?"}"#[..],
br#"{"kind":"sticker","seq":0}"#,
br#"{"kind":"sticker","seq":-1}"#,
br#"{"kind":"sticker","seq":"4"}"#,
br#"{"kind":"file","seq":4,"name":"?"}"#,
br#"{"kind":"poll","seq":4,"question":"?"}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[256]}"#,
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[-1]}"#,
@@ -1705,9 +1910,12 @@ mod tests {
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
let (mut eva, mut jan) = paired();
eva.set_receipts(true);
let out = seal_raw(&mut jan, r#"{"kind":"file","seq":1,"name":"Pivo.jpg"}"#);
let out = seal_raw(
&mut jan,
r#"{"kind":"sticker","seq":1,"mime":"image/webp"}"#,
);
jan.deliver(&out).expect("deliver");
let out = seal_raw(&mut jan, r#"{"kind":"file","name":"no seq"}"#);
let out = seal_raw(&mut jan, r#"{"kind":"sticker","mime":"no seq"}"#);
jan.deliver(&out).expect("deliver");
let got = eva.receive().expect("receive");
assert_eq!(
@@ -1971,6 +2179,107 @@ mod tests {
assert!(eva.contacts[0].polls[0].ballots.is_empty());
}
// Files (`.agents/features/files.md` §2.5).
fn their_file(seq: u64, name: &str, mime: &str, size: u64, thumb: Option<Vec<u8>>) -> Payload {
Payload::File {
seq,
file: tabellarius_protocol::FileId::from_bytes([4; 16]),
fetch_token: Token::from_bytes([5; 32]),
key: FileKey::from_bytes([6; 32]),
name: name.into(),
mime: mime.into(),
size,
thumb: thumb.map(Bytes),
}
}
const JPEG: [u8; 4] = [0xFF, 0xD8, 0xFF, 0xE0];
#[test]
fn a_malformed_file_is_refused_when_sending_and_dropped_when_received() {
let (mut eva, _jan) = paired();
let id = eva.contacts[0].id;
let up = eva.start_upload(10).expect("upload");
let long = "x".repeat(MAX_FILE_NAME_CHARS + 1);
let bad: [(&str, &str, u64); 7] = [
("", "image/jpeg", 10),
("a/b.jpg", "image/jpeg", 10),
("a\nb", "image/jpeg", 10),
(&long, "image/jpeg", 10),
("a.jpg", "jpeg", 10),
("a.jpg", "image/jpeg", 0),
("a.jpg", "image/jpeg", MAX_FILE_BYTES + 1),
];
for (name, mime, size) in bad {
if size == 10 {
assert_eq!(
eva.compose_file(id, &up, name, mime, None).err(),
Some(ClientError::BadFile),
"{name:?} {mime:?}"
);
} else {
assert_eq!(eva.start_upload(size).err(), Some(ClientError::BadFile));
}
assert_eq!(
eva.receive_payload(0, their_file(1, name, mime, size, None)),
Ok(None),
"{name:?} {mime:?} {size}"
);
}
assert_eq!(
eva.receive_payload(0, their_file(0, "a.jpg", "image/jpeg", 10, None)),
Ok(None),
"seq 0"
);
assert_eq!(
eva.contacts[0].received_seq, 0,
"a dropped file does not count"
);
assert_eq!(
eva.compose_file(id, &up, "a.jpg", "image/jpeg", Some(b"\x89PNG"))
.err(),
Some(ClientError::BadFile),
"a thumbnail that is not a JPEG"
);
assert_eq!(eva.sent_seq(id), Some(0), "nothing was sent");
assert!(eva
.compose_file(id, &up, "a.jpg", "image/jpeg", Some(&JPEG))
.is_ok());
assert_eq!(eva.sent_seq(id), Some(1));
}
#[test]
fn a_bad_thumbnail_is_dropped_and_the_file_kept() {
let (mut eva, _jan) = paired();
let mut big = JPEG.to_vec();
big.resize(MAX_THUMB_BYTES + 1, 0);
for (seq, thumb) in [(1, b"\x89PNG".to_vec()), (2, big)] {
let got =
eva.receive_payload(0, their_file(seq, "a.jpg", "image/jpeg", 10, Some(thumb)));
assert!(
matches!(&got, Ok(Some(Event::File { thumb: None, seq: s, .. })) if *s == seq),
"{got:?}"
);
}
let got = eva.receive_payload(
0,
their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())),
);
assert!(matches!(&got, Ok(Some(Event::File { thumb: Some(t), .. })) if t == &JPEG));
assert_eq!(eva.contacts[0].received_seq, 3);
}
#[test]
fn a_blocked_contacts_file_is_dropped() {
let (mut eva, _jan) = paired();
eva.contacts[0].blocked = true;
assert_eq!(
eva.receive_payload(0, their_file(1, "a.jpg", "image/jpeg", 10, None)),
Ok(None)
);
assert_eq!(eva.contacts[0].received_seq, 0);
}
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
/// *Unsupported* at a client of the same version.
#[test]
@@ -2012,6 +2321,7 @@ mod tests {
choices: vec![1],
}],
},
their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())),
];
assert_eq!(all.len(), KNOWN_KINDS.len());
for payload in all {