Address preserved path review feedback

This commit is contained in:
Eva Wong
2026-04-27 10:51:25 -07:00
parent 90d5f4304f
commit c5ddf213fe
12 changed files with 1768 additions and 357 deletions
+124 -120
View File
@@ -26,6 +26,7 @@ use std::process::Command;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result;
use codex_protocol::permissions::is_preserved_path_name;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_protocol::protocol::WritableRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -137,13 +138,17 @@ impl SyntheticMountTarget {
}
}
fn existing_empty_file(path: &Path, metadata: &Metadata) -> Self {
pub(crate) fn existing_empty_file(path: &Path, metadata: &Metadata) -> Self {
Self {
path: path.to_path_buf(),
pre_existing_file: Some(FileIdentity::from_metadata(metadata)),
}
}
pub(crate) fn preserves_pre_existing_file(&self) -> bool {
self.pre_existing_file.is_some()
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
@@ -335,7 +340,7 @@ fn create_filesystem_args(
unreadable_roots.sort();
unreadable_roots.dedup();
let mut args = if file_system_sandbox_policy.has_full_disk_read_access() {
let args = if file_system_sandbox_policy.has_full_disk_read_access() {
// Read-only root, then mount a minimal device tree.
// In bubblewrap (`bubblewrap.c`, `SETUP_MOUNT_DEV`), `--dev /dev`
// creates the standard minimal nodes: null, zero, full, random,
@@ -408,8 +413,11 @@ fn create_filesystem_args(
args
};
let mut preserved_files = Vec::new();
let mut synthetic_mount_targets = Vec::new();
let mut bwrap_args = BwrapArgs {
args,
preserved_files: Vec::new(),
synthetic_mount_targets: Vec::new(),
};
let mut allowed_write_paths = Vec::with_capacity(writable_roots.len());
for writable_root in &writable_roots {
let root = writable_root.root.as_path();
@@ -440,13 +448,7 @@ fn create_filesystem_args(
unreadable_ancestors_of_writable_roots.sort_by_key(|path| path_depth(path));
for unreadable_root in &unreadable_ancestors_of_writable_roots {
append_unreadable_root_args(
&mut args,
&mut preserved_files,
&mut synthetic_mount_targets,
unreadable_root,
&allowed_write_paths,
)?;
append_unreadable_root_args(&mut bwrap_args, unreadable_root, &allowed_write_paths)?;
}
for writable_root in &sorted_writable_roots {
@@ -460,13 +462,13 @@ fn create_filesystem_args(
.filter(|unreadable_root| root.starts_with(unreadable_root))
.max_by_key(|unreadable_root| path_depth(unreadable_root))
{
append_mount_target_parent_dir_args(&mut args, root, masking_root);
append_mount_target_parent_dir_args(&mut bwrap_args.args, root, masking_root);
}
let mount_root = symlink_target.as_deref().unwrap_or(root);
args.push("--bind".to_string());
args.push(path_to_string(mount_root));
args.push(path_to_string(mount_root));
bwrap_args.args.push("--bind".to_string());
bwrap_args.args.push(path_to_string(mount_root));
bwrap_args.args.push(path_to_string(mount_root));
let mut read_only_subpaths: Vec<PathBuf> = writable_root
.read_only_subpaths
@@ -479,13 +481,7 @@ fn create_filesystem_args(
}
read_only_subpaths.sort_by_key(|path| path_depth(path));
for subpath in read_only_subpaths {
append_read_only_subpath_args(
&mut args,
&mut preserved_files,
&mut synthetic_mount_targets,
&subpath,
&allowed_write_paths,
)?;
append_read_only_subpath_args(&mut bwrap_args, &subpath, &allowed_write_paths)?;
}
let mut nested_unreadable_roots: Vec<PathBuf> = unreadable_roots
.iter()
@@ -498,13 +494,7 @@ fn create_filesystem_args(
}
nested_unreadable_roots.sort_by_key(|path| path_depth(path));
for unreadable_root in nested_unreadable_roots {
append_unreadable_root_args(
&mut args,
&mut preserved_files,
&mut synthetic_mount_targets,
&unreadable_root,
&allowed_write_paths,
)?;
append_unreadable_root_args(&mut bwrap_args, &unreadable_root, &allowed_write_paths)?;
}
}
@@ -520,20 +510,10 @@ fn create_filesystem_args(
.collect();
rootless_unreadable_roots.sort_by_key(|path| path_depth(path));
for unreadable_root in rootless_unreadable_roots {
append_unreadable_root_args(
&mut args,
&mut preserved_files,
&mut synthetic_mount_targets,
&unreadable_root,
&allowed_write_paths,
)?;
append_unreadable_root_args(&mut bwrap_args, &unreadable_root, &allowed_write_paths)?;
}
Ok(BwrapArgs {
args,
preserved_files,
synthetic_mount_targets,
})
Ok(bwrap_args)
}
fn expand_unreadable_globs_with_ripgrep(
@@ -858,9 +838,7 @@ fn append_mount_target_parent_dir_args(args: &mut Vec<String>, mount_target: &Pa
}
fn append_read_only_subpath_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
synthetic_mount_targets: &mut Vec<SyntheticMountTarget>,
bwrap_args: &mut BwrapArgs,
subpath: &Path,
allowed_write_paths: &[PathBuf],
) -> Result<()> {
@@ -884,13 +862,7 @@ fn append_read_only_subpath_args(
// Another concurrent bwrap setup can leave a zero-byte mount target at
// a missing preserved path. Treat it like the missing case instead of
// binding that transient host path as the stable source.
append_existing_empty_file_bind_data_args(
args,
preserved_files,
synthetic_mount_targets,
subpath,
&metadata,
)?;
append_existing_empty_file_bind_data_args(bwrap_args, subpath, &metadata)?;
return Ok(());
}
@@ -898,66 +870,52 @@ fn append_read_only_subpath_args(
if let Some(first_missing_component) = find_first_non_existent_component(subpath)
&& is_within_allowed_write_paths(&first_missing_component, allowed_write_paths)
{
append_missing_empty_file_bind_data_args(
args,
preserved_files,
synthetic_mount_targets,
&first_missing_component,
)?;
append_missing_empty_file_bind_data_args(bwrap_args, &first_missing_component)?;
}
return Ok(());
}
if is_within_allowed_write_paths(subpath, allowed_write_paths) {
args.push("--ro-bind".to_string());
args.push(path_to_string(subpath));
args.push(path_to_string(subpath));
bwrap_args.args.push("--ro-bind".to_string());
bwrap_args.args.push(path_to_string(subpath));
bwrap_args.args.push(path_to_string(subpath));
}
Ok(())
}
fn append_empty_file_bind_data_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
path: &Path,
) -> Result<()> {
if preserved_files.is_empty() {
preserved_files.push(File::open("/dev/null")?);
fn append_empty_file_bind_data_args(bwrap_args: &mut BwrapArgs, path: &Path) -> Result<()> {
if bwrap_args.preserved_files.is_empty() {
bwrap_args.preserved_files.push(File::open("/dev/null")?);
}
let null_fd = preserved_files[0].as_raw_fd().to_string();
args.push("--ro-bind-data".to_string());
args.push(null_fd);
args.push(path_to_string(path));
let null_fd = bwrap_args.preserved_files[0].as_raw_fd().to_string();
bwrap_args.args.push("--ro-bind-data".to_string());
bwrap_args.args.push(null_fd);
bwrap_args.args.push(path_to_string(path));
Ok(())
}
fn append_missing_empty_file_bind_data_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
synthetic_mount_targets: &mut Vec<SyntheticMountTarget>,
path: &Path,
) -> Result<()> {
append_empty_file_bind_data_args(args, preserved_files, path)?;
synthetic_mount_targets.push(SyntheticMountTarget::missing(path));
fn append_missing_empty_file_bind_data_args(bwrap_args: &mut BwrapArgs, path: &Path) -> Result<()> {
append_empty_file_bind_data_args(bwrap_args, path)?;
bwrap_args
.synthetic_mount_targets
.push(SyntheticMountTarget::missing(path));
Ok(())
}
fn append_existing_empty_file_bind_data_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
synthetic_mount_targets: &mut Vec<SyntheticMountTarget>,
bwrap_args: &mut BwrapArgs,
path: &Path,
metadata: &Metadata,
) -> Result<()> {
append_empty_file_bind_data_args(args, preserved_files, path)?;
synthetic_mount_targets.push(SyntheticMountTarget::existing_empty_file(path, metadata));
append_empty_file_bind_data_args(bwrap_args, path)?;
bwrap_args
.synthetic_mount_targets
.push(SyntheticMountTarget::existing_empty_file(path, metadata));
Ok(())
}
fn append_unreadable_root_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
synthetic_mount_targets: &mut Vec<SyntheticMountTarget>,
bwrap_args: &mut BwrapArgs,
unreadable_root: &Path,
allowed_write_paths: &[PathBuf],
) -> Result<()> {
@@ -982,27 +940,16 @@ fn append_unreadable_root_args(
if let Some(first_missing_component) = find_first_non_existent_component(unreadable_root)
&& is_within_allowed_write_paths(&first_missing_component, allowed_write_paths)
{
append_missing_empty_file_bind_data_args(
args,
preserved_files,
synthetic_mount_targets,
&first_missing_component,
)?;
append_missing_empty_file_bind_data_args(bwrap_args, &first_missing_component)?;
}
return Ok(());
}
append_existing_unreadable_path_args(
args,
preserved_files,
unreadable_root,
allowed_write_paths,
)
append_existing_unreadable_path_args(bwrap_args, unreadable_root, allowed_write_paths)
}
fn append_existing_unreadable_path_args(
args: &mut Vec<String>,
preserved_files: &mut Vec<File>,
bwrap_args: &mut BwrapArgs,
unreadable_root: &Path,
allowed_write_paths: &[PathBuf],
) -> Result<()> {
@@ -1012,33 +959,37 @@ fn append_existing_unreadable_path_args(
.map(PathBuf::as_path)
.filter(|path| *path != unreadable_root && path.starts_with(unreadable_root))
.collect();
args.push("--perms".to_string());
bwrap_args.args.push("--perms".to_string());
// Execute-only perms let the process traverse into explicitly
// re-opened writable descendants while still hiding the denied
// directory contents. Plain denied directories with no writable child
// mounts stay at `000`.
args.push(if writable_descendants.is_empty() {
bwrap_args.args.push(if writable_descendants.is_empty() {
"000".to_string()
} else {
"111".to_string()
});
args.push("--tmpfs".to_string());
args.push(path_to_string(unreadable_root));
bwrap_args.args.push("--tmpfs".to_string());
bwrap_args.args.push(path_to_string(unreadable_root));
// Recreate any writable descendants inside the tmpfs before remounting
// the denied parent read-only. Otherwise bubblewrap cannot mkdir the
// nested mount targets after the parent has been frozen.
writable_descendants.sort_by_key(|path| path_depth(path));
for writable_descendant in writable_descendants {
append_mount_target_parent_dir_args(args, writable_descendant, unreadable_root);
append_mount_target_parent_dir_args(
&mut bwrap_args.args,
writable_descendant,
unreadable_root,
);
}
args.push("--remount-ro".to_string());
args.push(path_to_string(unreadable_root));
bwrap_args.args.push("--remount-ro".to_string());
bwrap_args.args.push(path_to_string(unreadable_root));
return Ok(());
}
args.push("--perms".to_string());
args.push("000".to_string());
append_empty_file_bind_data_args(args, preserved_files, unreadable_root)
bwrap_args.args.push("--perms".to_string());
bwrap_args.args.push("000".to_string());
append_empty_file_bind_data_args(bwrap_args, unreadable_root)
}
/// Returns true when `path` is under any allowed writable root.
@@ -1049,7 +1000,7 @@ fn is_within_allowed_write_paths(path: &Path, allowed_write_paths: &[PathBuf]) -
}
fn transient_empty_preserved_file_metadata(path: &Path) -> Option<Metadata> {
if !has_preserved_path_name(path) {
if !path.file_name().is_some_and(is_preserved_path_name) {
return None;
}
@@ -1061,11 +1012,6 @@ fn transient_empty_preserved_file_metadata(path: &Path) -> Option<Metadata> {
}
}
fn has_preserved_path_name(path: &Path) -> bool {
path.file_name()
.is_some_and(|name| name == ".git" || name == ".agents" || name == ".codex")
}
fn first_writable_symlink_component_in_path(
target_path: &Path,
allowed_write_paths: &[PathBuf],
@@ -1143,6 +1089,7 @@ fn find_first_non_existent_component(target_path: &Path) -> Option<PathBuf> {
#[cfg(test)]
mod tests {
use super::*;
use codex_protocol::protocol::FileSystemAccessMode;
use codex_protocol::protocol::FileSystemPath;
use codex_protocol::protocol::FileSystemSandboxEntry;
@@ -1533,7 +1480,15 @@ mod tests {
assert_empty_file_bound_without_perms(&args.args, &blocked);
assert_eq!(args.preserved_files.len(), 1);
assert_eq!(synthetic_mount_target_paths(&args), vec![blocked.clone()]);
assert_eq!(
synthetic_mount_target_paths(&args),
vec![
workspace.join(".git"),
workspace.join(".agents"),
workspace.join(".codex"),
blocked.clone(),
]
);
assert!(
!blocked.exists(),
"missing path mask should not materialize host-side preserved paths at arg construction time",
@@ -1563,7 +1518,14 @@ mod tests {
let dot_git_str = path_to_string(&dot_git);
assert_empty_file_bound_without_perms(&args.args, &dot_git);
assert_eq!(synthetic_mount_target_paths(&args), vec![dot_git.clone()]);
assert_eq!(
synthetic_mount_target_paths(&args),
vec![
dot_git.clone(),
workspace.join(".agents"),
workspace.join(".codex"),
]
);
assert!(
!args
.args
@@ -1578,6 +1540,36 @@ mod tests {
);
}
#[test]
fn missing_child_git_under_parent_repo_stays_absent() {
let temp_dir = TempDir::new().expect("temp dir");
let repo = temp_dir.path().join("repo");
let workspace = repo.join("workspace");
let dot_git = workspace.join(".git");
std::fs::create_dir_all(repo.join(".git")).expect("create parent .git");
std::fs::create_dir_all(&workspace).expect("create workspace");
let workspace_root =
AbsolutePathBuf::from_absolute_path(&workspace).expect("absolute workspace");
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: workspace_root,
},
access: FileSystemAccessMode::Write,
}]);
let args = create_filesystem_args(&policy, &workspace, NO_UNREADABLE_GLOB_SCAN_MAX_DEPTH)
.expect("filesystem args");
assert!(
!args.args.iter().any(|arg| arg == &path_to_string(&dot_git)),
"missing child .git under an existing parent repo must not be materialized",
);
assert!(
!synthetic_mount_target_paths(&args).contains(&dot_git),
"missing child .git should not be tracked for post-bwrap cleanup",
);
}
#[test]
fn ignores_missing_writable_roots() {
let temp_dir = TempDir::new().expect("temp dir");
@@ -1638,6 +1630,9 @@ mod tests {
PathBuf::from("/.git"),
PathBuf::from("/.agents"),
PathBuf::from("/.codex"),
PathBuf::from("/dev/.git"),
PathBuf::from("/dev/.agents"),
PathBuf::from("/dev/.codex"),
]
);
let null_fd = args.preserved_files[0].as_raw_fd().to_string();
@@ -1665,13 +1660,22 @@ mod tests {
null_fd.clone(),
"/.agents".to_string(),
"--ro-bind-data".to_string(),
null_fd,
null_fd.clone(),
"/.codex".to_string(),
// Rebind /dev after the root bind so device nodes remain
// writable/usable inside the writable root.
"--bind".to_string(),
"/dev".to_string(),
"/dev".to_string(),
"--ro-bind-data".to_string(),
null_fd.clone(),
"/dev/.git".to_string(),
"--ro-bind-data".to_string(),
null_fd.clone(),
"/dev/.agents".to_string(),
"--ro-bind-data".to_string(),
null_fd,
"/dev/.codex".to_string(),
]
);
}
+325 -40
View File
@@ -3,10 +3,15 @@ use std::ffi::CString;
use std::fmt;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use crate::bwrap::BwrapNetworkMode;
use crate::bwrap::BwrapOptions;
@@ -21,6 +26,20 @@ use codex_protocol::protocol::NetworkSandboxPolicy;
use codex_protocol::protocol::SandboxPolicy;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
static BWRAP_CHILD_PID: AtomicI32 = AtomicI32::new(0);
const FORWARDED_SIGNALS: &[libc::c_int] =
&[libc::SIGHUP, libc::SIGINT, libc::SIGQUIT, libc::SIGTERM];
const SYNTHETIC_MOUNT_MARKER_SYNTHETIC: &[u8] = b"synthetic\n";
const SYNTHETIC_MOUNT_MARKER_EXISTING: &[u8] = b"existing\n";
#[derive(Debug)]
struct SyntheticMountTargetRegistration {
target: crate::bwrap::SyntheticMountTarget,
marker_file: PathBuf,
marker_dir: PathBuf,
}
#[derive(Debug, Parser)]
/// CLI surface for the Linux sandbox helper.
///
@@ -578,7 +597,13 @@ fn run_or_exec_bwrap(bwrap_args: crate::bwrap::BwrapArgs) -> ! {
}
fn run_bwrap_in_child_with_synthetic_mount_cleanup(bwrap_args: crate::bwrap::BwrapArgs) -> ! {
let synthetic_mount_targets = bwrap_args.synthetic_mount_targets.clone();
let crate::bwrap::BwrapArgs {
args,
preserved_files,
synthetic_mount_targets,
} = bwrap_args;
let synthetic_mount_registrations = register_synthetic_mount_targets(&synthetic_mount_targets);
let parent_pid = unsafe { libc::getpid() };
let pid = unsafe { libc::fork() };
if pid < 0 {
let err = std::io::Error::last_os_error();
@@ -586,45 +611,305 @@ fn run_bwrap_in_child_with_synthetic_mount_cleanup(bwrap_args: crate::bwrap::Bwr
}
if pid == 0 {
exec_bwrap(bwrap_args.args, bwrap_args.preserved_files);
let setpgid_res = unsafe { libc::setpgid(0, 0) };
if setpgid_res < 0 {
let err = std::io::Error::last_os_error();
panic!("failed to place bubblewrap child in its own process group: {err}");
}
terminate_with_parent(parent_pid);
exec_bwrap(args, preserved_files);
}
let mut status: libc::c_int = 0;
let wait_res = unsafe { libc::waitpid(pid, &mut status as *mut libc::c_int, 0) };
if wait_res < 0 {
let err = std::io::Error::last_os_error();
panic!("waitpid failed for bubblewrap child: {err}");
}
cleanup_synthetic_mount_targets(&synthetic_mount_targets);
install_bwrap_signal_forwarders(pid);
let status = wait_for_bwrap_child(pid);
BWRAP_CHILD_PID.store(0, Ordering::SeqCst);
cleanup_synthetic_mount_targets(&synthetic_mount_registrations);
exit_with_wait_status(status);
}
fn cleanup_synthetic_mount_targets(targets: &[crate::bwrap::SyntheticMountTarget]) {
for target in targets.iter().rev() {
let path = target.path();
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
Err(err) => panic!(
"failed to inspect synthetic bubblewrap mount target {}: {err}",
path.display()
),
};
if !target.should_remove_after_bwrap(&metadata) {
continue;
}
match fs::remove_file(path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => panic!(
"failed to remove synthetic bubblewrap mount target {}: {err}",
path.display()
),
fn terminate_with_parent(parent_pid: libc::pid_t) {
let res = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) };
if res < 0 {
let err = std::io::Error::last_os_error();
panic!("failed to set bubblewrap child parent-death signal: {err}");
}
if unsafe { libc::getppid() } != parent_pid {
unsafe {
libc::raise(libc::SIGTERM);
}
}
}
fn install_bwrap_signal_forwarders(pid: libc::pid_t) {
BWRAP_CHILD_PID.store(pid, Ordering::SeqCst);
for signal in FORWARDED_SIGNALS {
let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
action.sa_sigaction = forward_signal_to_bwrap_child as *const () as libc::sighandler_t;
unsafe {
libc::sigemptyset(&mut action.sa_mask);
if libc::sigaction(*signal, &action, std::ptr::null_mut()) < 0 {
let err = std::io::Error::last_os_error();
panic!("failed to install bubblewrap signal forwarder for {signal}: {err}");
}
}
}
}
extern "C" fn forward_signal_to_bwrap_child(signal: libc::c_int) {
let pid = BWRAP_CHILD_PID.load(Ordering::SeqCst);
if pid > 0 {
unsafe {
libc::kill(-pid, signal);
libc::kill(pid, signal);
}
}
}
fn wait_for_bwrap_child(pid: libc::pid_t) -> libc::c_int {
loop {
let mut status: libc::c_int = 0;
let wait_res = unsafe { libc::waitpid(pid, &mut status as *mut libc::c_int, 0) };
if wait_res >= 0 {
return status;
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::EINTR) {
continue;
}
panic!("waitpid failed for bubblewrap child: {err}");
}
}
fn register_synthetic_mount_targets(
targets: &[crate::bwrap::SyntheticMountTarget],
) -> Vec<SyntheticMountTargetRegistration> {
with_synthetic_mount_registry_lock(|| {
targets
.iter()
.map(|target| {
let marker_dir = synthetic_mount_marker_dir(target.path());
fs::create_dir_all(&marker_dir).unwrap_or_else(|err| {
panic!(
"failed to create synthetic bubblewrap mount marker directory {}: {err}",
marker_dir.display()
)
});
let target = if target.preserves_pre_existing_file()
&& synthetic_mount_marker_dir_has_active_synthetic_owner(&marker_dir)
{
crate::bwrap::SyntheticMountTarget::missing(target.path())
} else {
target.clone()
};
let marker_file = marker_dir.join(std::process::id().to_string());
fs::write(&marker_file, synthetic_mount_marker_contents(&target)).unwrap_or_else(
|err| {
panic!(
"failed to register synthetic bubblewrap mount target {}: {err}",
target.path().display()
)
},
);
SyntheticMountTargetRegistration {
target,
marker_file,
marker_dir,
}
})
.collect()
})
}
fn synthetic_mount_marker_contents(target: &crate::bwrap::SyntheticMountTarget) -> &'static [u8] {
if target.preserves_pre_existing_file() {
SYNTHETIC_MOUNT_MARKER_EXISTING
} else {
SYNTHETIC_MOUNT_MARKER_SYNTHETIC
}
}
fn synthetic_mount_marker_dir_has_active_synthetic_owner(marker_dir: &Path) -> bool {
synthetic_mount_marker_dir_has_active_process_matching(marker_dir, |path| {
match fs::read(path) {
Ok(contents) => contents == SYNTHETIC_MOUNT_MARKER_SYNTHETIC,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
Err(err) => panic!(
"failed to read synthetic bubblewrap mount marker {}: {err}",
path.display()
),
}
})
}
fn synthetic_mount_marker_dir_has_active_process(marker_dir: &Path) -> bool {
synthetic_mount_marker_dir_has_active_process_matching(marker_dir, |_| true)
}
fn synthetic_mount_marker_dir_has_active_process_matching(
marker_dir: &Path,
matches_marker: impl Fn(&Path) -> bool,
) -> bool {
let entries = match fs::read_dir(marker_dir) {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return false,
Err(err) => panic!(
"failed to read synthetic bubblewrap mount marker directory {}: {err}",
marker_dir.display()
),
};
for entry in entries {
let entry = entry.unwrap_or_else(|err| {
panic!(
"failed to read synthetic bubblewrap mount marker in {}: {err}",
marker_dir.display()
)
});
let path = entry.path();
let Some(pid) = path
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.parse::<libc::pid_t>().ok())
else {
continue;
};
if !process_is_active(pid) {
match fs::remove_file(&path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => panic!(
"failed to remove stale synthetic bubblewrap mount marker {}: {err}",
path.display()
),
}
continue;
}
let matches_marker = matches_marker(&path);
if matches_marker {
return true;
}
}
false
}
fn cleanup_synthetic_mount_targets(targets: &[SyntheticMountTargetRegistration]) {
with_synthetic_mount_registry_lock(|| {
for target in targets.iter().rev() {
match fs::remove_file(&target.marker_file) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => panic!(
"failed to unregister synthetic bubblewrap mount target {}: {err}",
target.target.path().display()
),
}
}
for target in targets.iter().rev() {
if synthetic_mount_marker_dir_has_active_process(&target.marker_dir) {
continue;
}
remove_synthetic_mount_target(&target.target);
match fs::remove_dir(&target.marker_dir) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) if err.kind() == std::io::ErrorKind::DirectoryNotEmpty => {}
Err(err) => panic!(
"failed to remove synthetic bubblewrap mount marker directory {}: {err}",
target.marker_dir.display()
),
}
}
});
}
fn remove_synthetic_mount_target(target: &crate::bwrap::SyntheticMountTarget) {
let path = target.path();
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
Err(err) => panic!(
"failed to inspect synthetic bubblewrap mount target {}: {err}",
path.display()
),
};
if !target.should_remove_after_bwrap(&metadata) {
return;
}
match fs::remove_file(path) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => panic!(
"failed to remove synthetic bubblewrap mount target {}: {err}",
path.display()
),
}
}
fn process_is_active(pid: libc::pid_t) -> bool {
let result = unsafe { libc::kill(pid, 0) };
if result == 0 {
return true;
}
let err = std::io::Error::last_os_error();
!matches!(err.raw_os_error(), Some(libc::ESRCH))
}
fn with_synthetic_mount_registry_lock<T>(f: impl FnOnce() -> T) -> T {
let registry_root = synthetic_mount_registry_root();
fs::create_dir_all(&registry_root).unwrap_or_else(|err| {
panic!(
"failed to create synthetic bubblewrap mount registry {}: {err}",
registry_root.display()
)
});
let lock_path = registry_root.join("lock");
let lock_file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.unwrap_or_else(|err| {
panic!(
"failed to open synthetic bubblewrap mount registry lock {}: {err}",
lock_path.display()
)
});
if unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX) } < 0 {
let err = std::io::Error::last_os_error();
panic!(
"failed to lock synthetic bubblewrap mount registry {}: {err}",
lock_path.display()
);
}
let result = f();
if unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_UN) } < 0 {
let err = std::io::Error::last_os_error();
panic!(
"failed to unlock synthetic bubblewrap mount registry {}: {err}",
lock_path.display()
);
}
result
}
fn synthetic_mount_marker_dir(path: &Path) -> PathBuf {
synthetic_mount_registry_root().join(format!("{:016x}", hash_path(path)))
}
fn synthetic_mount_registry_root() -> PathBuf {
std::env::temp_dir().join("codex-bwrap-synthetic-mount-targets")
}
fn hash_path(path: &Path) -> u64 {
let mut hash = 0xcbf29ce484222325u64;
for byte in path.as_os_str().as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
fn exit_with_wait_status(status: libc::c_int) -> ! {
if libc::WIFEXITED(status) {
std::process::exit(libc::WEXITSTATUS(status));
@@ -655,7 +940,12 @@ fn exit_with_wait_status(status: libc::c_int) -> ! {
/// command, and reads are bounded to a fixed max size.
fn run_bwrap_in_child_capture_stderr(bwrap_args: crate::bwrap::BwrapArgs) -> String {
const MAX_PREFLIGHT_STDERR_BYTES: u64 = 64 * 1024;
let synthetic_mount_targets = bwrap_args.synthetic_mount_targets.clone();
let crate::bwrap::BwrapArgs {
args,
preserved_files,
synthetic_mount_targets,
} = bwrap_args;
let synthetic_mount_registrations = register_synthetic_mount_targets(&synthetic_mount_targets);
let mut pipe_fds = [0; 2];
let pipe_res = unsafe { libc::pipe2(pipe_fds.as_mut_ptr(), libc::O_CLOEXEC) };
@@ -683,7 +973,7 @@ fn run_bwrap_in_child_capture_stderr(bwrap_args: crate::bwrap::BwrapArgs) -> Str
close_fd_or_panic(write_fd, "close write end in bubblewrap child");
}
exec_bwrap(bwrap_args.args, bwrap_args.preserved_files);
exec_bwrap(args, preserved_files);
}
// Parent: close the write end and read stderr while the child runs.
@@ -697,13 +987,8 @@ fn run_bwrap_in_child_capture_stderr(bwrap_args: crate::bwrap::BwrapArgs) -> Str
panic!("failed to read bubblewrap stderr: {err}");
}
let mut status: libc::c_int = 0;
let wait_res = unsafe { libc::waitpid(pid, &mut status as *mut libc::c_int, 0) };
if wait_res < 0 {
let err = std::io::Error::last_os_error();
panic!("waitpid failed for bubblewrap child: {err}");
}
cleanup_synthetic_mount_targets(&synthetic_mount_targets);
wait_for_bwrap_child(pid);
cleanup_synthetic_mount_targets(&synthetic_mount_registrations);
String::from_utf8_lossy(&stderr_bytes).into_owned()
}
@@ -1,6 +1,10 @@
#[cfg(test)]
use super::*;
#[cfg(test)]
use crate::linux_run_main::install_bwrap_signal_forwarders;
#[cfg(test)]
use crate::linux_run_main::wait_for_bwrap_child;
#[cfg(test)]
use codex_protocol::protocol::FileSystemSandboxPolicy;
#[cfg(test)]
use codex_protocol::protocol::NetworkSandboxPolicy;
@@ -264,11 +268,12 @@ fn cleanup_synthetic_mount_targets_removes_only_empty_files() {
std::fs::write(&empty_file, "").expect("write empty file");
std::fs::write(&non_empty_file, "keep").expect("write nonempty file");
cleanup_synthetic_mount_targets(&[
let registrations = register_synthetic_mount_targets(&[
crate::bwrap::SyntheticMountTarget::missing(&empty_file),
crate::bwrap::SyntheticMountTarget::missing(&non_empty_file),
crate::bwrap::SyntheticMountTarget::missing(&missing_file),
]);
cleanup_synthetic_mount_targets(&registrations);
assert!(!empty_file.exists());
assert_eq!(
@@ -278,6 +283,115 @@ fn cleanup_synthetic_mount_targets_removes_only_empty_files() {
assert!(!missing_file.exists());
}
#[test]
fn cleanup_synthetic_mount_targets_waits_for_other_active_registrations() {
let temp_dir = tempfile::TempDir::new().expect("tempdir");
let empty_file = temp_dir.path().join(".git");
std::fs::write(&empty_file, "").expect("write empty file");
let target = crate::bwrap::SyntheticMountTarget::missing(&empty_file);
let registrations = register_synthetic_mount_targets(std::slice::from_ref(&target));
let active_marker = registrations[0].marker_dir.join("1");
std::fs::write(&active_marker, "").expect("write active marker");
cleanup_synthetic_mount_targets(&registrations);
assert!(empty_file.exists());
std::fs::remove_file(active_marker).expect("remove active marker");
let registrations = register_synthetic_mount_targets(std::slice::from_ref(&target));
cleanup_synthetic_mount_targets(&registrations);
assert!(!empty_file.exists());
}
#[test]
fn cleanup_synthetic_mount_targets_removes_transient_file_after_concurrent_owner_exits() {
let temp_dir = tempfile::TempDir::new().expect("tempdir");
let empty_file = temp_dir.path().join(".git");
let first_target = crate::bwrap::SyntheticMountTarget::missing(&empty_file);
let first_registrations = register_synthetic_mount_targets(&[first_target]);
std::fs::write(&empty_file, "").expect("write transient empty file");
let active_marker = first_registrations[0].marker_dir.join("1");
std::fs::write(&active_marker, SYNTHETIC_MOUNT_MARKER_SYNTHETIC).expect("write active marker");
let metadata = std::fs::symlink_metadata(&empty_file).expect("stat empty file");
let second_target =
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
let second_registrations = register_synthetic_mount_targets(&[second_target]);
cleanup_synthetic_mount_targets(&first_registrations);
assert!(empty_file.exists());
std::fs::remove_file(active_marker).expect("remove active marker");
cleanup_synthetic_mount_targets(&second_registrations);
assert!(!empty_file.exists());
}
#[test]
fn cleanup_synthetic_mount_targets_preserves_real_pre_existing_empty_file() {
let temp_dir = tempfile::TempDir::new().expect("tempdir");
let empty_file = temp_dir.path().join(".git");
std::fs::write(&empty_file, "").expect("write pre-existing empty file");
let metadata = std::fs::symlink_metadata(&empty_file).expect("stat empty file");
let first_target =
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
let second_target =
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
let first_registrations = register_synthetic_mount_targets(&[first_target]);
let second_registrations = register_synthetic_mount_targets(&[second_target]);
cleanup_synthetic_mount_targets(&first_registrations);
cleanup_synthetic_mount_targets(&second_registrations);
assert!(empty_file.exists());
}
#[test]
fn bwrap_signal_forwarder_terminates_child_and_keeps_parent_alive() {
let supervisor_pid = unsafe { libc::fork() };
assert!(supervisor_pid >= 0, "failed to fork supervisor");
if supervisor_pid == 0 {
run_bwrap_signal_forwarder_test_supervisor();
}
let status = wait_for_bwrap_child(supervisor_pid);
assert!(libc::WIFEXITED(status), "supervisor status: {status}");
assert_eq!(libc::WEXITSTATUS(status), 0);
}
#[cfg(test)]
fn run_bwrap_signal_forwarder_test_supervisor() -> ! {
let child_pid = unsafe { libc::fork() };
if child_pid < 0 {
unsafe {
libc::_exit(2);
}
}
if child_pid == 0 {
loop {
unsafe {
libc::pause();
}
}
}
install_bwrap_signal_forwarders(child_pid);
unsafe {
libc::raise(libc::SIGTERM);
}
let status = wait_for_bwrap_child(child_pid);
let child_terminated_by_sigterm =
libc::WIFSIGNALED(status) && libc::WTERMSIG(status) == libc::SIGTERM;
unsafe {
libc::_exit(if child_terminated_by_sigterm { 0 } else { 1 });
}
}
#[test]
fn managed_proxy_inner_command_includes_route_spec() {
let sandbox_policy = SandboxPolicy::new_read_only_policy();