forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

upload.rs736 lines, 27.4 KiBHistoryRawDownload
1//! The chunked upload API (architecture 4.2). A file is sent in chunks of 8 MiB, each to its own URL, and
2//! the server joins them when the client finishes. Every route needs the session cookie and the
3//! `X-CSRF-Token` header; a missing or wrong token is `403`, a missing session is `401`, both as JSON.
4//!
5//! The routes:
6//! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is
7//! reserved against the quota in the same transaction that creates the row, so two creates cannot
8//! together promise more than the headroom. A person may hold 64 open uploads; the next one is `429`
9//! `too_many_uploads`.
10//! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk
11//! indexes on disk. A client that lost its connection asks this, then sends only what is missing.
12//! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the
13//! upload, and the body must be exactly the length that chunk has: `chunk_size` for every chunk but the
14//! last, which is the remainder. A longer body is `413` and a shorter one `400`; the bytes are read with a
15//! hard limit, so a client cannot make the server store more than the declared size. Sending a chunk that
16//! is already there replaces it with the same bytes.
17//! - `POST /api/uploads/{id}/finish` joins the chunks into a blob, inserts the file row and marks the upload
18//! done → `{file_id}`. Missing chunks are `409` with their indexes. The quota is checked again in the
19//! insert transaction, against the other open uploads.
20//! - `DELETE /api/uploads/{id}` cancels an open upload and removes its staging directory.
21//!
22//! An upload that is not finished within 24 hours of its last chunk expires; the sweeper removes it.
23//! Another member's upload id is `404`, the same as a missing one.
24
25use std::path::Path;
26
27use futures_util::StreamExt;
28use http::header::{CACHE_CONTROL, CONTENT_TYPE};
29use http::{HeaderValue, StatusCode};
30use in_core::error::Error as CoreError;
31use in_core::names::upload_name;
32use in_core::sniff::sniff;
33use in_core::staging::{
34 CHUNK_BYTES, Staged, StagedFile, chunk_count, chunk_path, expected_chunk_len,
35 remove_upload_dir, upload_dir,
36};
37use in_core::store::files::{NewFile, files_blob_key};
38use in_core::store::new_id;
39use in_core::store::uploads::{NewUpload, Upload};
40use in_core::time::{now_stamp, stamp_after};
41use serde::Deserialize;
42use serde_json::{Value, json};
43use tokio::io::AsyncReadExt;
44use topcoat::Result;
45use topcoat::context::{Cx, app_context};
46use topcoat::router::request::headers;
47use topcoat::router::response::Response;
48use topcoat::router::{Body, path_param_segment, route, to_bytes};
49
50use crate::auth::{Viewer, csrf_matches, current_member};
51use crate::pages::drive::{changed, optional_folder};
52use crate::state::AppState;
53
54/// The header that carries the session's CSRF token.
55const CSRF_HEADER: &str = "x-csrf-token";
56
57/// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count.
58pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
59
60/// Largest body the create route reads. Its JSON is a few hundred bytes.
61const CREATE_BODY_LIMIT: usize = 4096;
62
63/// How many bytes a chunk is copied with when the chunks are joined.
64const COPY_BUFFER: usize = 64 * 1024;
65
66/// How many leading bytes of the file the sniffer reads.
67const SNIFF_BYTES: usize = 8192;
68
69/// A refused call: the status and the fixed word the client gets as `{"error": word}`.
70#[derive(Debug, Clone, Copy)]
71struct Refusal {
72 status: StatusCode,
73 word: &'static str,
74}
75
76impl Refusal {
77 /// The JSON answer of this refusal.
78 fn answer(self) -> Response {
79 json_answer(self.status, json!({ "error": self.word }))
80 }
81}
82
83/// Shorthand for a [`Refusal`].
84const fn refuse(status: StatusCode, word: &'static str) -> Refusal {
85 Refusal { status, word }
86}
87
88/// A JSON response with the given status. Upload answers are never cached.
89fn json_answer(status: StatusCode, value: Value) -> Response {
90 let body = serde_json::to_vec(&value).unwrap_or_default();
91 http::Response::builder()
92 .status(status)
93 .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
94 .header(CACHE_CONTROL, HeaderValue::from_static("no-store"))
95 .body(Body::from(body))
96 .unwrap_or_else(|_| http::Response::new(Body::empty()))
97}
98
99/// The signed-in viewer, when the request carries the session cookie and a matching CSRF header. The
100/// outer `Result` is a server failure; the inner one is the refusal to send.
101async fn api_viewer(cx: &Cx) -> Result<std::result::Result<Viewer, Refusal>> {
102 let Some(viewer) = current_member(cx).await? else {
103 return Ok(Err(refuse(StatusCode::UNAUTHORIZED, "signed_out")));
104 };
105 let submitted = headers(cx)
106 .get(CSRF_HEADER)
107 .and_then(|value| value.to_str().ok())
108 .unwrap_or("");
109 if !csrf_matches(&viewer.session, submitted) {
110 return Ok(Err(refuse(StatusCode::FORBIDDEN, "csrf")));
111 }
112 Ok(Ok(viewer))
113}
114
115/// The viewer's upload by id, which must still be open. Another member's or a missing id is `404`; an
116/// upload that already finished or was cancelled is `409`; one past its expiry is `410`.
117async fn open_upload(
118 state: &AppState,
119 viewer: &Viewer,
120 id: &str,
121) -> Result<std::result::Result<Upload, Refusal>> {
122 let Some(upload) = state.store.upload(&viewer.member.sub, id).await? else {
123 return Ok(Err(refuse(StatusCode::NOT_FOUND, "not_found")));
124 };
125 if upload.state != "active" {
126 return Ok(Err(refuse(StatusCode::CONFLICT, "not_active")));
127 }
128 if !upload.is_open(&now_stamp()) {
129 return Ok(Err(refuse(StatusCode::GONE, "expired")));
130 }
131 Ok(Ok(upload))
132}
133
134/// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored.
135pub async fn max_upload_bytes(state: &AppState) -> Result<i64> {
136 let resolved = in_core::settings::resolve(
137 &state.store,
138 &state.config.limits,
139 in_core::settings::MAX_UPLOAD_KEY,
140 )
141 .await?;
142 Ok(resolved.value.max(1))
143}
144
145/// The indexes of the chunks that are on disk. A missing directory has none.
146async fn received_chunks(dir: &Path) -> Result<Vec<u64>> {
147 let mut found = Vec::new();
148 let mut entries = match tokio::fs::read_dir(dir).await {
149 Ok(entries) => entries,
150 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(found),
151 Err(error) => return Err(CoreError::from(error).into()),
152 };
153 while let Some(entry) = entries.next_entry().await.map_err(CoreError::from)? {
154 // Chunk files are named by their index. Temporary files have ULID names, which never parse.
155 if let Some(index) = entry
156 .file_name()
157 .to_str()
158 .and_then(|n| n.parse::<u64>().ok())
159 {
160 found.push(index);
161 }
162 }
163 found.sort_unstable();
164 Ok(found)
165}
166
167/// The body of `POST /api/uploads`.
168#[derive(Debug, Deserialize)]
169struct CreateRequest {
170 /// Destination folder, or absent for the top level.
171 #[serde(default)]
172 folder_id: Option<String>,
173 /// The file name as the client has it. It is cleaned, not refused.
174 name: String,
175 /// Declared size in bytes.
176 size: u64,
177}
178
179/// `POST /api/uploads`: starts an upload.
180#[route(POST "/api/uploads")]
181async fn create_upload(cx: &Cx, body: Body) -> Result<Response> {
182 let state = app_context::<AppState>(cx);
183 let viewer = match api_viewer(cx).await? {
184 Ok(viewer) => viewer,
185 Err(refusal) => return Ok(refusal.answer()),
186 };
187 let Ok(bytes) = to_bytes(body, CREATE_BODY_LIMIT).await else {
188 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer());
189 };
190 let Ok(request) = serde_json::from_slice::<CreateRequest>(&bytes) else {
191 return Ok(refuse(StatusCode::BAD_REQUEST, "bad_request").answer());
192 };
193 let Ok(size) = i64::try_from(request.size) else {
194 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer());
195 };
196 let folder =
197 optional_folder(state, &viewer, request.folder_id.as_deref().unwrap_or("")).await?;
198 let max = max_upload_bytes(state).await?;
199 let id = new_id();
200 let new = NewUpload {
201 id: id.clone(),
202 owner: viewer.member.sub.clone(),
203 folder,
204 name: upload_name(&request.name),
205 size,
206 chunk_size: i64::try_from(CHUNK_BYTES).unwrap_or(i64::MAX),
207 expires_at: stamp_after(UPLOAD_TTL),
208 };
209 let upload = match state.store.create_upload(new, max).await {
210 Ok(upload) => upload,
211 Err(CoreError::Invalid(word)) if word == "too_large" => {
212 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer());
213 }
214 Err(CoreError::Conflict(word)) if word == "quota_exceeded" => {
215 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer());
216 }
217 Err(CoreError::Conflict(word)) if word == "too_many_uploads" => {
218 return Ok(refuse(StatusCode::TOO_MANY_REQUESTS, "too_many_uploads").answer());
219 }
220 Err(error) => return Err(error.into()),
221 };
222 // The directory is made after the row commits. A crash in between leaves a row with no directory, which
223 // the sweeper expires; the other order could leave a directory no row names.
224 let dir = upload_dir(&state.config.data_dir, &upload.id)?;
225 tokio::fs::DirBuilder::new()
226 .recursive(true)
227 .mode(0o700)
228 .create(&dir)
229 .await
230 .map_err(CoreError::from)?;
231 Ok(json_answer(
232 StatusCode::CREATED,
233 json!({ "id": upload.id, "chunk_size": CHUNK_BYTES }),
234 ))
235}
236
237/// `GET /api/uploads/{id}`: the state of an upload and the chunks it has.
238#[route(GET "/api/uploads/{id}")]
239async fn upload_status(cx: &Cx) -> Result<Response> {
240 let state = app_context::<AppState>(cx);
241 let viewer = match api_viewer(cx).await? {
242 Ok(viewer) => viewer,
243 Err(refusal) => return Ok(refusal.answer()),
244 };
245 let id = path_param_segment(cx, "id").to_owned();
246 let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else {
247 return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer());
248 };
249 let dir = upload_dir(&state.config.data_dir, &upload.id)?;
250 let received = received_chunks(&dir).await?;
251 let word = if upload.state == "active" && !upload.is_open(&now_stamp()) {
252 "expired"
253 } else {
254 upload.state.as_str()
255 };
256 Ok(json_answer(
257 StatusCode::OK,
258 json!({
259 "id": upload.id,
260 "state": word,
261 "size": upload.size,
262 "chunk_size": upload.chunk_size,
263 "received": received,
264 }),
265 ))
266}
267
268/// `PUT /api/uploads/{id}/{index}`: stores one chunk.
269#[route(PUT "/api/uploads/{id}/{index}")]
270async fn put_chunk(cx: &Cx, body: Body) -> Result<Response> {
271 let state = app_context::<AppState>(cx);
272 let viewer = match api_viewer(cx).await? {
273 Ok(viewer) => viewer,
274 Err(refusal) => return Ok(refusal.answer()),
275 };
276 let id = path_param_segment(cx, "id").to_owned();
277 let raw_index = path_param_segment(cx, "index").to_owned();
278 let upload = match open_upload(state, &viewer, &id).await? {
279 Ok(upload) => upload,
280 Err(refusal) => return Ok(refusal.answer()),
281 };
282 let Ok(index) = raw_index.parse::<u64>() else {
283 return Ok(refuse(StatusCode::BAD_REQUEST, "bad_index").answer());
284 };
285 let (size, chunk) = (upload.size as u64, upload.chunk_size as u64);
286 let Some(expected) = expected_chunk_len(size, chunk, index) else {
287 return Ok(refuse(StatusCode::BAD_REQUEST, "index_out_of_range").answer());
288 };
289 let dir = upload_dir(&state.config.data_dir, &upload.id)?;
290 // The bytes go to a temporary file in the staging directory, which is then renamed onto the index. A
291 // reader sees either the old chunk or the new one, never a partial write.
292 let mut staged = match StagedFile::create_in(&dir, expected).await {
293 Ok(staged) => staged,
294 Err(CoreError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
295 return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer());
296 }
297 Err(error) => return Err(error.into()),
298 };
299 let mut frames = body.into_data_stream();
300 let mut received: u64 = 0;
301 while let Some(frame) = frames.next().await {
302 let Ok(bytes) = frame else {
303 staged.abort().await;
304 return Ok(refuse(StatusCode::BAD_REQUEST, "body_read").answer());
305 };
306 let len = bytes.len() as u64;
307 if received + len > expected {
308 staged.abort().await;
309 return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "chunk_too_large").answer());
310 }
311 if let Err(error) = staged.write(&bytes).await {
312 staged.abort().await;
313 return Err(error.into());
314 }
315 received += len;
316 }
317 if received != expected {
318 staged.abort().await;
319 return Ok(refuse(StatusCode::BAD_REQUEST, "chunk_length").answer());
320 }
321 let Staged { path, .. } = staged.finish().await?;
322 let target = chunk_path(&dir, index);
323 if let Err(error) = tokio::fs::rename(&path, &target).await {
324 let _ = tokio::fs::remove_file(&path).await;
325 return Err(CoreError::from(error).into());
326 }
327 // The rename is durable only once the directory entry is: fsync the directory, as the blob store does.
328 tokio::fs::File::open(&dir)
329 .await
330 .map_err(CoreError::from)?
331 .sync_all()
332 .await
333 .map_err(CoreError::from)?;
334 if !state
335 .store
336 .touch_upload(&viewer.member.sub, &upload.id, &stamp_after(UPLOAD_TTL))
337 .await?
338 {
339 // The upload was finished or cancelled after the check above. Its directory is removed by that
340 // request or by the sweeper, so this chunk does not outlive it.
341 return Ok(refuse(StatusCode::CONFLICT, "not_active").answer());
342 }
343 Ok(json_answer(StatusCode::OK, json!({ "index": index })))
344}
345
346/// Joins the chunks of `dir` into `staged`, in index order, and keeps the first bytes for the sniffer.
347async fn join_chunks(
348 dir: &Path,
349 count: u64,
350 staged: &mut StagedFile,
351 prefix: &mut Vec<u8>,
352) -> std::result::Result<(), CoreError> {
353 let mut buffer = vec![0u8; COPY_BUFFER];
354 for index in 0..count {
355 let mut part = tokio::fs::File::open(chunk_path(dir, index)).await?;
356 loop {
357 let read = part.read(&mut buffer).await?;
358 if read == 0 {
359 break;
360 }
361 if prefix.len() < SNIFF_BYTES {
362 let take = (SNIFF_BYTES - prefix.len()).min(read);
363 prefix.extend_from_slice(&buffer[..take]);
364 }
365 staged.write(&buffer[..read]).await?;
366 }
367 }
368 Ok(())
369}
370
371/// `POST /api/uploads/{id}/finish`: joins the chunks into the file.
372#[route(POST "/api/uploads/{id}/finish")]
373async fn finish_upload(cx: &Cx) -> Result<Response> {
374 let state = app_context::<AppState>(cx);
375 let viewer = match api_viewer(cx).await? {
376 Ok(viewer) => viewer,
377 Err(refusal) => return Ok(refusal.answer()),
378 };
379 let id = path_param_segment(cx, "id").to_owned();
380 let upload = match open_upload(state, &viewer, &id).await? {
381 Ok(upload) => upload,
382 Err(refusal) => return Ok(refusal.answer()),
383 };
384 let data_dir = state.config.data_dir.clone();
385 let dir = upload_dir(&data_dir, &upload.id)?;
386 let (size, chunk) = (upload.size as u64, upload.chunk_size as u64);
387 let count = chunk_count(size, chunk);
388 let received = received_chunks(&dir).await?;
389 let missing: Vec<u64> = (0..count)
390 .filter(|index| received.binary_search(index).is_err())
391 .collect();
392 if !missing.is_empty() {
393 return Ok(json_answer(
394 StatusCode::CONFLICT,
395 json!({ "error": "chunks_missing", "missing": missing }),
396 ));
397 }
398
399 let mut staged = StagedFile::create(&data_dir, size).await?;
400 let mut prefix = Vec::with_capacity(SNIFF_BYTES);
401 if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await {
402 staged.abort().await;
403 // A concurrent finish of this upload may have removed the chunks already. That is a conflict.
404 if matches!(&error, CoreError::Io(e) if e.kind() == std::io::ErrorKind::NotFound) {
405 return Ok(refuse(StatusCode::CONFLICT, "not_active").answer());
406 }
407 return Err(error.into());
408 }
409 let Staged {
410 path,
411 sha256,
412 size: measured,
413 } = staged.finish().await?;
414 // The row records the bytes that were joined. Chunks of the declared length that hold other bytes are
415 // refused here, not recorded with the declared size.
416 if measured != size {
417 let _ = tokio::fs::remove_file(&path).await;
418 return Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer());
419 }
420 let recorded = i64::try_from(measured).map_err(|_| CoreError::Invalid("too_large".into()))?;
421
422 // The bytes are durable at their key before the row that names them commits (architecture 3).
423 let file_id = new_id();
424 let key = files_blob_key(&file_id);
425 if let Err(error) = state.blobs.put_file(&key, &path).await {
426 let _ = tokio::fs::remove_file(&path).await;
427 return Err(error.into());
428 }
429 let new = NewFile {
430 id: file_id,
431 owner: viewer.member.sub.clone(),
432 folder: upload.folder_id.clone(),
433 name: upload.name.clone(),
434 mime: sniff(&prefix),
435 size: recorded,
436 sha256,
437 staged_claims: 0,
438 };
439 match state
440 .store
441 .finish_upload(&viewer.member.sub, &upload.id, new)
442 .await
443 {
444 Ok(file) => {
445 if let Err(error) = remove_upload_dir(&data_dir, &upload.id).await {
446 tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed");
447 }
448 changed(state, &viewer.member.sub);
449 Ok(json_answer(StatusCode::OK, json!({ "file_id": file.id })))
450 }
451 Err(error) => {
452 // No row names these bytes now, so they go.
453 let _ = state.blobs.delete(&key).await;
454 match error {
455 CoreError::Conflict(word) if word == "quota_exceeded" => {
456 Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer())
457 }
458 CoreError::Conflict(word) if word == "upload_not_active" => {
459 Ok(refuse(StatusCode::CONFLICT, "not_active").answer())
460 }
461 CoreError::Invalid(word) if word == "size_mismatch" => {
462 Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer())
463 }
464 CoreError::NotFound => Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()),
465 other => Err(other.into()),
466 }
467 }
468 }
469}
470
471/// `DELETE /api/uploads/{id}`: cancels an open upload and removes what it staged.
472#[route(DELETE "/api/uploads/{id}")]
473async fn cancel_upload(cx: &Cx) -> Result<Response> {
474 let state = app_context::<AppState>(cx);
475 let viewer = match api_viewer(cx).await? {
476 Ok(viewer) => viewer,
477 Err(refusal) => return Ok(refusal.answer()),
478 };
479 let id = path_param_segment(cx, "id").to_owned();
480 let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else {
481 return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer());
482 };
483 if !state
484 .store
485 .abort_upload(&viewer.member.sub, &upload.id)
486 .await?
487 {
488 return Ok(refuse(StatusCode::CONFLICT, "not_active").answer());
489 }
490 if let Err(error) = remove_upload_dir(&state.config.data_dir, &upload.id).await {
491 tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed");
492 }
493 Ok(json_answer(StatusCode::OK, json!({ "state": "aborted" })))
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499 use crate::auth::SESSION_COOKIE;
500 use crate::auth::test_support::signed_in;
501 use crate::boot::{router, test_state};
502 use http::Request;
503 use http::header::COOKIE;
504 use in_core::quota::DEFAULT_MEMBER_QUOTA;
505 use topcoat::router::{Body, to_bytes};
506
507 /// One call to the API as the session `token`, with the CSRF header `csrf` when given. Returns the
508 /// status and the JSON body.
509 async fn call(
510 state: &AppState,
511 method: &str,
512 path: &str,
513 token: &str,
514 csrf: Option<&str>,
515 body: Vec<u8>,
516 ) -> (StatusCode, Value) {
517 let mut request = Request::builder()
518 .method(method)
519 .uri(path)
520 .header(COOKIE, format!("{SESSION_COOKIE}={token}"));
521 if let Some(csrf) = csrf {
522 request = request.header(CSRF_HEADER, csrf);
523 }
524 let request = request.body(Body::from(body)).expect("request");
525 let response = router(state.clone()).handle(request).await;
526 let status = response.status();
527 let bytes = to_bytes(response.into_body(), 64 * 1024)
528 .await
529 .expect("body");
530 (
531 status,
532 serde_json::from_slice(&bytes).unwrap_or(Value::Null),
533 )
534 }
535
536 /// Starts an upload of `size` bytes as `ann`, and returns its id.
537 async fn start(state: &AppState, token: &str, size: u64) -> String {
538 let body = json!({ "name": "clip.bin", "size": size }).to_string();
539 let (status, value) = call(
540 state,
541 "POST",
542 "/api/uploads",
543 token,
544 Some("csrf-ann"),
545 body.into_bytes(),
546 )
547 .await;
548 assert_eq!(status, StatusCode::CREATED);
549 value["id"].as_str().expect("an id").to_owned()
550 }
551
552 #[tokio::test]
553 async fn chunk_bounds_are_enforced() {
554 let (_dir, state) = test_state().await;
555 let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
556 let id = start(&state, &token, 10).await;
557 let put = |index: u64| format!("/api/uploads/{id}/{index}");
558
559 // One chunk of ten bytes: index 1 does not exist.
560 let (status, value) = call(
561 &state,
562 "PUT",
563 &put(1),
564 &token,
565 Some("csrf-ann"),
566 vec![0; 10],
567 )
568 .await;
569 assert_eq!(status, StatusCode::BAD_REQUEST);
570 assert_eq!(value["error"], "index_out_of_range");
571
572 // The last chunk must be exactly the remainder: longer is refused as too large, shorter as bad.
573 let (status, value) = call(
574 &state,
575 "PUT",
576 &put(0),
577 &token,
578 Some("csrf-ann"),
579 vec![0; 11],
580 )
581 .await;
582 assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
583 assert_eq!(value["error"], "chunk_too_large");
584 let (status, value) =
585 call(&state, "PUT", &put(0), &token, Some("csrf-ann"), vec![0; 9]).await;
586 assert_eq!(status, StatusCode::BAD_REQUEST);
587 assert_eq!(value["error"], "chunk_length");
588 }
589
590 #[tokio::test]
591 async fn a_whole_upload_becomes_a_file_that_can_be_downloaded() {
592 let (_dir, state) = test_state().await;
593 let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
594 let id = start(&state, &token, 10).await;
595 let (status, _) = call(
596 &state,
597 "PUT",
598 &format!("/api/uploads/{id}/0"),
599 &token,
600 Some("csrf-ann"),
601 b"0123456789".to_vec(),
602 )
603 .await;
604 assert_eq!(status, StatusCode::OK);
605 let (status, value) = call(
606 &state,
607 "POST",
608 &format!("/api/uploads/{id}/finish"),
609 &token,
610 Some("csrf-ann"),
611 Vec::new(),
612 )
613 .await;
614 assert_eq!(status, StatusCode::OK);
615 let file_id = value["file_id"].as_str().expect("a file id").to_owned();
616
617 let request = Request::get(format!("/file/{file_id}?dl=1"))
618 .header(COOKIE, format!("{SESSION_COOKIE}={token}"))
619 .body(Body::empty())
620 .expect("request");
621 let response = router(state.clone()).handle(request).await;
622 assert_eq!(response.status(), StatusCode::OK);
623 // The byte policy alone: the page policy must not be added on top of it.
624 let policies: Vec<_> = response
625 .headers()
626 .get_all(http::header::CONTENT_SECURITY_POLICY)
627 .iter()
628 .collect();
629 assert_eq!(policies, [crate::serve_bytes::BYTES_CSP]);
630 let bytes = to_bytes(response.into_body(), 64 * 1024)
631 .await
632 .expect("body");
633 assert_eq!(&bytes[..], b"0123456789");
634 }
635
636 #[tokio::test]
637 async fn finishing_with_a_missing_chunk_is_a_conflict() {
638 let (_dir, state) = test_state().await;
639 let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
640 // Two chunks: the first is 8 MiB, so the test sends only the one-byte last chunk.
641 let id = start(&state, &token, CHUNK_BYTES + 1).await;
642 let (status, _) = call(
643 &state,
644 "PUT",
645 &format!("/api/uploads/{id}/1"),
646 &token,
647 Some("csrf-ann"),
648 vec![7],
649 )
650 .await;
651 assert_eq!(status, StatusCode::OK);
652 let (status, value) = call(
653 &state,
654 "POST",
655 &format!("/api/uploads/{id}/finish"),
656 &token,
657 Some("csrf-ann"),
658 Vec::new(),
659 )
660 .await;
661 assert_eq!(status, StatusCode::CONFLICT);
662 assert_eq!(value["error"], "chunks_missing");
663 assert_eq!(value["missing"], json!([0]));
664 }
665
666 #[tokio::test]
667 async fn another_members_upload_is_not_found_and_a_bad_csrf_token_is_forbidden() {
668 let (_dir, state) = test_state().await;
669 let ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await;
670 let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await;
671 let id = start(&state, &ann, 10).await;
672
673 let (status, _) = call(
674 &state,
675 "GET",
676 &format!("/api/uploads/{id}"),
677 &bob,
678 Some("csrf-bob"),
679 Vec::new(),
680 )
681 .await;
682 assert_eq!(status, StatusCode::NOT_FOUND);
683 let (status, _) = call(
684 &state,
685 "PUT",
686 &format!("/api/uploads/{id}/0"),
687 &bob,
688 Some("csrf-bob"),
689 vec![0; 10],
690 )
691 .await;
692 assert_eq!(status, StatusCode::NOT_FOUND);
693 let (status, _) = call(
694 &state,
695 "POST",
696 &format!("/api/uploads/{id}/finish"),
697 &bob,
698 Some("csrf-bob"),
699 Vec::new(),
700 )
701 .await;
702 assert_eq!(status, StatusCode::NOT_FOUND);
703 let (status, _) = call(
704 &state,
705 "DELETE",
706 &format!("/api/uploads/{id}"),
707 &bob,
708 Some("csrf-bob"),
709 Vec::new(),
710 )
711 .await;
712 assert_eq!(status, StatusCode::NOT_FOUND);
713
714 let (status, value) = call(
715 &state,
716 "GET",
717 &format!("/api/uploads/{id}"),
718 &ann,
719 Some("csrf-wrong"),
720 Vec::new(),
721 )
722 .await;
723 assert_eq!(status, StatusCode::FORBIDDEN);
724 assert_eq!(value["error"], "csrf");
725 let (status, _) = call(
726 &state,
727 "GET",
728 &format!("/api/uploads/{id}"),
729 &ann,
730 None,
731 Vec::new(),
732 )
733 .await;
734 assert_eq!(status, StatusCode::FORBIDDEN);
735 }
736}