[relay] Files: same-size encrypted chunks through the relay, a file payload inside MLS (Amicitia F29) #23

Closed
mnovak wants to merge 0 commits from feature/files into main
Owner

Amicitia F29, step 4 of its full-chat plan: photos, videos and files, end-to-end encrypted. A protocol change: the relay stores two new tables (docs/PROTOCOL.md §5) behind four new routes (§8). Analysis: .agents/features/files.md.

What changes

  • Relay — the files route. POST /v0/files {id, uploadTokenHash, fetchTokenHash, chunks}; PUT /v0/files/{id}/chunks/{index} (exactly 256 000 bytes, upload token); GET …/chunks/{index} (fetch token); DELETE /v0/files/{id} (upload token). Tables files (id, upload_hash, fetch_hash, chunks, uploaded_hour) and chunks (file_id, idx, ciphertext): no size column (every chunk is the same size), no name, type, sender, recipient, and no fetch count.
  • Quotas (507). Per file: its declared chunks, at most 410 (100 MiB). Relay-wide: --max-files (10 000) and --max-file-bytes (4 GiB), each file counted at full size from creation so an upload is never cut off; apart from the blob quota.
  • Purge. Files go after 30 days, or after 24 hours if not all chunks arrived; their chunks with them.
  • A chunk never changes: the same bytes again are accepted (an upload resumed), other bytes are 409.
  • Client — chunked encryption. A fresh 32-byte key per file; the file padded with zeros to whole chunks of 255 984 bytes; each chunk sealed with ChaCha20-Poly1305 in STREAM (aead::stream::StreamBE32: index counter + last-chunk flag). So every chunk is 256 000 bytes on the wire, and a chunk tampered with, swapped, repeated, cut, or from another file does not open (ClientError::FileDamaged). chacha20poly1305 0.10 was already in the tree through openmls_rust_crypto; its stream feature adds no crate (Cargo.lock: one new edge).
  • Client — the file payload in MLS: seq (shared with text/poll), file, fetchToken, key, name, mime, size, thumb? (JPEG ≤ 32 KiB). The key, name, type, exact size and thumbnail travel only here. API: start_upload, create_file, put_chunk, upload, delete_file, compose_file, get_chunk, download, FileUpload, FileRef, Event::File; Transport gains four methods; TransportError::Full (507).
  • Found on the way, fixed: axum's own 413 for a body over a route's limit carried a text body, on the blob and JSON routes too, against §8's a refusal has no body. Every route now answers a bare 413 (test in relay.rs).

Tests (cargo test --workspace --locked, quoted per crate)

crate test binary passed failed
tabellarius-client unit (lib, incl. files module) 24 0
block / files / pairing / polls / push / reactions / real_relay / state 7 / 8 / 8 / 4 / 3 / 5 / 3 / 14 0
client total 76 0
tabellarius-protocol wire 20 0
tabellarius-relay unit / files / quotas / relay / wake 2 / 8 / 8 / 19 / 9 0
relay total 46 0

New in this PR: client unit +10 (7 in files, 3 in lib), client/tests/files.rs 8, real_relay.rs +1 (the canary), protocol/tests/wire.rs +2, relay/tests/files.rs 8; relay.rs and quotas.rs extended (schema, bare 413, flags).

Also: cargo fmt --all --check clean; cargo clippy --workspace --all-targets --locked -- -D warnings clean; scripts/check-deps.sh ok (relay does not depend on client; protocol on nothing); scripts/test-hooks.sh 7 passed, 0 failed.

Not verified

  • On a phone: nothing here runs on one by itself; Amicitia's PR says what it ran.
  • The NixOS module's relay with the new flags (--max-files, --max-file-bytes) is not run (as F23's VM test).

The adversarial review is posted in this PR.

