[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
+3
View File
@@ -20,6 +20,9 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
# The snapshot's byte fields (already in the tree through the protocol crate).
base64 = "0.22"
# Files (files.md §2.2): ChaCha20-Poly1305 in the aead crate's STREAM construction. Already in the
# tree through openmls_rust_crypto (same version); `stream` adds no dependency.
chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc", "stream"] }
[dev-dependencies]
# The real relay, for the end-to-end test only. `check-deps.sh` checks normal edges: the client
+352
View File
@@ -0,0 +1,352 @@
//! Files (`.agents/features/files.md`): a file is padded to whole chunks and each chunk sealed with
//! ChaCha20-Poly1305 in the STREAM construction (`aead::stream::StreamBE32`, RustCrypto), under a
//! key made for that one file. Every chunk on the wire is [`FILE_CHUNK_BYTES`]. Nothing here is
//! hand-written cryptography: the cipher and the construction are the crates'.
use crate::ClientError;
use chacha20poly1305::aead::stream::{NewStream, StreamBE32, StreamPrimitive};
use chacha20poly1305::{ChaCha20Poly1305, KeyInit};
use serde::{Deserialize, Serialize};
use std::fmt;
use tabellarius_protocol::{FileId, FileKey, Token, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS};
/// The Poly1305 tag on every chunk.
const TAG_BYTES: usize = 16;
/// The plaintext in one chunk: the chunk minus its tag.
pub const FILE_CHUNK_PLAIN: usize = FILE_CHUNK_BYTES - TAG_BYTES;
/// The largest file sent through the relay (Amicitia's plan, full-chat.md §5.5).
pub const MAX_FILE_BYTES: u64 = 100 * 1024 * 1024;
/// The largest thumbnail inside a `file` payload: a JPEG.
pub const MAX_THUMB_BYTES: usize = 32 * 1024;
/// The longest file name, in characters.
pub const MAX_FILE_NAME_CHARS: usize = 255;
/// The longest media type, in bytes.
pub const MAX_MIME_BYTES: usize = 127;
/// How many chunks a file of `size` bytes has, or `None` for an empty file or one over
/// [`MAX_FILE_BYTES`].
pub fn chunks_for(size: u64) -> Option<u32> {
if size == 0 || size > MAX_FILE_BYTES {
return None;
}
let n = size.div_ceil(FILE_CHUNK_PLAIN as u64);
u32::try_from(n).ok().filter(|&n| n <= MAX_FILE_CHUNKS)
}
fn stream(key: &FileKey) -> StreamBE32<ChaCha20Poly1305> {
// The nonce prefix is zeros: a key seals one file only, so a (key, nonce) pair never repeats.
let prefix = Default::default();
StreamBE32::from_aead(ChaCha20Poly1305::new(key.as_bytes().into()), &prefix)
}
/// A file on its way up: what an app keeps in its outbox until the `file` message is delivered,
/// so that an upload interrupted by a crash resumes. `Debug` shows only its size in chunks.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FileUpload {
pub(crate) id: FileId,
pub(crate) upload_token: Token,
pub(crate) fetch_token: Token,
pub(crate) key: FileKey,
pub(crate) size: u64,
}
impl fmt::Debug for FileUpload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FileUpload({} chunks)", self.chunks())
}
}
impl FileUpload {
/// The file's size in bytes.
pub fn size(&self) -> u64 {
self.size
}
/// The file's id on the relay.
pub fn id(&self) -> FileId {
self.id
}
/// How many chunks it has.
pub fn chunks(&self) -> u32 {
// `start_upload` checked the size.
chunks_for(self.size).unwrap_or(0)
}
/// What the recipient needs to fetch and open it (the `file` payload carries it).
pub fn file_ref(&self) -> FileRef {
FileRef {
id: self.id,
fetch_token: self.fetch_token,
key: self.key,
size: self.size,
}
}
/// How many plaintext bytes chunk `index` carries before padding.
fn plain_len(&self, index: u32) -> Option<usize> {
let n = self.chunks();
if index >= n {
return None;
}
let before = u64::from(index) * FILE_CHUNK_PLAIN as u64;
Some((self.size - before).min(FILE_CHUNK_PLAIN as u64) as usize)
}
/// Seals chunk `index`: exactly its share of the file (all of [`FILE_CHUNK_PLAIN`], or the rest
/// for the last one), padded with zeros to the chunk size. The same bytes give the same chunk.
/// Never seal other bytes for an index already sealed: see [`crate::Client::put_chunk`].
pub fn seal(&self, index: u32, plain: &[u8]) -> Result<Vec<u8>, ClientError> {
let want = self.plain_len(index).ok_or(ClientError::BadFile)?;
if plain.len() != want {
return Err(ClientError::BadFile);
}
let mut buffer = Vec::with_capacity(FILE_CHUNK_BYTES);
buffer.extend_from_slice(plain);
buffer.resize(FILE_CHUNK_PLAIN, 0);
let last = index + 1 == self.chunks();
stream(&self.key)
.encrypt_in_place(index, last, b"", &mut buffer)
.map_err(|_| ClientError::BadFile)?;
Ok(buffer)
}
/// The part of `bytes` (the whole file) that chunk `index` carries.
pub fn part<'a>(&self, bytes: &'a [u8], index: u32) -> Option<&'a [u8]> {
let len = self.plain_len(index)?;
let start = index as usize * FILE_CHUNK_PLAIN;
bytes.get(start..start + len)
}
}
/// A file someone sent: where it is on the relay, the token to fetch it, its key and its size.
/// An app keeps it in its encrypted database. `Debug` hides the token and the key.
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FileRef {
pub(crate) id: FileId,
pub(crate) fetch_token: Token,
pub(crate) key: FileKey,
pub(crate) size: u64,
}
impl fmt::Debug for FileRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FileRef({:?}, {} bytes)", self.id, self.size)
}
}
impl FileRef {
pub fn id(&self) -> FileId {
self.id
}
pub fn size(&self) -> u64 {
self.size
}
pub fn chunks(&self) -> u32 {
chunks_for(self.size).unwrap_or(0)
}
/// Opens chunk `index`: its plaintext, without the padding. A chunk that is not
/// [`FILE_CHUNK_BYTES`], does not open at this index (or as the last one when it is), or whose
/// padding is not zeros is [`ClientError::FileDamaged`].
pub fn open(&self, index: u32, chunk: &[u8]) -> Result<Vec<u8>, ClientError> {
let n = self.chunks();
if index >= n || chunk.len() != FILE_CHUNK_BYTES {
return Err(ClientError::FileDamaged);
}
let mut buffer = chunk.to_vec();
let last = index + 1 == n;
stream(&self.key)
.decrypt_in_place(index, last, b"", &mut buffer)
.map_err(|_| ClientError::FileDamaged)?;
let before = u64::from(index) * FILE_CHUNK_PLAIN as u64;
let len = (self.size - before).min(FILE_CHUNK_PLAIN as u64) as usize;
if buffer[len..].iter().any(|&b| b != 0) {
return Err(ClientError::FileDamaged);
}
buffer.truncate(len);
Ok(buffer)
}
}
/// A file name as the wire allows it: 1–255 characters, not blank, no control character, no `/`
/// or `\` (a name is never a path).
pub(crate) fn name_ok(name: &str) -> bool {
!name.trim().is_empty()
&& name.chars().count() <= MAX_FILE_NAME_CHARS
&& !name
.chars()
.any(|c| c.is_control() || c == '/' || c == '\\')
}
/// A media type as the wire allows it: `type/subtype`, 3–127 printable ASCII bytes, one `/` with
/// something on each side, no space.
pub(crate) fn mime_ok(mime: &str) -> bool {
let printable = mime.bytes().all(|b| (0x21..=0x7e).contains(&b));
let mut halves = mime.split('/');
let shape = matches!(
(halves.next(), halves.next(), halves.next()),
(Some(t), Some(s), None) if !t.is_empty() && !s.is_empty()
);
(3..=MAX_MIME_BYTES).contains(&mime.len()) && printable && shape
}
/// A thumbnail as the wire allows it: at most 32 KiB, and it starts like a JPEG.
pub(crate) fn thumb_ok(thumb: &[u8]) -> bool {
thumb.len() <= MAX_THUMB_BYTES && thumb.starts_with(&[0xFF, 0xD8, 0xFF])
}
#[cfg(test)]
mod tests {
use super::*;
fn upload(size: u64, key: u8) -> FileUpload {
FileUpload {
id: FileId::from_bytes([1; 16]),
upload_token: Token::from_bytes([2; 32]),
fetch_token: Token::from_bytes([3; 32]),
key: FileKey::from_bytes([key; 32]),
size,
}
}
fn content(size: usize) -> Vec<u8> {
(0..size).map(|i| (i % 251) as u8).collect()
}
fn seal_all(up: &FileUpload, bytes: &[u8]) -> Vec<Vec<u8>> {
(0..up.chunks())
.map(|i| up.seal(i, up.part(bytes, i).expect("part")).expect("seal"))
.collect()
}
#[test]
fn chunk_counts_round_up_and_stop_at_the_limit() {
assert_eq!(chunks_for(0), None);
assert_eq!(chunks_for(1), Some(1));
assert_eq!(chunks_for(FILE_CHUNK_PLAIN as u64), Some(1));
assert_eq!(chunks_for(FILE_CHUNK_PLAIN as u64 + 1), Some(2));
assert_eq!(chunks_for(MAX_FILE_BYTES), Some(MAX_FILE_CHUNKS));
assert_eq!(chunks_for(MAX_FILE_BYTES + 1), None);
}
#[test]
fn every_chunk_is_the_same_size_and_opens_back_to_the_file() {
for size in [
1,
100,
FILE_CHUNK_PLAIN,
FILE_CHUNK_PLAIN + 1,
3 * FILE_CHUNK_PLAIN - 7,
] {
let up = upload(size as u64, 9);
let bytes = content(size);
let sealed = seal_all(&up, &bytes);
assert!(sealed.iter().all(|c| c.len() == FILE_CHUNK_BYTES), "{size}");
let file = up.file_ref();
let back: Vec<u8> = sealed
.iter()
.enumerate()
.flat_map(|(i, c)| file.open(i as u32, c).expect("open"))
.collect();
assert_eq!(back, bytes, "{size}");
}
}
#[test]
fn a_chunk_tampered_swapped_cut_short_or_from_another_key_does_not_open() {
let size = 2 * FILE_CHUNK_PLAIN + 5;
let up = upload(size as u64, 9);
let sealed = seal_all(&up, &content(size));
let file = up.file_ref();
let mut flipped = sealed[1].clone();
flipped[500] ^= 1;
assert_eq!(file.open(1, &flipped), Err(ClientError::FileDamaged));
// Swapped: chunk 0 at position 1.
assert_eq!(file.open(1, &sealed[0]), Err(ClientError::FileDamaged));
// Cut short: a file that claims to end at chunk 1 cannot open it as its last.
let shorter = FileRef {
size: 2 * FILE_CHUNK_PLAIN as u64,
..file
};
assert_eq!(shorter.open(1, &sealed[1]), Err(ClientError::FileDamaged));
// The true last chunk does not open as a middle one.
let longer = FileRef {
size: 4 * FILE_CHUNK_PLAIN as u64,
..file
};
assert_eq!(longer.open(2, &sealed[2]), Err(ClientError::FileDamaged));
// Another file's key.
let other = upload(size as u64, 8).file_ref();
assert_eq!(other.open(0, &sealed[0]), Err(ClientError::FileDamaged));
// The wrong length, or past the end.
assert_eq!(file.open(0, &sealed[0][1..]), Err(ClientError::FileDamaged));
assert_eq!(file.open(3, &sealed[2]), Err(ClientError::FileDamaged));
assert!(file.open(0, &sealed[0]).is_ok());
}
#[test]
fn the_padding_must_be_zeros_and_the_size_must_match() {
// A sender who claims 10 bytes but sealed 20 non-zero ones: the 10 past the size are not
// padding, so the chunk is refused rather than silently cut.
let honest = upload(20, 9);
let sealed = honest.seal(0, &[7; 20]).expect("seal");
let claims_less = FileRef {
size: 10,
..honest.file_ref()
};
assert_eq!(claims_less.open(0, &sealed), Err(ClientError::FileDamaged));
assert_eq!(honest.file_ref().open(0, &sealed), Ok(vec![7; 20]));
}
#[test]
fn sealing_takes_exactly_each_chunks_share() {
let up = upload(FILE_CHUNK_PLAIN as u64 + 3, 9);
assert_eq!(up.seal(0, &[0; 3]), Err(ClientError::BadFile));
assert_eq!(up.seal(1, &[0; 4]), Err(ClientError::BadFile));
assert_eq!(up.seal(2, &[0; 3]), Err(ClientError::BadFile));
assert!(up.seal(1, &[0; 3]).is_ok());
assert_eq!(up.seal(1, &[1; 3]), up.seal(1, &[1; 3]), "deterministic");
}
#[test]
fn names_types_and_thumbnails_follow_the_wire_rules() {
assert!(name_ok("Menu.jpg"));
assert!(name_ok(&"é".repeat(MAX_FILE_NAME_CHARS)));
for bad in ["", " ", "a/b", "a\\b", "a\u{0}", "a\nb"] {
assert!(!name_ok(bad), "{bad:?}");
}
assert!(!name_ok(&"x".repeat(MAX_FILE_NAME_CHARS + 1)));
assert!(mime_ok("image/jpeg"));
assert!(mime_ok("application/vnd.oasis.opendocument.text"));
for bad in [
"image",
"/jpeg",
"image/",
"a/b/c",
"image/ jpeg",
"a/",
"ö/x",
] {
assert!(!mime_ok(bad), "{bad:?}");
}
assert!(!mime_ok(&format!("a/{}", "b".repeat(MAX_MIME_BYTES))));
assert!(thumb_ok(&[0xFF, 0xD8, 0xFF, 0xE0]));
assert!(!thumb_ok(b"\x89PNG"));
let mut big = vec![0xFF, 0xD8, 0xFF];
big.resize(MAX_THUMB_BYTES + 1, 0);
assert!(!thumb_ok(&big));
}
#[test]
fn debug_shows_no_token_and_no_key() {
let up = upload(5, 9);
let shown = format!("{up:?} {:?}", up.file_ref());
assert!(!shown.contains(&Token::from_bytes([3; 32]).to_wire()));
assert!(!shown.contains(&FileKey::from_bytes([9; 32]).to_wire()));
}
}
+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 {
+7
View File
@@ -22,6 +22,13 @@ pub const SNAPSHOT_VERSION: u32 = 1;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Bytes(pub(crate) Vec<u8>);
/// Shows the length only: these bytes are a group's state or a thumbnail.
impl std::fmt::Debug for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Bytes({})", self.0.len())
}
}
impl Serialize for Bytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
+110 -3
View File
@@ -5,7 +5,8 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, MailboxId, PushEndpoint, Sha256Hash, Token,
blob_hash, CreateFile, CreateInvite, CreateMailbox, FileId, InviteId, MailboxId, PushEndpoint,
Sha256Hash, Token, FILE_CHUNK_BYTES,
};
/// Why the relay said no. Carries nothing of the request.
@@ -13,8 +14,10 @@ use tabellarius_protocol::{
pub enum TransportError {
/// 404: unknown, wrong token, expired, or already claimed.
NotFound,
/// 409: the id is taken.
/// 409: the id is taken, or a file chunk is already there with other bytes.
Conflict,
/// 507: a quota is reached — the relay's, a mailbox's, or a file's (`PROTOCOL.md` §8).
Full,
/// Anything else: the network, a 5xx, a body that did not parse.
Failed,
}
@@ -49,6 +52,28 @@ pub trait Transport {
fetch: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), TransportError>;
/// `POST /v0/files` (`.agents/features/files.md` §2.3).
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError>;
/// `PUT /v0/files/{id}/chunks/{index}` with the upload token.
fn put_chunk(
&self,
id: &FileId,
upload: &Token,
index: u32,
chunk: &[u8],
) -> Result<(), TransportError>;
/// `GET /v0/files/{id}/chunks/{index}` with the fetch token.
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError>;
/// `DELETE /v0/files/{id}` with the upload token.
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError>;
}
/// A file as the relay keeps it: the two hashes, the chunk count, and the chunks by index.
struct StoredFile {
upload: Sha256Hash,
fetch: Sha256Hash,
chunks: u32,
held: HashMap<u32, Vec<u8>>,
}
#[derive(Default)]
@@ -56,6 +81,7 @@ struct Boxes {
mailboxes: HashMap<MailboxId, (Sha256Hash, Sha256Hash, Vec<Vec<u8>>)>,
invites: HashMap<InviteId, (Sha256Hash, Vec<u8>)>,
push: HashMap<MailboxId, PushEndpoint>,
files: HashMap<FileId, StoredFile>,
}
/// An in-memory relay with the same rules as the real one (no expiry: there is no clock here).
@@ -82,7 +108,17 @@ impl MemoryTransport {
self.boxes().push.get(id).map(|e| e.as_str().to_string())
}
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints.
/// How many chunks the relay holds, in all files.
pub fn stored_chunks(&self) -> Vec<Vec<u8>> {
self.boxes()
.files
.values()
.flat_map(|f| f.held.values().cloned())
.collect()
}
/// Every byte the relay holds, for privacy tests: ids, hashes, blobs, KeyPackages, endpoints,
/// files and their chunks.
pub fn everything_stored(&self) -> Vec<u8> {
let b = self.boxes();
let mut out = Vec::new();
@@ -101,6 +137,12 @@ impl MemoryTransport {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(endpoint.as_str().as_bytes());
}
for (id, f) in &b.files {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(f.upload.as_bytes());
out.extend_from_slice(f.fetch.as_bytes());
f.held.values().for_each(|c| out.extend_from_slice(c));
}
out
}
}
@@ -208,4 +250,69 @@ impl Transport for MemoryTransport {
};
Ok(())
}
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> {
let mut b = self.boxes();
if b.files.contains_key(&req.id) {
return Err(TransportError::Conflict);
}
b.files.insert(
req.id,
StoredFile {
upload: req.upload_token_hash,
fetch: req.fetch_token_hash,
chunks: req.chunks.get(),
held: HashMap::new(),
},
);
Ok(())
}
fn put_chunk(
&self,
id: &FileId,
upload: &Token,
index: u32,
chunk: &[u8],
) -> Result<(), TransportError> {
if chunk.len() != FILE_CHUNK_BYTES {
return Err(TransportError::Failed);
}
let mut b = self.boxes();
let f = match b.files.get_mut(id) {
Some(f) if f.upload == upload.hash() => f,
_ => return Err(TransportError::NotFound),
};
if index >= f.chunks {
return Err(TransportError::Full);
}
match f.held.get(&index) {
Some(held) if held.as_slice() == chunk => Ok(()),
Some(_) => Err(TransportError::Conflict),
None => {
f.held.insert(index, chunk.to_vec());
Ok(())
}
}
}
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError> {
match self.boxes().files.get(id) {
Some(f) if f.fetch == fetch.hash() => {
f.held.get(&index).cloned().ok_or(TransportError::NotFound)
}
_ => Err(TransportError::NotFound),
}
}
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> {
let mut b = self.boxes();
match b.files.get(id) {
Some(f) if f.upload == upload.hash() => {
b.files.remove(id);
Ok(())
}
_ => Err(TransportError::NotFound),
}
}
}
+365
View File
@@ -0,0 +1,365 @@
//! Files (`.agents/features/files.md`). No I/O: runs on the Android emulator too.
use tabellarius_client::*;
use tabellarius_protocol::{CreateFile, MailboxId, Sha256Hash, Token};
type C = Client<MemoryTransport>;
fn pair(relay: &MemoryTransport, receipts: bool) -> (C, ContactId, C, ContactId) {
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(receipts);
jan.set_receipts(receipts);
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let Some(Event::Joined {
contact: eva_side, ..
}) = eva.poll().expect("poll").first().cloned()
else {
panic!("no join")
};
jan.poll().expect("poll");
(eva, eva_side, jan, jan_side)
}
fn content(size: usize, seed: u8) -> Vec<u8> {
(0..size)
.map(|i| ((i * 7 + seed as usize) % 253) as u8)
.collect()
}
/// Sends `bytes` from `from` to its contact `to`, and returns the event the other side receives.
fn send_file(from: &mut C, to: ContactId, other: &mut C, bytes: &[u8], name: &str) -> Event {
let up = from.start_upload(bytes.len() as u64).expect("start");
from.upload(&up, bytes).expect("upload");
let out = from
.compose_file(to, &up, name, "application/pdf", None)
.expect("compose");
from.deliver(&out).expect("deliver");
let mut events = other.poll().expect("poll");
assert_eq!(events.len(), 1, "{events:?}");
events.remove(0)
}
#[test]
fn files_of_every_shape_go_both_ways_and_come_back_byte_for_byte() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, false);
let sizes = [
1,
1000,
FILE_CHUNK_PLAIN,
FILE_CHUNK_PLAIN + 1,
3 * FILE_CHUNK_PLAIN - 1,
];
for (i, size) in sizes.into_iter().enumerate() {
let bytes = content(size, i as u8);
let (from, to, other) = if i % 2 == 0 {
(&mut eva, eva_side, &mut jan)
} else {
(&mut jan, jan_side, &mut eva)
};
let Event::File {
file, name, seq, ..
} = send_file(from, to, other, &bytes, "Lístky.pdf")
else {
panic!("not a file")
};
assert_eq!(name, "Lístky.pdf");
assert_eq!(seq, i as u64 / 2 + 1, "a file shares the sender's seq");
assert_eq!(file.size(), size as u64);
assert_eq!(other.download(&file).expect("download"), bytes, "{size}");
}
// Every chunk on the relay is the same size, whatever the file's.
let chunks = relay.stored_chunks();
assert_eq!(chunks.len(), 1 + 1 + 1 + 2 + 3);
assert!(chunks.iter().all(|c| c.len() == FILE_CHUNK_BYTES));
}
#[test]
fn a_file_is_a_message_a_receipt_covers_it_and_a_reaction_or_reply_can_name_it() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay, true);
eva.send(eva_side, "Posílám menu").expect("send");
jan.poll().expect("poll");
let Event::File { seq, .. } = send_file(&mut eva, eva_side, &mut jan, b"%PDF-1.7", "Menu.pdf")
else {
panic!("not a file")
};
assert_eq!(seq, 2);
assert_eq!(eva.sent_seq(eva_side), Some(2));
// Jan's receipt for it reached Eva.
let events = eva.poll().expect("poll");
assert!(
events.contains(&Event::Delivered {
contact: eva_side,
upto: 2
}),
"{events:?}"
);
let the_file = MessageRef {
author: eva.author(),
seq: 2,
};
let out = jan.react(jan_side, the_file, Some("👍")).expect("react");
jan.deliver(&out).expect("deliver");
let out = jan
.compose_text(jan_side, "Díky", Some(the_file))
.expect("reply");
jan.deliver(&out).expect("deliver");
let events = eva.poll().expect("poll");
assert!(events.contains(&Event::Reaction {
contact: eva_side,
to: the_file,
emoji: Some("👍".into())
}));
assert!(events.iter().any(|e| matches!(
e,
Event::Message { reply_to: Some(r), .. } if *r == the_file
)));
}
/// A relay that hands out another chunk than the one asked for, or a changed one.
#[derive(Clone)]
struct Lying {
inner: MemoryTransport,
how: fn(u32, Vec<u8>, &MemoryTransport, &tabellarius_protocol::FileId, &Token) -> Vec<u8>,
}
impl Transport for Lying {
fn create_mailbox(
&self,
r: &tabellarius_protocol::CreateMailbox,
) -> Result<(), TransportError> {
self.inner.create_mailbox(r)
}
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
self.inner.post(id, post, blob)
}
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
self.inner.fetch(id, fetch)
}
fn acknowledge(&self, id: &MailboxId, f: &Token, h: &Sha256Hash) -> Result<(), TransportError> {
self.inner.acknowledge(id, f, h)
}
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
self.inner.create_invite(r)
}
fn rotate_post_token(
&self,
id: &MailboxId,
f: &Token,
h: &Sha256Hash,
) -> Result<(), TransportError> {
self.inner.rotate_post_token(id, f, h)
}
fn claim_invite(
&self,
id: &tabellarius_protocol::InviteId,
s: &Token,
) -> Result<Vec<u8>, TransportError> {
self.inner.claim_invite(id, s)
}
fn set_push(
&self,
id: &MailboxId,
f: &Token,
e: Option<&tabellarius_protocol::PushEndpoint>,
) -> Result<(), TransportError> {
self.inner.set_push(id, f, e)
}
fn create_file(&self, r: &CreateFile) -> Result<(), TransportError> {
self.inner.create_file(r)
}
fn put_chunk(
&self,
id: &tabellarius_protocol::FileId,
u: &Token,
i: u32,
c: &[u8],
) -> Result<(), TransportError> {
self.inner.put_chunk(id, u, i, c)
}
fn get_chunk(
&self,
id: &tabellarius_protocol::FileId,
f: &Token,
i: u32,
) -> Result<Vec<u8>, TransportError> {
let honest = self.inner.get_chunk(id, f, i)?;
Ok((self.how)(i, honest, &self.inner, id, f))
}
fn delete_file(
&self,
id: &tabellarius_protocol::FileId,
u: &Token,
) -> Result<(), TransportError> {
self.inner.delete_file(id, u)
}
}
/// Uploads a three-chunk file from Eva and gives Jan a client whose relay lies in the way `how`.
fn through_a_lying_relay(
how: fn(u32, Vec<u8>, &MemoryTransport, &tabellarius_protocol::FileId, &Token) -> Vec<u8>,
) -> Result<Vec<u8>, ClientError> {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
let bytes = content(2 * FILE_CHUNK_PLAIN + 10, 3);
let Event::File { file, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a.bin") else {
panic!("not a file")
};
let honest = jan.download(&file).expect("honest relay");
assert_eq!(honest, bytes);
let liar = Client::new("Jan", Lying { inner: relay, how }).expect("liar");
liar.download(&file)
}
#[test]
fn a_chunk_tampered_with_swapped_or_repeated_on_the_relay_is_refused() {
// One bit flipped in the middle chunk.
let flipped = through_a_lying_relay(|i, mut c, _, _, _| {
if i == 1 {
c[1000] ^= 0x20;
}
c
});
assert_eq!(flipped, Err(ClientError::FileDamaged));
// Chunks 0 and 1 swapped.
let swapped = through_a_lying_relay(|i, c, inner, id, f| match i {
0 => inner.get_chunk(id, f, 1).expect("chunk"),
1 => inner.get_chunk(id, f, 0).expect("chunk"),
_ => c,
});
assert_eq!(swapped, Err(ClientError::FileDamaged));
// The middle chunk served as the last one too (a file cut short and padded out).
let repeated = through_a_lying_relay(|i, c, inner, id, f| {
if i == 2 {
inner.get_chunk(id, f, 1).expect("chunk")
} else {
c
}
});
assert_eq!(repeated, Err(ClientError::FileDamaged));
// A chunk one byte short.
let short = through_a_lying_relay(|_, mut c, _, _, _| {
c.pop();
c
});
assert_eq!(short, Err(ClientError::FileDamaged));
}
#[test]
fn a_chunk_from_another_file_does_not_open() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
let bytes = content(100, 1);
let Event::File { file: fa, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a") else {
panic!("not a file")
};
let chunk_a = relay.stored_chunks().remove(0);
assert!(fa.open(0, &chunk_a).is_ok());
// The same bytes sent again: another key, so a's chunk does not open as b's.
let Event::File { file: fb, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "b") else {
panic!("not a file")
};
assert_eq!(fb.open(0, &chunk_a), Err(ClientError::FileDamaged));
assert_eq!(jan.download(&fb).expect("b"), bytes);
}
#[test]
fn a_missing_chunk_is_not_found_and_the_download_works_once_it_is_up() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
let bytes = content(FILE_CHUNK_PLAIN + 5, 9);
let up = eva.start_upload(bytes.len() as u64).expect("start");
eva.create_file(&up).expect("create");
eva.put_chunk(&up, 0, up.part(&bytes, 0).expect("part"))
.expect("chunk 0");
// The message overtakes the upload.
let out = eva
.compose_file(eva_side, &up, "late.bin", "application/octet-stream", None)
.expect("compose");
eva.deliver(&out).expect("deliver");
let Some(Event::File { file, .. }) = jan.poll().expect("poll").first().cloned() else {
panic!("no file")
};
assert_eq!(
jan.download(&file),
Err(ClientError::Transport(TransportError::NotFound))
);
assert!(jan.get_chunk(&file, 0).is_ok(), "the first chunk is there");
eva.put_chunk(&up, 1, up.part(&bytes, 1).expect("part"))
.expect("chunk 1");
assert_eq!(jan.download(&file).expect("download"), bytes);
assert_eq!(
jan.get_chunk(&file, 2),
Err(ClientError::BadFile),
"past the end"
);
}
#[test]
fn an_upload_resumes_after_a_crash_from_its_saved_form() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
let bytes = content(3 * FILE_CHUNK_PLAIN, 4);
let up = eva.start_upload(bytes.len() as u64).expect("start");
let saved = serde_json::to_string(&up).expect("save");
eva.create_file(&up).expect("create");
eva.put_chunk(&up, 0, up.part(&bytes, 0).expect("part"))
.expect("chunk 0");
// Crash. The outbox gives the upload back; it starts again from the beginning.
let again: FileUpload = serde_json::from_str(&saved).expect("restore");
assert_eq!(again, up);
eva.upload(&again, &bytes)
.expect("create and chunk 0 again are accepted");
let out = eva
.compose_file(eva_side, &again, "a.bin", "application/octet-stream", None)
.expect("compose");
eva.deliver(&out).expect("deliver");
let Some(Event::File { file, .. }) = jan.poll().expect("poll").first().cloned() else {
panic!("no file")
};
assert_eq!(jan.download(&file).expect("download"), bytes);
assert_eq!(relay.stored_chunks().len(), 3);
// What is saved holds no plaintext, and its Debug shows no secret.
assert!(!saved.contains("a.bin"));
assert_eq!(format!("{up:?}"), "FileUpload(3 chunks)");
}
#[test]
fn the_wrong_bytes_for_a_file_are_refused_before_anything_is_sent() {
let relay = MemoryTransport::default();
let (eva, _, _jan, _) = pair(&relay, false);
let up = eva.start_upload(10).expect("start");
assert_eq!(eva.upload(&up, &[1; 9]), Err(ClientError::BadFile));
assert_eq!(eva.put_chunk(&up, 0, &[1; 11]), Err(ClientError::BadFile));
assert_eq!(eva.put_chunk(&up, 1, &[1; 10]), Err(ClientError::BadFile));
assert_eq!(relay.stored_chunks().len(), 0);
assert_eq!(eva.start_upload(0).err(), Some(ClientError::BadFile));
assert_eq!(
eva.start_upload(MAX_FILE_BYTES + 1).err(),
Some(ClientError::BadFile)
);
assert!(eva.start_upload(MAX_FILE_BYTES).is_ok());
}
#[test]
fn a_stranger_with_the_file_id_cannot_change_or_delete_it() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay, false);
let bytes = content(50, 2);
let Event::File { file, .. } = send_file(&mut eva, eva_side, &mut jan, &bytes, "a") else {
panic!()
};
let stranger = Token::from_bytes([7; 32]);
assert_eq!(
relay.put_chunk(&file.id(), &stranger, 0, &vec![0; FILE_CHUNK_BYTES]),
Err(TransportError::NotFound)
);
assert_eq!(
relay.delete_file(&file.id(), &stranger),
Err(TransportError::NotFound)
);
assert_eq!(jan.download(&file).expect("still there"), bytes);
}
+106
View File
@@ -51,6 +51,7 @@ impl Http {
"200" | "201" | "204" => Ok(resp[split + 4..].to_vec()),
"404" => Err(TransportError::NotFound),
"409" => Err(TransportError::Conflict),
"507" => Err(TransportError::Full),
_ => Err(TransportError::Failed),
}
}
@@ -148,6 +149,31 @@ impl Transport for Http {
}
.map(|_| ())
}
fn create_file(&self, req: &CreateFile) -> Result<(), TransportError> {
let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?;
self.call("POST", "/v0/files", None, &body, true)
.map(|_| ())
}
fn put_chunk(
&self,
id: &FileId,
upload: &Token,
index: u32,
chunk: &[u8],
) -> Result<(), TransportError> {
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
self.call("PUT", &path, Some(upload), chunk, false)
.map(|_| ())
}
fn get_chunk(&self, id: &FileId, fetch: &Token, index: u32) -> Result<Vec<u8>, TransportError> {
let path = format!("/v0/files/{}/chunks/{index}", id.to_wire());
self.call("GET", &path, Some(fetch), &[], false)
}
fn delete_file(&self, id: &FileId, upload: &Token) -> Result<(), TransportError> {
let path = format!("/v0/files/{}", id.to_wire());
self.call("DELETE", &path, Some(upload), &[], false)
.map(|_| ())
}
}
/// Starts the real relay on 127.0.0.1:<free port> with its database in `db`.
@@ -279,6 +305,86 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
assert!(waiting.len() >= 4096, "the relay stored something");
}
/// Files (`.agents/features/files.md` §5): a photo through the real relay. Its name, type,
/// thumbnail and content are in no byte of the relay's database, before or after the download, and
/// every chunk the relay holds is the same size.
#[test]
fn a_file_goes_through_the_real_relay_which_never_sees_its_name_type_or_content() {
let dir = tempfile::tempdir().expect("tempdir");
let db = dir.path().join("relay.db");
let relay = Http(start_relay(&db));
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
eva.set_receipts(false);
jan.set_receipts(false);
let invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
jan.poll().expect("poll");
// Two chunks and a bit, every one of them full of canaries, so any plaintext would be found.
let line = b"FILE-CONTENT-CANARY-7f3a ";
let content: Vec<u8> = line
.iter()
.copied()
.cycle()
.take(2 * FILE_CHUNK_PLAIN + 999)
.collect();
let name = "FILENAME-CANARY-Menu.jpg";
let mime = "image/x-mime-canary";
let mut thumb = vec![0xFF, 0xD8, 0xFF, 0xE0];
thumb.extend_from_slice(b"THUMBNAIL-CANARY");
let up = jan.start_upload(content.len() as u64).expect("start");
jan.upload(&up, &content).expect("upload");
let out = jan
.compose_file(jan_side, &up, name, mime, Some(&thumb))
.expect("compose");
jan.deliver(&out).expect("deliver");
let waiting = std::fs::read(&db).expect("db");
let events = eva.poll().expect("poll");
let Some(Event::File {
file,
name: got_name,
mime: got_mime,
thumb: got_thumb,
seq,
..
}) = events.first().cloned()
else {
panic!("no file: {events:?}");
};
assert_eq!((got_name.as_str(), got_mime.as_str(), seq), (name, mime, 1));
assert_eq!(got_thumb.as_deref(), Some(thumb.as_slice()));
assert_eq!(file.chunks(), 3);
assert_eq!(eva.download(&file).expect("download"), content);
let after = std::fs::read(&db).expect("db");
for snapshot in [&waiting, &after] {
for (what, needle) in [
("file content", &line[..]),
("file name", name.as_bytes()),
("media type", mime.as_bytes()),
("thumbnail", b"THUMBNAIL-CANARY".as_slice()),
] {
assert!(
!contains(snapshot, needle),
"{what} is readable in the relay's database"
);
}
}
assert!(
waiting.len() >= 3 * FILE_CHUNK_BYTES,
"the three chunks were stored"
);
// The sender deletes it early; the relay answers 404 from then on.
jan.delete_file(&up).expect("delete");
assert_eq!(
eva.get_chunk(&file, 0),
Err(ClientError::Transport(TransportError::NotFound))
);
}
// Wake-up (`.agents/features/wake-up.md` §2.4): an endpoint per mailbox, set and cleared through the
// real relay with the mailbox's fetch token.
#[test]
+27
View File
@@ -325,6 +325,33 @@ impl Transport for Flaky {
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
self.inner.create_invite(r)
}
fn create_file(&self, r: &tabellarius_protocol::CreateFile) -> Result<(), TransportError> {
self.inner.create_file(r)
}
fn put_chunk(
&self,
id: &tabellarius_protocol::FileId,
upload: &tabellarius_protocol::Token,
index: u32,
chunk: &[u8],
) -> Result<(), TransportError> {
self.inner.put_chunk(id, upload, index, chunk)
}
fn get_chunk(
&self,
id: &tabellarius_protocol::FileId,
fetch: &tabellarius_protocol::Token,
index: u32,
) -> Result<Vec<u8>, TransportError> {
self.inner.get_chunk(id, fetch, index)
}
fn delete_file(
&self,
id: &tabellarius_protocol::FileId,
upload: &tabellarius_protocol::Token,
) -> Result<(), TransportError> {
self.inner.delete_file(id, upload)
}
fn set_push(
&self,
id: &tabellarius_protocol::MailboxId,
+64 -1
View File
@@ -29,6 +29,13 @@ pub const MAX_PUSH_ENDPOINT_BYTES: usize = 1000;
pub const WAKE_BODY: &[u8] = b"wake";
/// A mailbox is woken at most once in this many seconds.
pub const WAKE_EVERY_SECS: i64 = 60;
/// Every file chunk on the wire is exactly this many bytes, the last one too (250 KiB; G41,
/// `.agents/features/files.md` §2.1).
pub const FILE_CHUNK_BYTES: usize = 256_000;
/// The most chunks one file may have: 100 MiB of plaintext at 255 984 bytes a chunk.
pub const MAX_FILE_CHUNKS: u32 = 410;
/// A file that is not complete this long after it was created is purged (`files.md` §2.3).
pub const INCOMPLETE_FILE_TTL_SECS: i64 = 24 * 3600;
/// Why a value from the wire was refused. Carries no part of the input.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -148,6 +155,11 @@ fixed_bytes!(
InviteId,
16
);
fixed_bytes!(
/// A file on the relay: 16 random bytes made by its uploader (`PROTOCOL.md` §8, files).
FileId,
16
);
fixed_bytes!(
/// A message's author: the 16 random bytes in their MLS credential, made on their device, never
/// a name. With the author's `seq` it names a message (`PROTOCOL.md` §4, reactions and replies).
@@ -166,6 +178,20 @@ fixed_bytes!(
32
);
fixed_bytes!(
/// A file's key: 32 random bytes made for one file, travelling only inside MLS (`PROTOCOL.md`
/// §4, `file`). The relay never sees it.
FileKey,
32
);
// A file key is a secret: never printed.
impl fmt::Debug for FileKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("FileKey(..)")
}
}
impl Token {
/// The hash the relay stores and compares against.
pub fn hash(&self) -> Sha256Hash {
@@ -199,7 +225,7 @@ macro_rules! debug_as_wire {
}
)*};
}
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author);
debug_as_wire!(MailboxId, InviteId, Sha256Hash, Author, FileId);
/// The SHA-256 of a blob: how its recipient acknowledges it.
pub fn blob_hash(blob: &[u8]) -> Sha256Hash {
@@ -333,6 +359,43 @@ pub struct VersionInfo {
pub relay: String,
}
/// How many chunks a file has: 1 to [`MAX_FILE_CHUNKS`]; anything else does not parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct ChunkCount(u32);
impl ChunkCount {
pub fn new(n: u32) -> Result<Self, ParseError> {
if (1..=MAX_FILE_CHUNKS).contains(&n) {
Ok(Self(n))
} else {
Err(ParseError::TooLarge {
max: MAX_FILE_CHUNKS as usize,
})
}
}
pub fn get(&self) -> u32 {
self.0
}
}
impl<'de> Deserialize<'de> for ChunkCount {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
ChunkCount::new(u32::deserialize(d)?).map_err(serde::de::Error::custom)
}
}
/// `POST /v0/files`: the uploader sends hashes of the two tokens it made, and the chunk count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CreateFile {
pub id: FileId,
pub upload_token_hash: Sha256Hash,
pub fetch_token_hash: Sha256Hash,
pub chunks: ChunkCount,
}
/// Rounds unix seconds down to the hour, as the relay stores arrival times.
pub fn hour_of(unix_secs: i64) -> i64 {
unix_secs.div_euclid(3600)
+40
View File
@@ -289,3 +289,43 @@ fn an_author_is_16_bytes_in_22_canonical_characters_and_prints_as_its_wire() {
);
assert_eq!(format!("{author:?}"), format!("Author({wire})"));
}
// Files (`.agents/features/files.md` §2.3).
#[test]
fn create_file_takes_one_to_410_chunks_and_no_other_field() {
let body = |chunks: i64, extra: &str| {
format!(
r#"{{"id":"{}","uploadTokenHash":"{}","fetchTokenHash":"{}","chunks":{chunks}{extra}}}"#,
FileId::from_bytes([1; 16]).to_wire(),
Token::from_bytes([2; 32]).hash().to_wire(),
Token::from_bytes([3; 32]).hash().to_wire(),
)
};
for ok in [1, 2, i64::from(MAX_FILE_CHUNKS)] {
let req: CreateFile = serde_json::from_str(&body(ok, "")).expect("parses");
assert_eq!(i64::from(req.chunks.get()), ok);
}
for bad in [0, -1, i64::from(MAX_FILE_CHUNKS) + 1, 1 << 40] {
assert!(
serde_json::from_str::<CreateFile>(&body(bad, "")).is_err(),
"{bad}"
);
}
assert!(serde_json::from_str::<CreateFile>(&body(1, r#","name":"a.jpg""#)).is_err());
assert!(serde_json::from_str::<CreateFile>(&body(1, r#","size":5"#)).is_err());
assert!(ChunkCount::new(0).is_err() && ChunkCount::new(MAX_FILE_CHUNKS + 1).is_err());
}
#[test]
fn a_file_key_is_never_printed_and_a_file_id_prints_as_its_wire() {
let key = FileKey::from_bytes([5; 32]);
assert_eq!(format!("{key:?}"), "FileKey(..)");
assert_eq!(FileKey::parse(&key.to_wire()), Ok(key));
let id = FileId::from_bytes([6; 16]);
assert_eq!(format!("{id:?}"), format!("FileId({})", id.to_wire()));
assert!(FileId::parse(&id.to_wire()[..21]).is_err());
// 410 chunks of 255 984 plaintext bytes hold 100 MiB; 409 do not.
let plain = FILE_CHUNK_BYTES as u64 - 16;
assert!(u64::from(MAX_FILE_CHUNKS) * plain >= 100 * 1024 * 1024);
assert!(u64::from(MAX_FILE_CHUNKS - 1) * plain < 100 * 1024 * 1024);
}
+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]