api_files.rs
| 1 | //! File API: listing, download/preview/content, editor save, mutations, |
| 2 | //! upload, access control and path-safety. |
| 3 | |
| 4 | mod common; |
| 5 | |
| 6 | use axum::http::StatusCode; |
| 7 | use common::*; |
| 8 | use serde_json::json; |
| 9 | |
| 10 | /// Root id for the whole-root (".") user root is 1 (first row inserted). |
| 11 | const ROOT: i64 = 1; |
| 12 | |
| 13 | fn 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] |
| 24 | async 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] |
| 56 | async 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] |
| 96 | async 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] |
| 124 | async 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] |
| 145 | async 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] |
| 200 | async 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] |
| 223 | async 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] |
| 246 | async 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] |
| 270 | async 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] |
| 288 | async 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] |
| 351 | async 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: `api_types::Op` has no such variant, so the body fails to |
| 425 | // deserialize. `dispatch_inner` parses it itself, so this stays a 400. |
| 426 | let r = admin |
| 427 | .post_json(&root_path("notes.md"), &json!({ "op": "explode" })) |
| 428 | .await; |
| 429 | assert_eq!(r.status, StatusCode::BAD_REQUEST); |
| 430 | } |
| 431 | |
| 432 | #[tokio::test] |
| 433 | async fn move_and_copy_across_dirs() { |
| 434 | let env = Env::new().await; |
| 435 | let admin = env.admin().await; |
| 436 | |
| 437 | // Move notes.md into docs/. |
| 438 | let r = admin |
| 439 | .post_json( |
| 440 | &root_path("notes.md"), |
| 441 | &json!({ "op": "move", "dst_root_id": ROOT, "dst": "docs" }), |
| 442 | ) |
| 443 | .await; |
| 444 | assert_eq!(r.status, StatusCode::OK); |
| 445 | assert!(!env.file("notes.md").exists()); |
| 446 | assert_eq!( |
| 447 | std::fs::read(env.file("docs/notes.md")).unwrap(), |
| 448 | b"# notes" |
| 449 | ); |
| 450 | |
| 451 | // Copy docs/inner back out — as a folder. |
| 452 | let r = admin |
| 453 | .post_json( |
| 454 | &root_path("docs/inner"), |
| 455 | &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }), |
| 456 | ) |
| 457 | .await; |
| 458 | assert_eq!(r.status, StatusCode::OK); |
| 459 | assert_eq!( |
| 460 | std::fs::read(env.file("src/inner/hello.txt")).unwrap(), |
| 461 | b"hello world" |
| 462 | ); |
| 463 | assert!(env.file("docs/inner/hello.txt").exists()); |
| 464 | |
| 465 | // Conflict without overwrite, ok with: copy into a folder that already |
| 466 | // holds a file with the same name. |
| 467 | let r = admin |
| 468 | .post_json( |
| 469 | &root_path("docs/a.txt"), |
| 470 | &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }), |
| 471 | ) |
| 472 | .await; |
| 473 | assert_eq!(r.status, StatusCode::OK); |
| 474 | assert_eq!(std::fs::read(env.file("src/a.txt")).unwrap(), b"file a"); |
| 475 | std::fs::write(env.file("docs/a.txt"), "file a2").unwrap(); |
| 476 | let r = admin |
| 477 | .post_json( |
| 478 | &root_path("docs/a.txt"), |
| 479 | &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src" }), |
| 480 | ) |
| 481 | .await; |
| 482 | assert_eq!(r.status, StatusCode::CONFLICT); |
| 483 | let r = admin |
| 484 | .post_json( |
| 485 | &root_path("docs/a.txt"), |
| 486 | &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "src", "overwrite": true }), |
| 487 | ) |
| 488 | .await; |
| 489 | assert_eq!(r.status, StatusCode::OK); |
| 490 | assert_eq!(std::fs::read(env.file("src/a.txt")).unwrap(), b"file a2"); |
| 491 | |
| 492 | // Copying an item into its own folder (same path) is a no-op success. |
| 493 | let r = admin |
| 494 | .post_json( |
| 495 | &root_path("docs/a.txt"), |
| 496 | &json!({ "op": "copy", "dst_root_id": ROOT, "dst": "docs" }), |
| 497 | ) |
| 498 | .await; |
| 499 | assert_eq!(r.status, StatusCode::OK); |
| 500 | |
| 501 | // Moving a folder into itself → 400. |
| 502 | let r = admin |
| 503 | .post_json( |
| 504 | &root_path("docs"), |
| 505 | &json!({ "op": "move", "dst_root_id": ROOT, "dst": "docs" }), |
| 506 | ) |
| 507 | .await; |
| 508 | assert_eq!(r.status, StatusCode::BAD_REQUEST); |
| 509 | |
| 510 | // Missing dst_root_id / dst dir. |
| 511 | let r = admin |
| 512 | .post_json(&root_path("docs/a.txt"), &json!({ "op": "move" })) |
| 513 | .await; |
| 514 | assert_eq!(r.status, StatusCode::BAD_REQUEST); |
| 515 | let r = admin |
| 516 | .post_json( |
| 517 | &root_path("docs/a.txt"), |
| 518 | &json!({ "op": "move", "dst_root_id": ROOT, "dst": "no-such-dir" }), |
| 519 | ) |
| 520 | .await; |
| 521 | assert_eq!(r.status, StatusCode::NOT_FOUND); |
| 522 | } |
| 523 | |
| 524 | #[tokio::test] |
| 525 | async fn delete_file_and_folder() { |
| 526 | let env = Env::new().await; |
| 527 | let admin = env.admin().await; |
| 528 | |
| 529 | let r = admin.delete(&root_path("editme.txt")).await; |
| 530 | assert_eq!(r.status, StatusCode::OK); |
| 531 | assert_eq!(r.json()["is_dir"], false); |
| 532 | assert!(!env.file("editme.txt").exists()); |
| 533 | |
| 534 | let r = admin.delete(&root_path("docs")).await; |
| 535 | assert_eq!(r.json()["is_dir"], true); |
| 536 | assert!(!env.file("docs").exists()); |
| 537 | |
| 538 | // Missing → 404. A DELETE on the bare root matches no route's method → |
| 539 | // 405 (the path only has GET/POST routes). |
| 540 | assert_eq!( |
| 541 | admin.delete(&root_path("ghost")).await.status, |
| 542 | StatusCode::NOT_FOUND |
| 543 | ); |
| 544 | assert_eq!( |
| 545 | admin.delete("/api/files/1").await.status, |
| 546 | StatusCode::METHOD_NOT_ALLOWED |
| 547 | ); |
| 548 | // DELETE with a trailing-slash root matches no route at all → 404 via |
| 549 | // the SPA fallback's API guard. |
| 550 | let r = admin.delete("/api/files/1/").await; |
| 551 | assert_eq!(r.status, StatusCode::NOT_FOUND); |
| 552 | assert_eq!(r.text(), "unknown endpoint"); |
| 553 | } |
| 554 | |
| 555 | #[tokio::test] |
| 556 | async fn upload_creates_files_and_folders() { |
| 557 | let env = Env::new().await; |
| 558 | let admin = env.admin().await; |
| 559 | |
| 560 | // Single file into the root, nested part name creates the folder. |
| 561 | let r = admin |
| 562 | .post_multipart( |
| 563 | &root_path(""), |
| 564 | &[("docs/uploaded.txt", b"up1"), ("new/nested.txt", b"up2")], |
| 565 | "", |
| 566 | ) |
| 567 | .await; |
| 568 | assert_eq!(r.status, StatusCode::OK); |
| 569 | assert_eq!(r.json()["uploaded"], 2); |
| 570 | assert_eq!( |
| 571 | std::fs::read(env.file("docs/uploaded.txt")).unwrap(), |
| 572 | b"up1" |
| 573 | ); |
| 574 | assert_eq!(std::fs::read(env.file("new/nested.txt")).unwrap(), b"up2"); |
| 575 | |
| 576 | // Conflict: existing file, no overwrite → 409 with the skipped list. |
| 577 | let r = admin |
| 578 | .post_multipart(&root_path(""), &[("docs/uploaded.txt", b"again")], "") |
| 579 | .await; |
| 580 | assert_eq!(r.status, StatusCode::CONFLICT); |
| 581 | assert_eq!(r.json()["skipped"], json!(["docs/uploaded.txt"])); |
| 582 | assert_eq!( |
| 583 | std::fs::read(env.file("docs/uploaded.txt")).unwrap(), |
| 584 | b"up1" |
| 585 | ); |
| 586 | |
| 587 | // Mixed: one conflict + one new file → 409, the new one is uploaded. |
| 588 | let r = admin |
| 589 | .post_multipart( |
| 590 | &root_path(""), |
| 591 | &[("docs/uploaded.txt", b"again"), ("fresh.txt", b"new")], |
| 592 | "", |
| 593 | ) |
| 594 | .await; |
| 595 | assert_eq!(r.status, StatusCode::CONFLICT); |
| 596 | assert_eq!(r.json()["skipped"], json!(["docs/uploaded.txt"])); |
| 597 | assert_eq!(r.json()["uploaded"], 1); |
| 598 | assert_eq!(std::fs::read(env.file("fresh.txt")).unwrap(), b"new"); |
| 599 | |
| 600 | // overwrite=true replaces. |
| 601 | let r = admin |
| 602 | .post_multipart( |
| 603 | &root_path(""), |
| 604 | &[("docs/uploaded.txt", b"v3")], |
| 605 | "overwrite=true", |
| 606 | ) |
| 607 | .await; |
| 608 | assert_eq!(r.status, StatusCode::OK); |
| 609 | assert_eq!(std::fs::read(env.file("docs/uploaded.txt")).unwrap(), b"v3"); |
| 610 | |
| 611 | // A part name that is an existing directory → 409. |
| 612 | let r = admin |
| 613 | .post_multipart(&root_path(""), &[("new", b"dir?")], "") |
| 614 | .await; |
| 615 | assert_eq!(r.status, StatusCode::CONFLICT); |
| 616 | |
| 617 | // Path traversal in a part name → 400. |
| 618 | let r = admin |
| 619 | .post_multipart(&root_path(""), &[("../evil.txt", b"x")], "") |
| 620 | .await; |
| 621 | assert!(matches!( |
| 622 | r.status, |
| 623 | StatusCode::BAD_REQUEST | StatusCode::FORBIDDEN |
| 624 | )); |
| 625 | assert!(!env.file("../evil.txt").exists()); |
| 626 | assert!(!env.root.path().parent().unwrap().join("evil.txt").exists()); |
| 627 | |
| 628 | // No parts at all → 400. |
| 629 | let (ct, body) = multipart_body(&[], "b"); |
| 630 | let r = admin |
| 631 | .raw( |
| 632 | axum::http::Method::POST, |
| 633 | &root_path(""), |
| 634 | &[("content-type", &ct)], |
| 635 | body, |
| 636 | ) |
| 637 | .await; |
| 638 | assert_eq!(r.status, StatusCode::BAD_REQUEST); |
| 639 | } |
| 640 | |
| 641 | #[tokio::test] |
| 642 | async fn read_only_root_blocks_writes_but_allows_reads() { |
| 643 | let env = Env::new().await; |
| 644 | let admin = env.admin().await; |
| 645 | create_user(&admin, "carol", "carolpass1", &[("docs", "ro")]).await; |
| 646 | let carol = login(&env, "carol", "carolpass1").await; |
| 647 | let carol_root_id = carol.get("/api/auth/me").await.json()["roots"][0]["id"] |
| 648 | .as_i64() |
| 649 | .unwrap(); |
| 650 | |
| 651 | // Reads work. |
| 652 | let r = carol.get(&format!("/api/files/{carol_root_id}")).await; |
| 653 | assert_eq!(r.status, StatusCode::OK); |
| 654 | assert!(!r.json()["entries"].as_array().unwrap().is_empty()); |
| 655 | let r = carol |
| 656 | .get(&format!("/api/files/{carol_root_id}/a.txt?action=download")) |
| 657 | .await; |
| 658 | assert_eq!(r.body, b"file a"); |
| 659 | |
| 660 | // Writes are blocked. |
| 661 | let base = format!("/api/files/{carol_root_id}/x"); |
| 662 | assert_eq!( |
| 663 | carol |
| 664 | .raw(axum::http::Method::POST, &base, &[], Vec::new()) |
| 665 | .await |
| 666 | .status, |
| 667 | StatusCode::FORBIDDEN |
| 668 | ); |
| 669 | assert_eq!( |
| 670 | carol |
| 671 | .delete(&format!("/api/files/{carol_root_id}/a.txt")) |
| 672 | .await |
| 673 | .status, |
| 674 | StatusCode::FORBIDDEN |
| 675 | ); |
| 676 | assert_eq!( |
| 677 | carol |
| 678 | .post_json( |
| 679 | &format!("/api/files/{carol_root_id}/a.txt"), |
| 680 | &json!({ "op": "rename", "new_name": "b.txt" }) |
| 681 | ) |
| 682 | .await |
| 683 | .status, |
| 684 | StatusCode::FORBIDDEN |
| 685 | ); |
| 686 | } |
| 687 | |
| 688 | #[tokio::test] |
| 689 | async fn user_cannot_touch_foreign_root() { |
| 690 | let env = Env::new().await; |
| 691 | let admin = env.admin().await; |
| 692 | create_user(&admin, "dave", "davepass12", &[("src", "rw")]).await; |
| 693 | let dave = login(&env, "dave", "davepass12").await; |
| 694 | let dave_root_id = dave.get("/api/auth/me").await.json()["roots"][0]["id"] |
| 695 | .as_i64() |
| 696 | .unwrap(); |
| 697 | |
| 698 | // His own root works. |
| 699 | assert_eq!( |
| 700 | dave.get(&format!("/api/files/{dave_root_id}")).await.status, |
| 701 | StatusCode::OK |
| 702 | ); |
| 703 | // The admin's root id (1) is not his → 403. |
| 704 | assert_eq!(dave.get("/api/files/1").await.status, StatusCode::FORBIDDEN); |
| 705 | // Writing into a root he doesn't have → 403. |
| 706 | assert_eq!( |
| 707 | dave.raw( |
| 708 | axum::http::Method::POST, |
| 709 | "/api/files/1/evil", |
| 710 | &[], |
| 711 | Vec::new() |
| 712 | ) |
| 713 | .await |
| 714 | .status, |
| 715 | StatusCode::FORBIDDEN |
| 716 | ); |
| 717 | } |
| 718 | |
| 719 | /// Listings report a content-sniffed `kind`, not an extension guess. |
| 720 | #[tokio::test] |
| 721 | async fn listing_reports_sniffed_kinds() { |
| 722 | let env = Env::new().await; |
| 723 | let admin = env.admin().await; |
| 724 | // A PNG named .txt and a text file named .png: the bytes must win. |
| 725 | std::fs::write( |
| 726 | env.file("lies.txt"), |
| 727 | [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A], |
| 728 | ) |
| 729 | .unwrap(); |
| 730 | std::fs::write(env.file("lies.png"), "just words\n").unwrap(); |
| 731 | std::fs::write(env.file("report.html"), "<!doctype html><p>hi").unwrap(); |
| 732 | std::fs::write(env.file("noext"), "plain text, no extension\n").unwrap(); |
| 733 | |
| 734 | let r = admin.get(&root_path("")).await; |
| 735 | assert_eq!(r.status, StatusCode::OK); |
| 736 | let j = r.json(); |
| 737 | let kind = |name: &str| -> String { |
| 738 | j["entries"] |
| 739 | .as_array() |
| 740 | .unwrap() |
| 741 | .iter() |
| 742 | .find(|e| e["name"] == name) |
| 743 | .unwrap_or_else(|| panic!("{name} missing from listing"))["kind"] |
| 744 | .as_str() |
| 745 | .unwrap() |
| 746 | .to_string() |
| 747 | }; |
| 748 | assert_eq!(kind("lies.txt"), "image"); |
| 749 | assert_eq!(kind("lies.png"), "text"); |
| 750 | assert_eq!(kind("report.html"), "text"); |
| 751 | assert_eq!(kind("noext"), "text"); |
| 752 | assert_eq!(kind("blob.bin"), "binary"); |
| 753 | assert_eq!(kind("docs"), "dir"); |
| 754 | assert_eq!(kind("config.json"), "text"); |
| 755 | } |
| 756 | |
| 757 | /// A file the browser would parse as a document is served sandboxed, so it can |
| 758 | /// render as a page without being able to act as the app. Everything else |
| 759 | /// keeps the app policy. |
| 760 | #[tokio::test] |
| 761 | async fn scriptable_files_are_served_sandboxed() { |
| 762 | let env = Env::new().await; |
| 763 | let admin = env.admin().await; |
| 764 | std::fs::write(env.file("page.html"), "<!doctype html><p>hi").unwrap(); |
| 765 | std::fs::write( |
| 766 | env.file("logo.svg"), |
| 767 | "<svg xmlns=\"http://www.w3.org/2000/svg\"/>", |
| 768 | ) |
| 769 | .unwrap(); |
| 770 | |
| 771 | for name in ["page.html", "logo.svg"] { |
| 772 | let r = admin |
| 773 | .get(&format!("{}?action=preview", root_path(name))) |
| 774 | .await; |
| 775 | assert_eq!(r.status, StatusCode::OK); |
| 776 | let csp = r.header("content-security-policy").unwrap(); |
| 777 | assert!(csp.contains("sandbox "), "{name} not sandboxed: {csp}"); |
| 778 | assert!(csp.contains("allow-scripts"), "{name}: {csp}"); |
| 779 | // The whole security property: an opaque origin. |
| 780 | assert!( |
| 781 | !csp.contains("allow-same-origin"), |
| 782 | "{name} must never get allow-same-origin: {csp}" |
| 783 | ); |
| 784 | assert!( |
| 785 | !csp.contains("allow-top-navigation ") && !csp.contains("allow-popups-to-escape"), |
| 786 | "{name}: {csp}" |
| 787 | ); |
| 788 | // Still rendered as a document, not downloaded. |
| 789 | assert!( |
| 790 | r.header("content-disposition") |
| 791 | .unwrap() |
| 792 | .starts_with("inline") |
| 793 | ); |
| 794 | } |
| 795 | |
| 796 | // A non-scriptable file keeps the app policy (no sandbox at all). |
| 797 | let r = admin |
| 798 | .get(&format!("{}?action=preview", root_path("blob.bin"))) |
| 799 | .await; |
| 800 | let csp = r.header("content-security-policy").unwrap(); |
| 801 | assert!(!csp.contains("sandbox"), "{csp}"); |
| 802 | assert!( |
| 803 | csp.contains("wasm-unsafe-eval"), |
| 804 | "expected app policy: {csp}" |
| 805 | ); |
| 806 | |
| 807 | // And the app's own pages are untouched by the `if_not_present` switch. |
| 808 | let r = admin.get("/").await; |
| 809 | let csp = r.header("content-security-policy").unwrap(); |
| 810 | assert!( |
| 811 | csp.contains("wasm-unsafe-eval") && !csp.contains("sandbox"), |
| 812 | "{csp}" |
| 813 | ); |
| 814 | } |
| 815 | |
| 816 | #[tokio::test] |
| 817 | async fn archive_does_not_follow_symlinks_out_of_the_root() { |
| 818 | let env = Env::new().await; |
| 819 | let admin = env.admin().await; |
| 820 | |
| 821 | // A directory outside the served root, linked to from inside it. |
| 822 | let outside = tempfile::tempdir().unwrap(); |
| 823 | std::fs::write(outside.path().join("secret.txt"), "leaked").unwrap(); |
| 824 | std::os::unix::fs::symlink(outside.path(), env.file("docs/link")).unwrap(); |
| 825 | |
| 826 | let r = admin |
| 827 | .get(&format!("{}?action=download&format=tar", root_path("docs"))) |
| 828 | .await; |
| 829 | assert_eq!(r.status, StatusCode::OK); |
| 830 | let map = tar_map(&r.body, Compress::None); |
| 831 | assert!( |
| 832 | !map.keys().any(|k| k.contains("secret.txt")), |
| 833 | "archive escaped the root: {:?}", |
| 834 | map.keys().collect::<Vec<_>>() |
| 835 | ); |
| 836 | // The legitimate entries are still there. |
| 837 | assert_eq!(map.get("docs/a.txt").unwrap(), b"file a"); |
| 838 | assert_eq!(map.get("docs/inner/hello.txt").unwrap(), b"hello world"); |
| 839 | } |
| 840 |