Amicitia F29, step 4 of its full-chat plan: photos, videos and files, end-to-end encrypted. **A protocol change**: the relay stores two new tables (`docs/PROTOCOL.md` §5) behind four new routes (§8). Analysis: `.agents/features/files.md`. ## What changes - **Relay — the `files` route.** `POST /v0/files` `{id, uploadTokenHash, fetchTokenHash, chunks}`; `PUT /v0/files/{id}/chunks/{index}` (exactly 256 000 bytes, upload token); `GET …/chunks/{index}` (fetch token); `DELETE /v0/files/{id}` (upload token). Tables `files (id, upload_hash, fetch_hash, chunks, uploaded_hour)` and `chunks (file_id, idx, ciphertext)`: no size column (every chunk is the same size), no name, type, sender, recipient, and **no fetch count**. - **Quotas (507).** Per file: its declared chunks, at most 410 (100 MiB). Relay-wide: `--max-files` (10 000) and `--max-file-bytes` (4 GiB), each file counted at full size from creation so an upload is never cut off; apart from the blob quota. - **Purge.** Files go after 30 days, or after 24 hours if not all chunks arrived; their chunks with them. - **A chunk never changes**: the same bytes again are accepted (an upload resumed), other bytes are 409. - **Client — chunked encryption.** A fresh 32-byte key per file; the file padded with zeros to whole chunks of 255 984 bytes; each chunk sealed with ChaCha20-Poly1305 in STREAM (`aead::stream::StreamBE32`: index counter + last-chunk flag). So every chunk is 256 000 bytes on the wire, and a chunk tampered with, swapped, repeated, cut, or from another file does not open (`ClientError::FileDamaged`). `chacha20poly1305` 0.10 was already in the tree through `openmls_rust_crypto`; its `stream` feature adds no crate (`Cargo.lock`: one new edge). - **Client — the `file` payload** in MLS: `seq` (shared with `text`/`poll`), `file`, `fetchToken`, `key`, `name`, `mime`, `size`, `thumb`? (JPEG ≤ 32 KiB). The key, name, type, exact size and thumbnail travel only here. API: `start_upload`, `create_file`, `put_chunk`, `upload`, `delete_file`, `compose_file`, `get_chunk`, `download`, `FileUpload`, `FileRef`, `Event::File`; `Transport` gains four methods; `TransportError::Full` (507). - **Found on the way, fixed:** axum's own 413 for a body over a route's limit carried a text body, on the blob and JSON routes too, against §8's *a refusal has no body*. Every route now answers a bare 413 (test in `relay.rs`). ## Tests (cargo test --workspace --locked, quoted per crate) | crate | test binary | passed | failed | |:--|:--|--:|--:| | tabellarius-client | unit (lib, incl. `files` module) | 24 | 0 | | | block / files / pairing / polls / push / reactions / real_relay / state | 7 / 8 / 8 / 4 / 3 / 5 / 3 / 14 | 0 | | | **client total** | **76** | **0** | | tabellarius-protocol | wire | 20 | 0 | | tabellarius-relay | unit / files / quotas / relay / wake | 2 / 8 / 8 / 19 / 9 | 0 | | | **relay total** | **46** | **0** | New in this PR: client unit +10 (7 in `files`, 3 in `lib`), `client/tests/files.rs` 8, `real_relay.rs` +1 (the canary), `protocol/tests/wire.rs` +2, `relay/tests/files.rs` 8; `relay.rs` and `quotas.rs` extended (schema, bare 413, flags). Also: `cargo fmt --all --check` clean; `cargo clippy --workspace --all-targets --locked -- -D warnings` clean; `scripts/check-deps.sh` ok (relay does not depend on client; protocol on nothing); `scripts/test-hooks.sh` 7 passed, 0 failed. ## Not verified - On a phone: nothing here runs on one by itself; Amicitia's PR says what it ran. - The NixOS module's relay with the new flags (`--max-files`, `--max-file-bytes`) is not run (as F23's VM test). The adversarial review is posted in this PR.
mnovak added 1 commit 2026-11-22 19:29:51 +01:00
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.
mnovak reviewed 2026-11-22 19:30:49 +01:00
mnovak left a comment
Author
Owner

Adversarial self-review — F29 files (protocol change)

Evidence

  • cargo test --workspace --locked on 3a0944e: tabellarius-client 76 passed, 0 failed (unit 24, block 7, files 8, pairing 8, polls 4, push 3, reactions 5, real_relay 3, state 14); tabellarius-protocol 20 passed, 0 failed (wire 20); tabellarius-relay 46 passed, 0 failed (unit 2, files 8, quotas 8, relay 19, wake 9).
  • cargo fmt --all --check clean; cargo clippy --workspace --all-targets --locked -- -D warnings clean; scripts/check-deps.sh ok; scripts/test-hooks.sh 7 passed, 0 failed.
  • Built offline (--offline); chacha20poly1305 0.10.1 was already in Cargo.lock through openmls_rust_crypto; the stream feature adds no crate.

