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/// Resolve a path that does not need to exist yet, but whose *parent* must.
379fn resolve_path_or_new(
380 server_root: &Path,
381 root_rel: &str,
382 req_rel: &str,
383) -> Result<PathBuf, FsError> {
384 let root_abs = resolve_root(server_root, root_rel)?;
385 let req = Path::new(req_rel);
386 for c in req.components() {
387 if matches!(c, Component::ParentDir) {
388 return Err(FsError::Forbidden);
389 }
390 }
391 let full = root_abs.join(req);
392 // The parent must exist and stay inside the root.
393 let parent = full
394 .parent()
395 .filter(|p| !p.as_os_str().is_empty())
396 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
397 let parent = parent.canonicalize().map_err(|e| io_err(e, parent))?;
398 ensure_within(&root_abs, &parent)?;
399 Ok(full)
400}
401
402/// Rename (or move within the same directory) an item.
403pub fn rename_item(
404 server_root: &Path,
405 root_rel: &str,
406 req_rel: &str,
407 new_name: &str,
408 overwrite: bool,
409) -> Result<(), FsError> {
410 validate_component(new_name)?;
411 let from = resolve_path(server_root, root_rel, req_rel)?;
412 let parent = from
413 .parent()
414 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
415 let to = parent.join(new_name);
416 // Renaming onto itself is a no-op (the overwrite path below would
417 // delete the file before the rename).
418 if to == from {
419 return Ok(());
420 }
421 if to.exists() {
422 if !overwrite || to.is_dir() || from.is_dir() {
423 return Err(FsError::Conflict);
424 }
425 std::fs::remove_file(&to).map_err(|e| io_err(e, &to))?;
426 }
427 std::fs::rename(&from, &to).map_err(|e| io_err(e, &to))?;
428 Ok(())
429}
430
431/// Delete a file or a directory tree. Returns whether it was a directory.
432pub fn remove_item(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<bool, FsError> {
433 let full = resolve_path(server_root, root_rel, req_rel)?;
434 let is_dir = full.is_dir();
435 if is_dir {
436 std::fs::remove_dir_all(&full).map_err(|e| io_err(e, &full))?;
437 } else {
438 std::fs::remove_file(&full).map_err(|e| io_err(e, &full))?;
439 }
440 Ok(is_dir)
441}
442
443/// Overwrite an existing file's contents (the editor's save path).
444///
445/// The file must already exist and be a regular file. If `expected_mtime`
446/// (whole unix seconds) is provided and differs from the file's current mtime,
447/// the file changed on disk since it was read → `Conflict` (409). Returns the
448/// file's new mtime (unix seconds) after a successful write.
449pub fn save_file(
450 server_root: &Path,
451 root_rel: &str,
452 req_rel: &str,
453 content: &[u8],
454 expected_mtime: Option<i64>,
455) -> Result<i64, FsError> {
456 let full = resolve_path(server_root, root_rel, req_rel)?; // must exist
457 write_checked(&full, content, expected_mtime)
458}
459
460/// The share-aware variant of [`save_file`]: for a *file* share the root is
461/// the file itself, so `target` (relative to `server_root`) points at the
462/// file — there is no directory root beneath it.
463pub fn save_file_at(
464 server_root: &Path,
465 target: &str,
466 content: &[u8],
467 expected_mtime: Option<i64>,
468) -> Result<i64, FsError> {
469 let full = resolve_file(server_root, target)?; // must exist
470 write_checked(&full, content, expected_mtime)
471}
472
473fn write_checked(full: &Path, content: &[u8], expected_mtime: Option<i64>) -> Result<i64, FsError> {
474 let meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
475 if meta.is_dir() {
476 return Err(FsError::NotADirectory);
477 }
478 if let Some(expected) = expected_mtime {
479 // No readable mtime means the check cannot pass: -1 never matches.
480 if mtime_secs(&meta).unwrap_or(-1) != expected {
481 return Err(FsError::Conflict);
482 }
483 }
484 std::fs::write(full, content).map_err(|e| io_err(e, full))?;
485 // Read the new mtime so the client can anchor the next conflict check.
486 let new_meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
487 Ok(mtime_secs(&new_meta).unwrap_or(0))
488}
489
490fn io_err(e: std::io::Error, p: &Path) -> FsError {
491 tracing::warn!(error = %e, path = %p.display(), "filesystem error");
492 match e.kind() {
493 std::io::ErrorKind::NotFound => FsError::NotFound,
494 _ => FsError::Forbidden,
495 }
496}
497
498/// True if `a` is `b` or a descendant of `b` (both canonical).
499pub(crate) fn is_within_or_eq(base: &Path, p: &Path) -> bool {
500 p == base || p.starts_with(base)
501}
502
503/// Move an item (possibly across roots). `dst_dir_rel` is the destination
504/// directory (relative to `dst_root_rel`); the item keeps its base name.
505pub fn move_item(
506 server_root: &Path,
507 src_root_rel: &str,
508 src_rel: &str,
509 dst_root_rel: &str,
510 dst_dir_rel: &str,
511 overwrite: bool,
512) -> Result<(), FsError> {
513 let from = resolve_path(server_root, src_root_rel, src_rel)?;
514 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
515 let name = from
516 .file_name()
517 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
518 .to_owned();
519 let to = dst_dir.join(&name);
520
521 // A no-op (item already at the destination) — treat as success.
522 if to == from {
523 return Ok(());
524 }
525
526 // Refuse moving a directory into itself or a descendant.
527 if from.is_dir() && is_within_or_eq(&from, &dst_dir) {
528 return Err(FsError::Invalid(
529 "cannot move a folder into itself".to_string(),
530 ));
531 }
532 check_move_conflict(&to, &from, overwrite)?;
533
534 match std::fs::rename(&from, &to) {
535 Ok(()) => Ok(()),
536 Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
537 copy_recursive(&from, &to)?;
538 if from.is_dir() {
539 std::fs::remove_dir_all(&from).map_err(|_| FsError::Forbidden)?;
540 } else {
541 std::fs::remove_file(&from).map_err(|_| FsError::Forbidden)?;
542 }
543 Ok(())
544 }
545 Err(e) => Err(io_err(e, &to)),
546 }
547}
548
549/// Copy an item (possibly across roots).
550pub fn copy_item(
551 server_root: &Path,
552 src_root_rel: &str,
553 src_rel: &str,
554 dst_root_rel: &str,
555 dst_dir_rel: &str,
556 overwrite: bool,
557) -> Result<(), FsError> {
558 let from = resolve_path(server_root, src_root_rel, src_rel)?;
559 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
560 let name = from
561 .file_name()
562 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
563 .to_owned();
564 let to = dst_dir.join(&name);
565
566 // A no-op (item already at the destination) — treat as success.
567 if to == from {
568 return Ok(());
569 }
570
571 if from.is_dir() && is_within_or_eq(&from, &dst_dir) {
572 return Err(FsError::Invalid(
573 "cannot copy a folder into itself".to_string(),
574 ));
575 }
576 check_move_conflict(&to, &from, overwrite)?;
577 copy_recursive(&from, &to)?;
578 Ok(())
579}
580
581/// Conflict rules shared by move and copy:
582/// - target is a directory → always conflict (no silent merge)
583/// - target is a file → conflict unless overwriting a file with a file
584fn check_move_conflict(to: &Path, from: &Path, overwrite: bool) -> Result<(), FsError> {
585 if to.exists() {
586 let to_dir = to.is_dir();
587 let from_dir = from.is_dir();
588 if to_dir || from_dir || !overwrite {
589 return Err(FsError::Conflict);
590 }
591 }
592 Ok(())
593}
594
595/// Recursively copy a file or directory tree, preserving mtime.
596fn copy_recursive(src: &Path, dst: &Path) -> Result<(), FsError> {
597 let meta = std::fs::metadata(src).map_err(|e| io_err(e, src))?;
598 if meta.is_dir() {
599 std::fs::create_dir(dst).map_err(|e| io_err(e, dst))?;
600 for e in std::fs::read_dir(src)
601 .map_err(|e| io_err(e, src))?
602 .flatten()
603 {
604 copy_recursive(&e.path(), &dst.join(e.file_name()))?;
605 }
606 } else {
607 std::fs::copy(src, dst).map_err(|e| io_err(e, dst))?;
608 }
609 set_mtime(dst, meta.modified().ok());
610 Ok(())
611}
612
613fn set_mtime(p: &Path, t: Option<std::time::SystemTime>) {
614 if let (Some(t), Ok(f)) = (t, std::fs::File::open(p)) {
615 let _ = f.set_modified(t);
616 }
617}
618
619// ---------------------------------------------------------------------------
620// Tests
621// ---------------------------------------------------------------------------
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626
627 /// A temp dir used as the "server root" with a small fixture tree:
628 ///
629 /// ```text
630 /// root/
631 /// docs/
632 /// inner/
633 /// hello.txt
634 /// a.txt
635 /// src/
636 /// main.rs
637 /// file.txt
638 /// ```
639 struct T {
640 tmp: tempfile::TempDir,
641 root: PathBuf,
642 }
643
644 impl T {
645 fn new() -> Self {
646 let tmp = tempfile::tempdir().unwrap();
647 let root = tmp.path().to_path_buf();
648 std::fs::create_dir_all(root.join("docs/inner")).unwrap();
649 std::fs::create_dir_all(root.join("src")).unwrap();
650 std::fs::write(root.join("docs/inner/hello.txt"), "hello").unwrap();
651 std::fs::write(root.join("docs/a.txt"), "a").unwrap();
652 std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
653 std::fs::write(root.join("file.txt"), "top file").unwrap();
654 Self { tmp, root }
655 }
656
657 /// A directory that lives *next to* the root (outside of it), for
658 /// symlink/escape tests. The tempdir name is unique, so the sibling
659 /// name is unique too.
660 fn sibling(&self, name: &str) -> PathBuf {
661 let base = self
662 .tmp
663 .path()
664 .file_name()
665 .unwrap()
666 .to_string_lossy()
667 .into_owned();
668 let p = self.tmp.path().with_file_name(format!("{base}-{name}"));
669 std::fs::create_dir_all(&p).unwrap();
670 p
671 }
672 }
673
674 // ---------- validate_component ----------
675
676 #[test]
677 fn validate_name_accepts_simple_names() {
678 for ok in ["a", "file.txt", "my folder", "Ünïcödé", "with-dash_1.2.3"] {
679 assert!(validate_component(ok).is_ok(), "{ok:?} should be valid");
680 }
681 }
682
683 #[test]
684 fn validate_name_rejects_traversal_and_paths() {
685 for bad in [
686 "", ".", "..", "a/b", "a\\b", "a\0b", "/abs", "../x", "x/../y", "x/", "/x",
687 ] {
688 assert!(
689 validate_component(bad).is_err(),
690 "{bad:?} should be invalid"
691 );
692 }
693 }
694
695 // ---------- resolve_root ----------
696
697 #[test]
698 fn resolve_root_whole_root_and_subdir() {
699 let t = T::new();
700 let root = t.root.canonicalize().unwrap();
701 // "." means the whole root.
702 assert_eq!(resolve_root(&root, ".").unwrap(), root);
703 assert_eq!(resolve_root(&root, "docs").unwrap(), root.join("docs"));
704 assert_eq!(
705 resolve_root(&root, "docs/inner").unwrap(),
706 root.join("docs/inner")
707 );
708 }
709
710 #[test]
711 fn resolve_root_rejects_escape_and_missing() {
712 let t = T::new();
713 let root = t.root.canonicalize().unwrap();
714 let sib = t.sibling("escape");
715 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
716 // Escapes that land on *existing* paths outside the root.
717 for esc in [
718 "..".to_string(),
719 "docs/../..".to_string(),
720 format!("../{sib_rel}"),
721 ] {
722 assert!(
723 matches!(resolve_root(&root, &esc), Err(FsError::Forbidden)),
724 "{esc:?} should be forbidden"
725 );
726 }
727 // Escapes to non-existing paths simply don't exist.
728 for esc in ["../no-such-dir", "a/b/../../..", "nope"] {
729 assert!(
730 matches!(resolve_root(&root, esc), Err(FsError::RootMissing)),
731 "{esc:?} should be missing"
732 );
733 }
734 // A file is not a valid root.
735 assert!(matches!(
736 resolve_root(&root, "file.txt"),
737 Err(FsError::RootMissing)
738 ));
739 }
740
741 #[cfg(unix)]
742 #[test]
743 fn resolve_root_rejects_symlink_escape() {
744 let t = T::new();
745 let root = t.root.canonicalize().unwrap();
746 let outside = t.sibling("outside");
747 std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
748 assert!(matches!(
749 resolve_root(&root, "link"),
750 Err(FsError::Forbidden)
751 ));
752 }
753
754 // ---------- resolve_path ----------
755
756 #[test]
757 fn resolve_path_traverses_inside_root() {
758 let t = T::new();
759 let root = t.root.canonicalize().unwrap();
760 // Empty relative path → the root itself.
761 assert_eq!(resolve_path(&root, ".", "").unwrap(), root);
762 assert_eq!(
763 resolve_path(&root, "docs", "inner/hello.txt").unwrap(),
764 root.join("docs/inner/hello.txt")
765 );
766 assert_eq!(
767 resolve_path(&root, ".", "file.txt").unwrap(),
768 root.join("file.txt")
769 );
770 }
771
772 #[test]
773 fn resolve_path_rejects_parent_traversal() {
774 let t = T::new();
775 let root = t.root.canonicalize().unwrap();
776 for p in ["..", "../file.txt", "docs/../../file.txt", "a/../../b"] {
777 assert!(
778 matches!(resolve_path(&root, ".", p), Err(FsError::Forbidden)),
779 "{p:?} should be forbidden"
780 );
781 }
782 }
783
784 #[test]
785 fn resolve_path_missing_is_not_found() {
786 let t = T::new();
787 let root = t.root.canonicalize().unwrap();
788 assert!(matches!(
789 resolve_path(&root, "docs", "nope.txt"),
790 Err(FsError::NotFound)
791 ));
792 assert!(matches!(
793 resolve_path(&root, "missing-root", ""),
794 Err(FsError::RootMissing)
795 ));
796 }
797
798 #[cfg(unix)]
799 #[test]
800 fn resolve_path_rejects_symlink_escape() {
801 let t = T::new();
802 let root = t.root.canonicalize().unwrap();
803 let outside = t.sibling("outside");
804 let secret = outside.join("secret.txt");
805 std::fs::write(&secret, "top secret").unwrap();
806 std::os::unix::fs::symlink(&secret, root.join("evil")).unwrap();
807 assert!(matches!(
808 resolve_path(&root, ".", "evil"),
809 Err(FsError::Forbidden)
810 ));
811 // A symlink that stays inside the root is fine.
812 std::os::unix::fs::symlink(root.join("file.txt"), root.join("alias")).unwrap();
813 assert_eq!(
814 resolve_path(&root, ".", "alias").unwrap(),
815 root.join("file.txt")
816 );
817 }
818
819 // ---------- resolve_file / resolve_dir ----------
820
821 #[test]
822 fn resolve_file_targets_files() {
823 let t = T::new();
824 let root = t.root.canonicalize().unwrap();
825 assert_eq!(
826 resolve_file(&root, "file.txt").unwrap(),
827 root.join("file.txt")
828 );
829 assert!(matches!(
830 resolve_file(&root, "nope.txt"),
831 Err(FsError::NotFound)
832 ));
833 // Escape to an existing sibling file.
834 let sib = t.sibling("escape");
835 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
836 std::fs::write(sib.join("s.txt"), "x").unwrap();
837 assert!(matches!(
838 resolve_file(&root, &format!("../{sib_rel}/s.txt")),
839 Err(FsError::Forbidden)
840 ));
841 }
842
843 #[test]
844 fn resolve_dir_requires_existing_directory() {
845 let t = T::new();
846 let root = t.root.canonicalize().unwrap();
847 assert_eq!(resolve_dir(&root, ".", "docs").unwrap(), root.join("docs"));
848 assert!(matches!(
849 resolve_dir(&root, ".", "file.txt"),
850 Err(FsError::NotADirectory)
851 ));
852 assert!(matches!(
853 resolve_dir(&root, ".", "nope"),
854 Err(FsError::NotFound)
855 ));
856 }
857
858 // ---------- list_dir ----------
859
860 #[test]
861 fn list_dir_sorts_folders_first_then_case_insensitive() {
862 let t = T::new();
863 let d = t.root.join("sortme");
864 std::fs::create_dir_all(d.join("Zeta")).unwrap();
865 std::fs::create_dir_all(d.join("alpha-dir")).unwrap();
866 std::fs::write(d.join("b.txt"), "x").unwrap();
867 std::fs::write(d.join("A.txt"), "x").unwrap();
868 std::fs::write(d.join("C.md"), "x").unwrap();
869 let entries = list_dir(&d).unwrap();
870 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
871 // Folders first (alpha-dir, Zeta), then files case-insensitively.
872 assert_eq!(names, vec!["alpha-dir", "Zeta", "A.txt", "b.txt", "C.md"]);
873 let a = &entries[2];
874 assert!(!a.is_dir);
875 assert_eq!(a.size, 1);
876 assert!(!a.mtime.is_empty());
877 }
878
879 #[test]
880 fn list_dir_error_cases() {
881 let t = T::new();
882 let root = t.root.canonicalize().unwrap();
883 assert!(matches!(
884 list_dir(&root.join("missing")),
885 Err(FsError::NotFound)
886 ));
887 assert!(matches!(
888 list_dir(&root.join("file.txt")),
889 Err(FsError::NotADirectory)
890 ));
891 }
892
893 #[cfg(unix)]
894 #[test]
895 fn list_dir_reports_broken_symlink_as_empty_file() {
896 let t = T::new();
897 let d = t.root.join("withlink");
898 std::fs::create_dir_all(&d).unwrap();
899 std::os::unix::fs::symlink(d.join("does-not-exist"), d.join("broken")).unwrap();
900 let entries = list_dir(&d).unwrap();
901 assert_eq!(entries.len(), 1);
902 assert_eq!(entries[0].name, "broken");
903 assert!(!entries[0].is_dir);
904 assert_eq!(entries[0].size, 0);
905 }
906
907 // ---------- mkdir ----------
908
909 #[test]
910 fn mkdir_creates_nested_dirs() {
911 let t = T::new();
912 let root = t.root.canonicalize().unwrap();
913 // The parent must exist; "new" first, then "new/sub".
914 mkdir(&root, ".", "new").unwrap();
915 assert!(root.join("new").is_dir());
916 mkdir(&root, ".", "new/sub").unwrap();
917 assert!(root.join("new/sub").is_dir());
918 }
919
920 #[test]
921 fn mkdir_rejects_conflict_and_bad_names() {
922 let t = T::new();
923 let root = t.root.canonicalize().unwrap();
924 assert!(matches!(mkdir(&root, ".", "docs"), Err(FsError::Conflict)));
925 assert!(matches!(
926 mkdir(&root, ".", "a/b/../../c"),
927 Err(FsError::Forbidden)
928 ));
929 assert!(matches!(
930 mkdir(&root, ".", "file.txt/x"),
931 Err(FsError::Forbidden) // parent is a file → ENOTDIR
932 ));
933 }
934
935 // ---------- rename ----------
936
937 #[test]
938 fn rename_moves_file_and_dir() {
939 let t = T::new();
940 let root = t.root.canonicalize().unwrap();
941 rename_item(&root, ".", "file.txt", "renamed.txt", false).unwrap();
942 assert!(!root.join("file.txt").exists());
943 assert_eq!(
944 std::fs::read_to_string(root.join("renamed.txt")).unwrap(),
945 "top file"
946 );
947 rename_item(&root, ".", "docs", "docs2", false).unwrap();
948 assert!(root.join("docs2/inner/hello.txt").exists());
949 }
950
951 #[test]
952 fn rename_conflicts_and_overwrite() {
953 let t = T::new();
954 let root = t.root.canonicalize().unwrap();
955 std::fs::write(root.join("other.txt"), "other").unwrap();
956 // Target file exists, no overwrite → conflict.
957 assert!(matches!(
958 rename_item(&root, ".", "file.txt", "other.txt", false),
959 Err(FsError::Conflict)
960 ));
961 // Overwrite a file target → replaces it.
962 rename_item(&root, ".", "file.txt", "other.txt", true).unwrap();
963 assert_eq!(
964 std::fs::read_to_string(root.join("other.txt")).unwrap(),
965 "top file"
966 );
967 // A dir target is never overwritten, even with the flag.
968 assert!(matches!(
969 rename_item(&root, ".", "other.txt", "docs", true),
970 Err(FsError::Conflict)
971 ));
972 // Renaming into a free slot works, then onto itself is a no-op.
973 rename_item(&root, ".", "other.txt", "free.txt", false).unwrap();
974 assert!(root.join("free.txt").exists());
975 rename_item(&root, ".", "free.txt", "free.txt", false).unwrap();
976 assert!(root.join("free.txt").exists());
977 assert!(root.join("free.txt").is_file());
978 }
979
980 #[test]
981 fn rename_validates_new_name() {
982 let t = T::new();
983 let root = t.root.canonicalize().unwrap();
984 for bad in ["a/b", "", ".", ".."] {
985 assert!(matches!(
986 rename_item(&root, ".", "file.txt", bad, false),
987 Err(FsError::Invalid(_))
988 ));
989 }
990 assert!(matches!(
991 rename_item(&root, ".", "missing", "x", false),
992 Err(FsError::NotFound)
993 ));
994 }
995
996 // ---------- remove ----------
997
998 #[test]
999 fn remove_file_and_dir() {
1000 let t = T::new();
1001 let root = t.root.canonicalize().unwrap();
1002 assert!(!remove_item(&root, ".", "file.txt").unwrap());
1003 assert!(!root.join("file.txt").exists());
1004 assert!(remove_item(&root, ".", "docs").unwrap());
1005 assert!(!root.join("docs").exists());
1006 assert!(matches!(
1007 remove_item(&root, ".", "file.txt"),
1008 Err(FsError::NotFound)
1009 ));
1010 }
1011
1012 // ---------- save_file ----------
1013
1014 fn mtime_of(p: &Path) -> i64 {
1015 std::fs::metadata(p)
1016 .unwrap()
1017 .modified()
1018 .unwrap()
1019 .duration_since(std::time::UNIX_EPOCH)
1020 .unwrap()
1021 .as_secs() as i64
1022 }
1023
1024 #[test]
1025 fn save_file_updates_content_and_returns_new_mtime() {
1026 let t = T::new();
1027 let root = t.root.canonicalize().unwrap();
1028 let before = mtime_of(&root.join("file.txt"));
1029 // Sleep so the mtime actually advances (filesystem granularity).
1030 std::thread::sleep(std::time::Duration::from_millis(1100));
1031 let new = save_file(&root, ".", "file.txt", b"brand new", Some(before)).unwrap();
1032 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"brand new");
1033 assert!(new >= before);
1034 // A second save with the *returned* mtime succeeds.
1035 let new2 = save_file(&root, ".", "file.txt", b"again", Some(new)).unwrap();
1036 assert!(new2 >= new);
1037 // Without an expected mtime, always saves.
1038 let _ = save_file(&root, ".", "file.txt", b"force", None).unwrap();
1039 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"force");
1040 }
1041
1042 #[test]
1043 fn save_file_conflict_on_stale_mtime() {
1044 let t = T::new();
1045 let root = t.root.canonicalize().unwrap();
1046 std::thread::sleep(std::time::Duration::from_millis(1100));
1047 // The mtime we pass is older than the file's real mtime → conflict.
1048 assert!(matches!(
1049 save_file(&root, ".", "file.txt", b"x", Some(1)),
1050 Err(FsError::Conflict)
1051 ));
1052 }
1053
1054 #[test]
1055 fn save_file_error_cases() {
1056 let t = T::new();
1057 let root = t.root.canonicalize().unwrap();
1058 assert!(matches!(
1059 save_file(&root, ".", "nope.txt", b"x", None),
1060 Err(FsError::NotFound)
1061 ));
1062 assert!(matches!(
1063 save_file(&root, ".", "docs", b"x", None),
1064 Err(FsError::NotADirectory)
1065 ));
1066 assert!(matches!(
1067 save_file(&root, ".", "../evil.txt", b"x", None),
1068 Err(FsError::Forbidden)
1069 ));
1070 }
1071
1072 // ---------- move / copy ----------
1073
1074 #[test]
1075 fn move_file_and_dir_across_dirs() {
1076 let t = T::new();
1077 let root = t.root.canonicalize().unwrap();
1078 move_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1079 assert!(!root.join("file.txt").exists());
1080 assert!(root.join("src/file.txt").exists());
1081 move_item(&root, ".", "src", ".", "docs", false).unwrap();
1082 assert!(root.join("docs/src/main.rs").exists());
1083 assert!(!root.join("src").exists());
1084 }
1085
1086 #[test]
1087 fn move_refuses_into_self_and_conflicts() {
1088 let t = T::new();
1089 let root = t.root.canonicalize().unwrap();
1090 // A dir cannot be moved into itself or a descendant.
1091 assert!(matches!(
1092 move_item(&root, ".", "docs", ".", "docs", false),
1093 Err(FsError::Invalid(_))
1094 ));
1095 assert!(matches!(
1096 move_item(&root, ".", "docs", ".", "docs/inner", false),
1097 Err(FsError::Invalid(_))
1098 ));
1099 // A dir target always conflicts, even with overwrite: move the file
1100 // "x" into a folder that already contains a subfolder "x".
1101 std::fs::create_dir_all(root.join("mv/case/x")).unwrap();
1102 std::fs::create_dir_all(root.join("mv/out")).unwrap();
1103 std::fs::write(root.join("mv/out/x"), "a file named x").unwrap();
1104 assert!(matches!(
1105 move_item(&root, ".", "mv/out/x", ".", "mv/case", true),
1106 Err(FsError::Conflict)
1107 ));
1108 // File onto file: conflict without overwrite, replaced with.
1109 std::fs::write(root.join("tmp-x.txt"), "x").unwrap();
1110 std::fs::write(root.join("tmp-y.txt"), "y").unwrap();
1111 std::fs::rename(root.join("tmp-x.txt"), root.join("tmp-target.txt")).unwrap();
1112 std::fs::rename(root.join("tmp-y.txt"), root.join("tmp-target2.txt")).unwrap();
1113 // Two distinct files with the same name in one folder.
1114 std::fs::create_dir_all(root.join("mv/dst")).unwrap();
1115 std::fs::create_dir_all(root.join("mv/out2")).unwrap();
1116 std::fs::write(root.join("mv/dst/dup.txt"), "old").unwrap();
1117 std::fs::write(root.join("mv/out2/dup.txt"), "new").unwrap();
1118 assert!(matches!(
1119 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", false),
1120 Err(FsError::Conflict)
1121 ));
1122 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", true).unwrap();
1123 assert_eq!(
1124 std::fs::read_to_string(root.join("mv/dst/dup.txt")).unwrap(),
1125 "new"
1126 );
1127 // Moving onto itself is a no-op success.
1128 move_item(&root, ".", "tmp-target.txt", ".", ".", false).unwrap();
1129 assert!(root.join("tmp-target.txt").exists());
1130 // Missing destination dir.
1131 assert!(matches!(
1132 move_item(&root, ".", "file.txt", ".", "nope", false),
1133 Err(FsError::NotFound)
1134 ));
1135 }
1136
1137 #[test]
1138 fn copy_file_and_dir_preserves_mtime() {
1139 let t = T::new();
1140 let root = t.root.canonicalize().unwrap();
1141 let before = mtime_of(&root.join("file.txt"));
1142 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1143 let copy = root.join("src/file.txt");
1144 assert_eq!(std::fs::read(&copy).unwrap(), b"top file");
1145 assert_eq!(mtime_of(&copy), before);
1146 // Dir copy.
1147 copy_item(&root, ".", "docs", ".", "src", false).unwrap();
1148 assert_eq!(
1149 std::fs::read_to_string(root.join("src/docs/inner/hello.txt")).unwrap(),
1150 "hello"
1151 );
1152 // Originals still there.
1153 assert!(root.join("file.txt").exists());
1154 assert!(root.join("docs/a.txt").exists());
1155 }
1156
1157 #[test]
1158 fn copy_refuses_into_self_and_handles_conflict() {
1159 let t = T::new();
1160 let root = t.root.canonicalize().unwrap();
1161 assert!(matches!(
1162 copy_item(&root, ".", "docs", ".", "docs", false),
1163 Err(FsError::Invalid(_))
1164 ));
1165 assert!(matches!(
1166 copy_item(&root, ".", "docs", ".", "docs/inner", false),
1167 Err(FsError::Invalid(_))
1168 ));
1169 // First copy is fine, the second one conflicts, overwrite replaces.
1170 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1171 assert!(matches!(
1172 copy_item(&root, ".", "file.txt", ".", "src", false),
1173 Err(FsError::Conflict)
1174 ));
1175 std::fs::write(root.join("file.txt"), "v2").unwrap();
1176 copy_item(&root, ".", "file.txt", ".", "src", true).unwrap();
1177 assert_eq!(
1178 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1179 "v2"
1180 );
1181 // Copying onto itself is a no-op success.
1182 copy_item(&root, ".", "src/file.txt", ".", "src", false).unwrap();
1183 assert_eq!(
1184 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1185 "v2"
1186 );
1187 // Missing destination dir.
1188 assert!(matches!(
1189 copy_item(&root, ".", "file.txt", ".", "nope", false),
1190 Err(FsError::NotFound)
1191 ));
1192 }
1193
1194 #[test]
1195 fn copy_recursive_missing_source() {
1196 let t = T::new();
1197 let dst = t.tmp.path().join("dst");
1198 assert!(matches!(
1199 copy_recursive(&t.root.join("nope"), &dst),
1200 Err(FsError::NotFound)
1201 ));
1202 }
1203
1204 // ---------- is_within_or_eq ----------
1205
1206 #[test]
1207 fn is_within_or_eq_matrix() {
1208 let t = T::new();
1209 let root = t.root.canonicalize().unwrap();
1210 let docs = root.join("docs");
1211 assert!(is_within_or_eq(&docs, &docs));
1212 assert!(is_within_or_eq(&docs, &root.join("docs/inner")));
1213 assert!(!is_within_or_eq(&docs, &root));
1214 assert!(!is_within_or_eq(&docs, &root.join("src")));
1215 }
1216
1217 // ---------- content sniffing ----------
1218
1219 fn kind(bytes: &[u8], name: &str) -> FileKind {
1220 kind_from_bytes(bytes, Path::new(name))
1221 }
1222
1223 #[test]
1224 fn magic_numbers_classify_by_content() {
1225 let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
1226 // The name is a lie in every case: the bytes decide.
1227 assert_eq!(kind(&png, "notes.txt"), FileKind::Image);
1228 assert_eq!(kind(b"%PDF-1.7\n%aaa\n", "x.bin"), FileKind::Pdf);
1229 assert_eq!(
1230 kind(b"PK\x03\x04\x14\x00\x00\x00", "x.png"),
1231 FileKind::Archive
1232 );
1233 assert_eq!(
1234 kind(&[0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0], "x"),
1235 FileKind::Archive
1236 );
1237 assert_eq!(
1238 kind(
1239 &[
1240 0, 0, 0, 0x20, b'f', b't', b'y', b'p', b'i', b's', b'o', b'm'
1241 ],
1242 "x"
1243 ),
1244 FileKind::Video
1245 );
1246 assert_eq!(
1247 kind(b"ID3\x04\x00\x00\x00\x00\x00\x00", "x"),
1248 FileKind::Audio
1249 );
1250 assert_eq!(kind(b"RIFF\x24\x00\x00\x00WAVEfmt ", "x"), FileKind::Audio);
1251 assert_eq!(kind(b"<!doctype html><p>hi", "x"), FileKind::Text);
1252 // Recognized but not viewable in a browser.
1253 assert_eq!(
1254 kind(&[0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0], "x.wasm"),
1255 FileKind::Binary
1256 );
1257 }
1258
1259 #[test]
1260 fn unsigned_files_fall_back_to_the_text_heuristic() {
1261 // No magic number: plain text, source, config.
1262 assert_eq!(kind(b"hello world\n", "notes"), FileKind::Text);
1263 assert_eq!(kind(b"fn main() {}\n", "main.rs"), FileKind::Text);
1264 assert_eq!(
1265 kind("# über\nkey: wert\n".as_bytes(), "c.yaml"),
1266 FileKind::Text
1267 );
1268 // Extensionless text files work, which the old extension list missed.
1269 assert_eq!(kind(b"all:\n\tcargo build\n", "Makefile"), FileKind::Text);
1270 // Empty file → editable.
1271 assert_eq!(kind(b"", "new.txt"), FileKind::Text);
1272 // A NUL byte means binary, whatever the name says. (ELF has no
1273 // `infer` signature, so this is the path that catches it.)
1274 assert_eq!(
1275 kind(&[0x7F, b'E', b'L', b'F', 2, 1, 1, 0, 0], "run.txt"),
1276 FileKind::Binary
1277 );
1278 assert_eq!(kind(&[0xC3, 0x28, 0xFF, 0xFE], "x.txt"), FileKind::Binary);
1279 }
1280
1281 #[test]
1282 fn svg_is_offered_as_an_image() {
1283 // SVG is XML text with no magic number, but browsers draw it, so the
1284 // extension is the only signal available.
1285 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
1286 assert_eq!(kind(svg, "logo.svg"), FileKind::Image);
1287 assert_eq!(kind(svg, "logo.txt"), FileKind::Text);
1288 }
1289
1290 #[test]
1291 fn truncated_utf8_at_the_read_boundary_is_still_text() {
1292 // 255 ASCII bytes plus the first byte of a 2-byte character: the read
1293 // cut a character in half, which must not read as binary.
1294 let mut b = vec![b'a'; SNIFF_BYTES - 1];
1295 b.push(0xC3);
1296 assert_eq!(kind(&b, "x.txt"), FileKind::Text);
1297 }
1298
1299 #[test]
1300 fn detect_kind_reads_from_disk() {
1301 let t = T::new();
1302 assert_eq!(detect_kind(&t.root.join("docs"), true), FileKind::Dir);
1303 assert_eq!(detect_kind(&t.root.join("file.txt"), false), FileKind::Text);
1304 // Unreadable / missing → Binary, never a failed listing.
1305 assert_eq!(detect_kind(&t.root.join("nope"), false), FileKind::Binary);
1306 }
1307
1308 /// `SNIFF_BUDGET` is process-wide, so the two tests that assert on it must
1309 /// not run at the same time as each other.
1310 static BUDGET_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
1311
1312 /// A directory big enough to take the fan-out path must produce exactly
1313 /// what the serial path would. Pass 2 fills `is_dir`, `size`, `mtime` and
1314 /// `kind`, all on worker threads, so a chunk-boundary mistake would show up
1315 /// as a row carrying another row's metadata or the untouched placeholders.
1316 #[test]
1317 fn parallel_rows_match_serial() {
1318 use std::sync::atomic::Ordering;
1319 let _guard = BUDGET_TESTS.lock().unwrap();
1320 let t = T::new();
1321 let big = t.root.join("big");
1322 std::fs::create_dir_all(&big).unwrap();
1323 // Well over SNIFF_CHUNK, so several chunks are handed out.
1324 let n = SNIFF_CHUNK * 3 + 7;
1325 for i in 0..n {
1326 let p = big.join(format!("f{i:05}"));
1327 // Every file gets a distinct length, so `size` pins the row identity.
1328 let pad = vec![b'A'; i];
1329 let mut body = match i % 3 {
1330 0 => vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1331 1 => b"plain text\n".to_vec(),
1332 _ => vec![0u8, 1, 2, 3],
1333 };
1334 body.extend_from_slice(&pad);
1335 std::fs::write(&p, &body).unwrap();
1336 }
1337 std::fs::create_dir(big.join("a-subdir")).unwrap();
1338
1339 let entries = list_dir(&big).unwrap();
1340 assert_eq!(entries.len(), n + 1);
1341
1342 // Every row must agree with what a single-threaded read of that same
1343 // file reports: kind, size and directory flag.
1344 for e in &entries {
1345 let p = big.join(&e.name);
1346 let m = std::fs::metadata(&p).unwrap();
1347 assert_eq!(e.is_dir, m.is_dir(), "{}", e.name);
1348 assert_eq!(e.size, m.len(), "size mismatch on {}", e.name);
1349 assert_eq!(e.mtime, mtime_str(&m), "mtime mismatch on {}", e.name);
1350 assert_eq!(
1351 e.kind,
1352 detect_kind(&p, e.is_dir),
1353 "kind mismatch on {}",
1354 e.name
1355 );
1356 }
1357
1358 // Sanity: several kinds are actually present, so the loop above is not
1359 // trivially true, and the directory sorts first.
1360 let kinds: Vec<FileKind> = entries.iter().map(|e| e.kind).collect();
1361 assert!(kinds.contains(&FileKind::Image));
1362 assert!(kinds.contains(&FileKind::Text));
1363 assert!(kinds.contains(&FileKind::Binary));
1364 assert_eq!(entries[0].name, "a-subdir");
1365 assert_eq!(entries[0].kind, FileKind::Dir);
1366
1367 // The thread budget is fully returned once the listing is done.
1368 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1369 }
1370
1371 #[test]
1372 fn sniff_permit_never_exceeds_the_budget() {
1373 use std::sync::atomic::Ordering;
1374 let _guard = BUDGET_TESTS.lock().unwrap();
1375 let total = sniff_budget_total();
1376 let a = SniffPermit::claim(total * 2);
1377 assert_eq!(a.0, total, "a single claim is capped at the total");
1378 // Nothing left: the next listing runs serially rather than queueing.
1379 let b = SniffPermit::claim(4);
1380 assert_eq!(b.0, 0);
1381 drop(a);
1382 drop(b);
1383 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1384 }
1385
1386 #[test]
1387 fn list_dir_reports_kinds() {
1388 let t = T::new();
1389 std::fs::write(
1390 t.root.join("docs/pic.dat"),
1391 [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1392 )
1393 .unwrap();
1394 let entries = list_dir(&t.root.join("docs")).unwrap();
1395 let kind_of = |n: &str| entries.iter().find(|e| e.name == n).unwrap().kind;
1396 assert_eq!(kind_of("inner"), FileKind::Dir);
1397 assert_eq!(kind_of("a.txt"), FileKind::Text);
1398 assert_eq!(kind_of("pic.dat"), FileKind::Image);
1399 }
1400}
1401