From 6813cf2c90854d603b1dea538a0bb4a4e53cccdc Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 18:06:34 +0000 Subject: [PATCH 1/2] fix(vfs): keep VFS paths slash-separated on Windows On Windows, `echo x > /dev/stderr` wrote a VFS file: dev_fd_alias re-normalized the target with PathBuf::push, producing /dev\stderr, which missed the device match (#2933). Use the shared normalize_path. A clippy run with host-separator joins banned found the rest of the class: PosixFs mkdir -p parent checks (backend saw /a\b), cd x/.., readlink -f prefix probes, OverlayFs upper-dir counting, and git refs/heads paths. All now use vfs_join. Guard against a third sweep: crates/bashkit/clippy.toml bans Path::join, PathBuf::push, set_file_name and with_file_name, with scoped allows for host-path code. testing::CheckedFs records the paths a filesystem receives; Windows CI now runs the device-path and separator integration tests. Public custom-fs examples no longer teach the push pattern. Closes #2933 --- .github/workflows/ci.yml | 5 + crates/bashkit/benches/remote_fs.rs | 3 + crates/bashkit/clippy.toml | 14 ++ crates/bashkit/examples/custom_backend.rs | 19 +- .../examples/custom_filesystem_impl.rs | 25 +- .../examples/generate_snapshot_fixtures.rs | 3 + crates/bashkit/examples/realfs_readonly.rs | 3 + crates/bashkit/examples/realfs_readwrite.rs | 3 + crates/bashkit/examples/terminal_record.rs | 2 + crates/bashkit/src/builtins/git/client.rs | 12 +- crates/bashkit/src/builtins/navigation.rs | 3 +- crates/bashkit/src/builtins/path.rs | 3 +- crates/bashkit/src/fs/mod.rs | 1 + crates/bashkit/src/fs/overlay.rs | 3 +- crates/bashkit/src/fs/posix.rs | 25 +- crates/bashkit/src/fs/realfs.rs | 3 + crates/bashkit/src/interpreter/mod.rs | 68 +++--- crates/bashkit/src/lib.rs | 11 +- crates/bashkit/src/testing.rs | 4 + crates/bashkit/src/testing/checked_fs.rs | 213 ++++++++++++++++++ crates/bashkit/tests/integration/main.rs | 4 + .../tests/integration/vfs_separator_tests.rs | 59 +++++ crates/bashkit/tests/realfs_tests.rs | 2 + knowledge/foundations/vfs.md | 34 ++- knowledge/log.md | 2 + knowledge/security/threat-model.md | 3 + 26 files changed, 444 insertions(+), 83 deletions(-) create mode 100644 crates/bashkit/clippy.toml create mode 100644 crates/bashkit/src/testing/checked_fs.rs create mode 100644 crates/bashkit/tests/integration/vfs_separator_tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60b5c82a0..bcdff895c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -528,6 +528,11 @@ jobs: - name: Run host mount mapping tests run: cargo test -p bashkit --test integration --features realfs -- host_mounts_tests + # The VFS is `/`-separated on every host; host-separator joins only show + # up here (#2425, #2933). Reuses the realfs build from the steps above. + - name: Run VFS separator and device path tests + run: cargo test -p bashkit --test integration --features realfs -- windows_containment dev_fd_path_tests dev_null_tests + - name: Run command resolver tests run: cargo test -p bashkit --test integration -- command_resolver_tests diff --git a/crates/bashkit/benches/remote_fs.rs b/crates/bashkit/benches/remote_fs.rs index 8d1771177..a1854f248 100644 --- a/crates/bashkit/benches/remote_fs.rs +++ b/crates/bashkit/benches/remote_fs.rs @@ -18,6 +18,9 @@ //! Run with: `cargo bench --bench remote_fs` //! Counts only: `cargo bench --bench remote_fs -- --counts` +// Reads the host checkout; the VFS separator ban targets library code. +#![allow(clippy::disallowed_methods)] + use bashkit::testing::{CallCounts, CountingFs}; use bashkit::{Bash, FileSystem, FsLimits}; use criterion::{BenchmarkId, Criterion, criterion_group}; diff --git a/crates/bashkit/clippy.toml b/crates/bashkit/clippy.toml new file mode 100644 index 000000000..73e22c279 --- /dev/null +++ b/crates/bashkit/clippy.toml @@ -0,0 +1,14 @@ +# Decision: the VFS is POSIX-rooted on every host (TM-ESC-033). `Path::join`, +# `PathBuf::push` and friends join with the host separator, so on Windows they +# turn `/a` + `b` into `/a\b`. That broke `/dev/stderr` redirects (#2933) and +# printed mixed separators (#2425); Linux CI and fuzzing cannot see it because +# the host separator there is already `/`. Build VFS paths with +# `crate::fs::vfs_join` instead. Code that really handles host paths (RealFs, +# host mounts, test temp dirs) opts out with a scoped +# `#[allow(clippy::disallowed_methods)]` and a reason. +disallowed-methods = [ + { path = "std::path::Path::join", reason = "joins with the host separator (`\\` on Windows); use crate::fs::vfs_join for VFS paths" }, + { path = "std::path::PathBuf::push", reason = "joins with the host separator (`\\` on Windows); use crate::fs::vfs_join for VFS paths" }, + { path = "std::path::PathBuf::set_file_name", reason = "joins with the host separator (`\\` on Windows); build VFS paths with crate::fs::vfs_join" }, + { path = "std::path::Path::with_file_name", reason = "joins with the host separator (`\\` on Windows); build VFS paths with crate::fs::vfs_join" }, +] diff --git a/crates/bashkit/examples/custom_backend.rs b/crates/bashkit/examples/custom_backend.rs index 4a83faf1e..9df224459 100644 --- a/crates/bashkit/examples/custom_backend.rs +++ b/crates/bashkit/examples/custom_backend.rs @@ -47,20 +47,9 @@ impl SimpleStorage { } fn normalize(path: &Path) -> PathBuf { - let mut result = PathBuf::from("/"); - for component in path.components() { - match component { - std::path::Component::Normal(name) => result.push(name), - std::path::Component::ParentDir => { - result.pop(); - } - _ => {} - } - } - if result.as_os_str().is_empty() { - result.push("/"); - } - result + // The VFS is `/`-separated on every host. Use bashkit's normalizer, not + // `PathBuf::push`, which joins with `\` on Windows. + bashkit::normalize_path(path) } } @@ -114,7 +103,7 @@ impl FsBackend for SimpleStorage { let mut current = PathBuf::from("/"); let mut entries = self.entries.write().unwrap(); for component in path.components().skip(1) { - current.push(component); + current = bashkit::vfs_join(¤t, component); entries .entry(current.clone()) .or_insert(StorageEntry::Directory); diff --git a/crates/bashkit/examples/custom_filesystem_impl.rs b/crates/bashkit/examples/custom_filesystem_impl.rs index 9c985b800..1a1a17241 100644 --- a/crates/bashkit/examples/custom_filesystem_impl.rs +++ b/crates/bashkit/examples/custom_filesystem_impl.rs @@ -79,26 +79,9 @@ impl SessionFileSystemAdapter { } fn normalize_path(&self, path: &Path) -> PathBuf { - let mut result = PathBuf::new(); - for component in path.components() { - match component { - std::path::Component::RootDir => { - result.push("/"); - } - std::path::Component::Normal(name) => { - result.push(name); - } - std::path::Component::ParentDir => { - result.pop(); - } - std::path::Component::CurDir => {} - std::path::Component::Prefix(_) => {} - } - } - if result.as_os_str().is_empty() { - result.push("/"); - } - result + // The VFS is `/`-separated on every host. Use bashkit's normalizer, not + // `PathBuf::push`, which joins with `\` on Windows. + bashkit::normalize_path(path) } } @@ -163,7 +146,7 @@ impl FileSystem for SessionFileSystemAdapter { if recursive { let mut current = PathBuf::new(); for component in path.components() { - current.push(component); + current = bashkit::vfs_join(¤t, component); let mut files = self.store.files.write().unwrap(); if !files.contains_key(¤t) { files.insert(current.clone(), Vec::new()); diff --git a/crates/bashkit/examples/generate_snapshot_fixtures.rs b/crates/bashkit/examples/generate_snapshot_fixtures.rs index 36cd3c281..b85c636bb 100644 --- a/crates/bashkit/examples/generate_snapshot_fixtures.rs +++ b/crates/bashkit/examples/generate_snapshot_fixtures.rs @@ -7,6 +7,9 @@ //! reads bytes written by an older one. See //! `knowledge/foundations/snapshot-history.md`. +// Writes host fixture files; the VFS separator ban targets VFS paths. +#![allow(clippy::disallowed_methods)] + use bashkit::{Bash, SnapshotOptions}; use std::path::Path; diff --git a/crates/bashkit/examples/realfs_readonly.rs b/crates/bashkit/examples/realfs_readonly.rs index 7104d8f23..fb3dd3c74 100644 --- a/crates/bashkit/examples/realfs_readonly.rs +++ b/crates/bashkit/examples/realfs_readonly.rs @@ -5,6 +5,9 @@ //! //! Run with: cargo run --example realfs_readonly --features realfs +// Host paths for the RealFs mount; the VFS separator ban targets VFS paths. +#![allow(clippy::disallowed_methods)] + use bashkit::Bash; #[tokio::main] diff --git a/crates/bashkit/examples/realfs_readwrite.rs b/crates/bashkit/examples/realfs_readwrite.rs index 69678272a..96e6b7c0a 100644 --- a/crates/bashkit/examples/realfs_readwrite.rs +++ b/crates/bashkit/examples/realfs_readwrite.rs @@ -7,6 +7,9 @@ //! //! Run with: cargo run --example realfs_readwrite --features realfs +// Host paths for the RealFs mount; the VFS separator ban targets VFS paths. +#![allow(clippy::disallowed_methods)] + use bashkit::Bash; #[tokio::main] diff --git a/crates/bashkit/examples/terminal_record.rs b/crates/bashkit/examples/terminal_record.rs index 3eb908741..5007f70fc 100644 --- a/crates/bashkit/examples/terminal_record.rs +++ b/crates/bashkit/examples/terminal_record.rs @@ -46,6 +46,8 @@ impl Recorder { #[tokio::main] async fn main() { let out_path = std::env::args().nth(1).unwrap_or_else(|| { + // Host temp dir, not a VFS path. + #[allow(clippy::disallowed_methods)] std::env::temp_dir() .join("terminal-demo.cast") .display() diff --git a/crates/bashkit/src/builtins/git/client.rs b/crates/bashkit/src/builtins/git/client.rs index caae6152d..6f7cfee90 100644 --- a/crates/bashkit/src/builtins/git/client.rs +++ b/crates/bashkit/src/builtins/git/client.rs @@ -1198,7 +1198,7 @@ impl GitClient { ) -> Result<()> { Self::validate_ref_name(name)?; let git_dir = vfs_join(repo_path, ".git"); - let branch_path = vfs_join(&git_dir, "refs/heads").join(name); + let branch_path = vfs_join(&vfs_join(&git_dir, "refs/heads"), name); if !fs.exists(&git_dir).await? { return Err(Error::Internal(format!( @@ -1238,7 +1238,7 @@ impl GitClient { Self::validate_ref_name(target)?; let git_dir = vfs_join(repo_path, ".git"); let head_path = vfs_join(&git_dir, "HEAD"); - let branch_path = vfs_join(&git_dir, "refs/heads").join(target); + let branch_path = vfs_join(&vfs_join(&git_dir, "refs/heads"), target); if !fs.exists(&git_dir).await? { return Err(Error::Internal(format!( @@ -1511,7 +1511,7 @@ impl GitClient { let head = String::from_utf8_lossy(&head_content); if let Some(branch) = head.trim().strip_prefix("ref: refs/heads/") { Self::validate_ref_name(branch)?; - let ref_path = vfs_join(&git_dir, "refs/heads").join(branch); + let ref_path = vfs_join(&vfs_join(&git_dir, "refs/heads"), branch); if fs.exists(&ref_path).await? { let hash = fs.read_file(&ref_path).await?; // Sanitize hash read from ref file (TM-GIT-015) @@ -1536,7 +1536,7 @@ impl GitClient { arg )) })?; - let ref_path = vfs_join(&git_dir, "refs/heads").join(arg); + let ref_path = vfs_join(&vfs_join(&git_dir, "refs/heads"), arg); if fs.exists(&ref_path).await? { let hash = fs.read_file(&ref_path).await?; // Sanitize hash read from ref file (TM-GIT-015) @@ -1735,7 +1735,7 @@ impl GitClient { let head = String::from_utf8_lossy(&head_content); if let Some(branch) = head.trim().strip_prefix("ref: refs/heads/") { Self::validate_ref_name(branch)?; - let ref_path = vfs_join(git_dir, "refs/heads").join(branch); + let ref_path = vfs_join(&vfs_join(git_dir, "refs/heads"), branch); if fs.exists(&ref_path).await? { let hash = fs.read_file(&ref_path).await?; return Ok(String::from_utf8_lossy(&hash).trim().to_string()); @@ -1746,7 +1746,7 @@ impl GitClient { // Try as branch name. Invalid ref names cannot be resolved via the VFS. if Self::validate_ref_name(refspec).is_ok() { - let ref_path = vfs_join(git_dir, "refs/heads").join(refspec); + let ref_path = vfs_join(&vfs_join(git_dir, "refs/heads"), refspec); if fs.exists(&ref_path).await? { let hash = fs.read_file(&ref_path).await?; return Ok(String::from_utf8_lossy(&hash).trim().to_string()); diff --git a/crates/bashkit/src/builtins/navigation.rs b/crates/bashkit/src/builtins/navigation.rs index ac44c7cec..a25a8c0ed 100644 --- a/crates/bashkit/src/builtins/navigation.rs +++ b/crates/bashkit/src/builtins/navigation.rs @@ -205,7 +205,8 @@ async fn logical_dir(fs: &dyn crate::fs::FileSystem, path: &std::path::Path) -> let mut out = PathBuf::from("/"); for comp in path.components() { match comp { - Component::Normal(name) => out.push(name), + // vfs_join, not `push`: keep `/` separators on Windows (#2933). + Component::Normal(name) => out = crate::fs::vfs_join(&out, name), Component::ParentDir => { if !fs.stat(&out).await.is_ok_and(|m| m.file_type.is_dir()) { return None; diff --git a/crates/bashkit/src/builtins/path.rs b/crates/bashkit/src/builtins/path.rs index 2698d9e65..a5d5a5f18 100644 --- a/crates/bashkit/src/builtins/path.rs +++ b/crates/bashkit/src/builtins/path.rs @@ -503,7 +503,8 @@ async fn follow_readlink_symlinks( match component { Component::RootDir => continue, - Component::Normal(part) => current.push(part), + // vfs_join, not `push`: keep `/` separators on Windows (#2933). + Component::Normal(part) => current = vfs_join(¤t, part), _ => continue, } diff --git a/crates/bashkit/src/fs/mod.rs b/crates/bashkit/src/fs/mod.rs index 10da9874e..5b4fe4cc3 100644 --- a/crates/bashkit/src/fs/mod.rs +++ b/crates/bashkit/src/fs/mod.rs @@ -468,6 +468,7 @@ pub fn vfs_join(base: &Path, child: impl AsRef) -> PathBuf { // 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 { + #[allow(clippy::disallowed_methods)] // non-UTF-8 fallback, see above return base.join(child); }; match (base, child) { diff --git a/crates/bashkit/src/fs/overlay.rs b/crates/bashkit/src/fs/overlay.rs index fb4e33a82..3f8209609 100644 --- a/crates/bashkit/src/fs/overlay.rs +++ b/crates/bashkit/src/fs/overlay.rs @@ -441,7 +441,8 @@ impl OverlayFs { let mut current = PathBuf::from("/"); let mut missing = 0u64; for component in path.components().skip(1) { - current.push(component); + // vfs_join, not `push`: keep `/` separators on Windows (#2933). + current = vfs_join(¤t, component); if !self.upper.exists(¤t).await.unwrap_or(false) { missing = missing.saturating_add(1); } diff --git a/crates/bashkit/src/fs/posix.rs b/crates/bashkit/src/fs/posix.rs index 2ceb97cf9..84c2a7f4b 100644 --- a/crates/bashkit/src/fs/posix.rs +++ b/crates/bashkit/src/fs/posix.rs @@ -55,8 +55,8 @@ use std::sync::Arc; use super::backend::FsBackend; use super::limits::{FsLimits, FsUsage}; -use super::normalize_path; use super::traits::{DirEntry, FileSystem, FileSystemExt, Metadata, fs_errors}; +use super::{normalize_path, vfs_join}; use crate::error::Result; /// POSIX-compatible filesystem wrapper. @@ -191,7 +191,9 @@ impl FileSystem for PosixFs { if let Some(parent) = path.parent() { let mut current = PathBuf::from("/"); for component in parent.components().skip(1) { - current.push(component); + // vfs_join, not `push`: `push` joins with `\` on Windows + // and the backend would see `/a\b` (#2933). + current = vfs_join(¤t, component); if let Ok(meta) = self.backend.stat(¤t).await && !meta.file_type.is_dir() { @@ -307,6 +309,8 @@ mod tests { files: Mutex>, symlinks: Mutex>, reads: AtomicUsize, + /// Every path `stat` received, as text (`PathBuf` equality would hide `\`). + stats: Mutex>, } impl AppendCreatesFileBackend { @@ -318,6 +322,7 @@ mod tests { files: Mutex::new(files), symlinks: Mutex::new(HashSet::new()), reads: AtomicUsize::new(0), + stats: Mutex::new(Vec::new()), } } } @@ -354,6 +359,10 @@ mod tests { } async fn stat(&self, path: &Path) -> Result { + self.stats + .lock() + .expect("backend lock poisoned") + .push(path.to_string_lossy().into_owned()); if self .symlinks .lock() @@ -526,4 +535,16 @@ mod tests { "raw backends may follow symlinks, so PosixFs must not delegate the read" ); } + + /// #2933 family: `mkdir -p` checks each parent on the backend. Those + /// paths must be `/`-joined on every host, or a string-keyed backend on + /// Windows sees `/a\b`. Named for the Windows CI `windows_containment` filter. + #[tokio::test] + async fn windows_containment_mkdir_p_hands_backend_slash_paths() { + let fs = PosixFs::new(AppendCreatesFileBackend::new()); + fs.mkdir(Path::new("/a/b/c/d"), true).await.unwrap(); + let stats = fs.backend.stats.lock().unwrap().clone(); + assert!(stats.iter().any(|p| p == "/a/b/c"), "{stats:?}"); + assert!(stats.iter().all(|p| !p.contains('\\')), "{stats:?}"); + } } diff --git a/crates/bashkit/src/fs/realfs.rs b/crates/bashkit/src/fs/realfs.rs index a4259dde3..9e07fff75 100644 --- a/crates/bashkit/src/fs/realfs.rs +++ b/crates/bashkit/src/fs/realfs.rs @@ -5,6 +5,9 @@ // Security: path traversal is prevented by canonicalizing the resolved path or // the nearest existing ancestor, then checking the root prefix before I/O. // This module is only available with the `realfs` feature flag. +// Host paths are built with `Path::join` on purpose: below `resolve` these are +// host paths, where the host separator is correct (see crates/bashkit/clippy.toml). +#![allow(clippy::disallowed_methods)] //! Real filesystem backend. //! diff --git a/crates/bashkit/src/interpreter/mod.rs b/crates/bashkit/src/interpreter/mod.rs index d4071e7fc..80b92b646 100644 --- a/crates/bashkit/src/interpreter/mod.rs +++ b/crates/bashkit/src/interpreter/mod.rs @@ -1018,16 +1018,13 @@ fn nested_syntax_report(e: &crate::error::Error, who: &str, source: &str) -> Str /// Check if a path refers to /dev/null after normalization. /// Handles attempts to bypass via paths like `/dev/../dev/null`. +/// +/// Uses the shared slash-only VFS normalizer: rebuilding with `PathBuf::push` +/// would join with `\` on Windows and miss every string match (#2933). fn is_dev_null(path: &Path) -> bool { - normalize_dev_path(path) == Path::new(DEV_NULL) + crate::fs::normalize_path(path) == Path::new(DEV_NULL) } -/// File descriptor aliased by `/dev/stdin`, `/dev/stdout`, `/dev/stderr` or -/// `/dev/fd/N` (after `..` normalization), as on Linux. -/// -/// Decision: these paths are resolved at the interpreter level like -/// `/dev/null`, never through the VFS. Writing them as regular files silently -/// swallowed `echo err > /dev/stderr`, a pattern agents use constantly. /// The script a body runs (see `Interpreter::reread_script_rest`). enum ScriptView<'a> { Parsed(&'a Script), @@ -1043,8 +1040,14 @@ impl ScriptView<'_> { } } +/// File descriptor aliased by `/dev/stdin`, `/dev/stdout`, `/dev/stderr` or +/// `/dev/fd/N` (after `..` normalization), as on Linux. +/// +/// Decision: these paths are resolved at the interpreter level like +/// `/dev/null`, never through the VFS. Writing them as regular files silently +/// swallowed `echo err > /dev/stderr`, a pattern agents use constantly. fn dev_fd_alias(path: &Path) -> Option { - let normalized = normalize_dev_path(path); + let normalized = crate::fs::normalize_path(path); match normalized.to_str()? { "/dev/stdin" => Some(0), "/dev/stdout" => Some(1), @@ -1059,26 +1062,6 @@ fn dev_fd_alias(path: &Path) -> Option { } } -fn normalize_dev_path(path: &Path) -> PathBuf { - // Normalize the path to handle .. and . components - let mut normalized = PathBuf::new(); - for component in path.components() { - match component { - std::path::Component::RootDir => normalized.push("/"), - std::path::Component::Normal(name) => normalized.push(name), - std::path::Component::ParentDir => { - normalized.pop(); - } - std::path::Component::CurDir => {} - std::path::Component::Prefix(_) => {} - } - } - if normalized.as_os_str().is_empty() { - normalized.push("/"); - } - normalized -} - /// THREAT[TM-INJ-009,TM-INJ-016]: Check if a variable name is an internal marker. /// Used by builtins and interpreter to block user assignment to internal prefixes. /// Note: `_TTY_` is intentionally excluded — it is user-configurable (bashkit extension). @@ -15394,6 +15377,35 @@ mod tests { use crate::fs::InMemoryFs; use crate::parser::Parser; + /// #2933: the device aliases must match on Windows too, where rebuilding + /// a path with `PathBuf::push` joins with `\`. Named for the Windows CI + /// job's `windows_containment` filter. + #[test] + fn windows_containment_dev_paths_alias_descriptors() { + for (path, fd) in [ + ("/dev/stdin", Some(0)), + ("/dev/stdout", Some(1)), + ("/dev/stderr", Some(2)), + ("/dev/fd/0", Some(0)), + ("/dev/fd/2", Some(2)), + ("/dev/fd/63", Some(63)), + ("/dev/../dev/stderr", Some(2)), + ("/dev/./stdout", Some(1)), + ("//dev//stderr", Some(2)), + ("/tmp/../dev/fd/1", Some(1)), + ("/dev/stderrx", None), + ("/dev/fd/", None), + ("/dev/fd/x", None), + ("/dev/fd/1234567890", None), + ("/tmp/stderr", None), + ] { + assert_eq!(dev_fd_alias(Path::new(path)), fd, "{path}"); + } + assert!(is_dev_null(Path::new("/dev/null"))); + assert!(is_dev_null(Path::new("/dev/../dev/./null"))); + assert!(!is_dev_null(Path::new("/dev/nullx"))); + } + fn ordinary_pipeline_commands() -> Vec { let parser = Parser::new("{ :; } | :"); let script = parser.parse().unwrap(); diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 552b49dd8..b96b55443 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -421,6 +421,9 @@ // Stricter panic prevention - prefer proper error handling over unwrap() #![warn(clippy::unwrap_used)] #![cfg_attr(test, allow(clippy::unwrap_used))] +// Tests build host temp paths freely; the VFS separator ban (clippy.toml) +// targets library code. +#![cfg_attr(test, allow(clippy::disallowed_methods))] // The rustls-backed HTTP client installs its own crypto provider (reqwest is // built with `rustls-no-provider`), so a backend must be selected. Fail here @@ -2041,10 +2044,10 @@ impl HostMounts { .iter() .filter_map(|mount| { let rest = vfs_path.strip_prefix(&mount.vfs_path).ok()?; - Some(( - mount.vfs_path.components().count(), - mount.host_path.join(rest), - )) + // Host side of the mount: the host separator is correct here. + #[allow(clippy::disallowed_methods)] + let host = mount.host_path.join(rest); + Some((mount.vfs_path.components().count(), host)) }) .max_by_key(|(depth, _)| *depth) .map(|(_, host)| host) diff --git a/crates/bashkit/src/testing.rs b/crates/bashkit/src/testing.rs index cfca3e742..57d464760 100644 --- a/crates/bashkit/src/testing.rs +++ b/crates/bashkit/src/testing.rs @@ -18,8 +18,10 @@ //! fuzzer can forge the canary into its own input — see //! `assert_fuzz_invariants`). +mod checked_fs; mod counting_fs; +pub use checked_fs::CheckedFs; pub use counting_fs::{CallCounts, CountingFs}; use crate::{Bash, ControlFlow, ExecResult}; @@ -108,6 +110,8 @@ pub fn fuzz_init() { /// A test that needs to *assert* on the child's profraw (as a bounded-artifact /// receipt, say) should set `LLVM_PROFILE_FILE` to its own path instead; the /// point is only that the child never writes into tarpaulin's merge set. +// Host temp dir, not a VFS path: the host separator is correct here. +#[allow(clippy::disallowed_methods)] pub fn child_profile_path() -> std::path::PathBuf { use std::sync::OnceLock; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/crates/bashkit/src/testing/checked_fs.rs b/crates/bashkit/src/testing/checked_fs.rs new file mode 100644 index 000000000..a88cdb3eb --- /dev/null +++ b/crates/bashkit/src/testing/checked_fs.rs @@ -0,0 +1,213 @@ +//! Path-recording filesystem: checks the separator contract on every call. +//! +//! Decisions: +//! - The VFS is POSIX-rooted on every host (TM-ESC-033): every path the +//! interpreter, builtins and wrapper filesystems hand to a `FileSystem` +//! must use `/` only. `Path::join`/`PathBuf::push` silently join with `\` +//! on Windows, so `/a` + `b` becomes `/a\b` (#2425, #2933). The bug is +//! invisible on Linux and to every backend that normalizes, so it only +//! shows up as a custom backend's key mismatch on Windows. +//! - `CheckedFs` records every path it receives and reports the ones that +//! contain `\`. Tests that never put `\` in a file name can then assert the +//! list is empty; on the Windows CI runner that catches host-separator +//! joins anywhere above the filesystem. The `clippy::disallowed_methods` +//! ban in `crates/bashkit/clippy.toml` is the matching static check. +//! - Records, never panics: a panic inside a builtin is caught and turned +//! into an error, which would hide the offending path. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; + +use crate::error::Result; +use crate::fs::{ + DirEntry, DirListing, FileSystem, FileSystemExt, FsLimits, FsUsage, InMemoryFs, Metadata, + SearchCapable, VfsSnapshot, WalkOptions, walk_with_read_dir, +}; +use crate::time_compat::SystemTime; + +/// Cap on recorded paths, so a long fuzz run cannot grow without bound. +const MAX_RECORDED: usize = 100_000; + +/// A [`FileSystem`] wrapper that records every path it is handed. +pub struct CheckedFs { + inner: Arc, + seen: Arc>>, +} + +impl CheckedFs { + /// Record calls into a fresh [`InMemoryFs`]. + pub fn new() -> Self { + Self::wrap(Arc::new(InMemoryFs::new())) + } + + /// Record calls into `inner`. + pub fn wrap(inner: Arc) -> Self { + Self { + inner, + seen: Arc::new(Mutex::new(Vec::new())), + } + } + + /// Every `(operation, path)` received so far, in call order. + pub fn seen(&self) -> Vec<(&'static str, String)> { + self.seen.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// Received paths that contain `\`, the host separator on Windows. + pub fn separator_violations(&self) -> Vec<(&'static str, String)> { + self.seen() + .into_iter() + .filter(|(_, p)| p.contains('\\')) + .collect() + } + + /// Panic with the offending calls if any path contained `\`. + #[track_caller] + pub fn assert_slash_only(&self, ctx: &str) { + let bad = self.separator_violations(); + assert!( + bad.is_empty(), + "[{ctx}] filesystem received host-separator paths (use vfs_join, not Path::join/PathBuf::push): {bad:?}" // debug-ok: test assertion + ); + } + + /// Forget recorded paths. + pub fn reset(&self) { + self.seen.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + + fn record(&self, op: &'static str, path: &Path) { + let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < MAX_RECORDED { + seen.push((op, path.to_string_lossy().into_owned())); + } + } +} + +impl Default for CheckedFs { + fn default() -> Self { + Self::new() + } +} + +#[async_trait] +impl FileSystemExt for CheckedFs { + fn usage(&self) -> FsUsage { + self.inner.usage() + } + async fn mkfifo(&self, path: &Path, mode: u32) -> Result<()> { + self.record("mkfifo", path); + self.inner.mkfifo(path, mode).await + } + fn limits(&self) -> FsLimits { + self.inner.limits() + } + fn vfs_snapshot(&self) -> Option { + self.inner.vfs_snapshot() + } + fn vfs_restore(&self, snapshot: &VfsSnapshot) -> Result<()> { + self.inner.vfs_restore(snapshot) + } + fn backend_kind(&self) -> &'static str { + self.inner.backend_kind() + } +} + +#[async_trait] +impl FileSystem for CheckedFs { + async fn read_file(&self, path: &Path) -> Result> { + self.record("read_file", path); + self.inner.read_file(path).await + } + async fn write_file(&self, path: &Path, content: &[u8]) -> Result<()> { + self.record("write_file", path); + self.inner.write_file(path, content).await + } + async fn append_file(&self, path: &Path, content: &[u8]) -> Result<()> { + self.record("append_file", path); + self.inner.append_file(path, content).await + } + async fn mkdir(&self, path: &Path, recursive: bool) -> Result<()> { + self.record("mkdir", path); + self.inner.mkdir(path, recursive).await + } + async fn remove(&self, path: &Path, recursive: bool) -> Result<()> { + self.record("remove", path); + self.inner.remove(path, recursive).await + } + async fn stat(&self, path: &Path) -> Result { + self.record("stat", path); + self.inner.stat(path).await + } + async fn lstat(&self, path: &Path) -> Result { + self.record("lstat", path); + self.inner.lstat(path).await + } + async fn read_dir(&self, path: &Path) -> Result> { + self.record("read_dir", path); + self.inner.read_dir(path).await + } + async fn exists(&self, path: &Path) -> Result { + self.record("exists", path); + self.inner.exists(path).await + } + async fn rename(&self, from: &Path, to: &Path) -> Result<()> { + self.record("rename", from); + self.record("rename", to); + self.inner.rename(from, to).await + } + async fn copy(&self, from: &Path, to: &Path) -> Result<()> { + self.record("copy", from); + self.record("copy", to); + self.inner.copy(from, to).await + } + async fn symlink(&self, target: &Path, link: &Path) -> Result<()> { + // `target` is stored verbatim, not resolved: only `link` is a VFS path. + self.record("symlink", link); + self.inner.symlink(target, link).await + } + async fn read_link(&self, path: &Path) -> Result { + self.record("read_link", path); + self.inner.read_link(path).await + } + async fn chmod(&self, path: &Path, mode: u32) -> Result<()> { + self.record("chmod", path); + self.inner.chmod(path, mode).await + } + async fn set_modified_time(&self, path: &Path, time: SystemTime) -> Result<()> { + self.record("set_modified_time", path); + self.inner.set_modified_time(path, time).await + } + async fn walk(&self, root: &Path, opts: WalkOptions) -> Result> { + self.record("walk", root); + // Walk through `self` so each listed directory is recorded too. + walk_with_read_dir(self, root, opts).await + } + fn as_search_capable(&self) -> Option<&dyn SearchCapable> { + self.inner.as_search_capable() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn records_paths_and_flags_backslashes() { + let fs = CheckedFs::new(); + fs.mkdir(Path::new("/a"), false).await.unwrap(); + fs.write_file(Path::new("/a/f"), b"x").await.unwrap(); + assert!(fs.separator_violations().is_empty()); + assert_eq!(fs.seen()[0], ("mkdir", "/a".to_string())); + + let _ = fs.stat(Path::new("/a\\f")).await; + assert_eq!( + fs.separator_violations(), + vec![("stat", "/a\\f".to_string())] + ); + fs.reset(); + assert!(fs.seen().is_empty()); + } +} diff --git a/crates/bashkit/tests/integration/main.rs b/crates/bashkit/tests/integration/main.rs index c8c4decce..8f001254d 100644 --- a/crates/bashkit/tests/integration/main.rs +++ b/crates/bashkit/tests/integration/main.rs @@ -11,6 +11,9 @@ //! binary (process-global env mutation, `--test-threads=1`, feature-isolation //! sweeps) stay as siblings at `tests/.rs`. +// Integration tests build host temp paths freely; the VFS separator ban +// (crates/bashkit/clippy.toml) targets library code. +#![allow(clippy::disallowed_methods)] #![allow(clippy::single_component_path_imports)] pub mod agent_skills_publication_tests; @@ -190,6 +193,7 @@ pub mod typescript_security_tests; pub mod unicode_security_tests; pub mod unset_function_tests; pub mod urandom_tests; +pub mod vfs_separator_tests; pub mod workflow_security_tests; pub mod yq_integration_tests; diff --git a/crates/bashkit/tests/integration/vfs_separator_tests.rs b/crates/bashkit/tests/integration/vfs_separator_tests.rs new file mode 100644 index 000000000..419bb6699 --- /dev/null +++ b/crates/bashkit/tests/integration/vfs_separator_tests.rs @@ -0,0 +1,59 @@ +//! The VFS is `/`-separated on every host (TM-ESC-033, #2425, #2933). +//! +//! `Path::join`/`PathBuf::push` join with `\` on Windows, so code that builds +//! VFS paths with them hands a custom filesystem `/a\b`, and string matches +//! such as `/dev/stderr` miss. Linux cannot show the bug (its separator is +//! already `/`), so these tests run on the Windows CI runner via the +//! `windows_containment` filter; `crates/bashkit/clippy.toml` bans the +//! methods statically. `CheckedFs` records every path the filesystem gets. + +use bashkit::Bash; +use bashkit::testing::CheckedFs; +use std::sync::Arc; + +async fn run(script: &str) -> (Arc, bashkit::ExecResult) { + let fs = Arc::new(CheckedFs::new()); + let mut bash = Bash::builder().fs(fs.clone()).build(); + let result = bash.exec(script).await.unwrap(); + (fs, result) +} + +#[tokio::test] +async fn windows_containment_dev_stderr_redirect_stays_in_interpreter() { + let (fs, r) = + run("echo err > /dev/stderr; echo out 2>&1 >/dev/stdout; echo two >> /dev/fd/2").await; + assert_eq!(r.stderr, "err\ntwo\n"); + assert_eq!(r.stdout, "out\n"); + let writes: Vec<_> = fs + .seen() + .into_iter() + .filter(|(op, p)| op.ends_with("_file") && p.starts_with("/dev")) + .collect(); + assert!( + writes.is_empty(), + "device redirect reached the VFS: {writes:?}" + ); + fs.assert_slash_only("dev redirect"); +} + +#[tokio::test] +async fn windows_containment_mkdir_p_and_cd_dotdot_use_slash_paths() { + let (fs, r) = run("mkdir -p /a/b/c && cd /a/b/c/.. && pwd").await; + assert_eq!(r.stdout, "/a/b\n", "stderr: {}", r.stderr); + fs.assert_slash_only("mkdir -p / cd .."); +} + +#[tokio::test] +async fn windows_containment_readlink_f_walks_slash_paths() { + let (fs, r) = + run("mkdir -p /a/b/c && ln -s /a/b /l && readlink -f /l/c && readlink -f /a/b/c/../c") + .await; + assert_eq!(r.stdout, "/a/b/c\n/a/b/c\n", "stderr: {}", r.stderr); + assert!( + fs.seen() + .iter() + .any(|(op, p)| *op == "read_link" && p == "/a/b"), + "readlink -f should probe each prefix" + ); + fs.assert_slash_only("readlink -f"); +} diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index 1ba26db50..680d6b8d8 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -2,6 +2,8 @@ //! //! Tests the full pipeline: host directory → RealFs → PosixFs → Bash interpreter. +// RealFs tests build host paths; the VFS separator ban targets library code. +#![allow(clippy::disallowed_methods)] #![cfg(feature = "realfs")] use bashkit::{Bash, BashBuilder}; diff --git a/knowledge/foundations/vfs.md b/knowledge/foundations/vfs.md index 55fa7c007..1d275f6a9 100644 --- a/knowledge/foundations/vfs.md +++ b/knowledge/foundations/vfs.md @@ -310,7 +310,31 @@ path asks `has_root()`, never `is_absolute()`. It joins with `/` on every host, keeps `Path::join` semantics (an absolute child replaces the base) and leaves `.`/`..` for the backends to normalize. It is re-exported as `bashkit::vfs_join`, since custom `FileSystem` -implementations have the same obligation. Two guards keep it that way: +implementations have the same obligation. + +The text scan below only knew two call shapes, so a second sweep still found +five more sites (issue #2933): `dev_fd_alias`'s private normalizer rebuilt +`/dev/stderr` as `/dev\stderr` on Windows, so `echo x > /dev/stderr` was +written to the VFS as a regular file; `PosixFs::mkdir -p` handed the backend +`/a\b` for its parent checks, before any normalization (a string-keyed custom +`FsBackend` misses); `cd x/..` and `readlink -f`/`realpath` probed the +filesystem with `\`-joined prefixes; `OverlayFs` counted missing upper +directories the same way (harmless, its upper is always `InMemoryFs`). The +public `custom_backend` and `custom_filesystem_impl` examples taught the +`push` pattern too; they now call `bashkit::normalize_path`/`vfs_join`. + +Fuzzing cannot find this class: the fuzz targets run on Linux, where the +host separator already is `/`. These guards keep it out: +- `crates/bashkit/clippy.toml` bans `Path::join`, `PathBuf::push`, + `PathBuf::set_file_name` and `Path::with_file_name` in the `bashkit` crate + (`clippy::disallowed_methods`, run by CI's `-D warnings` clippy on Linux). + Host-path code opts out with a scoped `#[allow]` and a reason: `realfs.rs`, + `HostMounts::host_path_for`, the non-UTF-8 fallback in `vfs_join`, + `testing::child_profile_path`, and test/bench/example targets that build + host temp paths. +- `bashkit::testing::CheckedFs` records every path a `FileSystem` receives; + `assert_slash_only` fails on `\`. `tests/integration/vfs_separator_tests.rs` + runs device redirects, `mkdir -p`, `cd ..` and `realpath` through it. - `builtins::tests::no_host_separator_joins_on_vfs_paths` — static scan of every workspace crate's `src/` for the `cwd.join(` and `.join(&entry.name)` shapes, with a `// host-join-ok: ` escape hatch. @@ -319,9 +343,11 @@ implementations have the same obligation. Two guards keep it that way: `\`, `is_absolute()` being false for `/etc/passwd`, `\` and `/` comparing equal). If std or the platform ever changed, it says so before the rules start looking arbitrary. -- `windows_containment_*` unit tests next to `vfs_join`, `grep`, `du`, `wc` and - `InMemoryFs::rename`, which the Windows CI job runs (`cargo test -p bashkit - --lib --features realfs windows_containment`). +- `windows_containment_*` unit tests next to `vfs_join`, `grep`, `du`, `wc`, + `InMemoryFs::rename`, `dev_fd_alias` and `PosixFs::mkdir`, which the Windows + CI job runs (`cargo test -p bashkit --lib --features realfs + windows_containment`). The `test-windows` job also runs the integration + binary's `windows_containment`, `dev_fd_path_tests` and `dev_null_tests`. Host paths are the exception and keep using `Path::join`: `RealFs` joining under its host root, and `HostMounts` mapping a VFS path back to a host path. diff --git a/knowledge/log.md b/knowledge/log.md index de996b771..5df2d827b 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,8 @@ ## 2026-11-18 +* **Windows `/dev/stderr` redirects hit the VFS (#2933), and four more host-separator joins**: `dev_fd_alias` re-normalized the already-clean redirect target with `PathBuf::push`, which joins with `\` on Windows, so `/dev\stderr` missed the string match and `echo x > /dev/stderr` wrote a VFS file. It now uses the shared `normalize_path`. A clippy trial run with the join methods banned found the rest of the class: `PosixFs::mkdir -p` parent checks (backend saw `/a\b`), `cd x/..`, `readlink -f`/`realpath` prefix probes, and `OverlayFs` upper-dir counting, all now `vfs_join`. Second sweep after #2425, so the fix is a guard, not a sweep: `crates/bashkit/clippy.toml` bans `Path::join`/`PathBuf::push`/`set_file_name`/`with_file_name` with scoped allows for host-path code; `testing::CheckedFs` records paths a filesystem receives; the Windows CI job now runs the device-path and separator integration tests. Fuzzing could not have found it: Linux's separator is `/`. See [Virtual Filesystem](foundations/vfs.md). + * **picomatch ReDoS suppressed: no patched release exists**: the nightly `Advisory Audit` went red on 2026-11-18 with GHSA-fc5q-39xc-vjpf (CVE-2026-112366, high) against `picomatch` in three of the five pnpm lockfiles (crates/bashkit-js, examples/browser, site). Nothing in the tree moved: picomatch 4.0.7 has been the resolution in all three since 2026-11-07 and every push scan was green, including main at 1bea26a eighteen hours earlier; the advisory was widened to cover `<= 4.0.7` on 2026-11-17. `<= 4.0.7` is picomatch's entire release history and the advisory lists no patched version, so the usual npm answer -- bump to the fix -- does not exist, and `pnpm audit` keys on the resolved version, so a `pnpm patch` would not clear it either. Suppressed by id in `IGNORED_NPM_ADVISORIES` with a rationale and a removal condition, the first npm entry since the `braces` exception was retired on 2026-10-23. The exposure is build tooling only: `ava` and `@napi-rs/cli` in crates/bashkit-js, `vite`/`tinyglobby` in examples/browser, `astro` and `vite` in site, plus `micromatch`/`anymatch` on picomatch 2.3.2. Every glob those compile comes from repo config or a build tool's own defaults, no tenant input reaches them, and no published crate, wheel or npm package resolves picomatch -- the published `@everruns/bashkit` ships only its JS wrappers and native binaries, with `@napi-rs/wasm-runtime` as its single optional dependency. A suppressed finding is still printed by the wrapper, so the entry stays visible until picomatch ships a release above 4.0.7. See [Threat Model](security/threat-model.md#suppressed-advisories). ## 2026-11-17 diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 6cd9153c0..6910f6cc6 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -404,6 +404,9 @@ its canonical root. Existing entries and nearest existing ancestors are then canonicalized, so symlink/junction targets, root-prefix siblings, and missing suffixes cannot escape. `windows_containment_*` tests run continuously on a Windows runner; drive roots are also sensitive mounts under TM-FS-013. +VFS paths must never be built with the host separator: `crates/bashkit/clippy.toml` +bans `Path::join`/`PathBuf::push` outside scoped host-path code, because a +`\`-joined `/dev\stderr` slipped past the interpreter's device match (#2933). **TM-ESC-034**: `HostMounts` normalizes both recorded VFS mount points and each absolute lookup path before matching. Parent components therefore affect mount From 59a09cbcd8fe38389594cb38fce13bc30e95f507 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Wed, 18 Nov 2026 18:10:26 +0000 Subject: [PATCH 2/2] test(dev-fd): run the real-bash oracle only on unix hosts The new Windows CI step runs dev_fd_path_tests; on windows-latest `bash` is the WSL launcher, which prints a UTF-16 notice instead of running the script. Bashkit's own output assertions still run on every host. --- crates/bashkit/tests/integration/dev_fd_path_tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/bashkit/tests/integration/dev_fd_path_tests.rs b/crates/bashkit/tests/integration/dev_fd_path_tests.rs index 621d5bb0b..c9673a9e3 100644 --- a/crates/bashkit/tests/integration/dev_fd_path_tests.rs +++ b/crates/bashkit/tests/integration/dev_fd_path_tests.rs @@ -183,6 +183,12 @@ async fn stream_aliases_and_append_match_bash() { let (_, result) = run(script).await; assert_eq!(result.stdout, "hihihi"); assert_eq!(result.stderr, "hihi"); + // Real-bash differential only where a POSIX bash is the host shell: on the + // Windows runner `bash` is the WSL launcher, which prints a UTF-16 "no + // distribution installed" notice instead of running the script. + if !cfg!(unix) { + return; + } let oracle = std::process::Command::new("bash") .args(["-c", script]) .output()