//! 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() -> [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 { vec![fill; FILE_CHUNK_BYTES] } struct Relay { app: axum::Router, store: Arc, now: Arc, } 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, ) -> (StatusCode, Vec) { 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) -> 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) { 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"); }