[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
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:
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user