bashkit 0.20.1

Awesomely fast virtual sandbox with bash and file system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Virtual filesystem for Bashkit.
//!
//! This module provides a virtual filesystem abstraction that allows Bashkit to
//! operate in a virtual environment without accessing the real filesystem.
//!
//! # Which Trait/Type Should I Use?
//!
//! ```text
//! Do you need a custom filesystem?
//!     │
//!     ├─ NO → Use InMemoryFs (default with Bash::new())
//!     │
//!     └─ YES → Is your storage simple (key-value, database, cloud)?
//!               │
//!               ├─ YES → Implement FsBackend + wrap with PosixFs
//!               │        (POSIX checks are automatic)
//!               │
//!               └─ NO → Implement FileSystem directly
//!                       (full control, you handle all checks)
//! ```
//!
//! # Architecture
//!
//! The filesystem abstraction has two layers:
//!
//! | Layer | Trait/Type | What You Implement |
//! |-------|------------|-------------------|
//! | Backend | [`FsBackend`] | Raw storage only (read/write/list) |
//! | POSIX | [`FileSystem`] | Full POSIX semantics (type checks, parent dirs) |
//!
//! **[`PosixFs`]** bridges these: it wraps any `FsBackend` and provides `FileSystem`.
//!
//! # Implementing Custom Filesystems
//!
//! ## Option 1: `FsBackend` + `PosixFs` (Recommended)
//!
//! Best for: databases, cloud storage, simple key-value stores.
//!
//! ```rust,ignore
//! use bashkit::{async_trait, FsBackend, PosixFs, Bash, Result, Metadata, DirEntry};
//! use std::sync::Arc;
//!
//! // Implement raw storage operations
//! struct MyStorage { /* ... */ }
//!
//! #[async_trait]
//! impl FsBackend for MyStorage {
//!     async fn read(&self, path: &Path) -> Result<Vec<u8>> { /* ... */ }
//!     async fn write(&self, path: &Path, content: &[u8]) -> Result<()> { /* ... */ }
//!     // ... other methods
//! }
//!
//! // Wrap with PosixFs - POSIX semantics are automatic!
//! let fs = Arc::new(PosixFs::new(MyStorage::new()));
//! let mut bash = Bash::builder().fs(fs).build();
//! ```
//!
//! ## Option 2: `FileSystem` Directly
//!
//! Best for: complex behavior, custom caching, specialized semantics.
//!
//! ```rust,ignore
//! use bashkit::{async_trait, FileSystem, FileSystemExt, Bash};
//!
//! struct MyFs { /* ... */ }
//!
//! #[async_trait]
//! impl FileSystemExt for MyFs {}
//!
//! #[async_trait]
//! impl FileSystem for MyFs {
//!     async fn write_file(&self, path: &Path, content: &[u8]) -> Result<()> {
//!         // You MUST check: is path a directory?
//!         if self.is_directory(path) {
//!             return Err(fs_errors::is_a_directory());
//!         }
//!         // ... write logic
//!     }
//!     // ... other methods with POSIX checks
//! }
//! ```
//!
//! See `examples/custom_backend.rs` and `examples/custom_filesystem_impl.rs`.
//!
//! # Built-in Implementations
//!
//! | Type | Description | Use Case |
//! |------|-------------|----------|
//! | [`InMemoryFs`] | HashMap-based storage with POSIX checks | Default, isolated execution |
//! | [`OverlayFs`] | Copy-on-write layered filesystem | Templates, immutable bases |
//! | [`MountableFs`] | Multiple filesystems at mount points | Complex multi-source setups |
//! | [`NamespaceFs`] | Static tree of rebased filesystem mounts | Build sandboxes, CI, plugin hosts |
//! | [`ReadOnlyFs`] | Mutation-denying wrapper around another filesystem | Inspection-only sessions |
//! | [`RealFs`] | Host directory access (`realfs` feature) | Expose host files to scripts |
//!
//! All implementations are thread-safe (`Send + Sync`) and fully async.
//!
//! # Quick Start
//!
//! ## Using InMemoryFs (Default)
//!
//! [`InMemoryFs`] is the default filesystem when using [`Bash::new()`](crate::Bash::new):
//!
//! ```rust
//! use bashkit::Bash;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! let mut bash = Bash::new();
//!
//! // Files are stored entirely in memory
//! bash.exec("echo 'hello' > /tmp/test.txt").await?;
//! let result = bash.exec("cat /tmp/test.txt").await?;
//! assert_eq!(result.stdout, "hello\n");
//! # Ok(())
//! # }
//! ```
//!
//! ## Using OverlayFs
//!
//! [`OverlayFs`] provides copy-on-write semantics - reads fall through to a base
//! layer while writes go to an overlay layer:
//!
//! ```rust
//! use bashkit::{Bash, FileSystem, InMemoryFs, OverlayFs};
//! use std::path::Path;
//! use std::sync::Arc;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! // Create a base filesystem with template files
//! let base = Arc::new(InMemoryFs::new());
//! base.mkdir(Path::new("/templates"), false).await?;
//! base.write_file(Path::new("/templates/config.txt"), b"default=true").await?;
//!
//! // Create overlay - base is read-only, changes go to overlay
//! let overlay = Arc::new(OverlayFs::new(base.clone()));
//!
//! let mut bash = Bash::builder().fs(overlay).build();
//!
//! // Read from base layer
//! let result = bash.exec("cat /templates/config.txt").await?;
//! assert_eq!(result.stdout, "default=true");
//!
//! // Modify - changes go to overlay, base is unchanged
//! bash.exec("echo 'modified=true' > /templates/config.txt").await?;
//!
//! // Base still has original content
//! let original = base.read_file(Path::new("/templates/config.txt")).await?;
//! assert_eq!(original, b"default=true");
//! # Ok(())
//! # }
//! ```
//!
//! ## Using MountableFs
//!
//! [`MountableFs`] allows mounting different filesystems at specific paths:
//!
//! ```rust
//! use bashkit::{Bash, FileSystem, InMemoryFs, MountableFs};
//! use std::path::Path;
//! use std::sync::Arc;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! // Create root and a separate data filesystem
//! let root = Arc::new(InMemoryFs::new());
//! let data_fs = Arc::new(InMemoryFs::new());
//!
//! // Pre-populate the data filesystem
//! data_fs.write_file(Path::new("/users.json"), br#"["alice", "bob"]"#).await?;
//!
//! // Create mountable filesystem and mount data_fs at /mnt/data
//! let mountable = MountableFs::new(root);
//! mountable.mount("/mnt/data", data_fs)?;
//!
//! let mut bash = Bash::builder().fs(Arc::new(mountable)).build();
//!
//! // Access the mounted filesystem
//! let result = bash.exec("cat /mnt/data/users.json").await?;
//! assert!(result.stdout.contains("alice"));
//! # Ok(())
//! # }
//! ```
//!
//! ## Using RealFs (Host Filesystem Access)
//!
//! [`RealFs`] exposes a host directory inside the VFS. It requires the `realfs`
//! feature flag. Two access modes are available:
//!
//! - **ReadOnly** — scripts can read host files but writes go to an in-memory overlay
//! - **ReadWrite** — scripts can modify host files directly (breaks sandbox)
//!
//! The easiest way to use it is through [`BashBuilder`](crate::BashBuilder):
//!
//! ```rust,ignore
//! use bashkit::Bash;
//!
//! // Readonly overlay at root — host files visible at /
//! let mut bash = Bash::builder()
//!     .mount_real_readonly("/path/to/project")
//!     .build();
//!
//! // Readonly mount at a specific path
//! let mut bash = Bash::builder()
//!     .mount_real_readonly_at("/path/to/data", "/mnt/data")
//!     .build();
//!
//! // Read-write mount (WARNING: breaks sandbox)
//! let mut bash = Bash::builder()
//!     .mount_real_readwrite_at("/path/to/workspace", "/mnt/ws")
//!     .build();
//! ```
//!
//! You can also use [`RealFs`] directly as an [`FsBackend`] with [`PosixFs`]:
//!
//! ```rust,ignore
//! use bashkit::{Bash, PosixFs};
//! use bashkit::fs::{RealFs, RealFsMode};
//! use std::sync::Arc;
//!
//! let backend = RealFs::open("/path/to/dir", RealFsMode::ReadOnly).await.unwrap();
//! let fs = Arc::new(PosixFs::new(backend));
//! let mut bash = Bash::builder().fs(fs).build();
//! ```
//!
//! See `examples/realfs_readonly.rs` and `examples/realfs_readwrite.rs`.
//!
//! # Direct Filesystem Access
//!
//! Access the filesystem directly for pre-populating files or reading output:
//!
//! ```rust
//! use bashkit::{Bash, FileSystem};
//! use std::path::Path;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! let mut bash = Bash::new();
//! let fs = bash.fs();
//!
//! // Create directories
//! fs.mkdir(Path::new("/data"), false).await?;
//! fs.mkdir(Path::new("/data/input"), false).await?;
//! fs.mkdir(Path::new("/data/output"), false).await?;
//!
//! // Pre-populate input files
//! fs.write_file(Path::new("/data/input/data.csv"), b"name,value\nalice,100").await?;
//!
//! // Run a script that processes the data
//! bash.exec("cat /data/input/data.csv | grep alice > /data/output/result.txt").await?;
//!
//! // Read the output directly
//! let output = fs.read_file(Path::new("/data/output/result.txt")).await?;
//! assert_eq!(output, b"alice,100\n");
//!
//! // Check file exists
//! assert!(fs.exists(Path::new("/data/output/result.txt")).await?);
//!
//! // Get file metadata
//! let stat = fs.stat(Path::new("/data/output/result.txt")).await?;
//! assert!(stat.file_type.is_file());
//!
//! // List directory contents
//! let entries = fs.read_dir(Path::new("/data")).await?;
//! let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
//! assert!(names.contains(&"input"));
//! assert!(names.contains(&"output"));
//! # Ok(())
//! # }
//! ```
//!
//! # Binary File Support
//!
//! The filesystem fully supports binary data including null bytes:
//!
//! ```rust
//! use bashkit::{Bash, FileSystem};
//! use std::path::Path;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! let bash = Bash::new();
//! let fs = bash.fs();
//!
//! // Write binary data (e.g., PNG header)
//! let binary_data = vec![0x89, 0x50, 0x4E, 0x47, 0x00, 0xFF];
//! fs.write_file(Path::new("/tmp/image.bin"), &binary_data).await?;
//!
//! // Read it back
//! let content = fs.read_file(Path::new("/tmp/image.bin")).await?;
//! assert_eq!(content, binary_data);
//! # Ok(())
//! # }
//! ```
//!
//! # Implementing Custom Filesystems
//!
//! Implement the [`FileSystem`] trait to create custom storage backends:
//!
//! ```rust
//! use bashkit::{async_trait, FileSystem, FileSystemExt, DirEntry, Metadata, FileType, Result, Error};
//! use std::path::{Path, PathBuf};
//! use std::collections::HashMap;
//! use std::sync::RwLock;
//! use std::time::SystemTime;
//!
//! /// A simple custom filesystem example
//! pub struct SimpleFs {
//!     files: RwLock<HashMap<PathBuf, Vec<u8>>>,
//! }
//!
//! impl SimpleFs {
//!     pub fn new() -> Self {
//!         let mut files = HashMap::new();
//!         // Initialize with root and common directories
//!         files.insert(PathBuf::from("/"), Vec::new());
//!         files.insert(PathBuf::from("/tmp"), Vec::new());
//!         Self { files: RwLock::new(files) }
//!     }
//! }
//!
//! #[async_trait]
//! impl FileSystemExt for SimpleFs {}
//!
//! #[async_trait]
//! impl FileSystem for SimpleFs {
//!     async fn read_file(&self, path: &Path) -> Result<Vec<u8>> {
//!         let files = self.files.read().unwrap();
//!         files.get(path)
//!             .cloned()
//!             .ok_or_else(|| Error::Io(std::io::Error::new(
//!                 std::io::ErrorKind::NotFound,
//!                 "file not found"
//!             )))
//!     }
//!
//!     async fn write_file(&self, path: &Path, content: &[u8]) -> Result<()> {
//!         let mut files = self.files.write().unwrap();
//!         files.insert(path.to_path_buf(), content.to_vec());
//!         Ok(())
//!     }
//!
//!     // ... implement remaining methods
//! #   async fn append_file(&self, _path: &Path, _content: &[u8]) -> Result<()> { Ok(()) }
//! #   async fn mkdir(&self, _path: &Path, _recursive: bool) -> Result<()> { Ok(()) }
//! #   async fn remove(&self, _path: &Path, _recursive: bool) -> Result<()> { Ok(()) }
//! #   async fn stat(&self, _path: &Path) -> Result<Metadata> {
//! #       Ok(Metadata::default())
//! #   }
//! #   async fn read_dir(&self, _path: &Path) -> Result<Vec<DirEntry>> { Ok(vec![]) }
//! #   async fn exists(&self, _path: &Path) -> Result<bool> { Ok(false) }
//! #   async fn rename(&self, _from: &Path, _to: &Path) -> Result<()> { Ok(()) }
//! #   async fn copy(&self, _from: &Path, _to: &Path) -> Result<()> { Ok(()) }
//! #   async fn symlink(&self, _target: &Path, _link: &Path) -> Result<()> { Ok(()) }
//! #   async fn read_link(&self, _path: &Path) -> Result<PathBuf> { Ok(PathBuf::new()) }
//! #   async fn chmod(&self, _path: &Path, _mode: u32) -> Result<()> { Ok(()) }
//! }
//! ```
//!
//! For a complete custom filesystem implementation example, see
//! `examples/custom_filesystem_impl.rs`.
//!
//! # Default Directory Structure
//!
//! [`InMemoryFs::new()`] creates these directories by default:
//!
//! - `/` - Root directory
//! - `/tmp` - Temporary files
//! - `/home` - Home directories
//! - `/home/user` - Default user home
//! - `/dev` - Device files
//! - `/dev/null` - Null device (discards writes, returns empty on read)
//!
//! # Requirements for Custom FileSystem Implementations
//!
//! When implementing [`FileSystem`] for custom storage backends, your implementation
//! **must** ensure:
//!
//! 1. **Root directory exists**: `exists("/")` must return `true`
//! 2. **Path normalization**: Paths like `/.`, `/tmp/..`, etc. must resolve correctly
//! 3. **Root is listable**: `read_dir("/")` must return the root's contents
//! 4. **Failed mutations are atomic**: `write_file`, `copy`, and `rename` errors
//!    must preserve entry contents, types, and reported usage
//!
//! Without these, commands like `cd /` and `ls /` will fail with "No such file or directory".
//!
//! Use [`verify_filesystem_requirements`] for the structural requirements in
//! items 1–3. Test mutation atomicity and other security invariants separately:
//!
//! ```rust
//! use bashkit::{verify_filesystem_requirements, InMemoryFs};
//! use std::sync::Arc;
//!
//! # #[tokio::main]
//! # async fn main() -> bashkit::Result<()> {
//! let fs = Arc::new(InMemoryFs::new());
//! verify_filesystem_requirements(&*fs).await?;
//! # Ok(())
//! # }
//! ```

