fs.rs
⎇
Raw
1//! Safe filesystem access: every operation resolves
2//! `<server-root>/<user-root>/<requested-path>`, canonicalizes it and verifies
3//! the result is still inside the user's root (blocks `..` and symlink escapes).
4
5use std::io::Read;
6use std::path::{Component, Path, PathBuf};
7use std::time::UNIX_EPOCH;
8
9use chrono::DateTime;
10
11use api_types::{Entry, FileKind};
12
13use crate::error::ApiError;
14
15#[derive(Debug, thiserror::Error)]
16pub enum FsError {
17 #[error("folder not found")]
18 NotFound,
19 #[error("not a folder")]
20 NotADirectory,
21 #[error("access denied")]
22 Forbidden,
23 #[error("the configured folder no longer exists")]
24 RootMissing,
25 #[error("already exists")]
26 Conflict,
27 #[error("{0}")]
28 Invalid(String),
29}
30
31impl From<FsError> for ApiError {
32 fn from(e: FsError) -> Self {
33 use axum::http::StatusCode as S;
34 match &e {
35 FsError::NotFound => {
36 ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_not_found")
37 }
38 FsError::NotADirectory => {
39 ApiError::localized(S::BAD_REQUEST, e.to_string(), "err_fs_not_a_dir")
40 }
41 FsError::Forbidden => {
42 ApiError::localized(S::FORBIDDEN, e.to_string(), "err_fs_forbidden")
43 }
44 FsError::RootMissing => {
45 ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_root_missing")
46 }
47 FsError::Conflict => ApiError::localized(S::CONFLICT, e.to_string(), "err_fs_conflict"),
48 // Dynamic message (e.g. an invalid name), not a fixed string.
49 FsError::Invalid(_) => ApiError::new(S::BAD_REQUEST, e.to_string()),
50 }
51 }
52}
53
54/// Resolve a user root (path relative to the server root) to a canonical
55/// absolute path, verified to be inside the server root.
56pub fn resolve_root(server_root: &Path, root_rel: &str) -> Result<PathBuf, FsError> {
57 let candidate = server_root.join(root_rel);
58 let canonical = candidate.canonicalize().map_err(|_| FsError::RootMissing)?;
59 ensure_within(server_root, &canonical)?;
60 if !canonical.is_dir() {
61 return Err(FsError::RootMissing);
62 }
63 Ok(canonical)
64}
65
66/// Resolve a requested path (relative to a user root) safely.
67pub fn resolve_path(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
68 let root_abs = resolve_root(server_root, root_rel)?;
69 let req = Path::new(req_rel);
70 for c in req.components() {
71 if matches!(c, Component::ParentDir) {
72 return Err(FsError::Forbidden);
73 }
74 }
75 let full = root_abs.join(req);
76 let full = full.canonicalize().map_err(|e| match e.kind() {
77 std::io::ErrorKind::NotFound => FsError::NotFound,
78 _ => FsError::Forbidden,
79 })?;
80 ensure_within(&root_abs, &full)?;
81 Ok(full)
82}
83
84/// Resolve a share target that is a single file (relative to the server root).
85/// Unlike [`resolve_path`], the target itself is the file — there is no
86/// directory root beneath it.
87pub fn resolve_file(server_root: &Path, rel: &str) -> Result<PathBuf, FsError> {
88 let full = server_root.join(rel);
89 let full = full.canonicalize().map_err(|e| match e.kind() {
90 std::io::ErrorKind::NotFound => FsError::NotFound,
91 _ => FsError::Forbidden,
92 })?;
93 ensure_within(server_root, &full)?;
94 Ok(full)
95}
96
97fn ensure_within(base: &Path, p: &Path) -> Result<(), FsError> {
98 if p == base || p.starts_with(base) {
99 Ok(())
100 } else {
101 Err(FsError::Forbidden)
102 }
103}
104
105/// List a directory (blocking — call via spawn_blocking).
106pub fn list_dir(dir: &Path) -> Result<Vec<Entry>, FsError> {
107 let rd = std::fs::read_dir(dir).map_err(|e| match e.kind() {
108 std::io::ErrorKind::NotFound => FsError::NotFound,
109 std::io::ErrorKind::NotADirectory => FsError::NotADirectory,
110 _ => FsError::Forbidden,
111 })?;
112
113 // Pass 1: names only. Walking the directory stream is inherently
114 // sequential, but it is also the only part that has to be: every field
115 // below comes from a per-entry syscall, which pass 2 can do in parallel.
116 // The values here are the fallbacks used when that syscall fails.
117 let mut rows: Vec<(Entry, PathBuf)> = Vec::new();
118 for e in rd.flatten() {
119 let entry = Entry {
120 name: e.file_name().to_string_lossy().into_owned(),
121 is_dir: false,
122 size: 0,
123 mtime: EPOCH_MTIME.to_string(),
124 kind: FileKind::Binary,
125 };
126 rows.push((entry, e.path()));
127 }
128
129 // Pass 2: the per-entry syscalls — metadata plus the content sniff.
130 describe_rows(&mut rows);
131
132 let mut entries: Vec<Entry> = rows.into_iter().map(|(e, _)| e).collect();
133 // Folders first, then case-insensitive name. Sorting after pass 2 means
134 // the parallel fan-out cannot affect the order.
135 entries.sort_by(|a, b| {
136 b.is_dir
137 .cmp(&a.is_dir)
138 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
139 .then_with(|| a.name.cmp(&b.name))
140 });
141 Ok(entries)
142}
143
144// ---------------------------------------------------------------------------
145// Content sniffing
146// ---------------------------------------------------------------------------
147
148/// How many leading bytes we read to classify a file. Every magic number
149/// `infer` knows lives in the first few dozen bytes; 256 also gives the
150/// text/binary heuristic enough to work with. Measured at ~4.6 µs per file,
151/// against ~1.4 µs for the `metadata` call in the same pass.
152const SNIFF_BYTES: usize = 256;
153
154/// Entries per thread, and the point below which parallelism is not worth it.
155/// Measured on a 22-core machine: at 50 entries fan-out is a wash (thread
156/// spawn costs about as much as the work), at 200 it is already 2x.
157const SNIFF_CHUNK: usize = 256;
158
159/// Process-wide ceiling on threads spawned for sniffing, so many concurrent
160/// listings of large directories cannot multiply into a thread explosion.
161/// One listing alone can use the whole budget; the next one degrades to fewer
162/// threads, and eventually to serial, instead of queueing.
163static SNIFF_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
164
165fn sniff_budget_total() -> usize {
166 static TOTAL: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
167 std::thread::available_parallelism()
168 .map(|n| n.get())
169 .unwrap_or(1)
170 });
171 *TOTAL
172}
173
174/// Claimed helper threads, returned to [`SNIFF_BUDGET`] on drop.
175struct SniffPermit(usize);
176
177impl SniffPermit {
178 /// Claim up to `want` helper threads, or fewer when the budget is thin.
179 fn claim(want: usize) -> Self {
180 use std::sync::atomic::Ordering;
181 let total = sniff_budget_total();
182 let mut granted = 0;
183 let _ = SNIFF_BUDGET.fetch_update(Ordering::AcqRel, Ordering::Acquire, |in_flight| {
184 granted = want.min(total.saturating_sub(in_flight));
185 (granted > 0).then_some(in_flight + granted)
186 });
187 Self(granted)
188 }
189}
190
191impl Drop for SniffPermit {
192 fn drop(&mut self) {
193 if self.0 > 0 {
194 SNIFF_BUDGET.fetch_sub(self.0, std::sync::atomic::Ordering::AcqRel);
195 }
196 }
197}
198
199/// Fill in each row from its own syscalls — `metadata` and the content sniff —
200/// fanning them out across threads for big directories.
201///
202/// The calling thread takes a chunk too, so `n` helper threads process `n + 1`
203/// chunks and a zero-thread grant is simply the serial path.
204fn describe_rows(rows: &mut [(Entry, PathBuf)]) {
205 fn describe(rows: &mut [(Entry, PathBuf)]) {
206 for (entry, path) in rows {
207 // Follows symlinks; a broken link keeps the caller's fallbacks and
208 // so shows up as an empty file.
209 if let Ok(m) = std::fs::metadata(&path) {
210 entry.is_dir = m.is_dir();
211 entry.size = m.len();
212 entry.mtime = mtime_str(&m);
213 }
214 entry.kind = detect_kind(path, entry.is_dir);
215 }
216 }
217
218 if rows.len() < SNIFF_CHUNK {
219 describe(rows);
220 return;
221 }
222 // One chunk per helper thread plus one for this thread.
223 let want = rows.len().div_ceil(SNIFF_CHUNK).saturating_sub(1);
224 let permit = SniffPermit::claim(want);
225 if permit.0 == 0 {
226 describe(rows);
227 return;
228 }
229 let chunk = rows.len().div_ceil(permit.0 + 1);
230 std::thread::scope(|s| {
231 let mut rest = rows;
232 // Hand every chunk but the last to a helper thread.
233 while rest.len() > chunk {
234 let (head, tail) = rest.split_at_mut(chunk);
235 s.spawn(|| describe(head));
236 rest = tail;
237 }
238 describe(rest);
239 });
240}
241
242/// Classify a directory entry by reading its first [`SNIFF_BYTES`] bytes.
243///
244/// Blocking — called from `list_dir` (itself under `spawn_blocking`), on
245/// several threads at once for large directories. An unreadable file is
246/// reported as [`FileKind::Binary`] rather than failing the whole listing.
247///
248// ponytail: one open() per entry, fanned out but not cached. Measured warm on
249// 22 cores: 5000 entries take 29 ms serially and 6.9 ms across threads. The
250// remaining ceiling is a cold cache or a network filesystem (NFS/SMB), where
251// each entry costs a round trip. If that shows up: cache by (dev, ino, mtime),
252// or skip the sniff for zero-byte files.
253pub fn detect_kind(path: &Path, is_dir: bool) -> FileKind {
254 if is_dir {
255 return FileKind::Dir;
256 }
257 let mut head = [0u8; SNIFF_BYTES];
258 // A read error is *not* the same as an empty file: an empty file is text
259 // (it opens in the editor), an unreadable one gets no viewer offered.
260 match std::fs::File::open(path).and_then(|mut f| f.read(&mut head)) {
261 Ok(n) => kind_from_bytes(&head[..n], path),
262 Err(_) => FileKind::Binary,
263 }
264}
265
266/// The pure half of [`detect_kind`], so it can be unit-tested without a disk.
267///
268/// `path` is consulted only for the SVG case: SVG is XML text with no magic
269/// number, but browsers render it as an image, so the extension is the only
270/// thing that can tell us to offer an image preview.
271fn kind_from_bytes(head: &[u8], path: &Path) -> FileKind {
272 if let Some(t) = infer::get(head) {
273 // PDF is filed under `Archive` by `infer`, so match the MIME first.
274 if t.mime_type() == "application/pdf" {
275 return FileKind::Pdf;
276 }
277 return match t.matcher_type() {
278 infer::MatcherType::Image => FileKind::Image,
279 infer::MatcherType::Video => FileKind::Video,
280 infer::MatcherType::Audio => FileKind::Audio,
281 infer::MatcherType::Archive => FileKind::Archive,
282 infer::MatcherType::Text => FileKind::Text,
283 // App / Book / Font / Doc / Custom: recognized, but nothing we
284 // can show in the browser.
285 _ => FileKind::Binary,
286 };
287 }
288 if !looks_like_text(head) {
289 return FileKind::Binary;
290 }
291 let ext = path
292 .extension()
293 .map(|e| e.to_string_lossy().to_lowercase())
294 .unwrap_or_default();
295 if ext == "svg" {
296 FileKind::Image
297 } else {
298 FileKind::Text
299 }
300}
301
302/// Text heuristic for the files `infer` has no signature for (plain text,
303/// source code, most config formats): no NUL byte, and the head decodes as
304/// UTF-8 once a truncated trailing character is discounted.
305///
306/// An empty file counts as text — it opens in the editor, which is what you
307/// want for a file you just created.
308fn looks_like_text(head: &[u8]) -> bool {
309 if head.contains(&0) {
310 return false;
311 }
312 match std::str::from_utf8(head) {
313 Ok(_) => true,
314 // A multi-byte character cut in half by the read boundary is fine;
315 // anything else is not text. `error_len() == None` means "unexpected
316 // end of input", i.e. truncation.
317 Err(e) => e.error_len().is_none() && e.valid_up_to() + 4 > head.len(),
318 }
319}
320
321/// Reported when a file's modification time is unavailable or unrepresentable.
322const EPOCH_MTIME: &str = "1970-01-01T00:00:00Z";
323
324/// A file's modification time in whole unix seconds, or `None` when the
325/// platform cannot report one. The single place that converts a `SystemTime`.
326pub fn mtime_secs(m: &std::fs::Metadata) -> Option<i64> {
327 m.modified()
328 .ok()
329 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
330 .map(|d| d.as_secs() as i64)
331}
332
333fn mtime_str(m: &std::fs::Metadata) -> String {
334 let dt: Option<DateTime<chrono::Utc>> =
335 mtime_secs(m).and_then(|s| DateTime::from_timestamp(s, 0));
336 dt.map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
337 .unwrap_or_else(|| EPOCH_MTIME.to_string())
338}
339
340// ---------------------------------------------------------------------------
341// Mutations (milestone 3): mkdir, rename, remove, move, copy, upload
342// ---------------------------------------------------------------------------
343
344/// Resolve a directory that must exist (relative to a user root). Used as the
345/// base for operations that target the *parent* of the item.
346pub fn resolve_dir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
347 let full = resolve_path(server_root, root_rel, req_rel)?;
348 if !full.is_dir() {
349 return Err(FsError::NotADirectory);
350 }
351 Ok(full)
352}
353
354/// Validate a new single-component name (for rename / new folder).
355fn validate_component(name: &str) -> Result<(), FsError> {
356 let p = Path::new(name);
357 if name.is_empty()
358 || p.components().count() != 1
359 || name == "."
360 || name == ".."
361 || name.contains(['/', '\\', '\0'])
362 {
363 return Err(FsError::Invalid("invalid name".to_string()));
364 }
365 Ok(())
366}
367
368/// Create a directory (and any missing parents) inside a user root.
369pub fn mkdir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
370 let full = resolve_path_or_new(server_root, root_rel, req_rel)?;
371 if full.exists() {
372 return Err(FsError::Conflict);
373 }
374 std::fs::create_dir_all(&full).map_err(|e| io_err(e, &full))?;
375 Ok(())
376}
377
378/// Create an empty file. The parent must exist; the file must not.
379pub fn create_file(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
380 let full = resolve_path_or_new(server_root, root_rel, req_rel)?;
381 // create_new = O_EXCL: fails on an existing path, does not follow a symlink.
382 std::fs::File::create_new(&full).map_err(|e| match e.kind() {
383 std::io::ErrorKind::AlreadyExists => FsError::Conflict,
384 _ => io_err(e, &full),
385 })?;
386 Ok(())
387}
388
389/// Resolve a path that does not need to exist yet, but whose *parent* must.
390fn resolve_path_or_new(
391 server_root: &Path,
392 root_rel: &str,
393 req_rel: &str,
394) -> Result<PathBuf, FsError> {
395 let root_abs = resolve_root(server_root, root_rel)?;
396 let req = Path::new(req_rel);
397 for c in req.components() {
398 if matches!(c, Component::ParentDir) {
399 return Err(FsError::Forbidden);
400 }
401 }
402 let full = root_abs.join(req);
403 // The parent must exist and stay inside the root.
404 let parent = full
405 .parent()
406 .filter(|p| !p.as_os_str().is_empty())
407 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
408 let parent = parent.canonicalize().map_err(|e| io_err(e, parent))?;
409 ensure_within(&root_abs, &parent)?;
410 Ok(full)
411}
412
413/// Rename (or move within the same directory) an item.
414pub fn rename_item(
415 server_root: &Path,
416 root_rel: &str,
417 req_rel: &str,
418 new_name: &str,
419 overwrite: bool,
420) -> Result<(), FsError> {
421 validate_component(new_name)?;
422 let from = resolve_path(server_root, root_rel, req_rel)?;
423 let parent = from
424 .parent()
425 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
426 let to = parent.join(new_name);
427 // Renaming onto itself is a no-op (the overwrite path below would
428 // delete the file before the rename).
429 if to == from {
430 return Ok(());
431 }
432 // `rename` replaces a file target atomically; no remove-then-rename gap.
433 if to.exists() && (!overwrite || to.is_dir() || from.is_dir()) {
434 return Err(FsError::Conflict);
435 }
436 std::fs::rename(&from, &to).map_err(|e| io_err(e, &to))?;
437 Ok(())
438}
439
440/// Delete a file or a directory tree. Returns whether it was a directory.
441pub fn remove_item(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<bool, FsError> {
442 let full = resolve_path(server_root, root_rel, req_rel)?;
443 let is_dir = full.is_dir();
444 if is_dir {
445 std::fs::remove_dir_all(&full).map_err(|e| io_err(e, &full))?;
446 } else {
447 std::fs::remove_file(&full).map_err(|e| io_err(e, &full))?;
448 }
449 Ok(is_dir)
450}
451
452/// Overwrite an existing file's contents (the editor's save path).
453///
454/// The file must already exist and be a regular file. If `expected_mtime`
455/// (whole unix seconds) is provided and differs from the file's current mtime,
456/// the file changed on disk since it was read → `Conflict` (409). Returns the
457/// file's new mtime (unix seconds) after a successful write.
458pub fn save_file(
459 server_root: &Path,
460 root_rel: &str,
461 req_rel: &str,
462 content: &[u8],
463 expected_mtime: Option<i64>,
464) -> Result<i64, FsError> {
465 let full = resolve_path(server_root, root_rel, req_rel)?; // must exist
466 write_checked(&full, content, expected_mtime)
467}
468
469/// The share-aware variant of [`save_file`]: for a *file* share the root is
470/// the file itself, so `target` (relative to `server_root`) points at the
471/// file — there is no directory root beneath it.
472pub fn save_file_at(
473 server_root: &Path,
474 target: &str,
475 content: &[u8],
476 expected_mtime: Option<i64>,
477) -> Result<i64, FsError> {
478 let full = resolve_file(server_root, target)?; // must exist
479 write_checked(&full, content, expected_mtime)
480}
481
482fn write_checked(full: &Path, content: &[u8], expected_mtime: Option<i64>) -> Result<i64, FsError> {
483 let meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
484 if meta.is_dir() {
485 return Err(FsError::NotADirectory);
486 }
487 if let Some(expected) = expected_mtime {
488 // No readable mtime means the check cannot pass: -1 never matches.
489 if mtime_secs(&meta).unwrap_or(-1) != expected {
490 return Err(FsError::Conflict);
491 }
492 }
493 std::fs::write(full, content).map_err(|e| io_err(e, full))?;
494 // Read the new mtime so the client can anchor the next conflict check.
495 let new_meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
496 Ok(mtime_secs(&new_meta).unwrap_or(0))
497}
498
499fn io_err(e: std::io::Error, p: &Path) -> FsError {
500 tracing::warn!(error = %e, path = %p.display(), "filesystem error");
501 match e.kind() {
502 std::io::ErrorKind::NotFound => FsError::NotFound,
503 _ => FsError::Forbidden,
504 }
505}
506
507/// True if `a` is `b` or a descendant of `b` (both canonical).
508pub(crate) fn is_within_or_eq(base: &Path, p: &Path) -> bool {
509 p == base || p.starts_with(base)
510}
511
512/// Move an item (possibly across roots). `dst_dir_rel` is the destination
513/// directory (relative to `dst_root_rel`); the item keeps its base name.
514pub fn move_item(
515 server_root: &Path,
516 src_root_rel: &str,
517 src_rel: &str,
518 dst_root_rel: &str,
519 dst_dir_rel: &str,
520 overwrite: bool,
521) -> Result<(), FsError> {
522 let from = resolve_path(server_root, src_root_rel, src_rel)?;
523 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
524 let name = from
525 .file_name()
526 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
527 .to_owned();
528 let to = dst_dir.join(&name);
529
530 // A no-op (item already at the destination) — treat as success.
531 if to == from {
532 return Ok(());
533 }
534
535 // Refuse moving a directory into itself or a descendant.
536 if from.is_dir() && is_within_or_eq(&from, &dst_dir) {
537 return Err(FsError::Invalid(
538 "cannot move a folder into itself".to_string(),
539 ));
540 }
541 check_move_conflict(&to, &from, overwrite)?;
542
543 match std::fs::rename(&from, &to) {
544 Ok(()) => Ok(()),
545 Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
546 copy_recursive(&from, &to)?;
547 if from.is_dir() {
548 std::fs::remove_dir_all(&from).map_err(|_| FsError::Forbidden)?;
549 } else {
550 std::fs::remove_file(&from).map_err(|_| FsError::Forbidden)?;
551 }
552 Ok(())
553 }
554 Err(e) => Err(io_err(e, &to)),
555 }
556}
557
558/// Copy an item (possibly across roots).
559pub fn copy_item(
560 server_root: &Path,
561 src_root_rel: &str,
562 src_rel: &str,
563 dst_root_rel: &str,
564 dst_dir_rel: &str,
565 overwrite: bool,
566) -> Result<(), FsError> {
567 let from = resolve_path(server_root, src_root_rel, src_rel)?;
568 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
569 let name = from
570 .file_name()
571 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
572 .to_owned();
573 let to = dst_dir.join(&name);
574
575 // A no-op (item already at the destination) — treat as success.
576 if to == from {
577 return Ok(());
578 }
579
580 if from.is_dir() && is_within_or_eq(&from, &dst_dir) {
581 return Err(FsError::Invalid(
582 "cannot copy a folder into itself".to_string(),
583 ));
584 }
585 check_move_conflict(&to, &from, overwrite)?;
586 copy_recursive(&from, &to)?;
587 Ok(())
588}
589
590/// Conflict rules shared by move and copy:
591/// - target is a directory → always conflict (no silent merge)
592/// - target is a file → conflict unless overwriting a file with a file
593fn check_move_conflict(to: &Path, from: &Path, overwrite: bool) -> Result<(), FsError> {
594 if to.exists() {
595 let to_dir = to.is_dir();
596 let from_dir = from.is_dir();
597 if to_dir || from_dir || !overwrite {
598 return Err(FsError::Conflict);
599 }
600 }
601 Ok(())
602}
603
604/// Recursively copy a file or directory tree, preserving mtime.
605fn copy_recursive(src: &Path, dst: &Path) -> Result<(), FsError> {
606 let meta = std::fs::metadata(src).map_err(|e| io_err(e, src))?;
607 if meta.is_dir() {
608 std::fs::create_dir(dst).map_err(|e| io_err(e, dst))?;
609 for e in std::fs::read_dir(src)
610 .map_err(|e| io_err(e, src))?
611 .flatten()
612 {
613 copy_recursive(&e.path(), &dst.join(e.file_name()))?;
614 }
615 } else {
616 std::fs::copy(src, dst).map_err(|e| io_err(e, dst))?;
617 }
618 set_mtime(dst, meta.modified().ok());
619 Ok(())
620}
621
622fn set_mtime(p: &Path, t: Option<std::time::SystemTime>) {
623 if let (Some(t), Ok(f)) = (t, std::fs::File::open(p)) {
624 let _ = f.set_modified(t);
625 }
626}
627
628// ---------------------------------------------------------------------------
629// Tests
630// ---------------------------------------------------------------------------
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 /// A temp dir used as the "server root" with a small fixture tree:
637 ///
638 /// ```text
639 /// root/
640 /// docs/
641 /// inner/
642 /// hello.txt
643 /// a.txt
644 /// src/
645 /// main.rs
646 /// file.txt
647 /// ```
648 struct T {
649 tmp: tempfile::TempDir,
650 root: PathBuf,
651 }
652
653 impl T {
654 fn new() -> Self {
655 let tmp = tempfile::tempdir().unwrap();
656 let root = tmp.path().to_path_buf();
657 std::fs::create_dir_all(root.join("docs/inner")).unwrap();
658 std::fs::create_dir_all(root.join("src")).unwrap();
659 std::fs::write(root.join("docs/inner/hello.txt"), "hello").unwrap();
660 std::fs::write(root.join("docs/a.txt"), "a").unwrap();
661 std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
662 std::fs::write(root.join("file.txt"), "top file").unwrap();
663 Self { tmp, root }
664 }
665
666 /// A directory that lives *next to* the root (outside of it), for
667 /// symlink/escape tests. The tempdir name is unique, so the sibling
668 /// name is unique too.
669 fn sibling(&self, name: &str) -> PathBuf {
670 let base = self
671 .tmp
672 .path()
673 .file_name()
674 .unwrap()
675 .to_string_lossy()
676 .into_owned();
677 let p = self.tmp.path().with_file_name(format!("{base}-{name}"));
678 std::fs::create_dir_all(&p).unwrap();
679 p
680 }
681 }
682
683 // ---------- validate_component ----------
684
685 #[test]
686 fn validate_name_accepts_simple_names() {
687 for ok in ["a", "file.txt", "my folder", "Ünïcödé", "with-dash_1.2.3"] {
688 assert!(validate_component(ok).is_ok(), "{ok:?} should be valid");
689 }
690 }
691
692 #[test]
693 fn validate_name_rejects_traversal_and_paths() {
694 for bad in [
695 "", ".", "..", "a/b", "a\\b", "a\0b", "/abs", "../x", "x/../y", "x/", "/x",
696 ] {
697 assert!(
698 validate_component(bad).is_err(),
699 "{bad:?} should be invalid"
700 );
701 }
702 }
703
704 // ---------- resolve_root ----------
705
706 #[test]
707 fn resolve_root_whole_root_and_subdir() {
708 let t = T::new();
709 let root = t.root.canonicalize().unwrap();
710 // "." means the whole root.
711 assert_eq!(resolve_root(&root, ".").unwrap(), root);
712 assert_eq!(resolve_root(&root, "docs").unwrap(), root.join("docs"));
713 assert_eq!(
714 resolve_root(&root, "docs/inner").unwrap(),
715 root.join("docs/inner")
716 );
717 }
718
719 #[test]
720 fn resolve_root_rejects_escape_and_missing() {
721 let t = T::new();
722 let root = t.root.canonicalize().unwrap();
723 let sib = t.sibling("escape");
724 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
725 // Escapes that land on *existing* paths outside the root.
726 for esc in [
727 "..".to_string(),
728 "docs/../..".to_string(),
729 format!("../{sib_rel}"),
730 ] {
731 assert!(
732 matches!(resolve_root(&root, &esc), Err(FsError::Forbidden)),
733 "{esc:?} should be forbidden"
734 );
735 }
736 // Escapes to non-existing paths simply don't exist.
737 for esc in ["../no-such-dir", "a/b/../../..", "nope"] {
738 assert!(
739 matches!(resolve_root(&root, esc), Err(FsError::RootMissing)),
740 "{esc:?} should be missing"
741 );
742 }
743 // A file is not a valid root.
744 assert!(matches!(
745 resolve_root(&root, "file.txt"),
746 Err(FsError::RootMissing)
747 ));
748 }
749
750 #[cfg(unix)]
751 #[test]
752 fn resolve_root_rejects_symlink_escape() {
753 let t = T::new();
754 let root = t.root.canonicalize().unwrap();
755 let outside = t.sibling("outside");
756 std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
757 assert!(matches!(
758 resolve_root(&root, "link"),
759 Err(FsError::Forbidden)
760 ));
761 }
762
763 // ---------- resolve_path ----------
764
765 #[test]
766 fn resolve_path_traverses_inside_root() {
767 let t = T::new();
768 let root = t.root.canonicalize().unwrap();
769 // Empty relative path → the root itself.
770 assert_eq!(resolve_path(&root, ".", "").unwrap(), root);
771 assert_eq!(
772 resolve_path(&root, "docs", "inner/hello.txt").unwrap(),
773 root.join("docs/inner/hello.txt")
774 );
775 assert_eq!(
776 resolve_path(&root, ".", "file.txt").unwrap(),
777 root.join("file.txt")
778 );
779 }
780
781 #[test]
782 fn resolve_path_rejects_parent_traversal() {
783 let t = T::new();
784 let root = t.root.canonicalize().unwrap();
785 for p in ["..", "../file.txt", "docs/../../file.txt", "a/../../b"] {
786 assert!(
787 matches!(resolve_path(&root, ".", p), Err(FsError::Forbidden)),
788 "{p:?} should be forbidden"
789 );
790 }
791 }
792
793 #[test]
794 fn resolve_path_missing_is_not_found() {
795 let t = T::new();
796 let root = t.root.canonicalize().unwrap();
797 assert!(matches!(
798 resolve_path(&root, "docs", "nope.txt"),
799 Err(FsError::NotFound)
800 ));
801 assert!(matches!(
802 resolve_path(&root, "missing-root", ""),
803 Err(FsError::RootMissing)
804 ));
805 }
806
807 #[cfg(unix)]
808 #[test]
809 fn resolve_path_rejects_symlink_escape() {
810 let t = T::new();
811 let root = t.root.canonicalize().unwrap();
812 let outside = t.sibling("outside");
813 let secret = outside.join("secret.txt");
814 std::fs::write(&secret, "top secret").unwrap();
815 std::os::unix::fs::symlink(&secret, root.join("evil")).unwrap();
816 assert!(matches!(
817 resolve_path(&root, ".", "evil"),
818 Err(FsError::Forbidden)
819 ));
820 // A symlink that stays inside the root is fine.
821 std::os::unix::fs::symlink(root.join("file.txt"), root.join("alias")).unwrap();
822 assert_eq!(
823 resolve_path(&root, ".", "alias").unwrap(),
824 root.join("file.txt")
825 );
826 }
827
828 // ---------- resolve_file / resolve_dir ----------
829
830 #[test]
831 fn resolve_file_targets_files() {
832 let t = T::new();
833 let root = t.root.canonicalize().unwrap();
834 assert_eq!(
835 resolve_file(&root, "file.txt").unwrap(),
836 root.join("file.txt")
837 );
838 assert!(matches!(
839 resolve_file(&root, "nope.txt"),
840 Err(FsError::NotFound)
841 ));
842 // Escape to an existing sibling file.
843 let sib = t.sibling("escape");
844 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
845 std::fs::write(sib.join("s.txt"), "x").unwrap();
846 assert!(matches!(
847 resolve_file(&root, &format!("../{sib_rel}/s.txt")),
848 Err(FsError::Forbidden)
849 ));
850 }
851
852 #[test]
853 fn resolve_dir_requires_existing_directory() {
854 let t = T::new();
855 let root = t.root.canonicalize().unwrap();
856 assert_eq!(resolve_dir(&root, ".", "docs").unwrap(), root.join("docs"));
857 assert!(matches!(
858 resolve_dir(&root, ".", "file.txt"),
859 Err(FsError::NotADirectory)
860 ));
861 assert!(matches!(
862 resolve_dir(&root, ".", "nope"),
863 Err(FsError::NotFound)
864 ));
865 }
866
867 // ---------- list_dir ----------
868
869 #[test]
870 fn list_dir_sorts_folders_first_then_case_insensitive() {
871 let t = T::new();
872 let d = t.root.join("sortme");
873 std::fs::create_dir_all(d.join("Zeta")).unwrap();
874 std::fs::create_dir_all(d.join("alpha-dir")).unwrap();
875 std::fs::write(d.join("b.txt"), "x").unwrap();
876 std::fs::write(d.join("A.txt"), "x").unwrap();
877 std::fs::write(d.join("C.md"), "x").unwrap();
878 let entries = list_dir(&d).unwrap();
879 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
880 // Folders first (alpha-dir, Zeta), then files case-insensitively.
881 assert_eq!(names, vec!["alpha-dir", "Zeta", "A.txt", "b.txt", "C.md"]);
882 let a = &entries[2];
883 assert!(!a.is_dir);
884 assert_eq!(a.size, 1);
885 assert!(!a.mtime.is_empty());
886 }
887
888 #[test]
889 fn list_dir_error_cases() {
890 let t = T::new();
891 let root = t.root.canonicalize().unwrap();
892 assert!(matches!(
893 list_dir(&root.join("missing")),
894 Err(FsError::NotFound)
895 ));
896 assert!(matches!(
897 list_dir(&root.join("file.txt")),
898 Err(FsError::NotADirectory)
899 ));
900 }
901
902 #[cfg(unix)]
903 #[test]
904 fn list_dir_reports_broken_symlink_as_empty_file() {
905 let t = T::new();
906 let d = t.root.join("withlink");
907 std::fs::create_dir_all(&d).unwrap();
908 std::os::unix::fs::symlink(d.join("does-not-exist"), d.join("broken")).unwrap();
909 let entries = list_dir(&d).unwrap();
910 assert_eq!(entries.len(), 1);
911 assert_eq!(entries[0].name, "broken");
912 assert!(!entries[0].is_dir);
913 assert_eq!(entries[0].size, 0);
914 }
915
916 // ---------- mkdir ----------
917
918 #[test]
919 fn mkdir_creates_nested_dirs() {
920 let t = T::new();
921 let root = t.root.canonicalize().unwrap();
922 // The parent must exist; "new" first, then "new/sub".
923 mkdir(&root, ".", "new").unwrap();
924 assert!(root.join("new").is_dir());
925 mkdir(&root, ".", "new/sub").unwrap();
926 assert!(root.join("new/sub").is_dir());
927 }
928
929 #[test]
930 fn mkdir_rejects_conflict_and_bad_names() {
931 let t = T::new();
932 let root = t.root.canonicalize().unwrap();
933 assert!(matches!(mkdir(&root, ".", "docs"), Err(FsError::Conflict)));
934 assert!(matches!(
935 mkdir(&root, ".", "a/b/../../c"),
936 Err(FsError::Forbidden)
937 ));
938 assert!(matches!(
939 mkdir(&root, ".", "file.txt/x"),
940 Err(FsError::Forbidden) // parent is a file → ENOTDIR
941 ));
942 }
943
944 // ---------- rename ----------
945
946 #[test]
947 fn rename_moves_file_and_dir() {
948 let t = T::new();
949 let root = t.root.canonicalize().unwrap();
950 rename_item(&root, ".", "file.txt", "renamed.txt", false).unwrap();
951 assert!(!root.join("file.txt").exists());
952 assert_eq!(
953 std::fs::read_to_string(root.join("renamed.txt")).unwrap(),
954 "top file"
955 );
956 rename_item(&root, ".", "docs", "docs2", false).unwrap();
957 assert!(root.join("docs2/inner/hello.txt").exists());
958 }
959
960 #[test]
961 fn rename_conflicts_and_overwrite() {
962 let t = T::new();
963 let root = t.root.canonicalize().unwrap();
964 std::fs::write(root.join("other.txt"), "other").unwrap();
965 // Target file exists, no overwrite → conflict.
966 assert!(matches!(
967 rename_item(&root, ".", "file.txt", "other.txt", false),
968 Err(FsError::Conflict)
969 ));
970 // Overwrite a file target → replaces it.
971 rename_item(&root, ".", "file.txt", "other.txt", true).unwrap();
972 assert_eq!(
973 std::fs::read_to_string(root.join("other.txt")).unwrap(),
974 "top file"
975 );
976 // A dir target is never overwritten, even with the flag.
977 assert!(matches!(
978 rename_item(&root, ".", "other.txt", "docs", true),
979 Err(FsError::Conflict)
980 ));
981 // Renaming into a free slot works, then onto itself is a no-op.
982 rename_item(&root, ".", "other.txt", "free.txt", false).unwrap();
983 assert!(root.join("free.txt").exists());
984 rename_item(&root, ".", "free.txt", "free.txt", false).unwrap();
985 assert!(root.join("free.txt").exists());
986 assert!(root.join("free.txt").is_file());
987 }
988
989 #[test]
990 fn rename_validates_new_name() {
991 let t = T::new();
992 let root = t.root.canonicalize().unwrap();
993 for bad in ["a/b", "", ".", ".."] {
994 assert!(matches!(
995 rename_item(&root, ".", "file.txt", bad, false),
996 Err(FsError::Invalid(_))
997 ));
998 }
999 assert!(matches!(
1000 rename_item(&root, ".", "missing", "x", false),
1001 Err(FsError::NotFound)
1002 ));
1003 }
1004
1005 // ---------- remove ----------
1006
1007 #[test]
1008 fn remove_file_and_dir() {
1009 let t = T::new();
1010 let root = t.root.canonicalize().unwrap();
1011 assert!(!remove_item(&root, ".", "file.txt").unwrap());
1012 assert!(!root.join("file.txt").exists());
1013 assert!(remove_item(&root, ".", "docs").unwrap());
1014 assert!(!root.join("docs").exists());
1015 assert!(matches!(
1016 remove_item(&root, ".", "file.txt"),
1017 Err(FsError::NotFound)
1018 ));
1019 }
1020
1021 // ---------- save_file ----------
1022
1023 fn mtime_of(p: &Path) -> i64 {
1024 std::fs::metadata(p)
1025 .unwrap()
1026 .modified()
1027 .unwrap()
1028 .duration_since(std::time::UNIX_EPOCH)
1029 .unwrap()
1030 .as_secs() as i64
1031 }
1032
1033 #[test]
1034 fn save_file_updates_content_and_returns_new_mtime() {
1035 let t = T::new();
1036 let root = t.root.canonicalize().unwrap();
1037 let before = mtime_of(&root.join("file.txt"));
1038 // Sleep so the mtime actually advances (filesystem granularity).
1039 std::thread::sleep(std::time::Duration::from_millis(1100));
1040 let new = save_file(&root, ".", "file.txt", b"brand new", Some(before)).unwrap();
1041 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"brand new");
1042 assert!(new >= before);
1043 // A second save with the *returned* mtime succeeds.
1044 let new2 = save_file(&root, ".", "file.txt", b"again", Some(new)).unwrap();
1045 assert!(new2 >= new);
1046 // Without an expected mtime, always saves.
1047 let _ = save_file(&root, ".", "file.txt", b"force", None).unwrap();
1048 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"force");
1049 }
1050
1051 #[test]
1052 fn save_file_conflict_on_stale_mtime() {
1053 let t = T::new();
1054 let root = t.root.canonicalize().unwrap();
1055 std::thread::sleep(std::time::Duration::from_millis(1100));
1056 // The mtime we pass is older than the file's real mtime → conflict.
1057 assert!(matches!(
1058 save_file(&root, ".", "file.txt", b"x", Some(1)),
1059 Err(FsError::Conflict)
1060 ));
1061 }
1062
1063 #[test]
1064 fn save_file_error_cases() {
1065 let t = T::new();
1066 let root = t.root.canonicalize().unwrap();
1067 assert!(matches!(
1068 save_file(&root, ".", "nope.txt", b"x", None),
1069 Err(FsError::NotFound)
1070 ));
1071 assert!(matches!(
1072 save_file(&root, ".", "docs", b"x", None),
1073 Err(FsError::NotADirectory)
1074 ));
1075 assert!(matches!(
1076 save_file(&root, ".", "../evil.txt", b"x", None),
1077 Err(FsError::Forbidden)
1078 ));
1079 }
1080
1081 // ---------- move / copy ----------
1082
1083 #[test]
1084 fn move_file_and_dir_across_dirs() {
1085 let t = T::new();
1086 let root = t.root.canonicalize().unwrap();
1087 move_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1088 assert!(!root.join("file.txt").exists());
1089 assert!(root.join("src/file.txt").exists());
1090 move_item(&root, ".", "src", ".", "docs", false).unwrap();
1091 assert!(root.join("docs/src/main.rs").exists());
1092 assert!(!root.join("src").exists());
1093 }
1094
1095 #[test]
1096 fn move_refuses_into_self_and_conflicts() {
1097 let t = T::new();
1098 let root = t.root.canonicalize().unwrap();
1099 // A dir cannot be moved into itself or a descendant.
1100 assert!(matches!(
1101 move_item(&root, ".", "docs", ".", "docs", false),
1102 Err(FsError::Invalid(_))
1103 ));
1104 assert!(matches!(
1105 move_item(&root, ".", "docs", ".", "docs/inner", false),
1106 Err(FsError::Invalid(_))
1107 ));
1108 // A dir target always conflicts, even with overwrite: move the file
1109 // "x" into a folder that already contains a subfolder "x".
1110 std::fs::create_dir_all(root.join("mv/case/x")).unwrap();
1111 std::fs::create_dir_all(root.join("mv/out")).unwrap();
1112 std::fs::write(root.join("mv/out/x"), "a file named x").unwrap();
1113 assert!(matches!(
1114 move_item(&root, ".", "mv/out/x", ".", "mv/case", true),
1115 Err(FsError::Conflict)
1116 ));
1117 // File onto file: conflict without overwrite, replaced with.
1118 std::fs::write(root.join("tmp-x.txt"), "x").unwrap();
1119 std::fs::write(root.join("tmp-y.txt"), "y").unwrap();
1120 std::fs::rename(root.join("tmp-x.txt"), root.join("tmp-target.txt")).unwrap();
1121 std::fs::rename(root.join("tmp-y.txt"), root.join("tmp-target2.txt")).unwrap();
1122 // Two distinct files with the same name in one folder.
1123 std::fs::create_dir_all(root.join("mv/dst")).unwrap();
1124 std::fs::create_dir_all(root.join("mv/out2")).unwrap();
1125 std::fs::write(root.join("mv/dst/dup.txt"), "old").unwrap();
1126 std::fs::write(root.join("mv/out2/dup.txt"), "new").unwrap();
1127 assert!(matches!(
1128 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", false),
1129 Err(FsError::Conflict)
1130 ));
1131 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", true).unwrap();
1132 assert_eq!(
1133 std::fs::read_to_string(root.join("mv/dst/dup.txt")).unwrap(),
1134 "new"
1135 );
1136 // Moving onto itself is a no-op success.
1137 move_item(&root, ".", "tmp-target.txt", ".", ".", false).unwrap();
1138 assert!(root.join("tmp-target.txt").exists());
1139 // Missing destination dir.
1140 assert!(matches!(
1141 move_item(&root, ".", "file.txt", ".", "nope", false),
1142 Err(FsError::NotFound)
1143 ));
1144 }
1145
1146 #[test]
1147 fn copy_file_and_dir_preserves_mtime() {
1148 let t = T::new();
1149 let root = t.root.canonicalize().unwrap();
1150 let before = mtime_of(&root.join("file.txt"));
1151 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1152 let copy = root.join("src/file.txt");
1153 assert_eq!(std::fs::read(&copy).unwrap(), b"top file");
1154 assert_eq!(mtime_of(&copy), before);
1155 // Dir copy.
1156 copy_item(&root, ".", "docs", ".", "src", false).unwrap();
1157 assert_eq!(
1158 std::fs::read_to_string(root.join("src/docs/inner/hello.txt")).unwrap(),
1159 "hello"
1160 );
1161 // Originals still there.
1162 assert!(root.join("file.txt").exists());
1163 assert!(root.join("docs/a.txt").exists());
1164 }
1165
1166 #[test]
1167 fn copy_refuses_into_self_and_handles_conflict() {
1168 let t = T::new();
1169 let root = t.root.canonicalize().unwrap();
1170 assert!(matches!(
1171 copy_item(&root, ".", "docs", ".", "docs", false),
1172 Err(FsError::Invalid(_))
1173 ));
1174 assert!(matches!(
1175 copy_item(&root, ".", "docs", ".", "docs/inner", false),
1176 Err(FsError::Invalid(_))
1177 ));
1178 // First copy is fine, the second one conflicts, overwrite replaces.
1179 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1180 assert!(matches!(
1181 copy_item(&root, ".", "file.txt", ".", "src", false),
1182 Err(FsError::Conflict)
1183 ));
1184 std::fs::write(root.join("file.txt"), "v2").unwrap();
1185 copy_item(&root, ".", "file.txt", ".", "src", true).unwrap();
1186 assert_eq!(
1187 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1188 "v2"
1189 );
1190 // Copying onto itself is a no-op success.
1191 copy_item(&root, ".", "src/file.txt", ".", "src", false).unwrap();
1192 assert_eq!(
1193 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1194 "v2"
1195 );
1196 // Missing destination dir.
1197 assert!(matches!(
1198 copy_item(&root, ".", "file.txt", ".", "nope", false),
1199 Err(FsError::NotFound)
1200 ));
1201 }
1202
1203 #[test]
1204 fn copy_recursive_missing_source() {
1205 let t = T::new();
1206 let dst = t.tmp.path().join("dst");
1207 assert!(matches!(
1208 copy_recursive(&t.root.join("nope"), &dst),
1209 Err(FsError::NotFound)
1210 ));
1211 }
1212
1213 // ---------- is_within_or_eq ----------
1214
1215 #[test]
1216 fn is_within_or_eq_matrix() {
1217 let t = T::new();
1218 let root = t.root.canonicalize().unwrap();
1219 let docs = root.join("docs");
1220 assert!(is_within_or_eq(&docs, &docs));
1221 assert!(is_within_or_eq(&docs, &root.join("docs/inner")));
1222 assert!(!is_within_or_eq(&docs, &root));
1223 assert!(!is_within_or_eq(&docs, &root.join("src")));
1224 }
1225
1226 // ---------- content sniffing ----------
1227
1228 fn kind(bytes: &[u8], name: &str) -> FileKind {
1229 kind_from_bytes(bytes, Path::new(name))
1230 }
1231
1232 #[test]
1233 fn magic_numbers_classify_by_content() {
1234 let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
1235 // The name is a lie in every case: the bytes decide.
1236 assert_eq!(kind(&png, "notes.txt"), FileKind::Image);
1237 assert_eq!(kind(b"%PDF-1.7\n%aaa\n", "x.bin"), FileKind::Pdf);
1238 assert_eq!(
1239 kind(b"PK\x03\x04\x14\x00\x00\x00", "x.png"),
1240 FileKind::Archive
1241 );
1242 assert_eq!(
1243 kind(&[0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0], "x"),
1244 FileKind::Archive
1245 );
1246 assert_eq!(
1247 kind(
1248 &[
1249 0, 0, 0, 0x20, b'f', b't', b'y', b'p', b'i', b's', b'o', b'm'
1250 ],
1251 "x"
1252 ),
1253 FileKind::Video
1254 );
1255 assert_eq!(
1256 kind(b"ID3\x04\x00\x00\x00\x00\x00\x00", "x"),
1257 FileKind::Audio
1258 );
1259 assert_eq!(kind(b"RIFF\x24\x00\x00\x00WAVEfmt ", "x"), FileKind::Audio);
1260 assert_eq!(kind(b"<!doctype html><p>hi", "x"), FileKind::Text);
1261 // Recognized but not viewable in a browser.
1262 assert_eq!(
1263 kind(&[0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0], "x.wasm"),
1264 FileKind::Binary
1265 );
1266 }
1267
1268 #[test]
1269 fn unsigned_files_fall_back_to_the_text_heuristic() {
1270 // No magic number: plain text, source, config.
1271 assert_eq!(kind(b"hello world\n", "notes"), FileKind::Text);
1272 assert_eq!(kind(b"fn main() {}\n", "main.rs"), FileKind::Text);
1273 assert_eq!(
1274 kind("# über\nkey: wert\n".as_bytes(), "c.yaml"),
1275 FileKind::Text
1276 );
1277 // Extensionless text files work, which the old extension list missed.
1278 assert_eq!(kind(b"all:\n\tcargo build\n", "Makefile"), FileKind::Text);
1279 // Empty file → editable.
1280 assert_eq!(kind(b"", "new.txt"), FileKind::Text);
1281 // A NUL byte means binary, whatever the name says. (ELF has no
1282 // `infer` signature, so this is the path that catches it.)
1283 assert_eq!(
1284 kind(&[0x7F, b'E', b'L', b'F', 2, 1, 1, 0, 0], "run.txt"),
1285 FileKind::Binary
1286 );
1287 assert_eq!(kind(&[0xC3, 0x28, 0xFF, 0xFE], "x.txt"), FileKind::Binary);
1288 }
1289
1290 #[test]
1291 fn svg_is_offered_as_an_image() {
1292 // SVG is XML text with no magic number, but browsers draw it, so the
1293 // extension is the only signal available.
1294 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
1295 assert_eq!(kind(svg, "logo.svg"), FileKind::Image);
1296 assert_eq!(kind(svg, "logo.txt"), FileKind::Text);
1297 }
1298
1299 #[test]
1300 fn truncated_utf8_at_the_read_boundary_is_still_text() {
1301 // 255 ASCII bytes plus the first byte of a 2-byte character: the read
1302 // cut a character in half, which must not read as binary.
1303 let mut b = vec![b'a'; SNIFF_BYTES - 1];
1304 b.push(0xC3);
1305 assert_eq!(kind(&b, "x.txt"), FileKind::Text);
1306 }
1307
1308 #[test]
1309 fn detect_kind_reads_from_disk() {
1310 let t = T::new();
1311 assert_eq!(detect_kind(&t.root.join("docs"), true), FileKind::Dir);
1312 assert_eq!(detect_kind(&t.root.join("file.txt"), false), FileKind::Text);
1313 // Unreadable / missing → Binary, never a failed listing.
1314 assert_eq!(detect_kind(&t.root.join("nope"), false), FileKind::Binary);
1315 }
1316
1317 /// `SNIFF_BUDGET` is process-wide, so the two tests that assert on it must
1318 /// not run at the same time as each other.
1319 static BUDGET_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
1320
1321 /// A directory big enough to take the fan-out path must produce exactly
1322 /// what the serial path would. Pass 2 fills `is_dir`, `size`, `mtime` and
1323 /// `kind`, all on worker threads, so a chunk-boundary mistake would show up
1324 /// as a row carrying another row's metadata or the untouched placeholders.
1325 #[test]
1326 fn parallel_rows_match_serial() {
1327 use std::sync::atomic::Ordering;
1328 let _guard = BUDGET_TESTS.lock().unwrap();
1329 let t = T::new();
1330 let big = t.root.join("big");
1331 std::fs::create_dir_all(&big).unwrap();
1332 // Well over SNIFF_CHUNK, so several chunks are handed out.
1333 let n = SNIFF_CHUNK * 3 + 7;
1334 for i in 0..n {
1335 let p = big.join(format!("f{i:05}"));
1336 // Every file gets a distinct length, so `size` pins the row identity.
1337 let pad = vec![b'A'; i];
1338 let mut body = match i % 3 {
1339 0 => vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1340 1 => b"plain text\n".to_vec(),
1341 _ => vec![0u8, 1, 2, 3],
1342 };
1343 body.extend_from_slice(&pad);
1344 std::fs::write(&p, &body).unwrap();
1345 }
1346 std::fs::create_dir(big.join("a-subdir")).unwrap();
1347
1348 let entries = list_dir(&big).unwrap();
1349 assert_eq!(entries.len(), n + 1);
1350
1351 // Every row must agree with what a single-threaded read of that same
1352 // file reports: kind, size and directory flag.
1353 for e in &entries {
1354 let p = big.join(&e.name);
1355 let m = std::fs::metadata(&p).unwrap();
1356 assert_eq!(e.is_dir, m.is_dir(), "{}", e.name);
1357 assert_eq!(e.size, m.len(), "size mismatch on {}", e.name);
1358 assert_eq!(e.mtime, mtime_str(&m), "mtime mismatch on {}", e.name);
1359 assert_eq!(
1360 e.kind,
1361 detect_kind(&p, e.is_dir),
1362 "kind mismatch on {}",
1363 e.name
1364 );
1365 }
1366
1367 // Sanity: several kinds are actually present, so the loop above is not
1368 // trivially true, and the directory sorts first.
1369 let kinds: Vec<FileKind> = entries.iter().map(|e| e.kind).collect();
1370 assert!(kinds.contains(&FileKind::Image));
1371 assert!(kinds.contains(&FileKind::Text));
1372 assert!(kinds.contains(&FileKind::Binary));
1373 assert_eq!(entries[0].name, "a-subdir");
1374 assert_eq!(entries[0].kind, FileKind::Dir);
1375
1376 // The thread budget is fully returned once the listing is done.
1377 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1378 }
1379
1380 #[test]
1381 fn sniff_permit_never_exceeds_the_budget() {
1382 use std::sync::atomic::Ordering;
1383 let _guard = BUDGET_TESTS.lock().unwrap();
1384 let total = sniff_budget_total();
1385 let a = SniffPermit::claim(total * 2);
1386 assert_eq!(a.0, total, "a single claim is capped at the total");
1387 // Nothing left: the next listing runs serially rather than queueing.
1388 let b = SniffPermit::claim(4);
1389 assert_eq!(b.0, 0);
1390 drop(a);
1391 drop(b);
1392 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1393 }
1394
1395 #[test]
1396 fn list_dir_reports_kinds() {
1397 let t = T::new();
1398 std::fs::write(
1399 t.root.join("docs/pic.dat"),
1400 [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1401 )
1402 .unwrap();
1403 let entries = list_dir(&t.root.join("docs")).unwrap();
1404 let kind_of = |n: &str| entries.iter().find(|e| e.name == n).unwrap().kind;
1405 assert_eq!(kind_of("inner"), FileKind::Dir);
1406 assert_eq!(kind_of("a.txt"), FileKind::Text);
1407 assert_eq!(kind_of("pic.dat"), FileKind::Image);
1408 }
1409}
1410