Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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_<NAME>` ([#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)).
Expand Down
25 changes: 21 additions & 4 deletions crates/fspy/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<fspy_shared::ipc::TrackingLoss<'_>> 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,
}
}
}
}
}
45 changes: 44 additions & 1 deletion crates/fspy/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ impl TryFrom<AccessReceiver<Global>> 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())
}
}
}
}
Expand All @@ -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<u16> = 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"));
}
}
87 changes: 79 additions & 8 deletions crates/fspy/tests/untracked_fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Global> {
/// 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<Global> {
let receiver = access_channel(1 << 30, Global).unwrap();
{
let preload_path: &IpcStr = Path::new(PRELOAD_CDYLIB).into();
Expand All @@ -41,13 +40,20 @@ fn preload_with_failing_seccomp(command: &mut Command) -> AccessReceiver<Global>
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<Global> {
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
Expand All @@ -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,
Expand All @@ -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<u8>| {
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
Expand Down
16 changes: 8 additions & 8 deletions crates/fspy_client_unix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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);
}
}

Expand Down
13 changes: 10 additions & 3 deletions crates/fspy_preload_unix/src/interceptions/spawn/exec/mod.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions crates/fspy_preload_unix/src/interceptions/spawn/posix_spawn.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) }
Expand Down
Loading
Loading