From 3beb6e9a3e18bab655a94a9f7802da3e30dd96be Mon Sep 17 00:00:00 2001 From: Aaron Reisman Date: Thu, 24 Sep 2026 06:45:41 +0700 Subject: [PATCH 1/3] fix(fspy): run exec untracked when injection fails If the preload can't set up tracking for an exec (for example, the seccomp filter for a static binary can't be installed because the sandbox denies the syscall), mark the trace incomplete and run the original call untracked instead of failing it. Resolution errors such as ENOENT or EACCES are still returned as-is. Each exec variant falls back to its own libc original with its original arguments, so execvp and execlp still search PATH, execveat keeps its dirfd and flags, and fexecve keeps its fd. Refs #700 --- CHANGELOG.md | 1 + crates/fspy/tests/untracked_fallback.rs | 116 ++++++++++++++++++ crates/fspy_client_unix/src/lib.rs | 60 ++++++++- crates/fspy_preload_unix/src/client.rs | 2 +- .../src/interceptions/spawn/exec/mod.rs | 70 ++++++----- .../src/interceptions/spawn/posix_spawn.rs | 17 ++- .../fspy_seccomp_unotify/src/payload/mod.rs | 14 +++ crates/fspy_shared/src/ipc/channel/mod.rs | 12 ++ .../src/ipc/channel/shm_io/writer.rs | 24 ++-- crates/fspy_shared_unix/src/spawn/mod.rs | 62 ++++++++-- 10 files changed, 324 insertions(+), 54 deletions(-) create mode 100644 crates/fspy/tests/untracked_fallback.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cadeec13..962d7b00a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Fixed** Cached tasks no longer fail to spawn child processes in restricted sandboxes (e.g. rootless bubblewrap that denies the `seccomp` syscall). When file-access tracking cannot be set up for a process, the process runs untracked instead and the run is reported as not cached ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). - **Fixed** On Windows, environment variable names used by `vp run` now match regardless of ASCII letter case. Assignments in task commands override earlier assignments and inherited variables spelled differently, and `FORCE_COLOR`, `VP_RUN_CONCURRENCY_LIMIT`, and variables requested through `@voidzero-dev/vite-task-client` are found under any spelling ([#747](https://github.com/voidzero-dev/vite-task/pull/747)). - **Changed** A task's cache settings now go inside `cache`, e.g. `cache: { env: ["NODE_ENV"], input: ["src/**"] }`; `cache: true` is the same as `cache: {}`. `env`, `untrackedEnv`, `input`, and `output` are no longer supported at the top level of a task ([#749](https://github.com/voidzero-dev/vite-task/pull/749)). - **Fixed** Cached tasks on macOS no longer intermittently fail with exit 2 and `oils I/O error (main): No such process` when a fast command finishes before the shell gets scheduled. The bundled shell that runs task commands is updated to Oils 0.38.0, which fixes this race ([#702](https://github.com/voidzero-dev/vite-task/issues/702), [#703](https://github.com/voidzero-dev/vite-task/pull/703)). diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs new file mode 100644 index 000000000..1679162d6 --- /dev/null +++ b/crates/fspy/tests/untracked_fallback.rs @@ -0,0 +1,116 @@ +//! Tests for the untracked-exec fallback: when the preload cannot install +//! its injection machinery, the exec must proceed untracked and the run must +//! be reported as incompletely tracked (so it is not cached), rather than +//! every spawn failing. Skipped on musl: no preload library exists there. +#![cfg(all(target_os = "linux", not(target_env = "musl")))] + +use std::{ + ffi::OsStr, + fs::{self, Permissions}, + os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _}, + path::{Path, PathBuf}, + process::Command, + sync::LazyLock, +}; + +use allocator_api2::alloc::Global; +use fspy_seccomp_unotify::payload::SeccompPayload; +use fspy_shared::ipc::{ + IpcStr, + channel::{RecordsLost, channel}, +}; +use fspy_shared_unix::payload::{Payload, encode_payload}; + +/// The preload cdylib, built as a dependency of this crate. +const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); + +const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); + +fn test_bin_path() -> &'static Path { + static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { + let test_bin_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fspy-test-bin"); + fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); + fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) + .expect("failed to set permissions on test binary"); + test_bin_path + }); + TEST_BIN_PATH.as_path() +} + +/// A static binary exec'd from a traced process needs the preload's inline +/// seccomp install. When that install fails (here: the payload's supervisor +/// IPC path is bogus, simulating a sandbox that denies it), the binary must +/// still run — untracked — and the channel must report the loss. +#[test] +fn static_binary_runs_untracked_when_injection_fails() { + let receiver = channel(1 << 30, Global).unwrap(); + let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); + let payload = Payload { + ipc_channel_conf: receiver.conf(), + preload_path, + seccomp_payload: SeccompPayload::unreachable( + b"/nonexistent/fspy-unreachable-supervisor".to_vec(), + ), + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_payload(payload, &bump); + + let output = Command::new("/bin/sh") + .arg("-c") + .arg(format!("exec {} stat /hello", test_bin_path().display())) + .env_clear() + .env("LD_PRELOAD", PRELOAD_CDYLIB) + .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) + .output() + .expect("failed to spawn the shell"); + assert!( + output.status.success(), + "the static binary did not run: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let Err(RecordsLost) = receiver.close() else { + panic!("the channel did not report the untracked exec"); + }; +} + +/// The untracked fallback must replay the interposed call as it was made, +/// not as `execve`. GNU `env` runs its command through `execvp`, so a bare +/// program name found only on `PATH` still runs when injection fails; +/// forwarding it to `execve` would fail with `ENOENT` instead. +#[test] +fn execvp_fallback_keeps_path_search() { + let receiver = channel(1 << 30, Global).unwrap(); + let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); + let payload = Payload { + ipc_channel_conf: receiver.conf(), + preload_path, + seccomp_payload: SeccompPayload::unreachable( + b"/nonexistent/fspy-unreachable-supervisor".to_vec(), + ), + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_payload(payload, &bump); + + let test_bin = test_bin_path(); + let output = Command::new("/usr/bin/env") + .arg(test_bin.file_name().unwrap()) + .arg("stat") + .arg("/hello") + .env_clear() + .env("PATH", test_bin.parent().unwrap()) + .env("LD_PRELOAD", PRELOAD_CDYLIB) + .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) + .current_dir("/") + .output() + .expect("failed to spawn env"); + assert!( + output.status.success(), + "the execvp fallback lost its PATH search: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let Err(RecordsLost) = receiver.close() else { + panic!("the channel did not report the untracked exec"); + }; +} diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs index a0a7d58ce..d82d6853c 100644 --- a/crates/fspy_client_unix/src/lib.rs +++ b/crates/fspy_client_unix/src/lib.rs @@ -16,10 +16,35 @@ use fspy_shared::ipc::{PathAccess, channel::Sender}; use fspy_shared_unix::{ exec::ExecResolveConfig, payload::{EncodedPayload, decode_payload_from_env}, - spawn::{PreExec, handle_exec}, + spawn::{PreExec, prepare_exec, resolve_exec}, }; use raw_exec::RawExec; +/// Why [`Client::handle_exec`] failed. +#[derive(Debug)] +pub enum ExecInjectionError { + /// Program resolution failed the way the real exec would have; the errno + /// is authentic and the caller should surface it as the exec's own + /// failure (set errno and return -1, or return it from `posix_spawn`). + Resolution(nix::Error), + /// The tracing injection machinery failed after the program resolved; + /// the exec was never attempted. The caller should mark the run's trace + /// incomplete ([`Client::report_loss`]) and perform the operation + /// untracked. + Injection(nix::Error), +} + +impl std::fmt::Display for ExecInjectionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Resolution(errno) => write!(f, "exec resolution failed: {errno}"), + Self::Injection(errno) => write!(f, "exec injection failed: {errno}"), + } + } +} + +impl std::error::Error for ExecInjectionError {} + pub struct Client<'a> { encoded_payload: EncodedPayload<'a>, ipc_sender: Option, @@ -87,8 +112,26 @@ impl<'a> Client<'a> { ipc_sender.send(&PathAccess { mode, path: path.into() }); } + /// Marks the run's trace incomplete, so the receiver treats it as + /// untracked (and the runner does not cache it). Used before executing + /// something untracked, e.g. when the injection machinery failed and the + /// exec is forwarded to the OS as-is. A no-op when this client has no + /// channel sender. + pub fn report_loss(&self) { + if let Some(ipc_sender) = &self.ipc_sender { + ipc_sender.report_loss(); + } + } + /// Resolves and reports an exec before forwarding its transformed arguments. /// + /// The callback contract: capture the real exec's own outcome (return + /// value, errno) into `R` and return it as `Ok`, even when the exec + /// itself fails. Reserve `Err` for injection machinery failures, such as + /// [`PreExec::run`] failing to install the seccomp filter — the caller + /// maps those to [`ExecInjectionError::Injection`], marks the trace + /// incomplete, and retries the operation untracked. + /// /// # Safety /// /// `raw_exec` must contain the valid C strings and pointer arrays required @@ -97,22 +140,27 @@ impl<'a> Client<'a> { /// /// # Errors /// - /// Returns errors from exec resolution, platform preparation, or the - /// forwarding callback. + /// [`ExecInjectionError::Resolution`] when program resolution fails the + /// way the real exec would have; [`ExecInjectionError::Injection`] when + /// the injection machinery fails after the program resolved. pub unsafe fn handle_exec( &self, config: ExecResolveConfig, raw_exec: RawExec, allocator: impl Allocator, f: impl FnOnce(RawExec, Option) -> nix::Result, - ) -> nix::Result { + ) -> Result { // SAFETY: raw_exec contains valid pointers to C strings and // null-terminated arrays, as provided by the caller. let mut exec = unsafe { raw_exec.to_exec() }; - let pre_exec = handle_exec(&mut exec, config, &self.encoded_payload, |mode, path| { + resolve_exec(&mut exec, config, |mode, path| { self.send(mode, path); - })?; + }) + .map_err(ExecInjectionError::Resolution)?; + let pre_exec = prepare_exec(&mut exec, &self.encoded_payload) + .map_err(ExecInjectionError::Injection)?; RawExec::from_exec(exec, allocator, |raw_command| f(raw_command, pre_exec)) + .map_err(ExecInjectionError::Injection) } /// Resolves and reports one intercepted file access. diff --git a/crates/fspy_preload_unix/src/client.rs b/crates/fspy_preload_unix/src/client.rs index 9f250d8c3..af0389e54 100644 --- a/crates/fspy_preload_unix/src/client.rs +++ b/crates/fspy_preload_unix/src/client.rs @@ -1,7 +1,7 @@ use std::sync::OnceLock; use convert::{ToAbsolutePath, ToAccessMode}; -pub use fspy_client_unix::{Client, convert, raw_exec}; +pub use fspy_client_unix::{Client, ExecInjectionError, convert, raw_exec}; static CLIENT: OnceLock> = OnceLock::new(); diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs index 729162d02..ab9e402f0 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs @@ -6,7 +6,7 @@ use libc::{c_char, c_int}; use with_argv::with_argv; use crate::{ - client::{global_client, raw_exec::RawExec}, + client::{ExecInjectionError, global_client, raw_exec::RawExec}, macros::intercept, }; @@ -25,12 +25,19 @@ pub unsafe fn environ() -> *const *const c_char { unsafe { environ } } +/// Resolves, reports, and performs a tracked exec. +/// +/// `untracked` performs the interposed call as the caller made it, through +/// that function's own original: `execvp` keeps its `PATH` search, +/// `execveat` its `dirfd` and flags, `fexecve` its descriptor. It runs when +/// the injection machinery fails, so the process still execs, untracked. fn handle_exec( allocator: impl Allocator, config: ExecResolveConfig, prog: *const libc::c_char, argv: *const *const libc::c_char, envp: *const *const libc::c_char, + untracked: impl FnOnce() -> libc::c_int, ) -> libc::c_int { let client = global_client().expect("exec unexpectedly called before client initialized in ctor"); @@ -50,10 +57,22 @@ fn handle_exec( }; match result { Ok(ret) => ret, - Err(errno) => { + Err(ExecInjectionError::Resolution(errno)) => { + // Resolution failed the way the real exec would have; the errno + // is authentic. errno.set(); -1 } + Err(ExecInjectionError::Injection(_)) => { + // The injection machinery failed (e.g. the seccomp filter cannot + // be installed under a restrictive sandbox). Mark the run's trace + // incomplete so it is not cached, then run the interposed call + // untracked. Its envp still carries LD_PRELOAD/FSPY_PAYLOAD, so + // each generation independently attempts tracking and + // independently degrades. + client.report_loss(); + untracked() + } } } @@ -73,6 +92,8 @@ unsafe extern "C" fn execve( prog, argv, envp, + // SAFETY: the interposed execve's own arguments. + || unsafe { execve::original()(prog, argv, envp) }, ) } @@ -92,6 +113,9 @@ unsafe extern "C" fn execl(path: *const c_char, arg0: *const c_char, valist: ... path, args.as_ptr(), environ(), + // A variadic original cannot be forwarded a collected argv; + // execl is execv over the same argv. + || execv::original()(path, args.as_ptr()), ) }) } @@ -113,6 +137,8 @@ unsafe extern "C" fn execlp(path: *const c_char, arg0: *const c_char, valist: .. path, args.as_ptr(), environ(), + // execlp is execvp over the same argv, PATH search included. + || execvp::original()(path, args.as_ptr()), ) }) } @@ -135,6 +161,8 @@ unsafe extern "C" fn execle(path: *const c_char, arg0: *const c_char, valist: .. path, args.as_ptr(), envp, + // execle is execve over the same argv and envp. + || execve::original()(path, args.as_ptr(), envp), ) }) } @@ -142,11 +170,6 @@ unsafe extern "C" fn execle(path: *const c_char, arg0: *const c_char, valist: .. intercept!(execv(64): unsafe extern "C" fn(path: *const c_char, argv: *const *const c_char) -> c_int); unsafe extern "C" fn execv(path: *const c_char, argv: *const *const c_char) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execv::original; // SAFETY: path, argv are valid pointers forwarded from the interposed function; environ() returns the process environment unsafe { handle_exec( @@ -155,6 +178,7 @@ unsafe extern "C" fn execv(path: *const c_char, argv: *const *const c_char) -> c path, argv, environ(), + || execv::original()(path, argv), ) } } @@ -164,18 +188,15 @@ intercept!(execvp(64): unsafe extern "C" fn( argv: *const *const libc::c_char, ) -> c_int); unsafe extern "C" fn execvp(prog: *const c_char, argv: *const *const c_char) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execvp::original; - // SAFETY: environ() returns the valid process environment pointer handle_exec( fspy_nostd_alloc::pooled_bump(), ExecResolveConfig::search_path_enabled(None), prog, argv, + // SAFETY: environ() returns the valid process environment pointer unsafe { environ() }, + // SAFETY: the interposed execvp's own arguments. + || unsafe { execvp::original()(prog, argv) }, ) } @@ -206,17 +227,14 @@ mod linux_only { argv: *const *const libc::c_char, envp: *const *const libc::c_char, ) -> c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execvpe::original; handle_exec( fspy_nostd_alloc::pooled_bump(), ExecResolveConfig::search_path_enabled(None), file, argv, envp, + // SAFETY: the interposed execvpe's own arguments. + || unsafe { execvpe::original()(file, argv, envp) }, ) } intercept!(execveat(64): unsafe extern "C" fn( @@ -233,11 +251,6 @@ mod linux_only { envp: *const *mut libc::c_char, flags: c_int, // TODO: conform to semantics of flags ) -> libc::c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = execveat::original; let arena = fspy_nostd_alloc::pooled_bump(); // SAFETY: dirfd and pathname are valid arguments from the interposed execveat call. @@ -262,6 +275,8 @@ mod linux_only { abs_path.as_ptr().cast(), argv.cast(), envp.cast(), + // SAFETY: the interposed execveat's own arguments. + || unsafe { execveat::original()(dirfd, pathname, argv, envp, flags) }, ) } @@ -275,11 +290,6 @@ mod linux_only { argv: *const *const libc::c_char, envp: *const *const libc::c_char, ) -> libc::c_int { - #[expect( - clippy::no_effect_underscore_binding, - reason = "suppresses unused warning on *::original" - )] - let _unused = fexecve::original; let prog = format!("/proc/self/fd/{fd}\0"); let prog = prog.as_ptr(); handle_exec( @@ -288,6 +298,10 @@ mod linux_only { prog.cast(), argv, envp, + // The descriptor itself, not its /proc path: a sandbox without + // /proc can still fexecve. + // SAFETY: the interposed fexecve's own arguments. + || unsafe { fexecve::original()(fd, argv, envp) }, ) } } diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs index e76373ff7..44f5f1ce7 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs @@ -4,7 +4,7 @@ use fspy_shared_unix::exec::ExecResolveConfig; use libc::{c_char, c_int}; use crate::{ - client::{global_client, raw_exec::RawExec}, + client::{ExecInjectionError, global_client, raw_exec::RawExec}, macros::intercept, }; @@ -78,8 +78,21 @@ unsafe fn handle_posix_spawn( ) }; match result { - Err(errno) => errno as _, Ok(ret) => ret, + Err(ExecInjectionError::Resolution(errno)) => { + // Resolution failed the way the real spawn would have; + // posix_spawn returns the errno code rather than -1. + errno as _ + } + Err(ExecInjectionError::Injection(_)) => { + // The injection machinery failed. Mark the run's trace incomplete + // so it is not cached, then spawn untracked with the original + // arguments. + client.report_loss(); + // SAFETY: all arguments are the interposed posix_spawn(p) + // function's own valid arguments. + unsafe { original(pid, file, file_actions, attrp, argv, envp) } + } } } diff --git a/crates/fspy_seccomp_unotify/src/payload/mod.rs b/crates/fspy_seccomp_unotify/src/payload/mod.rs index 6895bc55a..c4bd5342c 100644 --- a/crates/fspy_seccomp_unotify/src/payload/mod.rs +++ b/crates/fspy_seccomp_unotify/src/payload/mod.rs @@ -7,3 +7,17 @@ pub struct SeccompPayload { pub(crate) ipc_path: Vec, pub(crate) filter: Filter, } + +impl SeccompPayload { + /// Builds a payload whose installation is guaranteed to fail: the filter + /// is empty (the kernel refuses it) and nothing listens on `ipc_path`. + /// + /// Test support for the untracked-exec fallback: integration tests in + /// dependent crates use it to exercise a failing [`crate::target`] + /// install without a restricted sandbox. + #[doc(hidden)] + #[must_use] + pub const fn unreachable(ipc_path: Vec) -> Self { + Self { ipc_path, filter: Filter(Vec::new()) } + } +} diff --git a/crates/fspy_shared/src/ipc/channel/mod.rs b/crates/fspy_shared/src/ipc/channel/mod.rs index 97b3ebc5e..510ea7a5e 100644 --- a/crates/fspy_shared/src/ipc/channel/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/mod.rs @@ -216,6 +216,18 @@ pub struct Sender { } impl Sender { + /// Reports that this process went on to perform an operation it could + /// not record, sealing the channel as incomplete. + /// + /// Used when a traced process escapes tracing — e.g. a preload that + /// could not install its injection machinery and forwards the operation + /// to the OS untracked. The receiver's close then reports + /// [`RecordsLost`], so the run is treated as untracked rather than + /// cached from a partial trace. + pub fn report_loss(&self) { + self.writer.report_loss(); + } + /// Serializes one record into a committed frame. /// /// A claim the channel refuses is skipped, because that is all a sender diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs index 9cda0ab33..928c87c18 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs @@ -74,6 +74,22 @@ impl ShmWriter { self.mapped.claims().load(Ordering::Relaxed) & CLOSED != 0 } + /// Sets the CLOSED gate to report that this writer went on to perform an + /// operation it could not record. + /// + /// The seal then fails and every later claim is refused, so the receiver + /// learns the frames are incomplete rather than mistaking what arrived + /// for the whole trace. + /// + /// Storing the gate rather than or-ing it in drops the claim count, + /// which nothing reads once the gate is set. The seal fails on the + /// bit before it looks at the count, and a claim that reads the + /// cleared count reads the gate along with it, so it gives up + /// before using a slot index. + pub fn report_loss(&self) { + self.mapped.claims().store(CLOSED, Ordering::Relaxed); + } + /// Claims a frame of exactly `frame_size` bytes. Wait-free: two /// `fetch_add`s, no retry loop (rule 1). /// @@ -87,14 +103,8 @@ impl ShmWriter { // The loss report (rule 1): the gate marks the frames incomplete // and shuts the channel down for later claims. - // - // Storing the gate rather than or-ing it in drops the claim count, - // which nothing reads once the gate is set. The seal fails on the - // bit before it looks at the count, and a claim that reads the - // cleared count reads the gate along with it, so it gives up - // before using a slot index. let report_loss = || { - mapped.claims().store(CLOSED, Ordering::Relaxed); + self.report_loss(); ClaimError::Capacity }; diff --git a/crates/fspy_shared_unix/src/spawn/mod.rs b/crates/fspy_shared_unix/src/spawn/mod.rs index e48125772..8d250303f 100644 --- a/crates/fspy_shared_unix/src/spawn/mod.rs +++ b/crates/fspy_shared_unix/src/spawn/mod.rs @@ -19,27 +19,25 @@ use crate::{ payload::EncodedPayload, }; -/// Handles exec command resolution and injection +/// Resolves the exec's program path and reports the accesses that takes. /// -/// Resolves the program path and prepares the command for execution with -/// appropriate environment variables and hooks. +/// This is the half of [`handle_exec`] whose failures mean what the real +/// exec's failure would have meant (see [`Exec::resolve`]), so a caller can +/// forward the errno authentically. /// /// # Errors /// -/// Returns an error if: -/// - Program resolution fails (see [`Exec::resolve`] error variants, such as `ENOENT` (file not found) or `EACCES` (permission denied)) -/// - Environment variable operations fail (e.g., `ensure_env` may return `EINVAL` if an existing value conflicts) -/// - Platform-specific errors from `os_specific::handle_exec` +/// Returns an error if program resolution fails (see [`Exec::resolve`] error +/// variants, such as `ENOENT` (file not found) or `EACCES` (permission denied)). /// /// # Panics /// /// Panics if the current working directory cannot be determined when converting a relative path to absolute. -pub fn handle_exec( +pub fn resolve_exec( command: &mut Exec, config: ExecResolveConfig, - encoded_payload: &EncodedPayload, mut on_path_access: impl FnMut(AccessMode, &Path), -) -> nix::Result> { +) -> nix::Result<()> { let mut on_path_access = |mode: AccessMode, path: &Path| { if path.is_absolute() { on_path_access(mode, path); @@ -51,6 +49,50 @@ pub fn handle_exec( command.resolve(&mut on_path_access, config)?; on_path_access(AccessMode::READ, Path::new(OsStr::from_bytes(&command.program))); + Ok(()) +} +/// Prepares a resolved exec for tracked execution: injects the preload +/// environment, or arms the seccomp filter to install before exec. +/// +/// This is the half of [`handle_exec`] whose failures are the tracing +/// machinery's own, never the exec's. +/// +/// # Errors +/// +/// Returns an error if environment variable operations fail (e.g., +/// `ensure_env` may return `EINVAL` if an existing value conflicts) or from +/// platform-specific errors in `os_specific::handle_exec`. +pub fn prepare_exec( + command: &mut Exec, + encoded_payload: &EncodedPayload, +) -> nix::Result> { os_specific::handle_exec(command, encoded_payload) } + +/// Handles exec command resolution and injection +/// +/// Resolves the program path and prepares the command for execution with +/// appropriate environment variables and hooks. Composed of [`resolve_exec`] +/// followed by [`prepare_exec`]; call them separately to tell an authentic +/// resolution failure apart from an injection-machinery failure. +/// +/// # Errors +/// +/// Returns an error if: +/// - Program resolution fails (see [`Exec::resolve`] error variants, such as `ENOENT` (file not found) or `EACCES` (permission denied)) +/// - Environment variable operations fail (e.g., `ensure_env` may return `EINVAL` if an existing value conflicts) +/// - Platform-specific errors from `os_specific::handle_exec` +/// +/// # Panics +/// +/// Panics if the current working directory cannot be determined when converting a relative path to absolute. +pub fn handle_exec( + command: &mut Exec, + config: ExecResolveConfig, + encoded_payload: &EncodedPayload, + on_path_access: impl FnMut(AccessMode, &Path), +) -> nix::Result> { + resolve_exec(command, config, on_path_access)?; + prepare_exec(command, encoded_payload) +} From a774200b6cec104426ecbdb0d187a0d7cec14869 Mon Sep 17 00:00:00 2001 From: Aaron Reisman Date: Wed, 4 Nov 2026 16:59:49 +0700 Subject: [PATCH 2/3] fix(fspy): limit the untracked fallback to a failed seccomp install Only a failure of PreExec::run, which installs the seccomp filter, now makes an exec run untracked. Other handle_exec errors return their errno as before. On Linux these can be real exec errors, such as ENOEXEC for a script without a shebang, and they must not mark the trace incomplete. The not-cached message now says that automatic file tracking couldn't record everything the task did, so it fits both a full tracking channel and a sandbox that blocks seccomp. --- CHANGELOG.md | 2 +- crates/fspy/src/error.rs | 5 +- crates/fspy/tests/untracked_fallback.rs | 44 ++++++++++++- crates/fspy_client_unix/src/lib.rs | 53 +++------------- crates/fspy_preload_unix/src/client.rs | 2 +- .../src/interceptions/spawn/exec/mod.rs | 27 ++++---- .../src/interceptions/spawn/posix_spawn.rs | 26 ++++---- crates/fspy_shared_unix/src/spawn/mod.rs | 62 +++---------------- crates/vt/src/session/event.rs | 11 ++-- crates/vt/src/session/execute/cache_update.rs | 4 +- crates/vt/src/session/reporter/summary.rs | 6 +- ...capacity_env_sizes_the_tracking_channel.md | 4 +- 12 files changed, 102 insertions(+), 144 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f524d68a..986a186fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -- **Fixed** Cached tasks no longer fail to spawn child processes in restricted sandboxes (e.g. rootless bubblewrap that denies the `seccomp` syscall). When file-access tracking cannot be set up for a process, the process runs untracked instead and the run is reported as not cached ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). +- **Fixed** Cached tasks no longer fail to spawn child processes in restricted sandboxes (e.g. rootless bubblewrap that denies the `seccomp` syscall). When the `seccomp` filter for file-access tracking cannot be installed, the process runs untracked instead and the run is reported as not cached. The not-cached message now reads "automatic file tracking couldn't record everything this task did", which fits both this case and a full tracking channel ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). - **Changed** Tasks that write a file they also read are now cached, instead of being reported as `not cached because it modified its inputs`. For example, `tsc --incremental` reads and rewrites `tsconfig.tsbuildinfo`: the next run is a cache hit if the file is as `tsc` left it, or if it is missing, as on a fresh clone, in which case the hit restores it ([#913](https://github.com/voidzero-dev/vite-task/pull/913)). - **Fixed** A cache hit restores the symbolic links a task's `output` globs match as links, instead of dropping them, so a replayed output that links a directory, such as a bundler's `node_modules/` link, is complete ([#885](https://github.com/voidzero-dev/vite-task/pull/885)). - **Fixed** On Linux and macOS, programs using automatic file-access tracking no longer abort when they call `execve`, `execv`, `execl`, `execle`, or `posix_spawn` with an empty path; the call fails with `ENOENT`, as it does without tracking. On Linux, `execveat` with an empty path and without `AT_EMPTY_PATH` now also fails with `ENOENT`, instead of trying to run what its directory descriptor refers to ([#896](https://github.com/voidzero-dev/vite-task/pull/896)). diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index 6df8e4a5d..e47f84d42 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -35,10 +35,13 @@ pub enum SpawnError { /// so the accesses collected for the run are a subset of what it really /// touched. /// +/// The tracking channel can be full, or a process can continue untracked +/// because the seccomp filter could not be installed. +/// /// The run itself is unaffected: recording must never stop the program /// doing the work. What cannot be done is anything that needs every /// access, caching above all, which has to treat the run as untracked /// rather than as having touched only the paths that fit. #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] -#[error("the file-access records did not fit in the tracking channel")] +#[error("automatic file tracking could not record every file access")] pub struct TrackingIncomplete; diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index 1679162d6..e00a163e4 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -1,6 +1,6 @@ //! Tests for the untracked-exec fallback: when the preload cannot install -//! its injection machinery, the exec must proceed untracked and the run must -//! be reported as incompletely tracked (so it is not cached), rather than +//! the seccomp filter, the exec must proceed untracked and the run must be +//! reported as incompletely tracked (so it is not cached), rather than //! every spawn failing. Skipped on musl: no preload library exists there. #![cfg(all(target_os = "linux", not(target_env = "musl")))] @@ -114,3 +114,43 @@ fn execvp_fallback_keeps_path_search() { panic!("the channel did not report the untracked exec"); }; } + +/// Only a failed seccomp install takes the untracked path. An exec that +/// fails the way the real exec would, here `ENOEXEC` for a script without a +/// `#!` line, keeps its errno and leaves the trace complete. `sh` then runs +/// the script itself, as it does without tracking. +#[test] +fn exec_errors_are_not_reported_as_lost() { + let script = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fspy-script-without-shebang"); + fs::write(&script, "exit 0\n").expect("failed to write the script"); + fs::set_permissions(&script, Permissions::from_mode(0o755)) + .expect("failed to set permissions on the script"); + + let receiver = channel(1 << 30, Global).unwrap(); + let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); + let payload = Payload { + ipc_channel_conf: receiver.conf(), + preload_path, + seccomp_payload: SeccompPayload::unreachable( + b"/nonexistent/fspy-unreachable-supervisor".to_vec(), + ), + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_payload(payload, &bump); + + let output = Command::new("/bin/sh") + .arg("-c") + .arg(script.as_os_str()) + .env_clear() + .env("LD_PRELOAD", PRELOAD_CDYLIB) + .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) + .output() + .expect("failed to spawn the shell"); + assert!( + output.status.success(), + "the script without a shebang did not run: {}", + String::from_utf8_lossy(&output.stderr) + ); + + assert!(receiver.close().is_ok(), "an authentic exec error was reported as an untracked exec"); +} diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs index 593ae7070..d51c90f10 100644 --- a/crates/fspy_client_unix/src/lib.rs +++ b/crates/fspy_client_unix/src/lib.rs @@ -16,35 +16,10 @@ use fspy_shared::ipc::{AccessMode, channel::Sender}; use fspy_shared_unix::{ exec::ExecResolveConfig, payload::{EncodedPayload, decode_payload_from_env}, - spawn::{PreExec, prepare_exec, resolve_exec}, + spawn::{PreExec, handle_exec}, }; use raw_exec::RawExec; -/// Why [`Client::handle_exec`] failed. -#[derive(Debug)] -pub enum ExecInjectionError { - /// Program resolution failed the way the real exec would have; the errno - /// is authentic and the caller should surface it as the exec's own - /// failure (set errno and return -1, or return it from `posix_spawn`). - Resolution(nix::Error), - /// The tracing injection machinery failed after the program resolved; - /// the exec was never attempted. The caller should mark the run's trace - /// incomplete ([`Client::report_loss`]) and perform the operation - /// untracked. - Injection(nix::Error), -} - -impl std::fmt::Display for ExecInjectionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Resolution(errno) => write!(f, "exec resolution failed: {errno}"), - Self::Injection(errno) => write!(f, "exec injection failed: {errno}"), - } - } -} - -impl std::error::Error for ExecInjectionError {} - pub struct Client<'a> { encoded_payload: EncodedPayload<'a>, ipc_sender: Option, @@ -113,10 +88,10 @@ impl<'a> Client<'a> { } /// Marks the run's trace incomplete, so the receiver treats it as - /// untracked (and the runner does not cache it). Used before executing - /// something untracked, e.g. when the injection machinery failed and the - /// exec is forwarded to the OS as-is. A no-op when this client has no - /// channel sender. + /// untracked and the runner does not cache it. Call it before the + /// process does something that tracking cannot record, such as an exec + /// that continues untracked because [`PreExec::run`] failed. It does + /// nothing when this client has no channel sender. pub fn report_loss(&self) { if let Some(ipc_sender) = &self.ipc_sender { ipc_sender.report_loss(); @@ -126,11 +101,6 @@ impl<'a> Client<'a> { /// Resolves and reports an exec, returning the transformed arguments to /// forward and what to run before forwarding them. /// - /// A failure of the returned [`PreExec::run`], such as failing to install - /// the seccomp filter, is an injection machinery failure too: the caller - /// treats it like [`ExecInjectionError::Injection`], marks the trace - /// incomplete, and retries the operation untracked. - /// /// # Safety /// /// `raw_exec` must contain the valid C strings and pointer arrays required @@ -139,24 +109,19 @@ impl<'a> Client<'a> { /// /// # Errors /// - /// [`ExecInjectionError::Resolution`] when program resolution fails the - /// way the real exec would have; [`ExecInjectionError::Injection`] when - /// the injection machinery fails after the program resolved. + /// Returns errors from exec resolution or platform preparation. pub unsafe fn handle_exec( &self, config: ExecResolveConfig, raw_exec: RawExec, allocator: &A, - ) -> Result<(RawExec, Option), ExecInjectionError> { + ) -> nix::Result<(RawExec, Option)> { // SAFETY: raw_exec contains valid pointers to C strings and // null-terminated arrays, as provided by the caller. let mut exec = unsafe { raw_exec.to_exec(allocator) }; - resolve_exec(&mut exec, config, |path| { + let pre_exec = handle_exec(&mut exec, config, &self.encoded_payload, |path| { self.send(AccessMode::Read, path); - }) - .map_err(ExecInjectionError::Resolution)?; - let pre_exec = prepare_exec(&mut exec, &self.encoded_payload) - .map_err(ExecInjectionError::Injection)?; + })?; Ok((RawExec::from_exec(exec), pre_exec)) } diff --git a/crates/fspy_preload_unix/src/client.rs b/crates/fspy_preload_unix/src/client.rs index af0389e54..9f250d8c3 100644 --- a/crates/fspy_preload_unix/src/client.rs +++ b/crates/fspy_preload_unix/src/client.rs @@ -1,7 +1,7 @@ use std::sync::OnceLock; use convert::{ToAbsolutePath, ToAccessMode}; -pub use fspy_client_unix::{Client, ExecInjectionError, convert, raw_exec}; +pub use fspy_client_unix::{Client, convert, raw_exec}; static CLIENT: OnceLock> = OnceLock::new(); diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs index 3e664c562..745577c1c 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs @@ -5,7 +5,7 @@ use fspy_shared_unix::exec::ExecResolveConfig; use libc::{c_char, c_int}; use crate::{ - client::{ExecInjectionError, global_client, raw_exec::RawExec}, + client::{global_client, raw_exec::RawExec}, macros::intercept, }; @@ -55,7 +55,8 @@ unsafe fn collect_argv( /// `untracked` performs the interposed call as the caller made it, through /// that function's own original: `execvp` keeps its `PATH` search, /// `execveat` its `dirfd` and flags, `fexecve` its descriptor. It runs when -/// the injection machinery fails, so the process still execs, untracked. +/// the seccomp filter cannot be installed, so the process still execs, +/// untracked. fn handle_exec( allocator: impl Allocator, config: ExecResolveConfig, @@ -66,31 +67,25 @@ fn handle_exec( ) -> libc::c_int { let client = global_client().expect("exec unexpectedly called before client initialized in ctor"); - // The injection machinery failed (e.g. the seccomp filter cannot be - // installed under a restrictive sandbox). Mark the run's trace incomplete - // so it is not cached, then run the interposed call untracked. Its envp - // still carries LD_PRELOAD/FSPY_PAYLOAD, so each generation independently - // attempts tracking and independently degrades. - let run_untracked = || { - client.report_loss(); - untracked() - }; // SAFETY: prog, argv, and envp are valid pointers to C strings/arrays forwarded from the interposed exec function let handled = unsafe { client.handle_exec(config, RawExec { prog, argv, envp }, &allocator) }; let (raw_command, pre_exec) = match handled { Ok(handled) => handled, - Err(ExecInjectionError::Resolution(errno)) => { - // Resolution failed the way the real exec would have; the errno - // is authentic. + Err(errno) => { errno.set(); return -1; } - Err(ExecInjectionError::Injection(_)) => return run_untracked(), }; if let Some(pre_exec) = pre_exec && pre_exec.run().is_err() { - return run_untracked(); + // The seccomp filter cannot be installed, for example in a sandbox + // that denies the `seccomp` syscall. Mark the run's trace incomplete + // so it is not cached, then run the interposed call untracked. Its + // envp still carries LD_PRELOAD/FSPY_PAYLOAD, so each generation + // tries tracking again on its own. + client.report_loss(); + return untracked(); } // SAFETY: raw_command's strings and arrays live in `allocator`, which outlives the call unsafe { execve::original()(raw_command.prog, raw_command.argv, raw_command.envp) } diff --git a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs index 2747da92d..b069df335 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs @@ -4,7 +4,7 @@ use fspy_shared_unix::exec::ExecResolveConfig; use libc::{c_char, c_int}; use crate::{ - client::{ExecInjectionError, global_client, raw_exec::RawExec}, + client::{global_client, raw_exec::RawExec}, macros::intercept, }; @@ -51,20 +51,9 @@ unsafe fn handle_posix_spawn( &arena, ) }; - // The injection machinery failed. Mark the run's trace incomplete so it - // is not cached, then spawn untracked with the original arguments. - let spawn_untracked = || { - client.report_loss(); - // SAFETY: all arguments are the interposed posix_spawn(p) function's - // own valid arguments. - unsafe { original(pid, file, file_actions, attrp, argv, envp) } - }; let (raw_command, pre_exec) = match handled { Ok(handled) => handled, - // Resolution failed the way the real spawn would have; posix_spawn - // returns the errno code rather than -1. - Err(ExecInjectionError::Resolution(errno)) => return errno as _, - Err(ExecInjectionError::Injection(_)) => return spawn_untracked(), + Err(errno) => return errno as _, }; let call_original = move || { // SAFETY: the caller's pointers are forwarded unchanged, and raw_command's @@ -94,8 +83,15 @@ unsafe fn handle_posix_spawn( .join() .unwrap() }) - // `pre_exec.run` failed, so the spawn never happened. - .unwrap_or_else(|_| spawn_untracked()) + .unwrap_or_else(|_| { + // The seccomp filter cannot be installed, so the spawn never + // happened. Mark the run's trace incomplete so it is not cached, + // then spawn untracked with the caller's own arguments. + client.report_loss(); + // SAFETY: all arguments are the interposed posix_spawn(p) function's + // own valid arguments. + unsafe { original(pid, file, file_actions, attrp, argv, envp) } + }) } intercept!(posix_spawnp(64): PosixSpawnFn); diff --git a/crates/fspy_shared_unix/src/spawn/mod.rs b/crates/fspy_shared_unix/src/spawn/mod.rs index 0a05a6cf5..34b2be0eb 100644 --- a/crates/fspy_shared_unix/src/spawn/mod.rs +++ b/crates/fspy_shared_unix/src/spawn/mod.rs @@ -62,25 +62,27 @@ pub(crate) fn absolute(path: &Path, allocator: A) -> nix::Result( +pub fn handle_exec( command: &mut Exec, config: ExecResolveConfig, + encoded_payload: &EncodedPayload, mut on_path_read: impl FnMut(&Path), -) -> nix::Result<()> { +) -> nix::Result> { let allocator = command.allocator().clone(); let mut on_path_read = |path: &Path| { if path.is_absolute() { @@ -93,54 +95,10 @@ pub fn resolve_exec( command.resolve(&mut on_path_read, config)?; on_path_read(Path::new(OsStr::from_bytes(&command.program))); - Ok(()) -} -/// Prepares a resolved exec for tracked execution: injects the preload -/// environment, or arms the seccomp filter to install before exec. -/// -/// This is the half of [`handle_exec`] whose failures are the tracing -/// machinery's own, never the exec's. -/// -/// # Errors -/// -/// Returns an error if environment variable operations fail (e.g., -/// `ensure_env` may return `EINVAL` if an existing value conflicts) or from -/// platform-specific errors in `os_specific::handle_exec`. -pub fn prepare_exec( - command: &mut Exec, - encoded_payload: &EncodedPayload, -) -> nix::Result> { os_specific::handle_exec(command, encoded_payload) } -/// Handles exec command resolution and injection -/// -/// Resolves the program path and prepares the command for execution with -/// appropriate environment variables and hooks. Composed of [`resolve_exec`] -/// followed by [`prepare_exec`]; call them separately to tell an authentic -/// resolution failure apart from an injection-machinery failure. -/// -/// # Errors -/// -/// Returns an error if: -/// - Program resolution fails (see [`Exec::resolve`] error variants, such as `ENOENT` (file not found) or `EACCES` (permission denied)) -/// - Environment variable operations fail (e.g., `ensure_env` may return `EINVAL` if an existing value conflicts) -/// - Platform-specific errors from `os_specific::handle_exec` -/// -/// # Panics -/// -/// Panics if the current working directory cannot be determined when converting a relative path to absolute. -pub fn handle_exec( - command: &mut Exec, - config: ExecResolveConfig, - encoded_payload: &EncodedPayload, - on_path_read: impl FnMut(&Path), -) -> nix::Result> { - resolve_exec(command, config, on_path_read)?; - prepare_exec(command, encoded_payload) -} - #[cfg(test)] mod tests { use std::{os::unix::ffi::OsStrExt, path::Path}; diff --git a/crates/vt/src/session/event.rs b/crates/vt/src/session/event.rs index a55b9f817..48acfa2ba 100644 --- a/crates/vt/src/session/event.rs +++ b/crates/vt/src/session/event.rs @@ -111,11 +111,12 @@ pub enum CacheNotUpdatedReason { /// A runner-aware tool explicitly requested that this run not be cached /// (e.g. vite dev-server, a watch task). ToolRequested, - /// A tracked process could not record a file access it went on to - /// perform: the channel it reports them through had no room left, or - /// none for a record that long. The accesses that did arrive are a - /// subset of what the task touched, so caching from them would bake in - /// inputs and outputs that are not all of them. + /// A tracked process could not record everything it did. For example, + /// the channel it reports file accesses through had no room left, or + /// the seccomp filter could not be installed and an exec continued + /// untracked. The accesses that did arrive are a subset of what the + /// task touched, so caching from them would bake in inputs and outputs + /// that are not all of them. #[cfg_attr(not(fspy), expect(dead_code, reason = "only fspy tracking can be incomplete"))] TrackingIncomplete, } diff --git a/crates/vt/src/session/execute/cache_update.rs b/crates/vt/src/session/execute/cache_update.rs index 857261632..e5452f384 100644 --- a/crates/vt/src/session/execute/cache_update.rs +++ b/crates/vt/src/session/execute/cache_update.rs @@ -93,8 +93,8 @@ pub(super) async fn update_cache( } // The accesses, or `None` when the task was not tracked at all. An - // `Err` means it made more file accesses than the tracking channel had - // room for, so what arrived is a subset of what it touched, and an entry + // `Err` means tracking could not record everything it did, so what + // arrived is a subset of what it touched, and an entry // built from a subset would replay with inputs and outputs missing. #[cfg(fspy)] let Ok(path_accesses) = outcome.path_accesses.as_ref().map(Result::as_ref).transpose() else { diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index af6cd5130..3aa42e81e 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -118,8 +118,8 @@ pub enum SpawnOutcome { fspy_unsupported: bool, /// The IPC server error that caused the cache to be skipped, if any. ipc_server_error: Option, - /// `true` when the task made more file accesses than tracking had - /// room for, so the inferred inputs and outputs were a subset of + /// `true` when automatic file tracking could not record everything + /// the task did, so the inferred inputs and outputs were a subset of /// what it touched. Task ran successfully but cache was not /// updated. #[serde(default)] @@ -552,7 +552,7 @@ impl TaskResult { { return ( Str::from( - "→ Not cached: this task used more files than automatic tracking can record. Configure `input` and `output` manually to enable caching.", + "→ Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching.", ), &[], ); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/fspy_shm_capacity/snapshots/shm_capacity_env_sizes_the_tracking_channel.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/fspy_shm_capacity/snapshots/shm_capacity_env_sizes_the_tracking_channel.md index ada21e605..eeedd0a19 100644 --- a/crates/vt_bin/tests/e2e_snapshots/fixtures/fspy_shm_capacity/snapshots/shm_capacity_env_sizes_the_tracking_channel.md +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/fspy_shm_capacity/snapshots/shm_capacity_env_sizes_the_tracking_channel.md @@ -23,7 +23,7 @@ Performance: 0% cache hit rate Task Details: ──────────────────────────────────────────────── [1] fspy-shm-capacity#stat: $ vtt stat-many 20000 ✓ - → Not cached: this task used more files than automatic tracking can record. Configure `input` and `output` manually to enable caching. + → Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` @@ -46,6 +46,6 @@ Performance: 0% cache hit rate Task Details: ──────────────────────────────────────────────── [1] fspy-shm-capacity#stat: $ vtt stat-many 20000 ✓ - → Not cached: this task used more files than automatic tracking can record. Configure `input` and `output` manually to enable caching. + → Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ``` From 74b03c600c15ae2266c01c8f63213b320303125b Mon Sep 17 00:00:00 2001 From: wan9chi Date: Tue, 10 Nov 2026 16:26:41 +0800 Subject: [PATCH 3/3] fix(fspy): tidy loss-report docs, changelog and fallback tests - Mention `report_loss` where the shm channel docs list what sets the CLOSED gate. - Say the sandbox fix is Linux-only in the changelog. - Share the static test binary helper between `static_executable` and `untracked_fallback`, writing one file per test binary so concurrent test binaries don't rewrite a file another is executing, and set up the failing seccomp payload in one place. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- crates/fspy/tests/static_executable.rs | 31 +---- crates/fspy/tests/test_utils/mod.rs | 43 +++++++ crates/fspy/tests/untracked_fallback.rs | 108 +++++++----------- .../src/ipc/channel/shm_io/README.md | 2 +- .../src/ipc/channel/shm_io/writer.rs | 10 +- 6 files changed, 93 insertions(+), 103 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 637d9b815..505c1af30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -- **Fixed** Cached tasks no longer fail to spawn child processes in restricted sandboxes (e.g. rootless bubblewrap that denies the `seccomp` syscall). When the `seccomp` filter for file-access tracking cannot be installed, the process runs untracked instead and the run is reported as not cached. The not-cached message now reads "automatic file tracking couldn't record everything this task did", which fits both this case and a full tracking channel ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). +- **Fixed** On Linux, cached tasks no longer fail to spawn child processes in restricted sandboxes, for example rootless bubblewrap that denies the `seccomp` syscall. When the `seccomp` filter for file-access tracking cannot be installed, the process runs untracked instead and the run is reported as not cached. The not-cached message now reads "automatic file tracking couldn't record everything this task did", which fits both this case and a full tracking channel ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). - **Fixed** `vp run ` in a package that doesn't define the task now reports `Task "" not found` when another package's `vite.config.*` fails to load, instead of failing with that package's error. Showing the tasks to choose from loads every package's config, so the task selector or task list is skipped then ([#987](https://github.com/voidzero-dev/vite-task/pull/987)). - **Fixed** A task specifier like `vp run nope#build`, where no workspace package is named `nope`, now fails with `Package 'nope' not found in the workspace` and exits 1, including from a task's command, instead of running nothing and exiting 0. A short name that auto-completes to several scoped packages, like `app` for `@a/app` and `@b/app`, now fails as ambiguous. `--filter nope` still only warns and exits 0, unless `--fail-if-no-match` is set ([#984](https://github.com/voidzero-dev/vite-task/pull/984)). - **Added** `vp run -vv` also lists what each cached run depends on, changed or not, and the output files a hit restores: in the detailed summary, under `Unchanged:` and `Outputs:`, and with `--dry-run --json`, as each step's `baseline.fingerprint` and `baseline.outputs`. It shows, for an unexpected hit, whether an edited file is an input at all. `-v` is now a counted flag, so `-vv` is the same as `--verbose --verbose` ([#969](https://github.com/voidzero-dev/vite-task/pull/969)). diff --git a/crates/fspy/tests/static_executable.rs b/crates/fspy/tests/static_executable.rs index 6e04158ea..9de887a03 100644 --- a/crates/fspy/tests/static_executable.rs +++ b/crates/fspy/tests/static_executable.rs @@ -3,42 +3,15 @@ //! the CI builds with `-crt-static` the binary becomes dynamically linked, //! defeating the purpose of these tests. #![cfg(all(target_os = "linux", not(target_env = "musl")))] -use std::{ - fs::{self, Permissions}, - os::unix::fs::PermissionsExt as _, - path::{Path, PathBuf}, - sync::LazyLock, -}; +use std::path::Path; use fspy::PathAccessIterable; -use fspy_shared_unix::is_dynamically_linked_to_libc; use test_log::test; -use crate::test_utils::assert_contains; +use crate::test_utils::{assert_contains, test_bin_path}; mod test_utils; -const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); - -fn test_bin_path() -> &'static Path { - static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { - assert_eq!( - is_dynamically_linked_to_libc(TEST_BIN_CONTENT), - Ok(false), - "Test binary is not a static executable" - ); - - let tmp_dir = env!("CARGO_TARGET_TMPDIR"); - let test_bin_path = PathBuf::from(tmp_dir).join("fspy-test-bin"); - fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); - fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) - .expect("failed to set permissions on test binary"); - - test_bin_path - }); - TEST_BIN_PATH.as_path() -} - async fn track_test_bin(args: &[&str], cwd: Option<&str>) -> PathAccessIterable { let mut cmd = fspy::Command::new(test_bin_path()); if let Some(cwd) = cwd { diff --git a/crates/fspy/tests/test_utils/mod.rs b/crates/fspy/tests/test_utils/mod.rs index 485b269fa..e8ded0561 100644 --- a/crates/fspy/tests/test_utils/mod.rs +++ b/crates/fspy/tests/test_utils/mod.rs @@ -155,3 +155,46 @@ pub async fn spawn_command(cmd: vt_subprocess_test::Command) -> anyhow::Result