mod backend;
mod follow;
mod limits;
mod memory;
mod mountable;
mod namespace;
mod overlay;
mod posix;
mod proc_sub_fds;
mod readonly;
#[cfg(feature = "realfs")]
mod realfs;
mod rootfs;
mod search;
mod std_streams;
mod traits;

pub use backend::FsBackend;
#[allow(unused_imports)]
pub(crate) use follow::{FollowFs, MAX_SYMLINK_HOPS};
pub use limits::{FsLimitExceeded, FsLimits, FsUsage};
pub use memory::{InMemoryFs, LazyLoader, VfsEntry, VfsEntryKind, VfsSnapshot};
pub use mountable::MountableFs;
pub use namespace::{NamespaceAccess, NamespaceFs, NamespaceFsBuilder};
pub use overlay::OverlayFs;
pub use posix::PosixFs;
pub(crate) use proc_sub_fds::{
    PROC_SUB_FIRST_FD, ProcSubBuffer, ProcSubData, ProcSubFs, proc_sub_fd,
};
pub use readonly::ReadOnlyFs;
#[cfg(feature = "realfs")]
pub use realfs::{RealFs, RealFsMode};
pub(crate) use rootfs::{RootFs, stub_command};
pub use search::{
    SearchCapabilities, SearchCapable, SearchMatch, SearchProvider, SearchQuery, SearchResults,
};
pub(crate) use std_streams::{StdStreamsFs, args_name_std_stream};
pub use traits::{DirEntry, FileSystem, FileSystemExt, FileType, Metadata, fs_errors};