Planted bugs — 14 of 14 caught (each applied alone, the named tests run, the file restored)

  1. relay: a fetch token can put a chunk → only_the_upload_token_puts_and_deletes_and_only_the_fetch_token_gets and 5 more
  2. relay: a chunk can be replaced with other bytes → a_chunk_is_exactly_the_chunk_size_and_never_changes
  3. relay: an incomplete file kept for 30 days → files_go_after_30_days_and_incomplete_ones_after_a_day
  4. relay: the quota counts chunks up instead of chunks declared → the_relay_wide_file_quota_counts_each_file_at_full_size_from_its_creation
  5. relay: an index past the declared chunks stored → a_file_holds_only_its_declared_chunks_and_at_most_the_protocols
  6. relay: a deleted file's chunks stay → nothing_of_a_file_is_left_after_it_is_deleted_or_purged (the first run found no test for this: get already 404s once the file row is gone, so orphaned chunks were invisible. The test was added, then the bug was caught.)
  7. client: every chunk sealed at position 0 → every_chunk_is_the_same_size_and_opens_back_to_the_file
  8. client: no chunk marked last → 3 unit tests
  9. client: padding that is not zeros accepted → the_padding_must_be_zeros_and_the_size_must_match
  10. client: a chunk put without encryption → a_file_goes_through_the_real_relay_which_never_sees_its_name_type_or_content (the canary)
  11. client: a blocked contact's file shown → a_blocked_contacts_file_is_dropped
  12. client: a bad thumbnail passed on → a_bad_thumbnail_is_dropped_and_the_file_kept
  13. client: a file does not count its seq → a_file_is_a_message_a_receipt_covers_it_and_a_reaction_or_reply_can_name_it
  14. client: file missing from KNOWN_KINDS → every_payload_kind_is_known, an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly

Findings (each has a line comment)

  1. Fixed in this PR — §8 was broken before it: axum's 413 carried a text body on every route. Now bare, with a test.
  2. Accepted, documented (G57 in Amicitia): a stranger can reserve the whole file quota for 24 h with ~40 empty files.
  3. Accepted, documented: a nonce is fixed by (key, index); putting different bytes for one index reuses it. The relay refuses the second (409) but has seen both. API doc says so; Amicitia keeps the bytes with the upload.
  4. Accepted: a zero nonce prefix and no associated data — safe only because a key seals one file. Said in PROTOCOL.md §4.
  5. Accepted, stated: the relay can link an upload to the next post and a download to the recipient's mailbox fetch, by timing and address (§1's honest limit).
  6. Note: download reserves the claimed size (≤ 100 MiB) before the first chunk; a peer can make a receiver allocate that. Bounded; get_chunk streams for apps that care.
  7. Note: the relay accepts 410 chunks (104 953 440 bytes) while the client refuses over 104 857 600; harmless slack, the client is the stricter side.

Privacy surface checked by hand

  • Relay schema: exactly §5's six tables (schema_is_exactly_protocol_section_5 test updated); no fetch count, no size, no name.
  • Nothing new is logged; main.rs prints only its start line.
  • Debug of FileUpload, FileRef, FileKey shows no token or key (unit test).

Not verified

  • No phone and no emulator run here (both were in use by other work); Amicitia's PR says what it ran.
  • The NixOS module with the new flags is not run.
