//! 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::arrivals::{Arrivals, MAX_WAITERS}; use crate::store::{Refused, Store}; use crate::turn::Turn; use crate::wake::Waker; use axum::body::Bytes; use axum::extract::rejection::BytesRejection; use axum::extract::{DefaultBodyLimit, Path, Query, 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 std::time::Duration; use tabellarius_protocol::{ CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId, RotatePostToken, SetPush, Sha256Hash, Token, TurnCredentials, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES, MAX_WAIT_SECS, 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, /// Who is long-polling which mailbox, in memory only (`calls-relay.md`). pub arrivals: Arc, /// TURN credentials for calls; `None` when the relay was started without a TURN secret. pub turn: Option>, } 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), arrivals: Arc::new(Arrivals::new(MAX_WAITERS)), turn: None, } } /// Hands out TURN credentials under this secret and these URLs (`POST /v0/mailboxes/{id}/turn`). pub fn with_turn(mut self, turn: Turn) -> Self { self.turn = Some(Arc::new(turn)); self } /// At most `max` long-polls held at once, relay-wide (tests set a small one). pub fn with_max_waiters(mut self, max: usize) -> Self { self.arrivals = Arc::new(Arrivals::new(max)); self } } /// 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/mailboxes/{id}/turn", post(turn_credentials)) .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)?; // Anyone long-polling this mailbox is answered now. s.arrivals.arrived(&id); // 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) } #[derive(serde::Deserialize)] pub struct Wait { wait: Option, } /// How long a fetch may be held: `?wait=` in seconds, at most [`MAX_WAIT_SECS`]; none means not at all. pub fn clamp_wait(wait: Option) -> Duration { Duration::from_secs(wait.unwrap_or(0).min(MAX_WAIT_SECS)) } /// `GET …/blobs[?wait=N]`: the waiting blobs; with `wait` and none waiting, held until one arrives or N seconds /// pass. The token is checked before anything is held, and the place is taken before the store is read, so a blob /// posted in between is never missed. async fn fetch_blobs( State(s): State, Path(id): Path, Query(q): Query, headers: HeaderMap, ) -> Result, Status> { let id = mailbox(&id)?; let token = bearer(&headers)?; let wait = clamp_wait(q.wait); let place = if wait.is_zero() { None } else { s.arrivals.enter(id) }; let Some(place) = place else { return Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? })); }; let notified = place.notify.notified(); tokio::pin!(notified); notified.as_mut().enable(); let blobs = s.store.fetch(&id, &token)?; if !blobs.is_empty() { return Ok(Json(FetchedBlobs { blobs })); } let _ = tokio::time::timeout(wait, notified).await; // The place is left when this returns. Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? })) } /// `POST …/turn` with the fetch token: a TURN REST pair (`calls-relay.md`). 404 without a TURN secret or with a /// wrong token, 429 over [`tabellarius_protocol::TURN_PER_HOUR`]. Nothing is stored. async fn turn_credentials( State(s): State, Path(id): Path, headers: HeaderMap, ) -> Result, Status> { let turn = s.turn.as_ref().ok_or(Status(StatusCode::NOT_FOUND))?; let id = mailbox(&id)?; let token = bearer(&headers)?; s.store.authorize_fetch(&id, &token)?; turn.credentials(id, (s.clock)()) .map(Json) .ok_or(Status(StatusCode::TOO_MANY_REQUESTS)) } 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(), }) }