use crate::error::Result;
use std::io::{Error as IoError, ErrorKind};
use std::path::{Path, PathBuf};

/// Join `child` onto the VFS path `base`, always using `/` as the separator.
///
/// `PathBuf::join`/`push` insert the *host* separator (`\` on Windows) whenever
/// the buffer does not already end in one, so `/d/proj` + `src` becomes
/// `/d/proj\src` there. The VFS is Unix-style on every host (see
/// [`normalize_path`]), and builtins print these paths verbatim, so a host
/// separator leaks into command output and error messages (issue #2425).
/// Every VFS path built from a cwd, an operand, or a directory entry goes
/// through this helper instead of `Path::join`; host paths (`RealFs` under its
/// root, host mount mapping) keep using `Path::join`, where the host separator
/// is the correct one.
///
/// Semantics match `Path::join` for VFS paths: an absolute `child` replaces
/// `base`, and no `.`/`..` resolution happens here (backends normalize on
/// entry). It differs only for an empty `child`, where the result is `base`
/// without a trailing separator.
pub fn vfs_join(base: &Path, child: impl AsRef<Path>) -> PathBuf {
    let child = child.as_ref();
    // Non-UTF-8 pieces cannot be reassembled as a string; they never occur in
    // the VFS (paths come from shell words and `DirEntry::name`, both `String`),
    // so fall back rather than mangle them through a lossy conversion.
    let (Some(base), Some(child)) = (base.to_str(), child.to_str()) else {
        return base.join(child);
    };
    match (base, child) {
        ("", _) => PathBuf::from(child),
        (_, "") => PathBuf::from(base),
        (_, _) if child.starts_with('/') => PathBuf::from(child),
        _ => PathBuf::from(format!("{}/{}", base.trim_end_matches('/'), child)),
    }
}