## Adversarial self-review — F29 files (protocol change) ### Evidence - `cargo test --workspace --locked` on 3a0944e: **tabellarius-client 76 passed, 0 failed** (unit 24, block 7, files 8, pairing 8, polls 4, push 3, reactions 5, real_relay 3, state 14); **tabellarius-protocol 20 passed, 0 failed** (wire 20); **tabellarius-relay 46 passed, 0 failed** (unit 2, files 8, quotas 8, relay 19, wake 9). - `cargo fmt --all --check` clean; `cargo clippy --workspace --all-targets --locked -- -D warnings` clean; `scripts/check-deps.sh` ok; `scripts/test-hooks.sh` 7 passed, 0 failed. - Built offline (`--offline`); `chacha20poly1305` 0.10.1 was already in `Cargo.lock` through `openmls_rust_crypto`; the `stream` feature adds no crate. ### Planted bugs — 14 of 14 caught (each applied alone, the named tests run, the file restored) 1. relay: a fetch token can put a chunk → `only_the_upload_token_puts_and_deletes_and_only_the_fetch_token_gets` and 5 more 2. relay: a chunk can be replaced with other bytes → `a_chunk_is_exactly_the_chunk_size_and_never_changes` 3. relay: an incomplete file kept for 30 days → `files_go_after_30_days_and_incomplete_ones_after_a_day` 4. relay: the quota counts chunks up instead of chunks declared → `the_relay_wide_file_quota_counts_each_file_at_full_size_from_its_creation` 5. relay: an index past the declared chunks stored → `a_file_holds_only_its_declared_chunks_and_at_most_the_protocols` 6. relay: a deleted file's chunks stay → `nothing_of_a_file_is_left_after_it_is_deleted_or_purged` (**the first run found no test for this**: `get` already 404s once the file row is gone, so orphaned chunks were invisible. The test was added, then the bug was caught.) 7. client: every chunk sealed at position 0 → `every_chunk_is_the_same_size_and_opens_back_to_the_file` 8. client: no chunk marked last → 3 unit tests 9. client: padding that is not zeros accepted → `the_padding_must_be_zeros_and_the_size_must_match` 10. client: a chunk put without encryption → `a_file_goes_through_the_real_relay_which_never_sees_its_name_type_or_content` (the canary) 11. client: a blocked contact's file shown → `a_blocked_contacts_file_is_dropped` 12. client: a bad thumbnail passed on → `a_bad_thumbnail_is_dropped_and_the_file_kept` 13. client: a file does not count its seq → `a_file_is_a_message_a_receipt_covers_it_and_a_reaction_or_reply_can_name_it` 14. client: `file` missing from KNOWN_KINDS → `every_payload_kind_is_known`, `an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly` ### Findings (each has a line comment) 1. **Fixed in this PR — §8 was broken before it:** axum's 413 carried a text body on every route. Now bare, with a test. 2. **Accepted, documented (G57 in Amicitia):** a stranger can reserve the whole file quota for 24 h with ~40 empty files. 3. **Accepted, documented:** a nonce is fixed by (key, index); putting *different* bytes for one index reuses it. The relay refuses the second (409) but has seen both. API doc says so; Amicitia keeps the bytes with the upload. 4. **Accepted:** a zero nonce prefix and no associated data — safe only because a key seals one file. Said in PROTOCOL.md §4. 5. **Accepted, stated:** the relay can link an upload to the next post and a download to the recipient's mailbox fetch, by timing and address (§1's honest limit). 6. **Note:** `download` reserves the claimed size (≤ 100 MiB) before the first chunk; a peer can make a receiver allocate that. Bounded; `get_chunk` streams for apps that care. 7. **Note:** the relay accepts 410 chunks (104 953 440 bytes) while the client refuses over 104 857 600; harmless slack, the client is the stricter side. ### Privacy surface checked by hand - Relay schema: exactly §5's six tables (`schema_is_exactly_protocol_section_5` test updated); no fetch count, no size, no name. - Nothing new is logged; `main.rs` prints only its start line. - `Debug` of `FileUpload`, `FileRef`, `FileKey` shows no token or key (unit test). ### Not verified - No phone and no emulator run here (both were in use by other work); Amicitia's PR says what it ran. - The NixOS module with the new flags is not run.
@@ -0,0 +35,4 @@
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();
Author
Owner

Finding 4 (accepted): a zero 7-byte STREAM prefix and empty associated data. Safe because a key is made for one file and never reused (start_upload); a later forward feature that reuses a key must keep the same chunks, never re-seal. Written in PROTOCOL.md §4 A file's chunks.

Finding 4 (accepted): a zero 7-byte STREAM prefix and empty associated data. Safe because a key is made for one file and never reused (`start_upload`); a later *forward* feature that reuses a key must keep the same chunks, never re-seal. Written in PROTOCOL.md §4 *A file's chunks*.
@@ -793,0 +863,4 @@
/// 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
Author
Owner

Finding 3 (accepted, documented): seal is deterministic in (key, index), which is what makes a resumed upload idempotent — but two different plaintexts for one index under the same key reuse a ChaCha20-Poly1305 nonce (keystream and Poly1305 key). The relay refuses the second with 409, yet it has received both bodies. Can happen if an app re-reads a source file that changed between tries. The doc says so; Amicitia stores the parts with the upload and never re-reads. A misuse-resistant AEAD (SIV) would remove the trap; not in the tree today.

