//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's //! address, and nothing here writes a request anywhere. 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}; use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; use serde::de::DeserializeOwned; use std::sync::Arc; use tabellarius_protocol::{ 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. pub type Clock = Arc i64 + Send + Sync>; #[derive(Clone)] pub struct AppState { pub store: Arc, pub clock: Clock, /// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` ยง6). pub waker: Arc, } impl AppState { /// A relay that wakes only global `https://` endpoints: what a relay facing the internet runs. pub fn new(store: Arc, clock: Clock) -> Self { Self::with_waker(store, clock, Waker::new(false)) } pub fn with_waker(store: Arc, clock: Clock, waker: Waker) -> Self { Self { store, clock, waker: Arc::new(waker), } } } /// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url. const MAX_JSON_BYTES: usize = 32 * 1024; 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) } /// Every refusal is a bare status code: no body that could echo the request back. struct Status(StatusCode); impl IntoResponse for Status { fn into_response(self) -> Response { self.0.into_response() } } impl From for Status { fn from(r: Refused) -> Self { Status(match r { Refused::NotFound => StatusCode::NOT_FOUND, Refused::Exists => StatusCode::CONFLICT, Refused::TooLarge => StatusCode::PAYLOAD_TOO_LARGE, Refused::Storage => StatusCode::INTERNAL_SERVER_ERROR, Refused::Full => StatusCode::INSUFFICIENT_STORAGE, }) } } /// A body over the route's limit is axum's rejection, which carries a text: a bare 413 instead. fn bare(body: Result) -> Result { 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(body: &Bytes) -> Result { serde_json::from_slice(body).map_err(|_| Status(StatusCode::BAD_REQUEST)) } /// A malformed id in the path is treated like an unknown one. fn mailbox(id: &str) -> Result { MailboxId::parse(id).map_err(|_| Status(StatusCode::NOT_FOUND)) } /// A missing or malformed bearer token is treated like a wrong one. fn bearer(headers: &HeaderMap) -> Result { headers .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .and_then(|v| Token::from_bearer(v).ok()) .ok_or(Status(StatusCode::NOT_FOUND)) } async fn create_mailbox( State(s): State, body: Result, ) -> Result { let body = bare(body)?; let req: CreateMailbox = json(&body)?; s.store.create_mailbox(&req, (s.clock)())?; Ok(StatusCode::CREATED) } async fn post_blob( State(s): State, Path(id): Path, headers: HeaderMap, body: Result, ) -> Result { let body = bare(body)?; let id = mailbox(&id)?; let token = bearer(&headers)?; let now = (s.clock)(); s.store.post(&id, &token, &body, now)?; // Only after the blob is stored under a valid post token; the 201 does not wait for the wake. if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) { s.waker.wake(Arc::clone(&s.store), id, endpoint, now); } Ok(StatusCode::CREATED) } async fn fetch_blobs( State(s): State, Path(id): Path, headers: HeaderMap, ) -> Result, Status> { let id = mailbox(&id)?; let token = bearer(&headers)?; let blobs = s.store.fetch(&id, &token)?; Ok(Json(FetchedBlobs { blobs })) } async fn acknowledge( State(s): State, Path((id, hash)): Path<(String, String)>, headers: HeaderMap, ) -> Result { let id = mailbox(&id)?; let token = bearer(&headers)?; let hash = Sha256Hash::parse(&hash).map_err(|_| Status(StatusCode::NOT_FOUND))?; s.store.acknowledge(&id, &token, &hash)?; Ok(StatusCode::NO_CONTENT) } async fn rotate_post_token( State(s): State, Path(id): Path, headers: HeaderMap, body: Result, ) -> Result { let body = bare(body)?; let id = mailbox(&id)?; let token = bearer(&headers)?; let req: RotatePostToken = json(&body)?; s.store .rotate_post_token(&id, &token, &req.post_token_hash)?; Ok(StatusCode::NO_CONTENT) } async fn set_push( State(s): State, Path(id): Path, headers: HeaderMap, body: Result, ) -> Result { let body = bare(body)?; let id = mailbox(&id)?; let token = bearer(&headers)?; let req: SetPush = json(&body)?; if !s.waker.accepts(&req.endpoint) { return Err(Status(StatusCode::BAD_REQUEST)); } s.store.set_push(&id, &token, Some(&req.endpoint))?; Ok(StatusCode::NO_CONTENT) } async fn clear_push( State(s): State, Path(id): Path, headers: HeaderMap, ) -> Result { let id = mailbox(&id)?; let token = bearer(&headers)?; s.store.set_push(&id, &token, None)?; Ok(StatusCode::NO_CONTENT) } /// A malformed file id in the path is treated like an unknown one. fn file(id: &str) -> Result { 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 { let canonical = !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()) && (text == "0" || !text.starts_with('0')); text.parse::() .ok() .filter(|_| canonical) .ok_or(Status(StatusCode::NOT_FOUND)) } async fn create_file( State(s): State, body: Result, ) -> Result { 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, Path((id, index)): Path<(String, String)>, headers: HeaderMap, body: Result, ) -> Result { 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, Path((id, index)): Path<(String, String)>, headers: HeaderMap, ) -> Result { 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, Path(id): Path, headers: HeaderMap, ) -> Result { 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, body: Result, ) -> Result { let body = bare(body)?; let req: CreateInvite = json(&body)?; s.store.create_invite(&req, (s.clock)())?; Ok(StatusCode::CREATED) } async fn claim_invite( State(s): State, Path(id): Path, headers: HeaderMap, ) -> Result { let id = InviteId::parse(&id).map_err(|_| Status(StatusCode::NOT_FOUND))?; let secret = bearer(&headers)?; let claimed = s.store.claim_invite(&id, &secret, (s.clock)())?; Ok(Json(claimed).into_response()) } async fn version() -> Json { Json(VersionInfo { protocol: VERSION.to_string(), relay: env!("CARGO_PKG_VERSION").to_string(), }) }