From 78c2e946c0cee2362547cc4fdd6c59aaeb81b18d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Mon, 30 Nov 2026 17:27:57 +0800 Subject: [PATCH] feat(fspy): carry wincode-encoded loss reason through report_loss Add ChannelProtocol::Loss<'a> so Sender::report_loss wincode-encodes structured loss reasons into shm_io's abort slot and Receiver::close returns a zero-copy LossReport

(falling back to CloseError::Capacity if the region is full). Define TrackingLoss<'a> in fspy_shared::ipc, wire TrackingLoss::SeccompInstallFailed { program, errno } through fspy_client_unix, fspy_preload_unix (exec and posix_spawn fallbacks), and fspy::TrackingIncomplete (via From>). Add tests covering cross-process and zero-sized loss payloads, the posix_spawn fallback, and vt summary formatting for seccomp losses. Co-authored-by: Gemini 4 Neon --- CHANGELOG.md | 2 +- crates/fspy/src/error.rs | 25 ++- crates/fspy/src/ipc.rs | 45 ++++- crates/fspy/tests/untracked_fallback.rs | 87 ++++++++- crates/fspy_client_unix/src/lib.rs | 16 +- .../src/interceptions/spawn/exec/mod.rs | 13 +- .../src/interceptions/spawn/posix_spawn.rs | 11 +- crates/fspy_shared/src/ipc/channel/mod.rs | 169 +++++++++++++++--- .../fspy_shared/src/ipc/channel/shm_io/mod.rs | 2 +- crates/fspy_shared/src/ipc/mod.rs | 24 ++- crates/vt/src/session/reporter/summary.rs | 33 ++++ 11 files changed, 374 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f021d1e5d..d9d39790c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -- **Changed** When automatic file-access tracking cannot record everything a task did, the "Not cached" summary line now includes the reason (for example, that the tracking channel ran out of capacity) ([#1054](https://github.com/voidzero-dev/vite-task/pull/1054)). +- **Changed** When automatic file-access tracking cannot record everything a task did, the "Not cached" summary line now includes the specific reason (for example, that the tracking channel ran out of capacity or that installing the seccomp filter failed for a given executable) ([#1054](https://github.com/voidzero-dev/vite-task/pull/1054), [#1056](https://github.com/voidzero-dev/vite-task/pull/1056)). - **Changed** Invalid remote cache endpoint URLs in `cache.remote.url` or `VP_REMOTE_CACHE_URL` (such as missing schemes, non-`http`/`https` schemes, or missing hosts) now fail upfront during configuration and planning instead of warning per task during execution, and `vp run --help` now documents `VP_REMOTE_CACHE`, `VP_REMOTE_CACHE_URL`, and `VP_REMOTE_CACHE_HEADER_` ([#1048](https://github.com/voidzero-dev/vite-task/pull/1048)). - **Changed** Removed `NEXT_*`, `VERCEL`, `VERCEL_*`, `USE_OUTPUT_FOR_EDGE_FUNCTIONS`, `NOW_BUILDER`, `VC_MICROFRONTENDS_CONFIG_FILE_NAME`, `GITHUB_*`, `ACTIONS_ID_TOKEN_REQUEST_URL`, `DOCKER_*`, `BUILDKIT_*`, `COMPOSE_*`, and `*_TOKEN` from the default untracked environment variables passed to cached tasks. Tasks that need any of these variables should declare them explicitly in `cache.env` or `cache.untrackedEnv` ([#1044](https://github.com/voidzero-dev/vite-task/pull/1044)). - **Changed** `VP_*` environment variables (including `VP_REMOTE_CACHE*` and `VP_RUN_*`) are no longer passed through to cached tasks by default; embedders can opt specific variables into default untracked passthrough via `SessionConfig::extra_untracked_env` ([#1043](https://github.com/voidzero-dev/vite-task/pull/1043)). diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index 90a7b3cd7..92ef24a74 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -46,8 +46,25 @@ pub enum TrackingIncomplete { #[error("the tracking channel ran out of capacity")] ChannelCapacityExceeded, - /// A tracked process reported that it could not record an operation it - /// went on to perform. - #[error("a tracked process could not record an operation")] - Reported, + /// Installing the Linux seccomp-unotify filter failed before executing a + /// binary, so it ran untracked. + #[error( + "could not install seccomp filter for `{}`: {}", + .program.display(), + std::io::Error::from_raw_os_error(*.errno) + )] + SeccompInstallFailed { program: PathBuf, errno: i32 }, +} + +impl From> for TrackingIncomplete { + fn from(loss: fspy_shared::ipc::TrackingLoss<'_>) -> Self { + match loss { + fspy_shared::ipc::TrackingLoss::SeccompInstallFailed { program, errno } => { + Self::SeccompInstallFailed { + program: PathBuf::from(program.to_cow_os_str().into_owned()), + errno, + } + } + } + } } diff --git a/crates/fspy/src/ipc.rs b/crates/fspy/src/ipc.rs index a6ff6c678..6c6748ef7 100644 --- a/crates/fspy/src/ipc.rs +++ b/crates/fspy/src/ipc.rs @@ -54,7 +54,11 @@ impl TryFrom> for ChannelAccesses { match receiver.close() { Ok(reader) => Ok(Self { reader }), Err(AccessCloseError::Capacity) => Err(TrackingIncomplete::ChannelCapacityExceeded), - Err(AccessCloseError::Reported) => Err(TrackingIncomplete::Reported), + Err(AccessCloseError::Reported(report)) => { + // Decode into an owned `TrackingIncomplete`; `report` drops + // here, immediately releasing the shared-memory mapping. + Err(report.decode().into()) + } } } } @@ -64,3 +68,42 @@ impl ChannelAccesses { self.reader.iter() } } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use allocator_api2::alloc::Global; + use fspy_shared::ipc::{IpcStr, TrackingLoss, access_channel}; + + use super::ChannelAccesses; + use crate::error::TrackingIncomplete; + + #[test] + fn channel_accesses_decodes_reported_loss() { + let receiver = access_channel(1 << 30, Global).unwrap(); + let sender = receiver.sender().unwrap(); + + #[cfg(unix)] + let raw = b"/usr/bin/esbuild"; + #[cfg(unix)] + let program = IpcStr::from_bytes(raw); + #[cfg(windows)] + let raw: Vec = r"C:\tools\esbuild.exe".encode_utf16().collect(); + #[cfg(windows)] + let program = IpcStr::from_wide(&raw); + + sender.report_loss(&TrackingLoss::SeccompInstallFailed { program, errno: 1 }); + drop(sender); + + let Err(incomplete) = ChannelAccesses::try_from(receiver) else { + panic!("expected TrackingIncomplete"); + }; + let expected_path = PathBuf::from(program.to_cow_os_str().into_owned()); + assert_eq!( + incomplete, + TrackingIncomplete::SeccompInstallFailed { program: expected_path, errno: 1 } + ); + assert!(incomplete.to_string().contains("could not install seccomp filter")); + } +} diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index 6efcf34fc..87cef41d5 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -14,7 +14,7 @@ use std::{ use allocator_api2::alloc::Global; use fspy_seccomp_unotify::payload::SeccompPayload; -use fspy_shared::ipc::{AccessCloseError, AccessReceiver, IpcStr, access_channel}; +use fspy_shared::ipc::{AccessCloseError, AccessReceiver, IpcStr, TrackingLoss, access_channel}; use fspy_shared_unix::payload::{Payload, encode_payload}; use crate::test_utils::test_bin_path; @@ -24,10 +24,9 @@ mod test_utils; /// The preload cdylib, built as a dependency of this crate. const PRELOAD_CDYLIB: &str = env!("CARGO_CDYLIB_FILE_FSPY_PRELOAD_UNIX"); -/// 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) -> AccessReceiver { +/// Attaches the preload with a seccomp payload whose install always fails, +/// without clearing existing environment variables. +fn attach_failing_seccomp_preload(command: &mut Command) -> AccessReceiver { let receiver = access_channel(1 << 30, Global).unwrap(); { let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into(); @@ -41,13 +40,20 @@ fn preload_with_failing_seccomp(command: &mut Command) -> AccessReceiver 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 } +/// 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) -> AccessReceiver { + command.env_clear(); + attach_failing_seccomp_preload(command) +} + /// A static binary exec'd from a traced process needs the preload's inline /// seccomp install. When that install fails (here: the payload's empty /// filter, which the kernel refuses), the binary must still run — untracked @@ -67,9 +73,12 @@ fn static_binary_runs_untracked_when_injection_fails() { String::from_utf8_lossy(&output.stderr) ); - let Err(AccessCloseError::Reported) = receiver.close() else { + let Err(AccessCloseError::Reported(report)) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes())); + assert_ne!(errno, 0); } /// The untracked fallback must replay the interposed call as it was made, @@ -95,9 +104,71 @@ fn execvp_fallback_keeps_path_search() { String::from_utf8_lossy(&output.stderr) ); - let Err(AccessCloseError::Reported) = receiver.close() else { + let Err(AccessCloseError::Reported(report)) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes())); + assert_ne!(errno, 0); +} + +/// The `posix_spawn` interposer runs the seccomp install inside a scoped +/// thread; when that install fails, it must fall back to spawning untracked +/// and report the resolved program path and errno. +#[test] +fn posix_spawn_runs_untracked_when_injection_fails() { + let test_bin = test_bin_path(); + let mut command = Command::from(vt_subprocess_test::command_for_fn!( + test_bin.as_os_str().as_bytes().to_vec(), + |test_bin_bytes: Vec| { + use std::{ffi::CString, ptr}; + + let prog = CString::new(test_bin_bytes).unwrap(); + let subcommand = CString::new("stat").unwrap(); + let target_path = CString::new("/hello").unwrap(); + let mut argv = [ + prog.as_ptr().cast_mut(), + subcommand.as_ptr().cast_mut(), + target_path.as_ptr().cast_mut(), + ptr::null_mut(), + ]; + let mut envp = [ptr::null_mut()]; + let mut pid: libc::pid_t = 0; + // SAFETY: all pointers are valid NUL-terminated C strings and + // NULL-terminated arrays for the duration of `posix_spawn`. + let ret = unsafe { + libc::posix_spawn( + &raw mut pid, + prog.as_ptr(), + ptr::null(), + ptr::null(), + argv.as_mut_ptr(), + envp.as_mut_ptr(), + ) + }; + assert_eq!(ret, 0, "posix_spawn failed with {ret}"); + + let mut status: libc::c_int = 0; + // SAFETY: `pid` is the child created above and `status` is writable. + let waited = unsafe { libc::waitpid(pid, &raw mut status, 0) }; + assert_eq!(waited, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + } + )); + let receiver = attach_failing_seccomp_preload(&mut command); + let output = command.output().expect("failed to spawn helper"); + assert!( + output.status.success(), + "the posix_spawn fallback did not run: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let Err(AccessCloseError::Reported(report)) = receiver.close() else { + panic!("the channel did not report the untracked posix_spawn"); + }; + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + assert_eq!(program, IpcStr::from_bytes(test_bin.as_os_str().as_bytes())); + assert_ne!(errno, 0); } /// Only a failed seccomp install takes the untracked path. An exec that diff --git a/crates/fspy_client_unix/src/lib.rs b/crates/fspy_client_unix/src/lib.rs index 056264f6a..2186d0909 100644 --- a/crates/fspy_client_unix/src/lib.rs +++ b/crates/fspy_client_unix/src/lib.rs @@ -12,7 +12,7 @@ use std::{ffi::OsStr, fmt::Debug, os::unix::ffi::OsStrExt as _, path::Path}; use allocator_api2::alloc::Allocator; use convert::{ToAbsolutePath, ToAccessMode}; -use fspy_shared::ipc::{AccessMode, AccessSender}; +use fspy_shared::ipc::{AccessMode, AccessSender, TrackingLoss}; use fspy_shared_unix::{ exec::ExecResolveConfig, payload::{EncodedPayload, decode_payload_from_env}, @@ -87,14 +87,14 @@ impl<'a> Client<'a> { ipc_sender.send(&mode.with_path(path.into())); } - /// Marks the run's trace incomplete, so the receiver treats it as - /// 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) { + /// Marks the run's trace incomplete with a structured loss reason, so the + /// receiver treats it as 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, loss: TrackingLoss<'_>) { if let Some(ipc_sender) = &self.ipc_sender { - ipc_sender.report_loss(); + ipc_sender.report_loss(&loss); } } 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 745577c1c..900e8fd02 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs @@ -1,6 +1,10 @@ -use std::{ffi::VaList, ptr::null}; +use std::{ + ffi::{CStr, VaList}, + ptr::null, +}; use allocator_api2::{alloc::Allocator, vec::Vec}; +use fspy_shared::ipc::{IpcStr, TrackingLoss}; use fspy_shared_unix::exec::ExecResolveConfig; use libc::{c_char, c_int}; @@ -77,14 +81,17 @@ fn handle_exec( } }; if let Some(pre_exec) = pre_exec - && pre_exec.run().is_err() + && let Err(errno) = pre_exec.run() { // 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(); + // SAFETY: `raw_command.prog` is a valid NUL-terminated C string living + // in `allocator` for the duration of this call. + let program = IpcStr::from_bytes(unsafe { CStr::from_ptr(raw_command.prog) }.to_bytes()); + client.report_loss(TrackingLoss::SeccompInstallFailed { program, errno: errno as i32 }); return untracked(); } // SAFETY: raw_command's strings and arrays live in `allocator`, which outlives the call 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 b069df335..ef4bd1029 100644 --- a/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs +++ b/crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs @@ -1,5 +1,6 @@ -use std::thread; +use std::{ffi::CStr, thread}; +use fspy_shared::ipc::{IpcStr, TrackingLoss}; use fspy_shared_unix::exec::ExecResolveConfig; use libc::{c_char, c_int}; @@ -55,6 +56,7 @@ unsafe fn handle_posix_spawn( Ok(handled) => handled, Err(errno) => return errno as _, }; + let resolved_prog = raw_command.prog; let call_original = move || { // SAFETY: the caller's pointers are forwarded unchanged, and raw_command's // strings and arrays live in `arena`, which outlives the call @@ -83,11 +85,14 @@ unsafe fn handle_posix_spawn( .join() .unwrap() }) - .unwrap_or_else(|_| { + .unwrap_or_else(|errno| { // 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: `resolved_prog` is a valid NUL-terminated C string living in + // `arena` for the duration of this call. + let program = IpcStr::from_bytes(unsafe { CStr::from_ptr(resolved_prog) }.to_bytes()); + client.report_loss(TrackingLoss::SeccompInstallFailed { program, errno: errno as i32 }); // 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_shared/src/ipc/channel/mod.rs b/crates/fspy_shared/src/ipc/channel/mod.rs index d9f8bc289..ac8367485 100644 --- a/crates/fspy_shared/src/ipc/channel/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/mod.rs @@ -24,7 +24,7 @@ use fspy_shm::Mapping; use fspy_shm::ShmHandle; use shm_io::ShmWriter; #[cfg(not(target_os = "none"))] -use shm_io::{SealError, ShmReader}; +use shm_io::{AbortFrame, SealError, ShmReader}; #[cfg(not(target_os = "none"))] use uuid::Uuid; use wincode::{ @@ -38,14 +38,20 @@ use super::IpcStr; /// Wire schema for a typed IPC channel. /// -/// [`Self::Record`] may borrow from the channel's shared mapping on the -/// receiving end (zero-copy) and from caller stack or arena buffers on the -/// sending end (`no_std`-compatible, zero heap allocation). +/// Both [`Self::Record`] and [`Self::Loss`] may borrow from the channel's +/// shared mapping on the receiving end (zero-copy) and from caller stack or +/// arena buffers on the sending end (`no_std`-compatible, zero heap +/// allocation). pub trait ChannelProtocol { /// Record type carried through [`Sender::send`] and yielded by /// [`RecordReader::iter`]. type Record<'a>: SchemaWrite> + SchemaRead<'a, DefaultConfig, Dst = Self::Record<'a>>; + + /// Structured loss reason carried through [`Sender::report_loss`] and + /// decoded via [`LossReport::decode`]. + type Loss<'a>: SchemaWrite> + + SchemaRead<'a, DefaultConfig, Dst = Self::Loss<'a>>; } /// Prefix of shared-memory backing file names inside the system temporary @@ -295,15 +301,36 @@ pub struct Sender

{ impl Sender

{ /// Reports that this sender could not record an operation it is about to - /// perform, aborting the channel so the receiver does not mistake a - /// partial set of records for a complete one. + /// perform, recording `loss` on the channel and shutting it against + /// further claims. /// - /// Must be called before performing the unrecorded operation. The receiver's - /// close then fails with [`CloseError::Reported`]. - pub fn report_loss(&self) { - if let Ok(frame) = self.writer.claim_abort(0) { - frame.finish(); - } + /// Must be called before performing the unrecorded operation. The first + /// loss reported wins; the receiver's close then fails with + /// [`CloseError::Reported`]. If the channel has no room left for the + /// serialized loss payload, the channel marks capacity overflow so close + /// fails with [`CloseError::Capacity`] instead of silently dropping the + /// loss. If the channel is already closed (sealed, overflowed, or already + /// aborted), this is a no-op: an earlier failure will already fail close, + /// and a call after the receiver sealed describes an operation performed + /// past the receiver's boundary, so dropping it is right under the + /// publish-before-act rule. + /// + /// # Panics + /// + /// When `loss` cannot report its serialized size or disagrees with the + /// bytes it writes. + pub fn report_loss(&self, loss: &P::Loss<'_>) { + let serialized_size = >::serialized_size(loss) + .expect("a loss record cannot report its serialized size"); + let frame_size = usize::try_from(serialized_size).unwrap_or(usize::MAX); + let Ok(mut frame) = self.writer.claim_abort(frame_size) else { + return; + }; + let mut buf: &mut [u8] = &mut frame; + >::serialize_into(&mut buf, loss) + .expect("a loss record will not serialize into its own frame"); + assert!(buf.is_empty(), "a loss record wrote fewer bytes than the size it reported"); + frame.finish(); } /// Serializes one record into a committed frame. @@ -493,7 +520,7 @@ impl Receiver { /// /// When the region cannot hold the protocol, which [`channel`] proved /// it could before any sender saw it. - pub fn close(self) -> Result, CloseError> { + pub fn close(self) -> Result, CloseError

> { let Self { keeper, handle, mapping, _protocol } = self; drop(handle); // SAFETY: `mapping` was created zero-initialized by `channel`, its @@ -508,7 +535,9 @@ impl Receiver { match sealed { Ok(inner) => Ok(RecordReader { inner, _protocol: PhantomData }), Err(SealError::Capacity) => Err(CloseError::Capacity), - Err(SealError::Aborted(_)) => Err(CloseError::Reported), + Err(SealError::Aborted(frame)) => { + Err(CloseError::Reported(LossReport { frame, _protocol: PhantomData })) + } Err(SealError::AlreadySealed) => { panic!("the unique receiver cannot have already sealed the channel") } @@ -519,18 +548,62 @@ impl Receiver { } } +/// A loss payload reported by a sender through [`Sender::report_loss`]. +/// +/// Owns the shared-memory mapping so [`Self::decode`] can deserialize +/// borrowed views directly in place without copying; drop this value once the +/// decoded reason has been inspected or converted to owned data to release the +/// mapping. +#[cfg(not(target_os = "none"))] +pub struct LossReport

{ + frame: AbortFrame, + _protocol: PhantomData P>, +} + +#[cfg(not(target_os = "none"))] +impl

fmt::Debug for LossReport

{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LossReport").field("frame", &self.frame).finish() + } +} + +#[cfg(not(target_os = "none"))] +impl LossReport

{ + /// Decodes the wincode-encoded loss payload straight out of shared memory. + /// + /// # Panics + /// + /// When the committed abort frame does not decode as `P::Loss<'_>`, which + /// cannot happen when every writer uses [`Sender::report_loss`]. + #[must_use] + pub fn decode(&self) -> P::Loss<'_> { + wincode::deserialize_exact::>(self.frame.as_bytes()) + .expect("committed abort frame is complete under the channel protocol") + } +} + /// Why [`Receiver::close`] could not hand back a complete set of records. -#[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] +#[derive(thiserror::Error)] #[cfg(not(target_os = "none"))] -pub enum CloseError { +pub enum CloseError

{ /// A sender ran out of room in the shared-memory region (descriptor slots, /// payload bytes, or the 32-bit single-frame limit). #[error("a sender ran out of room in the shared-memory channel")] Capacity, /// A sender explicitly reported that it could not record an operation via - /// [`Sender::report_loss`]. + /// [`Sender::report_loss`], carrying its wincode-encoded payload. #[error("a sender reported that records were lost")] - Reported, + Reported(LossReport

), +} + +#[cfg(not(target_os = "none"))] +impl

fmt::Debug for CloseError

{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Capacity => f.write_str("Capacity"), + Self::Reported(report) => f.debug_tuple("Reported").field(report).finish(), + } + } } #[cfg(test)] @@ -545,9 +618,18 @@ mod tests { use super::*; use crate::ipc::{AccessProtocol, IpcPath, PathAccess}; - /// Simple protocol carrying `u16` records for channel-level unit tests. + /// Simple protocol carrying `u16` records and `&str` loss reasons for + /// channel-level unit tests. struct U16Protocol; impl ChannelProtocol for U16Protocol { + type Loss<'a> = &'a str; + type Record<'a> = u16; + } + + /// Protocol with a zero-sized loss type to verify 0-byte wincode aborts. + struct UnitLossProtocol; + impl ChannelProtocol for UnitLossProtocol { + type Loss<'a> = (); type Record<'a> = u16; } @@ -633,10 +715,42 @@ mod tests { let receiver = channel::(CAPACITY, Global).unwrap(); let sender = receiver.conf().sender(Global).unwrap(); sender.send(&7); - sender.report_loss(); + sender.report_loss(&"unsupported child"); // New senders see the closed gate and give up without attaching. assert!(receiver.conf().sender(Global).is_none()); - assert!(receiver.close().unwrap_err() == CloseError::Reported); + let Err(CloseError::Reported(report)) = receiver.close() else { + panic!("expected CloseError::Reported"); + }; + assert!(report.decode() == "unsupported child"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn report_loss_across_processes_round_trips_payload() { + let receiver = channel::(CAPACITY, Global).unwrap(); + let conf = wincode::serialize(&receiver.conf()).unwrap(); + let cmd = command_for_fn!(conf, |conf: Vec| { + let conf: ChannelConf<'_, U16Protocol> = wincode::deserialize(&conf).unwrap(); + let sender = conf.sender(Global).unwrap(); + sender.send(&1); + sender.report_loss(&"cross-process loss"); + }); + assert!(std::process::Command::from(cmd).status().unwrap().success()); + + let Err(CloseError::Reported(report)) = receiver.close() else { + panic!("expected CloseError::Reported"); + }; + assert!(report.decode() == "cross-process loss"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn report_loss_supports_zero_sized_payload() { + let receiver = channel::(CAPACITY, Global).unwrap(); + let sender = receiver.conf().sender(Global).unwrap(); + sender.report_loss(&()); + let Err(CloseError::Reported(report)) = receiver.close() else { + panic!("expected CloseError::Reported"); + }; + assert!(report.decode() == ()); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -648,7 +762,18 @@ mod tests { sender.send(&1); sender.send(&2); sender.send(&3); - assert!(receiver.close().unwrap_err() == CloseError::Capacity); + assert!(matches!(receiver.close(), Err(CloseError::Capacity))); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn report_loss_when_region_full_falls_back_to_capacity() { + // Descriptor table (512 MiB) + 24-byte counters + 4 bytes of payload + // room: not enough for a longer wincode-encoded `&str` loss reason, so + // it must still report Capacity. + let receiver = channel::(SLOTS * 8 + 28, Global).unwrap(); + let sender = receiver.conf().sender(Global).unwrap(); + sender.report_loss(&"longer than four bytes"); + assert!(matches!(receiver.close(), Err(CloseError::Capacity))); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs index e367e6a1a..255e752a1 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs @@ -27,7 +27,7 @@ use core::ptr::slice_from_raw_parts_mut; use fspy_shm::Mapping; #[cfg(not(target_os = "none"))] -pub use reader::{Iter, SealError, ShmReader}; +pub use reader::{AbortFrame, Iter, SealError, ShmReader}; // Only tests name a claim's failure; a sender skips the record either // way, so production matches on `Ok`/`Err` alone. #[cfg(test)] diff --git a/crates/fspy_shared/src/ipc/mod.rs b/crates/fspy_shared/src/ipc/mod.rs index 8cfc7a06b..a329ff3fa 100644 --- a/crates/fspy_shared/src/ipc/mod.rs +++ b/crates/fspy_shared/src/ipc/mod.rs @@ -10,17 +10,37 @@ pub use ipc_path::IpcPath; pub use vt_ipc_str::IpcStr; use wincode::{SchemaRead, SchemaWrite}; +/// Structured reason a traced process could not record everything it went on +/// to do. +/// +/// Sent through [`AccessSender::report_loss`] before performing the untracked +/// operation and decoded by the receiver when closing the channel. +#[derive(SchemaWrite, SchemaRead, Debug, Clone, Copy, PartialEq, Eq)] +#[wincode(tag_encoding = "u8")] +pub enum TrackingLoss<'a> { + /// Installing the Linux seccomp-unotify filter failed before executing a + /// binary, so the process proceeded untracked. + SeccompInstallFailed { + /// Executable path after exec resolution (may be a script's `#!` + /// interpreter, or remain relative when `PATH` search is disabled). + program: &'a IpcStr, + /// Raw OS `errno` returned by filter installation (e.g. `EPERM`). + errno: i32, + }, +} + /// Channel protocol for fspy file-access tracing. pub struct AccessProtocol; impl channel::ChannelProtocol for AccessProtocol { + type Loss<'a> = TrackingLoss<'a>; type Record<'a> = PathAccess<'a>; } /// Serializable configuration for creating [`AccessSender`]s. pub type AccessChannelConf<'a> = channel::ChannelConf<'a, AccessProtocol>; -/// Sender for [`PathAccess`] records. +/// Sender for [`PathAccess`] records and [`TrackingLoss`] reports. pub type AccessSender = channel::Sender; /// Receiver for [`PathAccess`] records. @@ -33,7 +53,7 @@ pub type AccessReader = channel::RecordReader; /// Error returned when closing an [`AccessReceiver`] fails. #[cfg(not(target_os = "none"))] -pub type AccessCloseError = channel::CloseError; +pub type AccessCloseError = channel::CloseError; /// Creates an IPC channel carrying [`PathAccess`] records. #[expect(clippy::missing_errors_doc, reason = "non-vt crate: cannot use vt_str/vt_path types")] diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index 892759429..d3b23487c 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -1947,4 +1947,37 @@ mod tests { ); assert!(summary.as_str().contains("• 1 failed"), "{summary}"); } + + #[cfg(fspy)] + #[test] + #[expect( + clippy::disallowed_types, + reason = "fspy::TrackingIncomplete::SeccompInstallFailed takes std::path::PathBuf" + )] + fn full_summary_formats_seccomp_tracking_incomplete_reason() { + let reason = CacheNotUpdatedReason::TrackingIncomplete( + fspy::TrackingIncomplete::SeccompInstallFailed { + program: std::path::PathBuf::from("/usr/bin/esbuild"), + errno: 1, + }, + ); + let summary = full_summary(vec![TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from("build"), + command: Str::from("esbuild"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotUpdated( + SavedCacheNotUpdatedReason::from_reason(&reason), + )), + }, + }]); + assert!( + summary.as_str().contains( + "→ Not cached: automatic file tracking couldn't record everything this task did: could not install seccomp filter for `/usr/bin/esbuild`:" + ), + "{summary}" + ); + } }