/// Normalize a virtual filesystem path by resolving `.` and `..` components.
///
/// Returns a canonical absolute path. If the result would be empty (e.g., from
/// `/../..`), returns `/`.
pub fn normalize_path(path: &Path) -> PathBuf {
    use std::path::Component;
    // THREAT[TM-ESC-033]: Discard host namespace prefixes before any backend
    // join. On Windows this contains drive-relative, drive-absolute, UNC, and
    // device paths inside the POSIX VFS root instead of preserving host syntax.
    // Build path as String with forward slashes to ensure Unix-style paths
    // on all platforms (the VFS is always Unix-style, even on Windows).
    let mut segments: Vec<&str> = Vec::new();
    for component in path.components() {
        match component {
            Component::RootDir => {
                segments.clear();
            }
            Component::Normal(name) => {
                if let Some(s) = name.to_str() {
                    segments.push(s);
                }
            }
            Component::ParentDir => {
                segments.pop();
            }
            Component::CurDir | Component::Prefix(_) => {}
        }
    }
    if segments.is_empty() {
        PathBuf::from("/")
    } else {
        PathBuf::from(format!("/{}", segments.join("/")))
    }
}

#[cfg(all(test, windows))]
mod windows_containment_tests {
    use super::*;

    /// Pins the host behavior the VFS rules exist for, so the reasoning behind
    /// [`vfs_join`] and the `has_root()` guards is checked on Windows rather
    /// than asserted in a comment. If std ever changed these, this test says so
    /// before the rules start looking arbitrary.
    #[test]
    fn windows_containment_host_path_hazards_are_still_real() {
        // Why `vfs_join` exists: `Path::join` inserts the host separator.
        assert_eq!(
            Path::new("/d/proj").join("src").to_string_lossy(),
            r"/d/proj\src"
        );
        assert_eq!(
            vfs_join(Path::new("/d/proj"), "src").to_string_lossy(),
            "/d/proj/src"
        );

        // Why absolute-target guards test `has_root()`: a VFS-absolute path
        // carries no drive prefix, so `is_absolute()` is false here.
        assert!(!Path::new("/etc/passwd").is_absolute());
        assert!(Path::new("/etc/passwd").has_root());

        // Why a mixed-separator path still resolves: both are separators here,
        // which is what keeps the leak cosmetic rather than functional.
        assert_eq!(Path::new(r"/d/proj\src"), Path::new("/d/proj/src"));
    }

