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