3a0944ebff
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.
307 lines
9.8 KiB
Rust
307 lines
9.8 KiB
Rust
//! 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<dyn Fn() -> i64 + Send + Sync>;
|
|
|
|
#[derive(Clone)]
|
|
pub struct AppState {
|
|
pub store: Arc<Store>,
|
|
pub clock: Clock,
|
|
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
|
|
pub waker: Arc<Waker>,
|
|
}
|
|
|
|
impl AppState {
|
|
/// A relay that wakes only global `https://` endpoints: what a relay facing the internet runs.
|
|
pub fn new(store: Arc<Store>, clock: Clock) -> Self {
|
|
Self::with_waker(store, clock, Waker::new(false))
|
|
}
|
|
|
|
pub fn with_waker(store: Arc<Store>, 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<Refused> 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<Bytes, BytesRejection>) -> Result<Bytes, Status> {
|
|
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<T: DeserializeOwned>(body: &Bytes) -> Result<T, Status> {
|
|
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, Status> {
|
|
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<Token, Status> {
|
|
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<AppState>,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
) -> Result<Json<FetchedBlobs>, 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<AppState>,
|
|
Path((id, hash)): Path<(String, String)>,
|
|
headers: HeaderMap,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
) -> Result<StatusCode, Status> {
|
|
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, Status> {
|
|
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<u32, Status> {
|
|
let canonical = !text.is_empty()
|
|
&& text.bytes().all(|b| b.is_ascii_digit())
|
|
&& (text == "0" || !text.starts_with('0'));
|
|
text.parse::<u32>()
|
|
.ok()
|
|
.filter(|_| canonical)
|
|
.ok_or(Status(StatusCode::NOT_FOUND))
|
|
}
|
|
|
|
async fn create_file(
|
|
State(s): State<AppState>,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path((id, index)): Path<(String, String)>,
|
|
headers: HeaderMap,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path((id, index)): Path<(String, String)>,
|
|
headers: HeaderMap,
|
|
) -> Result<Response, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
body: Result<Bytes, BytesRejection>,
|
|
) -> Result<StatusCode, Status> {
|
|
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<AppState>,
|
|
Path(id): Path<String>,
|
|
headers: HeaderMap,
|
|
) -> Result<Response, Status> {
|
|
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<VersionInfo> {
|
|
Json(VersionInfo {
|
|
protocol: VERSION.to_string(),
|
|
relay: env!("CARGO_PKG_VERSION").to_string(),
|
|
})
|
|
}
|