    #[test]
    fn windows_containment_normalizes_host_path_syntax_into_vfs_root() {
        assert_eq!(
            normalize_path(Path::new(r"\tmp\..\safe")),
            Path::new("/safe")
        );
        assert_eq!(
            normalize_path(Path::new(r"C:relative\file.txt")),
            Path::new("/relative/file.txt")
        );
        assert_eq!(
            normalize_path(Path::new(r"C:\absolute\file.txt")),
            Path::new("/absolute/file.txt")
        );
        assert_eq!(
            normalize_path(Path::new(r"\\server\share\file.txt")),
            Path::new("/file.txt")
        );
        assert_eq!(
            normalize_path(Path::new(r"\\?\C:\device\file.txt")),
            Path::new("/device/file.txt")
        );
    }
}

/// Verify that a filesystem implementation meets minimum requirements for Bashkit.
///
/// This function checks that your custom [`FileSystem`] implementation:
/// - Has root directory `/` that exists
/// - Can stat the root directory
/// - Can list the root directory contents
/// - Handles path normalization (e.g., `/.` resolves to `/`)
///
/// # Scope
///
/// This is a non-mutating structural smoke check, not a filesystem security
/// certification. It does not validate failure atomicity, symlink behavior,
/// quota accounting, or normalized error kinds. Custom implementations must
/// test those parts of the [`FileSystem`] contract separately.
///
/// # Errors
///
/// Returns an error describing what requirement is not met.
///
/// # Example
///
/// ```rust
/// use bashkit::{verify_filesystem_requirements, InMemoryFs};
/// use std::sync::Arc;
///
/// # #[tokio::main]
/// # async fn main() -> bashkit::Result<()> {
/// let fs = Arc::new(InMemoryFs::new());
/// verify_filesystem_requirements(&*fs).await?;
/// println!("Filesystem meets all requirements!");
/// # Ok(())
/// # }
/// ```
pub async fn verify_filesystem_requirements(fs: &dyn FileSystem) -> Result<()> {
    // Check 1: Root directory must exist
    if !fs.exists(Path::new("/")).await? {
        return Err(IoError::new(
            ErrorKind::NotFound,
            "FileSystem requirement not met: root directory '/' does not exist. \
             Custom FileSystem implementations must ensure '/' exists on creation.",
        )
        .into());
    }

    // Check 2: Root must be a directory
    let stat = fs.stat(Path::new("/")).await.map_err(|_| {
        IoError::new(
            ErrorKind::NotFound,
            "FileSystem requirement not met: cannot stat root directory '/'. \
             Ensure stat() works for the root path.",
        )
    })?;

    if !stat.file_type.is_dir() {
        return Err(IoError::new(
            ErrorKind::InvalidData,
            "FileSystem requirement not met: root '/' is not a directory.",
        )
        .into());
    }

    // Check 3: Root must be listable
    fs.read_dir(Path::new("/")).await.map_err(|_| {
        IoError::new(
            ErrorKind::NotFound,
            "FileSystem requirement not met: cannot list root directory '/'. \
             Ensure read_dir() works for the root path.",
        )
    })?;

    // Check 4: Path normalization - "/." should resolve to "/"
    if !fs.exists(Path::new("/.")).await? {
        return Err(IoError::new(
            ErrorKind::NotFound,
            "FileSystem requirement not met: path '/.' does not resolve to root. \
             Ensure your implementation normalizes paths (removes '.' components).",
        )
        .into());
    }

    Ok(())
}

