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