Finding 3 (accepted, documented): `seal` is deterministic in (key, index), which is what makes a resumed upload idempotent — but two different plaintexts for one index under the same key reuse a ChaCha20-Poly1305 nonce (keystream and Poly1305 key). The relay refuses the second with 409, yet it has received both bodies. Can happen if an app re-reads a source file that changed between tries. The doc says so; Amicitia stores the parts with the upload and never re-reads. A misuse-resistant AEAD (SIV) would remove the trap; not in the tree today.
@@ -793,0 +947,4 @@
}
/// Fetches and opens every chunk: the whole file, exactly `size` bytes.
pub fn download(&self, file: &FileRef) -> Result<Vec<u8>, ClientError> {
Author
Owner

Finding 6 (note): download reserves file.size bytes (at most 100 MiB, checked when the payload arrived) before the first chunk; a peer can make the receiver allocate that much for nothing. Bounded, and the app decides when to call it (Amicitia: automatically only ≤ 10 MiB). get_chunk is there for chunk-by-chunk use.

Finding 6 (note): `download` reserves `file.size` bytes (at most 100 MiB, checked when the payload arrived) before the first chunk; a peer can make the receiver allocate that much for nothing. Bounded, and the app decides when to call it (Amicitia: automatically only ≤ 10 MiB). `get_chunk` is there for chunk-by-chunk use.
@@ -32,0 +33,4 @@
/// `.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;
Author
Owner

Finding 7 (note): the relay allows 410 chunks = 104 953 440 plaintext bytes; the client refuses over 100 MiB = 104 857 600. The relay is the looser side by under 100 KB; nothing depends on the two matching. A wire test pins that 410 chunks hold 100 MiB and 409 do not.

Finding 7 (note): the relay allows 410 chunks = 104 953 440 plaintext bytes; the client refuses over 100 MiB = 104 857 600. The relay is the looser side by under 100 KB; nothing depends on the two matching. A wire test pins that 410 chunks hold 100 MiB and 409 do not.
@@ -85,2 +97,4 @@
}
/// 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> {
Author
Owner

Finding 1 (fixed): before this, a body over a route's DefaultBodyLimit got axum's own 413 with a text body — on the blob route and the JSON routes too, so PROTOCOL.md §8's A refusal has no body was not true. Every handler now takes Result<Bytes, BytesRejection> and answers a bare 413; a_blob_over_256_kib_is_refused checks the body is empty for a blob and for a 64 KiB JSON body.

Finding 1 (fixed): before this, a body over a route's `DefaultBodyLimit` got axum's own 413 *with a text body* — on the blob route and the JSON routes too, so `PROTOCOL.md` §8's *A refusal has no body* was not true. Every handler now takes `Result<Bytes, BytesRejection>` and answers a bare 413; `a_blob_over_256_kib_is_refused` checks the body is empty for a blob and for a 64 KiB JSON body.
@@ -410,0 +460,4 @@
})?;
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 {
Author
Owner

Finding 2 (accepted, documented as G57): POST /v0/files needs no token, and a file reserves chunks × 256 000 from creation (so an upload in progress is never cut off). About 40 empty 410-chunk files hold a default relay's 4 GiB until the 24-hour purge of incomplete files. As cheap as filling the blob quota today (F23's stated limit); the operator's flags bound it. Later: a shorter deadline for incomplete files, or reserving per chunk that arrives.

Finding 2 (accepted, documented as G57): `POST /v0/files` needs no token, and a file reserves `chunks × 256 000` from creation (so an upload in progress is never cut off). About 40 empty 410-chunk files hold a default relay's 4 GiB until the 24-hour purge of incomplete files. As cheap as filling the blob quota today (F23's stated limit); the operator's flags bound it. Later: a shorter deadline for incomplete files, or reserving per chunk that arrives.
@@ -85,2 +96,3 @@
Nothing else. No IP, no user agent, no request log beyond counts. *(2026-11-20:)* the relay also
Nothing else. *(2026-11-22:)* a file has no mailbox, no sender and no recipient, and the relay
keeps **no count of fetches**: it sees each one as it serves it. A file is deleted when its
Author
Owner

Finding 5 (accepted, stated): no fetch count is stored, but the relay sees each GET as it serves it, and the upload is followed by a blob post to the recipient's mailbox from the same address within seconds — so an operator who logs at the network layer links sender, file and recipient by timing. Same class as §1's existing honest limit; files.md §3 says it.

Finding 5 (accepted, stated): no fetch count is stored, but the relay sees each GET as it serves it, and the upload is followed by a blob post to the recipient's mailbox from the same address within seconds — so an operator who logs at the network layer links sender, file and recipient by timing. Same class as §1's existing honest limit; files.md §3 says it.
Author
Owner

Merged with --no-ff as 7f46bc5156 on main (remote hash verified). The review is above (14/14 planted bugs caught; 7 findings: one fixed here, four accepted and documented, two notes).

Merged with `--no-ff` as 7f46bc5156690305389e671bf42f11076821143c on `main` (remote hash verified). The review is above (14/14 planted bugs caught; 7 findings: one fixed here, four accepted and documented, two notes).
mnovak closed this pull request 2026-11-22 19:31:19 +01:00
Some checks are pending
ci / check (pull_request) Has been cancelled

Pull request closed

Sign in to join this conversation.