//! The chunked upload API (architecture 4.2). A file is sent in chunks of 8 MiB, each to its own URL, and //! the server joins them when the client finishes. Every route needs the session cookie and the //! `X-CSRF-Token` header; a missing or wrong token is `403`, a missing session is `401`, both as JSON. //! //! The routes: //! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is //! reserved against the quota in the same transaction that creates the row, so two creates cannot //! together promise more than the headroom. A person may hold 64 open uploads; the next one is `429` //! `too_many_uploads`. //! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk //! indexes on disk. A client that lost its connection asks this, then sends only what is missing. //! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the //! upload, and the body must be exactly the length that chunk has: `chunk_size` for every chunk but the //! last, which is the remainder. A longer body is `413` and a shorter one `400`; the bytes are read with a //! hard limit, so a client cannot make the server store more than the declared size. Sending a chunk that //! is already there replaces it with the same bytes. //! - `POST /api/uploads/{id}/finish` joins the chunks into a blob, inserts the file row and marks the upload //! done → `{file_id}`. Missing chunks are `409` with their indexes. The quota is checked again in the //! insert transaction, against the other open uploads. //! - `DELETE /api/uploads/{id}` cancels an open upload and removes its staging directory. //! //! An upload that is not finished within 24 hours of its last chunk expires; the sweeper removes it. //! Another member's upload id is `404`, the same as a missing one. use std::path::Path; use futures_util::StreamExt; use http::header::{CACHE_CONTROL, CONTENT_TYPE}; use http::{HeaderValue, StatusCode}; use in_core::error::Error as CoreError; use in_core::names::upload_name; use in_core::sniff::sniff; use in_core::staging::{ CHUNK_BYTES, Staged, StagedFile, chunk_count, chunk_path, expected_chunk_len, remove_upload_dir, upload_dir, }; use in_core::store::files::{NewFile, files_blob_key}; use in_core::store::new_id; use in_core::store::uploads::{NewUpload, Upload}; use in_core::time::{now_stamp, stamp_after}; use serde::Deserialize; use serde_json::{Value, json}; use tokio::io::AsyncReadExt; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, path_param_segment, route, to_bytes}; use crate::auth::{Viewer, csrf_matches, current_member}; use crate::pages::drive::{changed, optional_folder}; use crate::state::AppState; /// The header that carries the session's CSRF token. const CSRF_HEADER: &str = "x-csrf-token"; /// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count. pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); /// Largest body the create route reads. Its JSON is a few hundred bytes. const CREATE_BODY_LIMIT: usize = 4096; /// How many bytes a chunk is copied with when the chunks are joined. const COPY_BUFFER: usize = 64 * 1024; /// How many leading bytes of the file the sniffer reads. const SNIFF_BYTES: usize = 8192; /// A refused call: the status and the fixed word the client gets as `{"error": word}`. #[derive(Debug, Clone, Copy)] struct Refusal { status: StatusCode, word: &'static str, } impl Refusal { /// The JSON answer of this refusal. fn answer(self) -> Response { json_answer(self.status, json!({ "error": self.word })) } } /// Shorthand for a [`Refusal`]. const fn refuse(status: StatusCode, word: &'static str) -> Refusal { Refusal { status, word } } /// A JSON response with the given status. Upload answers are never cached. fn json_answer(status: StatusCode, value: Value) -> Response { let body = serde_json::to_vec(&value).unwrap_or_default(); http::Response::builder() .status(status) .header(CONTENT_TYPE, HeaderValue::from_static("application/json")) .header(CACHE_CONTROL, HeaderValue::from_static("no-store")) .body(Body::from(body)) .unwrap_or_else(|_| http::Response::new(Body::empty())) } /// The signed-in viewer, when the request carries the session cookie and a matching CSRF header. The /// outer `Result` is a server failure; the inner one is the refusal to send. async fn api_viewer(cx: &Cx) -> Result> { let Some(viewer) = current_member(cx).await? else { return Ok(Err(refuse(StatusCode::UNAUTHORIZED, "signed_out"))); }; let submitted = headers(cx) .get(CSRF_HEADER) .and_then(|value| value.to_str().ok()) .unwrap_or(""); if !csrf_matches(&viewer.session, submitted) { return Ok(Err(refuse(StatusCode::FORBIDDEN, "csrf"))); } Ok(Ok(viewer)) } /// The viewer's upload by id, which must still be open. Another member's or a missing id is `404`; an /// upload that already finished or was cancelled is `409`; one past its expiry is `410`. async fn open_upload( state: &AppState, viewer: &Viewer, id: &str, ) -> Result> { let Some(upload) = state.store.upload(&viewer.member.sub, id).await? else { return Ok(Err(refuse(StatusCode::NOT_FOUND, "not_found"))); }; if upload.state != "active" { return Ok(Err(refuse(StatusCode::CONFLICT, "not_active"))); } if !upload.is_open(&now_stamp()) { return Ok(Err(refuse(StatusCode::GONE, "expired"))); } Ok(Ok(upload)) } /// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored. pub async fn max_upload_bytes(state: &AppState) -> Result { let resolved = in_core::settings::resolve( &state.store, &state.config.limits, in_core::settings::MAX_UPLOAD_KEY, ) .await?; Ok(resolved.value.max(1)) } /// The indexes of the chunks that are on disk. A missing directory has none. async fn received_chunks(dir: &Path) -> Result> { let mut found = Vec::new(); let mut entries = match tokio::fs::read_dir(dir).await { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(found), Err(error) => return Err(CoreError::from(error).into()), }; while let Some(entry) = entries.next_entry().await.map_err(CoreError::from)? { // Chunk files are named by their index. Temporary files have ULID names, which never parse. if let Some(index) = entry .file_name() .to_str() .and_then(|n| n.parse::().ok()) { found.push(index); } } found.sort_unstable(); Ok(found) } /// The body of `POST /api/uploads`. #[derive(Debug, Deserialize)] struct CreateRequest { /// Destination folder, or absent for the top level. #[serde(default)] folder_id: Option, /// The file name as the client has it. It is cleaned, not refused. name: String, /// Declared size in bytes. size: u64, } /// `POST /api/uploads`: starts an upload. #[route(POST "/api/uploads")] async fn create_upload(cx: &Cx, body: Body) -> Result { let state = app_context::(cx); let viewer = match api_viewer(cx).await? { Ok(viewer) => viewer, Err(refusal) => return Ok(refusal.answer()), }; let Ok(bytes) = to_bytes(body, CREATE_BODY_LIMIT).await else { return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); }; let Ok(request) = serde_json::from_slice::(&bytes) else { return Ok(refuse(StatusCode::BAD_REQUEST, "bad_request").answer()); }; let Ok(size) = i64::try_from(request.size) else { return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); }; let folder = optional_folder(state, &viewer, request.folder_id.as_deref().unwrap_or("")).await?; let max = max_upload_bytes(state).await?; let id = new_id(); let new = NewUpload { id: id.clone(), owner: viewer.member.sub.clone(), folder, name: upload_name(&request.name), size, chunk_size: i64::try_from(CHUNK_BYTES).unwrap_or(i64::MAX), expires_at: stamp_after(UPLOAD_TTL), }; let upload = match state.store.create_upload(new, max).await { Ok(upload) => upload, Err(CoreError::Invalid(word)) if word == "too_large" => { return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); } Err(CoreError::Conflict(word)) if word == "quota_exceeded" => { return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()); } Err(CoreError::Conflict(word)) if word == "too_many_uploads" => { return Ok(refuse(StatusCode::TOO_MANY_REQUESTS, "too_many_uploads").answer()); } Err(error) => return Err(error.into()), }; // The directory is made after the row commits. A crash in between leaves a row with no directory, which // the sweeper expires; the other order could leave a directory no row names. let dir = upload_dir(&state.config.data_dir, &upload.id)?; tokio::fs::DirBuilder::new() .recursive(true) .mode(0o700) .create(&dir) .await .map_err(CoreError::from)?; Ok(json_answer( StatusCode::CREATED, json!({ "id": upload.id, "chunk_size": CHUNK_BYTES }), )) } /// `GET /api/uploads/{id}`: the state of an upload and the chunks it has. #[route(GET "/api/uploads/{id}")] async fn upload_status(cx: &Cx) -> Result { let state = app_context::(cx); let viewer = match api_viewer(cx).await? { Ok(viewer) => viewer, Err(refusal) => return Ok(refusal.answer()), }; let id = path_param_segment(cx, "id").to_owned(); let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); }; let dir = upload_dir(&state.config.data_dir, &upload.id)?; let received = received_chunks(&dir).await?; let word = if upload.state == "active" && !upload.is_open(&now_stamp()) { "expired" } else { upload.state.as_str() }; Ok(json_answer( StatusCode::OK, json!({ "id": upload.id, "state": word, "size": upload.size, "chunk_size": upload.chunk_size, "received": received, }), )) } /// `PUT /api/uploads/{id}/{index}`: stores one chunk. #[route(PUT "/api/uploads/{id}/{index}")] async fn put_chunk(cx: &Cx, body: Body) -> Result { let state = app_context::(cx); let viewer = match api_viewer(cx).await? { Ok(viewer) => viewer, Err(refusal) => return Ok(refusal.answer()), }; let id = path_param_segment(cx, "id").to_owned(); let raw_index = path_param_segment(cx, "index").to_owned(); let upload = match open_upload(state, &viewer, &id).await? { Ok(upload) => upload, Err(refusal) => return Ok(refusal.answer()), }; let Ok(index) = raw_index.parse::() else { return Ok(refuse(StatusCode::BAD_REQUEST, "bad_index").answer()); }; let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); let Some(expected) = expected_chunk_len(size, chunk, index) else { return Ok(refuse(StatusCode::BAD_REQUEST, "index_out_of_range").answer()); }; let dir = upload_dir(&state.config.data_dir, &upload.id)?; // The bytes go to a temporary file in the staging directory, which is then renamed onto the index. A // reader sees either the old chunk or the new one, never a partial write. let mut staged = match StagedFile::create_in(&dir, expected).await { Ok(staged) => staged, Err(CoreError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => { return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); } Err(error) => return Err(error.into()), }; let mut frames = body.into_data_stream(); let mut received: u64 = 0; while let Some(frame) = frames.next().await { let Ok(bytes) = frame else { staged.abort().await; return Ok(refuse(StatusCode::BAD_REQUEST, "body_read").answer()); }; let len = bytes.len() as u64; if received + len > expected { staged.abort().await; return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "chunk_too_large").answer()); } if let Err(error) = staged.write(&bytes).await { staged.abort().await; return Err(error.into()); } received += len; } if received != expected { staged.abort().await; return Ok(refuse(StatusCode::BAD_REQUEST, "chunk_length").answer()); } let Staged { path, .. } = staged.finish().await?; let target = chunk_path(&dir, index); if let Err(error) = tokio::fs::rename(&path, &target).await { let _ = tokio::fs::remove_file(&path).await; return Err(CoreError::from(error).into()); } // The rename is durable only once the directory entry is: fsync the directory, as the blob store does. tokio::fs::File::open(&dir) .await .map_err(CoreError::from)? .sync_all() .await .map_err(CoreError::from)?; if !state .store .touch_upload(&viewer.member.sub, &upload.id, &stamp_after(UPLOAD_TTL)) .await? { // The upload was finished or cancelled after the check above. Its directory is removed by that // request or by the sweeper, so this chunk does not outlive it. return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); } Ok(json_answer(StatusCode::OK, json!({ "index": index }))) } /// Joins the chunks of `dir` into `staged`, in index order, and keeps the first bytes for the sniffer. async fn join_chunks( dir: &Path, count: u64, staged: &mut StagedFile, prefix: &mut Vec, ) -> std::result::Result<(), CoreError> { let mut buffer = vec![0u8; COPY_BUFFER]; for index in 0..count { let mut part = tokio::fs::File::open(chunk_path(dir, index)).await?; loop { let read = part.read(&mut buffer).await?; if read == 0 { break; } if prefix.len() < SNIFF_BYTES { let take = (SNIFF_BYTES - prefix.len()).min(read); prefix.extend_from_slice(&buffer[..take]); } staged.write(&buffer[..read]).await?; } } Ok(()) } /// `POST /api/uploads/{id}/finish`: joins the chunks into the file. #[route(POST "/api/uploads/{id}/finish")] async fn finish_upload(cx: &Cx) -> Result { let state = app_context::(cx); let viewer = match api_viewer(cx).await? { Ok(viewer) => viewer, Err(refusal) => return Ok(refusal.answer()), }; let id = path_param_segment(cx, "id").to_owned(); let upload = match open_upload(state, &viewer, &id).await? { Ok(upload) => upload, Err(refusal) => return Ok(refusal.answer()), }; let data_dir = state.config.data_dir.clone(); let dir = upload_dir(&data_dir, &upload.id)?; let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); let count = chunk_count(size, chunk); let received = received_chunks(&dir).await?; let missing: Vec = (0..count) .filter(|index| received.binary_search(index).is_err()) .collect(); if !missing.is_empty() { return Ok(json_answer( StatusCode::CONFLICT, json!({ "error": "chunks_missing", "missing": missing }), )); } let mut staged = StagedFile::create(&data_dir, size).await?; let mut prefix = Vec::with_capacity(SNIFF_BYTES); if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { staged.abort().await; // A concurrent finish of this upload may have removed the chunks already. That is a conflict. if matches!(&error, CoreError::Io(e) if e.kind() == std::io::ErrorKind::NotFound) { return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); } return Err(error.into()); } let Staged { path, sha256, size: measured, } = staged.finish().await?; // The row records the bytes that were joined. Chunks of the declared length that hold other bytes are // refused here, not recorded with the declared size. if measured != size { let _ = tokio::fs::remove_file(&path).await; return Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()); } let recorded = i64::try_from(measured).map_err(|_| CoreError::Invalid("too_large".into()))?; // The bytes are durable at their key before the row that names them commits (architecture 3). let file_id = new_id(); let key = files_blob_key(&file_id); if let Err(error) = state.blobs.put_file(&key, &path).await { let _ = tokio::fs::remove_file(&path).await; return Err(error.into()); } let new = NewFile { id: file_id, owner: viewer.member.sub.clone(), folder: upload.folder_id.clone(), name: upload.name.clone(), mime: sniff(&prefix), size: recorded, sha256, staged_claims: 0, }; match state .store .finish_upload(&viewer.member.sub, &upload.id, new) .await { Ok(file) => { if let Err(error) = remove_upload_dir(&data_dir, &upload.id).await { tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); } changed(state, &viewer.member.sub); Ok(json_answer(StatusCode::OK, json!({ "file_id": file.id }))) } Err(error) => { // No row names these bytes now, so they go. let _ = state.blobs.delete(&key).await; match error { CoreError::Conflict(word) if word == "quota_exceeded" => { Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()) } CoreError::Conflict(word) if word == "upload_not_active" => { Ok(refuse(StatusCode::CONFLICT, "not_active").answer()) } CoreError::Invalid(word) if word == "size_mismatch" => { Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()) } CoreError::NotFound => Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()), other => Err(other.into()), } } } } /// `DELETE /api/uploads/{id}`: cancels an open upload and removes what it staged. #[route(DELETE "/api/uploads/{id}")] async fn cancel_upload(cx: &Cx) -> Result { let state = app_context::(cx); let viewer = match api_viewer(cx).await? { Ok(viewer) => viewer, Err(refusal) => return Ok(refusal.answer()), }; let id = path_param_segment(cx, "id").to_owned(); let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); }; if !state .store .abort_upload(&viewer.member.sub, &upload.id) .await? { return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); } if let Err(error) = remove_upload_dir(&state.config.data_dir, &upload.id).await { tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); } Ok(json_answer(StatusCode::OK, json!({ "state": "aborted" }))) } #[cfg(test)] mod tests { use super::*; use crate::auth::SESSION_COOKIE; use crate::auth::test_support::signed_in; use crate::boot::{router, test_state}; use http::Request; use http::header::COOKIE; use in_core::quota::DEFAULT_MEMBER_QUOTA; use topcoat::router::{Body, to_bytes}; /// One call to the API as the session `token`, with the CSRF header `csrf` when given. Returns the /// status and the JSON body. async fn call( state: &AppState, method: &str, path: &str, token: &str, csrf: Option<&str>, body: Vec, ) -> (StatusCode, Value) { let mut request = Request::builder() .method(method) .uri(path) .header(COOKIE, format!("{SESSION_COOKIE}={token}")); if let Some(csrf) = csrf { request = request.header(CSRF_HEADER, csrf); } let request = request.body(Body::from(body)).expect("request"); let response = router(state.clone()).handle(request).await; let status = response.status(); let bytes = to_bytes(response.into_body(), 64 * 1024) .await .expect("body"); ( status, serde_json::from_slice(&bytes).unwrap_or(Value::Null), ) } /// Starts an upload of `size` bytes as `ann`, and returns its id. async fn start(state: &AppState, token: &str, size: u64) -> String { let body = json!({ "name": "clip.bin", "size": size }).to_string(); let (status, value) = call( state, "POST", "/api/uploads", token, Some("csrf-ann"), body.into_bytes(), ) .await; assert_eq!(status, StatusCode::CREATED); value["id"].as_str().expect("an id").to_owned() } #[tokio::test] async fn chunk_bounds_are_enforced() { let (_dir, state) = test_state().await; let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let id = start(&state, &token, 10).await; let put = |index: u64| format!("/api/uploads/{id}/{index}"); // One chunk of ten bytes: index 1 does not exist. let (status, value) = call( &state, "PUT", &put(1), &token, Some("csrf-ann"), vec![0; 10], ) .await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(value["error"], "index_out_of_range"); // The last chunk must be exactly the remainder: longer is refused as too large, shorter as bad. let (status, value) = call( &state, "PUT", &put(0), &token, Some("csrf-ann"), vec![0; 11], ) .await; assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); assert_eq!(value["error"], "chunk_too_large"); let (status, value) = call(&state, "PUT", &put(0), &token, Some("csrf-ann"), vec![0; 9]).await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(value["error"], "chunk_length"); } #[tokio::test] async fn a_whole_upload_becomes_a_file_that_can_be_downloaded() { let (_dir, state) = test_state().await; let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let id = start(&state, &token, 10).await; let (status, _) = call( &state, "PUT", &format!("/api/uploads/{id}/0"), &token, Some("csrf-ann"), b"0123456789".to_vec(), ) .await; assert_eq!(status, StatusCode::OK); let (status, value) = call( &state, "POST", &format!("/api/uploads/{id}/finish"), &token, Some("csrf-ann"), Vec::new(), ) .await; assert_eq!(status, StatusCode::OK); let file_id = value["file_id"].as_str().expect("a file id").to_owned(); let request = Request::get(format!("/file/{file_id}?dl=1")) .header(COOKIE, format!("{SESSION_COOKIE}={token}")) .body(Body::empty()) .expect("request"); let response = router(state.clone()).handle(request).await; assert_eq!(response.status(), StatusCode::OK); // The byte policy alone: the page policy must not be added on top of it. let policies: Vec<_> = response .headers() .get_all(http::header::CONTENT_SECURITY_POLICY) .iter() .collect(); assert_eq!(policies, [crate::serve_bytes::BYTES_CSP]); let bytes = to_bytes(response.into_body(), 64 * 1024) .await .expect("body"); assert_eq!(&bytes[..], b"0123456789"); } #[tokio::test] async fn finishing_with_a_missing_chunk_is_a_conflict() { let (_dir, state) = test_state().await; let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; // Two chunks: the first is 8 MiB, so the test sends only the one-byte last chunk. let id = start(&state, &token, CHUNK_BYTES + 1).await; let (status, _) = call( &state, "PUT", &format!("/api/uploads/{id}/1"), &token, Some("csrf-ann"), vec![7], ) .await; assert_eq!(status, StatusCode::OK); let (status, value) = call( &state, "POST", &format!("/api/uploads/{id}/finish"), &token, Some("csrf-ann"), Vec::new(), ) .await; assert_eq!(status, StatusCode::CONFLICT); assert_eq!(value["error"], "chunks_missing"); assert_eq!(value["missing"], json!([0])); } #[tokio::test] async fn another_members_upload_is_not_found_and_a_bad_csrf_token_is_forbidden() { let (_dir, state) = test_state().await; let ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; let id = start(&state, &ann, 10).await; let (status, _) = call( &state, "GET", &format!("/api/uploads/{id}"), &bob, Some("csrf-bob"), Vec::new(), ) .await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, _) = call( &state, "PUT", &format!("/api/uploads/{id}/0"), &bob, Some("csrf-bob"), vec![0; 10], ) .await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, _) = call( &state, "POST", &format!("/api/uploads/{id}/finish"), &bob, Some("csrf-bob"), Vec::new(), ) .await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, _) = call( &state, "DELETE", &format!("/api/uploads/{id}"), &bob, Some("csrf-bob"), Vec::new(), ) .await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, value) = call( &state, "GET", &format!("/api/uploads/{id}"), &ann, Some("csrf-wrong"), Vec::new(), ) .await; assert_eq!(status, StatusCode::FORBIDDEN); assert_eq!(value["error"], "csrf"); let (status, _) = call( &state, "GET", &format!("/api/uploads/{id}"), &ann, None, Vec::new(), ) .await; assert_eq!(status, StatusCode::FORBIDDEN); } }