Files
Amicitia-Tabellarius/crates/client/src/transport.rs
T
mnovak 3a0944ebff
ci / check (pull_request) Has been cancelled
[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
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.
2026-11-22 19:29:37 +01:00

319 lines
11 KiB
Rust

//! How the client reaches a relay. The library makes no network calls itself: an app gives it a
//! [`Transport`] (HTTP in Amicitia, F22). [`MemoryTransport`] is a stand-in with the relay's rules,
//! for tests and for running the client on a device without a relay.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tabellarius_protocol::{
blob_hash, CreateFile, CreateInvite, CreateMailbox, FileId, InviteId, MailboxId, PushEndpoint,
Sha256Hash, Token, FILE_CHUNK_BYTES,
};
/// Why the relay said no. Carries nothing of the request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportError {
/// 404: unknown, wrong token, expired, or already claimed.
NotFound,
/// 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,
}
/// The relay's operations (`PROTOCOL.md` §8), one method each.
pub trait Transport {
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError>;
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError>;
/// The waiting blobs, oldest first.
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError>;
fn acknowledge(
&self,
id: &MailboxId,
fetch: &Token,
hash: &Sha256Hash,
) -> Result<(), TransportError>;
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>;
/// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on.
fn rotate_post_token(
&self,
id: &MailboxId,
fetch: &Token,
new_hash: &Sha256Hash,
) -> Result<(), TransportError>;
/// The KeyPackage, once.
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
/// Where the relay wakes the mailbox's owner when a blob arrives (`Some`), or nowhere (`None`).
/// `PROTOCOL.md` §6, `.agents/features/wake-up.md`.
fn set_push(
&self,
id: &MailboxId,
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)]
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).
/// Clone it to give two clients the same relay.
#[derive(Clone, Default)]
pub struct MemoryTransport(Arc<Mutex<Boxes>>);
impl MemoryTransport {
fn boxes(&self) -> std::sync::MutexGuard<'_, Boxes> {
self.0.lock().unwrap_or_else(|p| p.into_inner())
}
/// How many blobs wait on the relay, in all mailboxes: what was not acknowledged.
pub fn waiting_blobs(&self) -> usize {
self.boxes()
.mailboxes
.values()
.map(|(_, _, b)| b.len())
.sum()
}
/// The push endpoint a mailbox holds, if any.
pub fn push_endpoint(&self, id: &MailboxId) -> Option<String> {
self.boxes().push.get(id).map(|e| e.as_str().to_string())
}
/// 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();
for (id, (post, fetch, blobs)) in &b.mailboxes {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(post.as_bytes());
out.extend_from_slice(fetch.as_bytes());
blobs.iter().for_each(|blob| out.extend_from_slice(blob));
}
for (id, (hash, kp)) in &b.invites {
out.extend_from_slice(id.as_bytes());
out.extend_from_slice(hash.as_bytes());
out.extend_from_slice(kp);
}
for (id, endpoint) in &b.push {
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
}
}
impl Transport for MemoryTransport {
fn create_mailbox(&self, req: &CreateMailbox) -> Result<(), TransportError> {
let mut b = self.boxes();
if b.mailboxes.contains_key(&req.id) {
return Err(TransportError::Conflict);
}
b.mailboxes.insert(
req.id,
(req.post_token_hash, req.fetch_token_hash, Vec::new()),
);
Ok(())
}
fn post(&self, id: &MailboxId, post: &Token, blob: &[u8]) -> Result<(), TransportError> {
match self.boxes().mailboxes.get_mut(id) {
Some((hash, _, blobs)) if *hash == post.hash() => {
blobs.push(blob.to_vec());
Ok(())
}
_ => Err(TransportError::NotFound),
}
}
fn fetch(&self, id: &MailboxId, fetch: &Token) -> Result<Vec<Vec<u8>>, TransportError> {
match self.boxes().mailboxes.get(id) {
Some((_, hash, blobs)) if *hash == fetch.hash() => Ok(blobs.clone()),
_ => Err(TransportError::NotFound),
}
}
fn acknowledge(
&self,
id: &MailboxId,
fetch: &Token,
hash: &Sha256Hash,
) -> Result<(), TransportError> {
match self.boxes().mailboxes.get_mut(id) {
Some((_, f, blobs)) if *f == fetch.hash() => {
let at = blobs
.iter()
.position(|b| blob_hash(b) == *hash)
.ok_or(TransportError::NotFound)?;
blobs.remove(at);
Ok(())
}
_ => Err(TransportError::NotFound),
}
}
fn rotate_post_token(
&self,
id: &MailboxId,
fetch: &Token,
new_hash: &Sha256Hash,
) -> Result<(), TransportError> {
match self.boxes().mailboxes.get_mut(id) {
Some((post, f, _)) if *f == fetch.hash() => {
*post = *new_hash;
Ok(())
}
_ => Err(TransportError::NotFound),
}
}
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
let mut b = self.boxes();
if b.invites.contains_key(&req.id) {
return Err(TransportError::Conflict);
}
b.invites
.insert(req.id, (req.secret_hash, req.key_package.bytes().to_vec()));
Ok(())
}
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError> {
let mut b = self.boxes();
match b.invites.get(id) {
Some((hash, _)) if *hash == secret.hash() => b
.invites
.remove(id)
.map(|(_, kp)| kp)
.ok_or(TransportError::NotFound),
_ => Err(TransportError::NotFound),
}
}
fn set_push(
&self,
id: &MailboxId,
fetch: &Token,
endpoint: Option<&PushEndpoint>,
) -> Result<(), TransportError> {
let mut b = self.boxes();
match b.mailboxes.get(id) {
Some((_, f, _)) if *f == fetch.hash() => {}
_ => return Err(TransportError::NotFound),
}
match endpoint {
Some(e) => b.push.insert(*id, e.clone()),
None => b.push.remove(id),
};
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),
}
}
}