/// Resolve every symlink to a POSIX VFS path on every host, with an ELOOP hop cap.
pub(crate) async fn canonicalize(fs: &dyn FileSystem, path: &Path) -> crate::Result<PathBuf> {
    let mut rest: std::collections::VecDeque<String> = path
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
            std::path::Component::ParentDir => Some("..".to_string()),
            _ => None,
        })
        .collect();
    let mut out = PathBuf::from("/");
    let mut hops = 0;
    while let Some(comp) = rest.pop_front() {
        if comp == ".." {
            out.pop();
            continue;
        }
        let candidate = vfs_join(&out, &comp);
        match fs.lstat(&candidate).await {
            Ok(m) if m.file_type.is_symlink() => {
                hops += 1;
                if hops > MAX_SYMLINK_HOPS {
                    return Err(std::io::Error::other("Too many levels of symbolic links").into());
                }
                let target = fs.read_link(&candidate).await?;
                if target.has_root() {
                    out = PathBuf::from("/");
                }
                let mut parts: Vec<String> = target
                    .components()
                    .filter_map(|c| match c {
                        std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
                        std::path::Component::ParentDir => Some("..".to_string()),
                        _ => None,
                    })
                    .collect();
                while let Some(p) = parts.pop() {
                    rest.push_front(p);
                }
            }
            Ok(_) => out = candidate,
            Err(e) => return Err(e),
        }
    }
    Ok(out)
}