&'static Path { + use std::{ + fs::{self, Permissions}, + os::unix::fs::PermissionsExt as _, + path::PathBuf, + sync::LazyLock, + }; + + use fspy_shared_unix::is_dynamically_linked_to_libc; + + const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); + + static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { + assert_eq!( + is_dynamically_linked_to_libc(TEST_BIN_CONTENT), + Ok(false), + "Test binary is not a static executable" + ); + + let test_bin_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join(concat!("fspy-test-bin-", env!("CARGO_CRATE_NAME"))); + fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); + fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) + .expect("failed to set permissions on test binary"); + + test_bin_path + }); + TEST_BIN_PATH.as_path() +} diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index e00a163e4..c3e95b94b 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -10,57 +10,58 @@ use std::{ os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _}, path::{Path, PathBuf}, process::Command, - sync::LazyLock, }; use allocator_api2::alloc::Global; use fspy_seccomp_unotify::payload::SeccompPayload; use fspy_shared::ipc::{ IpcStr, - channel::{RecordsLost, channel}, + channel::{Receiver, RecordsLost, channel}, }; use fspy_shared_unix::payload::{Payload, encode_payload}; +use crate::test_utils::test_bin_path; + +mod test_utils; + /// The preload cdylib, built as a dependency of this crate. const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); -const TEST_BIN_CONTENT: &[u8] = include_bytes!(env!("CARGO_BIN_FILE_FSPY_TEST_BIN")); - -fn test_bin_path() -> &'static Path { - static TEST_BIN_PATH: LazyLock = LazyLock::new(|| { - let test_bin_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("fspy-test-bin"); - fs::write(&test_bin_path, TEST_BIN_CONTENT).expect("failed to write test binary"); - fs::set_permissions(&test_bin_path, Permissions::from_mode(0o755)) - .expect("failed to set permissions on test binary"); - test_bin_path - }); - TEST_BIN_PATH.as_path() +/// Clears `command`'s environment and preloads fspy into it with a seccomp +/// payload whose install always fails. Returns the channel the preload +/// reports to. +fn preload_with_failing_seccomp(command: &mut Command) -> Receiver { + let receiver = channel(1 << 30, Global).unwrap(); + { + let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); + let payload = Payload { + ipc_channel_conf: receiver.conf(), + preload_path, + seccomp_payload: SeccompPayload::unreachable( + b"/nonexistent/fspy-unreachable-supervisor".to_vec(), + ), + }; + let bump = bumpalo::Bump::new(); + let encoded = encode_payload(payload, &bump); + command + .env_clear() + .env("LD_PRELOAD", PRELOAD_CDYLIB) + .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())); + } + receiver } /// A static binary exec'd from a traced process needs the preload's inline -/// seccomp install. When that install fails (here: the payload's supervisor -/// IPC path is bogus, simulating a sandbox that denies it), the binary must -/// still run — untracked — and the channel must report the loss. +/// seccomp install. When that install fails (here: the payload's empty +/// filter, which the kernel refuses), the binary must still run — untracked +/// — and the channel must report the loss. #[test] fn static_binary_runs_untracked_when_injection_fails() { - let receiver = channel(1 << 30, Global).unwrap(); - let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); - let payload = Payload { - ipc_channel_conf: receiver.conf(), - preload_path, - seccomp_payload: SeccompPayload::unreachable( - b"/nonexistent/fspy-unreachable-supervisor".to_vec(), - ), - }; - let bump = bumpalo::Bump::new(); - let encoded = encode_payload(payload, &bump); - - let output = Command::new("/bin/sh") + let mut command = Command::new("/bin/sh"); + let receiver = preload_with_failing_seccomp(&mut command); + let output = command .arg("-c") .arg(format!("exec {} stat /hello", test_bin_path().display())) - .env_clear() - .env("LD_PRELOAD", PRELOAD_CDYLIB) - .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) .output() .expect("failed to spawn the shell"); assert!( @@ -80,27 +81,14 @@ fn static_binary_runs_untracked_when_injection_fails() { /// forwarding it to `execve` would fail with `ENOENT` instead. #[test] fn execvp_fallback_keeps_path_search() { - let receiver = channel(1 << 30, Global).unwrap(); - let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); - let payload = Payload { - ipc_channel_conf: receiver.conf(), - preload_path, - seccomp_payload: SeccompPayload::unreachable( - b"/nonexistent/fspy-unreachable-supervisor".to_vec(), - ), - }; - let bump = bumpalo::Bump::new(); - let encoded = encode_payload(payload, &bump); - let test_bin = test_bin_path(); - let output = Command::new("/usr/bin/env") + let mut command = Command::new("/usr/bin/env"); + let receiver = preload_with_failing_seccomp(&mut command); + let output = command .arg(test_bin.file_name().unwrap()) .arg("stat") .arg("/hello") - .env_clear() .env("PATH", test_bin.parent().unwrap()) - .env("LD_PRELOAD", PRELOAD_CDYLIB) - .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) .current_dir("/") .output() .expect("failed to spawn env"); @@ -126,26 +114,10 @@ fn exec_errors_are_not_reported_as_lost() { fs::set_permissions(&script, Permissions::from_mode(0o755)) .expect("failed to set permissions on the script"); - let receiver = channel(1 << 30, Global).unwrap(); - let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); - let payload = Payload { - ipc_channel_conf: receiver.conf(), - preload_path, - seccomp_payload: SeccompPayload::unreachable( - b"/nonexistent/fspy-unreachable-supervisor".to_vec(), - ), - }; - let bump = bumpalo::Bump::new(); - let encoded = encode_payload(payload, &bump); - - let output = Command::new("/bin/sh") - .arg("-c") - .arg(script.as_os_str()) - .env_clear() - .env("LD_PRELOAD", PRELOAD_CDYLIB) - .env("FSPY_PAYLOAD", OsStr::from_bytes(encoded.encoded_string.as_ref())) - .output() - .expect("failed to spawn the shell"); + let mut command = Command::new("/bin/sh"); + let receiver = preload_with_failing_seccomp(&mut command); + let output = + command.arg("-c").arg(script.as_os_str()).output().expect("failed to spawn the shell"); assert!( output.status.success(), "the script without a shebang did not run: {}", diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/README.md b/crates/fspy_shared/src/ipc/channel/shm_io/README.md index 02c0193a0..17542c894 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/README.md +++ b/crates/fspy_shared/src/ipc/channel/shm_io/README.md @@ -18,7 +18,7 @@ Any zero-initialized shared memory works. In practice it is a sparse file mapped Two `AtomicU64` counters sit at the front, followed by one 8-byte descriptor slot per frame. -- The **claim counter** counts frames ever claimed. Bit 63 is the CLOSED gate: the receiver sets it when it seals, and so does any writer whose claim failed, which is how the receiver hears about a lost record. +- The **claim counter** counts frames ever claimed. Bit 63 is the CLOSED gate: the receiver sets it when it seals, and so does any writer whose claim failed or that went on to do something it could not record, which is how the receiver hears about a lost record. - The **payload counter** counts payload bytes ever reserved. The mapping's size and the number of slots are the whole geometry, and every process attaching to a region passes the slot count it was created with. Payloads take what the table leaves. Attaching checks one bound: the counters and the table fit, and what remains is small enough for the descriptors' 32-bit offsets. Splitting 4 GiB at one slot per 64 bytes, say, gives ~67 million slots and ~3.5 GiB of payload room, which is tens of millions of records of a few hundred bytes; payload space runs out first. diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs index 928c87c18..4b7eb1b9b 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs @@ -35,9 +35,10 @@ unsafe impl Sync for ShmWriter {} /// Why a frame could not be claimed. #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] pub enum ClaimError { - /// The CLOSED gate is set, by a seal or by an earlier failed claim. - /// Dropping the record is right either way: the receiver had stopped - /// collecting, or that same bit already fails its seal. + /// The CLOSED gate is set, by a seal, by an earlier failed claim, or by + /// [`ShmWriter::report_loss`]. Dropping the record is right in every + /// case: the receiver had stopped collecting, or that same bit already + /// fails its seal. #[error("the channel has been closed")] Closed, /// No room left, or a frame longer than the `u32::MAX` a descriptor @@ -69,7 +70,8 @@ impl ShmWriter { Some(Self { mapped, _mem: mem }) } - /// Whether the CLOSED gate is set, by a seal or by a failed claim. + /// Whether the CLOSED gate is set, by a seal, by a failed claim, or by + /// [`ShmWriter::report_loss`]. pub fn is_closed(&self) -> bool { self.mapped.claims().load(Ordering::Relaxed) & CLOSED != 0 }