api_files.rs
⎇
Raw
1//! File API: listing, download/preview/content, editor save, mutations,
2//! upload, access control and path-safety.
3
4mod common;
5
6use axum::http::StatusCode;
7use common::*;
8use serde_json::json;
9
10/// Root id for the whole-root (".") user root is 1 (first row inserted).
11const ROOT: i64 = 1;
12
13fn root_path(rel: &str) -> String {
14 // No trailing slash for the bare root: axum's routes are
15 // `/api/files/{root_id}` and `/api/files/{root_id}/{*path}`.
16 if rel.is_empty() {
17 format!("/api/files/{ROOT}")
18 } else {
19 format!("/api/files/{ROOT}/{rel}")
20 }
21}
22
23#[tokio::test]
24async fn list_root_sorted_folders_first() {
25 let env = Env::new().await;
26 let admin = env.admin().await;
27 let r = admin.get(&root_path("")).await;
28 assert_eq!(r.status, StatusCode::OK);
29 let j = r.json();
30 let entries = j["entries"].as_array().unwrap();
31 let names: Vec<&str> = entries
32 .iter()
33 .map(|e| e["name"].as_str().unwrap())
34 .collect();
35 assert_eq!(
36 names,
37 vec![
38 "docs",
39 "src",
40 "blob.bin",
41 "config.json",
42 "editme.txt",
43 "notes.md"
44 ]
45 );
46 // Entry fields.
47 let docs = &entries[0];
48 assert_eq!(docs["is_dir"], true);
49 let editme = entries.iter().find(|e| e["name"] == "editme.txt").unwrap();
50 assert_eq!(editme["is_dir"], false);
51 assert_eq!(editme["size"], 2);
52 assert!(editme["mtime"].as_str().unwrap().ends_with('Z'));
53}
54
55#[tokio::test]
56async fn list_subdir_and_errors() {
57 let env = Env::new().await;
58 let admin = env.admin().await;
59
60 let r = admin.get(&root_path("docs")).await;
61 let j = r.json();
62 let names: Vec<&str> = j
63 .get("entries")
64 .unwrap()
65 .as_array()
66 .unwrap()
67 .iter()
68 .map(|e| e["name"].as_str().unwrap())
69 .collect();
70 assert_eq!(names, vec!["inner", "a.txt"]);
71
72 // Missing path → 404.
73 assert_eq!(
74 admin.get(&root_path("nope")).await.status,
75 StatusCode::NOT_FOUND
76 );
77 // Listing a file → 400.
78 assert_eq!(
79 admin.get(&root_path("editme.txt")).await.status,
80 StatusCode::BAD_REQUEST
81 );
82 // Unknown root id → 403.
83 assert_eq!(
84 admin.get("/api/files/999").await.status,
85 StatusCode::FORBIDDEN
86 );
87 // No session → 401.
88 let anon = Client::new(env.app.clone());
89 assert_eq!(
90 anon.get(&root_path("")).await.status,
91 StatusCode::UNAUTHORIZED
92 );
93}
94
95#[tokio::test]
96async fn path_traversal_is_blocked() {
97 let env = Env::new().await;
98 let admin = env.admin().await;
99
100 // Encoded `..` segments reach the handler and are rejected.
101 let r = admin.get("/api/files/1/%2e%2e%2f%2e%2e%2fetc").await;
102 assert!(
103 r.status == StatusCode::FORBIDDEN || r.status == StatusCode::NOT_FOUND,
104 "traversal returned {:?}",
105 r.status
106 );
107 // Literal `..` segments: must never succeed.
108 let r = admin.get("/api/files/1/../../etc").await;
109 assert_ne!(
110 r.status,
111 StatusCode::OK,
112 "literal traversal must not be served"
113 );
114 // Traversal inside a deeper path.
115 let r = admin.get("/api/files/1/docs/..%2f..%2fsrc").await;
116 assert!(
117 r.status == StatusCode::FORBIDDEN || r.status == StatusCode::NOT_FOUND,
118 "deep traversal returned {:?}",
119 r.status
120 );
121}
122
123#[tokio::test]
124async fn download_single_file() {
125 let env = Env::new().await;
126 let admin = env.admin().await;
127 let r = admin
128 .get(&format!("{}?action=download", root_path("editme.txt")))
129 .await;
130 assert_eq!(r.status, StatusCode::OK);
131 assert_eq!(
132 r.header("content-disposition").as_deref(),
133 Some("attachment; filename=\"editme.txt\"")
134 );
135 assert_eq!(r.header("content-type").as_deref(), Some("text/plain"));
136 assert_eq!(r.body, b"v1");
137 // Binary content survives.
138 let r = admin
139 .get(&format!("{}?action=download", root_path("blob.bin")))
140 .await;
141 assert_eq!(r.body, (0..64u8).collect::<Vec<_>>());
142}
143
144#[tokio::test]
145async fn download_folder_as_all_archive_formats() {
146 let env = Env::new().await;
147 let admin = env.admin().await;
148 let path = format!("{}?action=download", root_path("docs"));
149
150 let r = admin.get(&format!("{path}&format=zip")).await;
151 assert_eq!(r.status, StatusCode::OK);
152 assert_eq!(r.header("content-type").as_deref(), Some("application/zip"));
153 assert_eq!(
154 r.header("content-disposition").as_deref(),
155 Some("attachment; filename=\"docs.zip\"")
156 );
157 let map = zip_map(&r.body);
158 assert_eq!(map.get("docs/a.txt").unwrap(), b"file a");
159 assert_eq!(map.get("docs/inner/hello.txt").unwrap(), b"hello world");
160
161 let r = admin.get(&format!("{path}&format=tar")).await;
162 assert_eq!(
163 r.header("content-type").as_deref(),
164 Some("application/x-tar")
165 );
166 assert_eq!(
167 r.header("content-disposition").as_deref(),
168 Some("attachment; filename=\"docs.tar\"")
169 );
170 let map = tar_map(&r.body, Compress::None);
171 assert_eq!(map.get("docs/a.txt").unwrap(), b"file a");
172 assert_eq!(map.get("docs/inner/hello.txt").unwrap(), b"hello world");
173
174 let r = admin.get(&format!("{path}&format=tar.gz")).await;
175 assert_eq!(
176 r.header("content-type").as_deref(),
177 Some("application/gzip")
178 );
179 assert_eq!(
180 r.header("content-disposition").as_deref(),
181 Some("attachment; filename=\"docs.tar.gz\"")
182 );
183 let map = tar_map(&r.body, Compress::Gz);
184 assert_eq!(map.get("docs/inner/hello.txt").unwrap(), b"hello world");
185
186 let r = admin.get(&format!("{path}&format=tar.zst")).await;
187 assert_eq!(
188 r.header("content-type").as_deref(),
189 Some("application/zstd")
190 );
191 assert_eq!(
192 r.header("content-disposition").as_deref(),
193 Some("attachment; filename=\"docs.tar.zst\"")
194 );
195 let map = tar_map(&r.body, Compress::Zst);
196 assert_eq!(map.get("docs/a.txt").unwrap(), b"file a");
197}
198
199#[tokio::test]
200async fn download_folder_requires_valid_format() {
201 let env = Env::new().await;
202 let admin = env.admin().await;
203 let path = format!("{}?action=download", root_path("docs"));
204 // No format → 400.
205 assert_eq!(admin.get(&path).await.status, StatusCode::BAD_REQUEST);
206 // Unknown format → 400.
207 assert_eq!(
208 admin.get(&format!("{path}&format=rar")).await.status,
209 StatusCode::BAD_REQUEST
210 );
211 // Downloading a file with a format is fine (format ignored).
212 let r = admin
213 .get(&format!(
214 "{}?action=download&format=zip",
215 root_path("editme.txt")
216 ))
217 .await;
218 assert_eq!(r.status, StatusCode::OK);
219 assert_eq!(r.body, b"v1");
220}
221
222#[tokio::test]
223async fn preview_serves_inline_and_rejects_dirs() {
224 let env = Env::new().await;
225 let admin = env.admin().await;
226 let r = admin
227 .get(&format!("{}?action=preview", root_path("config.json")))
228 .await;
229 assert_eq!(r.status, StatusCode::OK);
230 assert!(
231 r.header("content-disposition")
232 .unwrap()
233 .starts_with("inline;")
234 );
235 assert_eq!(r.body, b"{\"k\": 1}");
236 assert_eq!(
237 admin
238 .get(&format!("{}?action=preview", root_path("docs")))
239 .await
240 .status,
241 StatusCode::BAD_REQUEST
242 );
243}
244
245#[tokio::test]
246async fn content_action_serves_raw_bytes_with_mtime() {
247 let env = Env::new().await;
248 let admin = env.admin().await;
249 let r = admin
250 .get(&format!("{}?action=content", root_path("notes.md")))
251 .await;
252 assert_eq!(r.status, StatusCode::OK);
253 assert_eq!(
254 r.header("content-type").as_deref(),
255 Some("text/plain; charset=utf-8")
256 );
257 let mtime = r.header("x-file-mtime").unwrap();
258 assert!(mtime.parse::<i64>().is_ok());
259 assert_eq!(r.body, b"# notes");
260 assert_eq!(
261 admin
262 .get(&format!("{}?action=content", root_path("docs")))
263 .await
264 .status,
265 StatusCode::BAD_REQUEST
266 );
267}
268
269#[tokio::test]
270async fn content_is_capped_at_two_mibibytes() {
271 let env = Env::new().await;
272 let admin = env.admin().await;
273 let big = vec![b'x'; 2 * 1024 * 1024 + 1];
274 std::fs::write(env.file("big.bin"), &big).unwrap();
275 let r = admin
276 .get(&format!("{}?action=content", root_path("big.bin")))
277 .await;
278 assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE);
279 // The file itself still downloads fine.
280 let r = admin
281 .get(&format!("{}?action=download", root_path("big.bin")))
282 .await;
283 assert_eq!(r.status, StatusCode::OK);
284 assert_eq!(r.body.len(), big.len());
285}
286
287#[tokio::test]
288async fn editor_save_round_trip_and_conflict() {
289 let env = Env::new().await;
290 let admin = env.admin().await;
291 let path = format!("{}?action=content", root_path("editme.txt"));
292
293 // Read current mtime via the content endpoint.
294 let r = admin.get(&path).await;
295 assert_eq!(r.status, StatusCode::OK);
296 let mtime: i64 = r.header("x-file-mtime").unwrap().parse().unwrap();
297
298 // Save with a matching expected mtime.
299 let r = admin.put_content(&path, b"v2", Some(mtime)).await;
300 assert_eq!(r.status, StatusCode::OK);
301 let new_mtime = r.json()["mtime"].as_i64().unwrap();
302 assert!(new_mtime >= mtime);
303 assert_eq!(std::fs::read(env.file("editme.txt")).unwrap(), b"v2");
304
305 // A stale/wrong expected mtime conflicts (409). Use a value far from the
306 // current mtime so this is deterministic regardless of the filesystem's
307 // timestamp granularity (the mtime may not have advanced after the save).
308 let r = admin.put_content(&path, b"v3", Some(mtime + 999_999)).await;
309 assert_eq!(r.status, StatusCode::CONFLICT);
310 // A conflict must not modify the file.
311 assert_eq!(std::fs::read(env.file("editme.txt")).unwrap(), b"v2");
312
313 // No expected mtime → force save.
314 let r = admin.put_content(&path, b"v4", None).await;
315 assert_eq!(r.status, StatusCode::OK);
316 assert_eq!(std::fs::read(env.file("editme.txt")).unwrap(), b"v4");
317
318 // Saving a missing file → 404; a directory → 400.
319 // (PUT without action=content → 400.)
320 let r = admin
321 .raw(
322 axum::http::Method::PUT,
323 &root_path("editme.txt"),
324 &[("content-type", "text/plain")],
325 b"x".to_vec(),
326 )
327 .await;
328 assert_eq!(r.status, StatusCode::BAD_REQUEST);
329
330 let r = admin
331 .put_content(
332 &format!("{}?action=content", root_path("ghost.txt")),
333 b"x",
334 None,
335 )
336 .await;
337 assert_eq!(r.status, StatusCode::NOT_FOUND);
338 let r = admin
339 .put_content(&format!("{}?action=content", root_path("docs")), b"x", None)
340 .await;
341 assert_eq!(r.status, StatusCode::BAD_REQUEST);
342
343 // Oversized body → 413.
344 let r = admin
345 .put_content(&path, &vec![b'a'; 2 * 1024 * 1024 + 1], None)
346 .await;
347 assert_eq!(r.status, StatusCode::PAYLOAD_TOO_LARGE);
348}
349
350#[tokio::test]
351async fn mkdir_and_rename() {
352 let env = Env::new().await;
353 let admin = env.admin().await;
354
355 // mkdir (no content-type → mkdir dispatch).
356 let r = admin
357 .raw(
358 axum::http::Method::POST,
359 &root_path("newdir"),
360 &[],
361 Vec::new(),
362 )
363 .await;
364 assert_eq!(r.status, StatusCode::OK);
365 assert!(env.file("newdir").is_dir());
366 // Duplicate → 409.
367 let r = admin
368 .raw(
369 axum::http::Method::POST,
370 &root_path("newdir"),
371 &[],
372 Vec::new(),
373 )
374 .await;
375 assert_eq!(r.status, StatusCode::CONFLICT);
376 // Empty name → 400 (bare root POST with JSON op is rejected too).
377 let r = admin
378 .raw(axum::http::Method::POST, &root_path(""), &[], Vec::new())
379 .await;
380 assert_eq!(r.status, StatusCode::BAD_REQUEST);
381
382 // Rename.
383 let r = admin
384 .post_json(
385 &root_path("editme.txt"),
386 &json!({ "op": "rename", "new_name": "renamed.txt" }),
387 )
388 .await;
389 assert_eq!(r.status, StatusCode::OK);
390 assert!(env.file("renamed.txt").exists());
391 // Conflict.
392 let r = admin
393 .post_json(
394 &root_path("renamed.txt"),
395 &json!({ "op": "rename", "new_name": "config.json" }),
396 )
397 .await;
398 assert_eq!(r.status, StatusCode::CONFLICT);
399 // With overwrite.
400 let r = admin
401 .post_json(
402 &root_path("renamed.txt"),
403 &json!({ "op": "rename", "new_name": "config.json", "overwrite": true }),
404 )
405 .await;
406 assert_eq!(r.status, StatusCode::OK);
407 assert_eq!(std::fs::read(env.file("config.json")).unwrap(), b"v1");
408 // Invalid name.
409 let r = admin
410 .post_json(
411 &root_path("notes.md"),
412 &json!({ "op": "rename", "new_name": "a/b" }),
413 )
414 .await;
415 assert_eq!(r.status, StatusCode::BAD_REQUEST);
416 // Missing source.
417 let r = admin
418 .post_json(
419 &root_path("ghost"),
420 &json!({ "op": "rename", "new_name": "x" }),
421 )
422 .await;
423 assert_eq!(r.status, StatusCode::NOT_FOUND);
424 // Unknown op.
425 let r = admin
426 .post_json(&root_path("notes.md"), &json!({ "op": "explode" }))
427 .await;
428 assert_eq!(r.status, StatusCode::BAD_REQUEST);
429}
430
431#[tokio::test]
432async fn move_and_copy_across_dirs() {
433 let env = Env::new().await;
434 let admin = env.admin().await;
435
436 // Move notes.md into docs/.
437 let r = admin
438 .post_json(
439 &root_path("notes.md"),
440 &json!({ "op": "move", "dst_root_id": ROOT, "dst": "docs" }),
441 )
442 .await;
443 assert_eq!(r.status, StatusCode::OK);
444 assert!(!env.file("notes.md").exists());
445 assert_eq!(
446 std::fs::read(env.file("docs/notes.md")).unwrap(),
447 b"# notes"
448 );
449
450 // Copy docs/inner back out — as a folder.
451 let r = admin
452 .post_json(
453 &root_path("docs/inner"),
454 &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }),
455 )
456 .await;
457 assert_eq!(r.status, StatusCode::OK);
458 assert_eq!(
459 std::fs::read(env.file("src/inner/hello.txt")).unwrap(),
460 b"hello world"
461 );
462 assert!(env.file("docs/inner/hello.txt").exists());
463
464 // Conflict without overwrite, ok with: copy into a folder that already
465 // holds a file with the same name.
466 let r = admin
467 .post_json(
468 &root_path("docs/a.txt"),
469 &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }),
470 )
471 .await;
472 assert_eq!(r.status, StatusCode::OK);
473 assert_eq!(std::fs::read(env.file("src/a.txt")).unwrap(), b"file a");
474 std::fs::write(env.file("docs/a.txt"), "file a2").unwrap();
475 let r = admin
476 .post_json(
477 &root_path("docs/a.txt"),
478 &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }),
479 )
480 .await;
481 assert_eq!(r.status, StatusCode::CONFLICT);
482 let r = admin
483 .post_json(
484 &root_path("docs/a.txt"),
485 &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src", "overwrite": true }),
486 )
487 .await;
488 assert_eq!(r.status, StatusCode::OK);
489 assert_eq!(std::fs::read(env.file("src/a.txt")).unwrap(), b"file a2");
490
491 // Copying an item into its own folder (same path) is a no-op success.
492 let r = admin
493 .post_json(
494 &root_path("docs/a.txt"),
495 &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "docs" }),
496 )
497 .await;
498 assert_eq!(r.status, StatusCode::OK);
499
500 // Moving a folder into itself → 400.
501 let r = admin
502 .post_json(
503 &root_path("docs"),
504 &json!({ "op": "move", "dst_root_id": ROOT, "dst": "docs" }),
505 )
506 .await;
507 assert_eq!(r.status, StatusCode::BAD_REQUEST);
508
509 // Missing dst_root_id / dst dir.
510 let r = admin
511 .post_json(&root_path("docs/a.txt"), &json!({ "op": "move" }))
512 .await;
513 assert_eq!(r.status, StatusCode::BAD_REQUEST);
514 let r = admin
515 .post_json(
516 &root_path("docs/a.txt"),
517 &json!({ "op": "move", "dst_root_id": ROOT, "dst": "no-such-dir" }),
518 )
519 .await;
520 assert_eq!(r.status, StatusCode::NOT_FOUND);
521}
522
523#[tokio::test]
524async fn delete_file_and_folder() {
525 let env = Env::new().await;
526 let admin = env.admin().await;
527
528 let r = admin.delete(&root_path("editme.txt")).await;
529 assert_eq!(r.status, StatusCode::OK);
530 assert_eq!(r.json()["is_dir"], false);
531 assert!(!env.file("editme.txt").exists());
532
533 let r = admin.delete(&root_path("docs")).await;
534 assert_eq!(r.json()["is_dir"], true);
535 assert!(!env.file("docs").exists());
536
537 // Missing → 404. A DELETE on the bare root matches no route's method →
538 // 405 (the path only has GET/POST routes).
539 assert_eq!(
540 admin.delete(&root_path("ghost")).await.status,
541 StatusCode::NOT_FOUND
542 );
543 assert_eq!(
544 admin.delete("/api/files/1").await.status,
545 StatusCode::METHOD_NOT_ALLOWED
546 );
547 // DELETE with a trailing-slash root matches no route at all → 404 via
548 // the SPA fallback's API guard.
549 let r = admin.delete("/api/files/1/").await;
550 assert_eq!(r.status, StatusCode::NOT_FOUND);
551 assert_eq!(r.text(), "unknown endpoint");
552}
553
554#[tokio::test]
555async fn upload_creates_files_and_folders() {
556 let env = Env::new().await;
557 let admin = env.admin().await;
558
559 // Single file into the root, nested part name creates the folder.
560 let r = admin
561 .post_multipart(
562 &root_path(""),
563 &[("docs/uploaded.txt", b"up1"), ("new/nested.txt", b"up2")],
564 "",
565 )
566 .await;
567 assert_eq!(r.status, StatusCode::OK);
568 assert_eq!(r.json()["uploaded"], 2);
569 assert_eq!(
570 std::fs::read(env.file("docs/uploaded.txt")).unwrap(),
571 b"up1"
572 );
573 assert_eq!(std::fs::read(env.file("new/nested.txt")).unwrap(), b"up2");
574
575 // Conflict: existing file, no overwrite → 409 with the skipped list.
576 let r = admin
577 .post_multipart(&root_path(""), &[("docs/uploaded.txt", b"again")], "")
578 .await;
579 assert_eq!(r.status, StatusCode::CONFLICT);
580 assert_eq!(r.json()["skipped"], json!(["docs/uploaded.txt"]));
581 assert_eq!(
582 std::fs::read(env.file("docs/uploaded.txt")).unwrap(),
583 b"up1"
584 );
585
586 // Mixed: one conflict + one new file → 409, the new one is uploaded.
587 let r = admin
588 .post_multipart(
589 &root_path(""),
590 &[("docs/uploaded.txt", b"again"), ("fresh.txt", b"new")],
591 "",
592 )
593 .await;
594 assert_eq!(r.status, StatusCode::CONFLICT);
595 assert_eq!(r.json()["skipped"], json!(["docs/uploaded.txt"]));
596 assert_eq!(r.json()["uploaded"], 1);
597 assert_eq!(std::fs::read(env.file("fresh.txt")).unwrap(), b"new");
598
599 // overwrite=true replaces.
600 let r = admin
601 .post_multipart(
602 &root_path(""),
603 &[("docs/uploaded.txt", b"v3")],
604 "overwrite=true",
605 )
606 .await;
607 assert_eq!(r.status, StatusCode::OK);
608 assert_eq!(std::fs::read(env.file("docs/uploaded.txt")).unwrap(), b"v3");
609
610 // A part name that is an existing directory → 409.
611 let r = admin
612 .post_multipart(&root_path(""), &[("new", b"dir?")], "")
613 .await;
614 assert_eq!(r.status, StatusCode::CONFLICT);
615
616 // Path traversal in a part name → 400.
617 let r = admin
618 .post_multipart(&root_path(""), &[("../evil.txt", b"x")], "")
619 .await;
620 assert!(matches!(
621 r.status,
622 StatusCode::BAD_REQUEST | StatusCode::FORBIDDEN
623 ));
624 assert!(!env.file("../evil.txt").exists());
625 assert!(!env.root.path().parent().unwrap().join("evil.txt").exists());
626
627 // No parts at all → 400.
628 let (ct, body) = multipart_body(&[], "b");
629 let r = admin
630 .raw(
631 axum::http::Method::POST,
632 &root_path(""),
633 &[("content-type", &ct)],
634 body,
635 )
636 .await;
637 assert_eq!(r.status, StatusCode::BAD_REQUEST);
638}
639
640#[tokio::test]
641async fn read_only_root_blocks_writes_but_allows_reads() {
642 let env = Env::new().await;
643 let admin = env.admin().await;
644 create_user(&admin, "carol", "carolpass1", &[("docs", "ro")]).await;
645 let carol = login(&env, "carol", "carolpass1").await;
646 let carol_root_id = carol.get("/api/auth/me").await.json()["roots"][0]["id"]
647 .as_i64()
648 .unwrap();
649
650 // Reads work.
651 let r = carol.get(&format!("/api/files/{carol_root_id}")).await;
652 assert_eq!(r.status, StatusCode::OK);
653 assert!(!r.json()["entries"].as_array().unwrap().is_empty());
654 let r = carol
655 .get(&format!("/api/files/{carol_root_id}/a.txt?action=download"))
656 .await;
657 assert_eq!(r.body, b"file a");
658
659 // Writes are blocked.
660 let base = format!("/api/files/{carol_root_id}/x");
661 assert_eq!(
662 carol
663 .raw(axum::http::Method::POST, &base, &[], Vec::new())
664 .await
665 .status,
666 StatusCode::FORBIDDEN
667 );
668 assert_eq!(
669 carol
670 .delete(&format!("/api/files/{carol_root_id}/a.txt"))
671 .await
672 .status,
673 StatusCode::FORBIDDEN
674 );
675 assert_eq!(
676 carol
677 .post_json(
678 &format!("/api/files/{carol_root_id}/a.txt"),
679 &json!({ "op": "rename", "new_name": "b.txt" })
680 )
681 .await
682 .status,
683 StatusCode::FORBIDDEN
684 );
685}
686
687#[tokio::test]
688async fn user_cannot_touch_foreign_root() {
689 let env = Env::new().await;
690 let admin = env.admin().await;
691 create_user(&admin, "dave", "davepass12", &[("src", "rw")]).await;
692 let dave = login(&env, "dave", "davepass12").await;
693 let dave_root_id = dave.get("/api/auth/me").await.json()["roots"][0]["id"]
694 .as_i64()
695 .unwrap();
696
697 // His own root works.
698 assert_eq!(
699 dave.get(&format!("/api/files/{dave_root_id}")).await.status,
700 StatusCode::OK
701 );
702 // The admin's root id (1) is not his → 403.
703 assert_eq!(dave.get("/api/files/1").await.status, StatusCode::FORBIDDEN);
704 // Writing into a root he doesn't have → 403.
705 assert_eq!(
706 dave.raw(
707 axum::http::Method::POST,
708 "/api/files/1/evil",
709 &[],
710 Vec::new()
711 )
712 .await
713 .status,
714 StatusCode::FORBIDDEN
715 );
716}
717
718/// Listings report a content-sniffed `kind`, not an extension guess.
719#[tokio::test]
720async fn listing_reports_sniffed_kinds() {
721 let env = Env::new().await;
722 let admin = env.admin().await;
723 // A PNG named .txt and a text file named .png: the bytes must win.
724 std::fs::write(
725 env.file("lies.txt"),
726 [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
727 )
728 .unwrap();
729 std::fs::write(env.file("lies.png"), "just words\n").unwrap();
730 std::fs::write(env.file("report.html"), "<!doctype html><p>hi").unwrap();
731 std::fs::write(env.file("noext"), "plain text, no extension\n").unwrap();
732
733 let r = admin.get(&root_path("")).await;
734 assert_eq!(r.status, StatusCode::OK);
735 let j = r.json();
736 let kind = |name: &str| -> String {
737 j["entries"]
738 .as_array()
739 .unwrap()
740 .iter()
741 .find(|e| e["name"] == name)
742 .unwrap_or_else(|| panic!("{name} missing from listing"))["kind"]
743 .as_str()
744 .unwrap()
745 .to_string()
746 };
747 assert_eq!(kind("lies.txt"), "image");
748 assert_eq!(kind("lies.png"), "text");
749 assert_eq!(kind("report.html"), "text");
750 assert_eq!(kind("noext"), "text");
751 assert_eq!(kind("blob.bin"), "binary");
752 assert_eq!(kind("docs"), "dir");
753 assert_eq!(kind("config.json"), "text");
754}
755
756/// A file the browser would parse as a document is served sandboxed, so it can
757/// render as a page without being able to act as the app. Everything else
758/// keeps the app policy.
759#[tokio::test]
760async fn scriptable_files_are_served_sandboxed() {
761 let env = Env::new().await;
762 let admin = env.admin().await;
763 std::fs::write(env.file("page.html"), "<!doctype html><p>hi").unwrap();
764 std::fs::write(
765 env.file("logo.svg"),
766 "<svg xmlns=\"http://www.w3.org/2000/svg\"/>",
767 )
768 .unwrap();
769
770 for name in ["page.html", "logo.svg"] {
771 let r = admin
772 .get(&format!("{}?action=preview", root_path(name)))
773 .await;
774 assert_eq!(r.status, StatusCode::OK);
775 let csp = r.header("content-security-policy").unwrap();
776 assert!(csp.contains("sandbox "), "{name} not sandboxed: {csp}");
777 assert!(csp.contains("allow-scripts"), "{name}: {csp}");
778 // The whole security property: an opaque origin.
779 assert!(
780 !csp.contains("allow-same-origin"),
781 "{name} must never get allow-same-origin: {csp}"
782 );
783 assert!(
784 !csp.contains("allow-top-navigation ") && !csp.contains("allow-popups-to-escape"),
785 "{name}: {csp}"
786 );
787 // Still rendered as a document, not downloaded.
788 assert!(
789 r.header("content-disposition")
790 .unwrap()
791 .starts_with("inline")
792 );
793 }
794
795 // A non-scriptable file keeps the app policy (no sandbox at all).
796 let r = admin
797 .get(&format!("{}?action=preview", root_path("blob.bin")))
798 .await;
799 let csp = r.header("content-security-policy").unwrap();
800 assert!(!csp.contains("sandbox"), "{csp}");
801 assert!(
802 csp.contains("wasm-unsafe-eval"),
803 "expected app policy: {csp}"
804 );
805
806 // And the app's own pages are untouched by the `if_not_present` switch.
807 let r = admin.get("/").await;
808 let csp = r.header("content-security-policy").unwrap();
809 assert!(
810 csp.contains("wasm-unsafe-eval") && !csp.contains("sandbox"),
811 "{csp}"
812 );
813}
814