#[cfg(test)]
mod vfs_join_tests {
    use super::*;

    /// The separator is `/` on every host, so these assertions are the same
    /// ones the Windows CI job checks — there `Path::join` would produce
    /// `/d/proj\src`.
    #[test]
    fn windows_containment_vfs_join_always_uses_forward_slashes() {
        let base = Path::new("/d/proj");
        let src = vfs_join(base, "src");
        assert_eq!(src.to_string_lossy(), "/d/proj/src");
        // Nested joins are where `PathBuf::push` accumulates host separators.
        let file = vfs_join(&src, "main.rs");
        assert_eq!(file.to_string_lossy(), "/d/proj/src/main.rs");
        assert!(!file.to_string_lossy().contains('\\'));
    }

    #[test]
    fn windows_containment_vfs_join_matches_path_join_semantics() {
        // Absolute child replaces the base, like `Path::join`.
        assert_eq!(
            vfs_join(Path::new("/d/proj"), "/etc/hosts").to_string_lossy(),
            "/etc/hosts"
        );
        // A trailing separator on the base is not doubled.
        assert_eq!(
            vfs_join(Path::new("/d/proj/"), "src").to_string_lossy(),
            "/d/proj/src"
        );
        // Root is still a single separator.
        assert_eq!(vfs_join(Path::new("/"), "etc").to_string_lossy(), "/etc");
        // Multi-segment children keep their own separators.
        assert_eq!(
            vfs_join(Path::new("/d/proj"), "src/main.rs").to_string_lossy(),
            "/d/proj/src/main.rs"
        );
        // `.`/`..` are left for the backends to normalize.
        assert_eq!(
            vfs_join(Path::new("/d/proj"), "../other").to_string_lossy(),
            "/d/proj/../other"
        );
        // Empty pieces: relative bases and empty children stay usable.
        assert_eq!(vfs_join(Path::new(""), "src").to_string_lossy(), "src");
        assert_eq!(
            vfs_join(Path::new("/d/proj"), "").to_string_lossy(),
            "/d/proj"
        );
    }

    #[test]
    fn windows_containment_vfs_join_result_normalizes_like_a_backend() {
        // What the backends do to the joined path must not change.
        assert_eq!(
            normalize_path(&vfs_join(Path::new("/d/proj"), "../other/./x")),
            Path::new("/d/other/x")
        );
    }
}