Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,369 @@
use crate::policy_transforms::should_require_platform_sandbox;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::ffi::CString;
use std::io::ErrorKind;
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Output;
use std::process::Stdio;
use std::thread;
use std::time::Duration;
use std::time::Instant;
const SYSTEM_BWRAP_PROGRAM: &str = "bwrap";
const MISSING_BWRAP_WARNING: &str = concat!(
"Codex could not find bubblewrap on PATH. ",
"Install bubblewrap with your OS package manager. ",
"See the sandbox prerequisites: ",
"https://developers.openai.com/codex/concepts/sandboxing#prerequisites. ",
"Codex will use the bundled bubblewrap in the meantime.",
);
const USER_NAMESPACE_WARNING: &str =
"Codex's Linux sandbox uses bubblewrap and needs access to create user namespaces.";
pub(crate) const WSL1_BWRAP_WARNING: &str = concat!(
"Codex's Linux sandbox uses bubblewrap, which is not supported on WSL1 ",
"because WSL1 cannot create the required user namespaces. ",
"Use WSL2 for sandboxed shell commands."
);
const USER_NAMESPACE_FAILURES: [&str; 4] = [
"loopback: Failed RTM_NEWADDR",
"loopback: Failed RTM_NEWLINK",
"setting up uid map: Permission denied",
"No permissions to create a new namespace",
];
const SYSTEM_BWRAP_PROBE_TIMEOUT: Duration = Duration::from_millis(500);
const SYSTEM_BWRAP_PROBE_POLL_INTERVAL: Duration = Duration::from_millis(50);
const SYSTEM_BWRAP_PROBE_STDERR_LIMIT_BYTES: u64 = 64 * 1024;
pub fn system_bwrap_warning(
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &Path,
) -> Option<String> {
if !should_warn_about_system_bwrap(permission_profile) {
return None;
}
let system_bwrap_path = find_system_bwrap_in_path(
&permission_profile.file_system_sandbox_policy(),
sandbox_policy_cwd,
);
system_bwrap_warning_for_path(system_bwrap_path.as_deref())
}
fn should_warn_about_system_bwrap(permission_profile: &PermissionProfile) -> bool {
let (file_system_policy, network_policy) = permission_profile.to_runtime_permissions();
should_require_platform_sandbox(
&file_system_policy,
network_policy,
/*has_managed_network_requirements*/ false,
)
}
fn system_bwrap_warning_for_path(system_bwrap_path: Option<&Path>) -> Option<String> {
if is_wsl1() {
return Some(WSL1_BWRAP_WARNING.to_string());
}
let Some(system_bwrap_path) = system_bwrap_path else {
return Some(MISSING_BWRAP_WARNING.to_string());
};
if !system_bwrap_has_user_namespace_access(system_bwrap_path, SYSTEM_BWRAP_PROBE_TIMEOUT) {
return Some(USER_NAMESPACE_WARNING.to_string());
}
None
}
fn system_bwrap_has_user_namespace_access(system_bwrap_path: &Path, timeout: Duration) -> bool {
let mut child = match Command::new(system_bwrap_path)
.args([
"--unshare-user",
"--unshare-net",
"--ro-bind",
"/",
"/",
"/bin/true",
])
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(_) => return true,
};
let deadline = Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(status)) => {
let stderr = child.stderr.take().map_or_else(Vec::new, |stderr| {
let fd = stderr.as_raw_fd();
let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
if flags < 0
|| unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0
{
return Vec::new();
}
let mut bytes = Vec::new();
let mut stderr = stderr.take(SYSTEM_BWRAP_PROBE_STDERR_LIMIT_BYTES);
if let Err(err) = stderr.read_to_end(&mut bytes)
&& err.kind() != ErrorKind::WouldBlock
{
return bytes;
}
bytes
});
let output = Output {
status,
stdout: Vec::new(),
stderr,
};
return output.status.success() || !is_user_namespace_failure(&output);
}
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return true;
}
thread::sleep(SYSTEM_BWRAP_PROBE_POLL_INTERVAL);
}
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return true;
}
}
}
}
pub(crate) fn is_wsl1() -> bool {
std::fs::read_to_string("/proc/version")
.is_ok_and(|proc_version| proc_version_indicates_wsl1(&proc_version))
}
fn proc_version_indicates_wsl1(proc_version: &str) -> bool {
let proc_version = proc_version.to_ascii_lowercase();
let mut remaining = proc_version.as_str();
while let Some(marker) = remaining.find("wsl") {
let version_start = marker + "wsl".len();
let version_digits: String = remaining[version_start..]
.chars()
.take_while(char::is_ascii_digit)
.collect();
if let Ok(version) = version_digits.parse::<u32>() {
return version == 1;
}
remaining = &remaining[version_start..];
}
proc_version.contains("microsoft") && !proc_version.contains("microsoft-standard")
}
fn is_user_namespace_failure(output: &Output) -> bool {
let stderr = String::from_utf8_lossy(&output.stderr);
USER_NAMESPACE_FAILURES
.iter()
.any(|failure| stderr.contains(failure))
}
pub fn find_system_bwrap_in_path(
file_system_policy: &FileSystemSandboxPolicy,
sandbox_policy_cwd: &Path,
) -> Option<PathBuf> {
find_pre_sandbox_executable_in_path(
SYSTEM_BWRAP_PROGRAM,
file_system_policy,
sandbox_policy_cwd,
)
}
/// Finds the first canonical PATH executable for use before sandbox construction.
/// Skips candidates under a non-root process cwd and candidates the current user
/// can modify or replace through writes allowed by the filesystem policy.
pub fn find_pre_sandbox_executable_in_path(
program: &str,
file_system_policy: &FileSystemSandboxPolicy,
sandbox_policy_cwd: &Path,
) -> Option<PathBuf> {
let search_path = std::env::var_os("PATH")?;
let cwd = std::env::current_dir().ok()?;
find_executable_in_search_paths(
program,
std::env::split_paths(&search_path),
&cwd,
file_system_policy,
sandbox_policy_cwd,
)
}
/// Apply the pre-sandbox executable selection rules to an explicit command context.
pub fn find_executable_in_search_paths(
program: &str,
search_paths: impl IntoIterator<Item = PathBuf>,
cwd: &Path,
file_system_policy: &FileSystemSandboxPolicy,
sandbox_policy_cwd: &Path,
) -> Option<PathBuf> {
let search_path = std::env::join_paths(search_paths).ok()?;
let cwd = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
let cwd_is_root = cwd.parent().is_none();
// Full-disk policies intentionally have no enumerated writable roots.
let full_disk_write = file_system_policy.has_full_disk_write_access();
let writable_roots = file_system_policy
.get_writable_roots_with_cwd_inheriting_root_metadata(sandbox_policy_cwd)
.into_iter()
.map(|mut root| {
if let Ok(canonical) = std::fs::canonicalize(&root.root)
&& let Ok(canonical) = AbsolutePathBuf::from_absolute_path_checked(canonical)
{
for subpath in &mut root.read_only_subpaths {
if let Ok(relative) = subpath.as_path().strip_prefix(root.root.as_path()) {
*subpath = canonical.join(relative);
}
}
root.root = canonical;
}
root
})
.collect::<Vec<_>>();
let policy_can_write = |path: &Path| {
full_disk_write
|| writable_roots
.iter()
.any(|root| root.is_path_writable(path))
};
let file_is_writable = |path: &Path| {
policy_can_write(path)
&& std::fs::symlink_metadata(path)
.map_or(true, |metadata| !metadata.file_type().is_symlink())
&& current_user_can_modify(path)
};
let path_is_replaceable = |path: &Path| {
path.ancestors().any(|component| {
let Some(parent) = component.parent() else {
return false;
};
let Some(file_name) = component.file_name() else {
return false;
};
let Ok(parent) = std::fs::canonicalize(parent) else {
return true;
};
// Match policy through parent aliases without resolving the child symlink.
let component = parent.join(file_name);
// Read-only carveouts are bind mounts and cannot themselves
// be renamed/unlinked. Continue checking above them, since a
// mutable ancestor could still redirect the installation path.
let is_read_only_mount = writable_roots.iter().any(|root| {
root.read_only_subpaths
.iter()
.any(|path| path.as_path() == component.as_path())
});
policy_can_write(&parent)
&& !is_read_only_mount
&& current_user_can_replace_child(&parent, &component)
})
};
std::env::split_paths(&search_path)
.filter_map(|path| {
// Let which resolve explicit program paths and expand ~/bin entries.
let binary = if Path::new(program).components().count() > 1 || path.starts_with("~") {
PathBuf::from(program)
} else {
cwd.join(&path).join(program)
};
which::which_in(binary, Some(path), &cwd).ok()
})
.find_map(|path| {
if !path.is_absolute() || path_is_replaceable(&path) {
return None;
}
let file_name = path.file_name()?;
let resolved_parent = std::fs::canonicalize(path.parent()?).ok()?;
let resolved_alias = resolved_parent.join(file_name);
if (!cwd_is_root && resolved_alias.starts_with(&cwd))
|| file_is_writable(&resolved_alias)
|| path_is_replaceable(&resolved_alias)
{
return None;
}
let path = std::fs::canonicalize(path).ok()?;
// Preserve read-only carveouts, but also check ancestors: a protected
// file can still be replaced by renaming a writable parent directory.
// Host-protected installations remain usable even with full-disk writes.
if (!cwd_is_root && path.starts_with(&cwd))
|| file_is_writable(&path)
|| path_is_replaceable(&path)
{
None
} else {
Some(path)
}
})
}
fn current_user_can_replace_child(parent: &Path, child: &Path) -> bool {
if !current_user_can_modify(parent) {
return false;
}
// SAFETY: geteuid has no preconditions.
let euid = unsafe { libc::geteuid() };
if euid == 0 {
return true;
}
let Ok(parent_metadata) = std::fs::metadata(parent) else {
return true;
};
if parent_metadata.mode() & libc::S_ISVTX == 0 || parent_metadata.uid() == euid {
return true;
}
std::fs::symlink_metadata(child).map_or(true, |metadata| metadata.uid() == euid)
}
fn current_user_can_modify(path: &Path) -> bool {
let Ok(metadata) = std::fs::metadata(path) else {
return true;
};
// Owners can chmod a currently read-only file or directory before writing it.
// SAFETY: geteuid has no preconditions.
if metadata.uid() == unsafe { libc::geteuid() } {
return true;
}
let Ok(path) = CString::new(path.as_os_str().as_bytes()) else {
return true;
};
// Ask the kernel to check effective credentials, including POSIX ACLs. Older
// libc faccessat emulation ignores ACLs, which could misclassify a writable path.
// SAFETY: path is a live, NUL-terminated string, and no pointer is retained.
if unsafe {
libc::syscall(
libc::SYS_faccessat2,
libc::AT_FDCWD,
path.as_ptr(),
libc::W_OK,
libc::AT_EACCESS,
)
} == 0
{
return true;
}
// Unknown errors must not turn an unverified candidate into a trusted one.
!matches!(
std::io::Error::last_os_error().raw_os_error(),
Some(libc::EACCES | libc::EROFS)
)
}
#[cfg(test)]
#[path = "bwrap_tests.rs"]
mod tests;

View File

@@ -0,0 +1,428 @@
use super::*;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use tempfile::tempdir;
#[test]
fn system_bwrap_warning_reports_missing_system_bwrap() {
assert_eq!(
system_bwrap_warning_for_path(/*system_bwrap_path*/ None),
Some(MISSING_BWRAP_WARNING.to_string())
);
}
#[test]
fn system_bwrap_warning_reports_user_namespace_failures() {
for failure in USER_NAMESPACE_FAILURES {
let fake_bwrap = write_fake_bwrap(&format!(
r#"#!/bin/sh
echo '{failure}' >&2
exit 1
"#
));
let fake_bwrap_path: &Path = fake_bwrap.as_ref();
assert_eq!(
system_bwrap_warning_for_path(Some(fake_bwrap_path)),
Some(USER_NAMESPACE_WARNING.to_string()),
"{failure}",
);
}
}
#[test]
fn system_bwrap_warning_skips_unrelated_bwrap_failures() {
let fake_bwrap = write_fake_bwrap(
r#"#!/bin/sh
echo 'bwrap: Unknown option --argv0' >&2
exit 1
"#,
);
let fake_bwrap_path: &Path = fake_bwrap.as_ref();
assert_eq!(system_bwrap_warning_for_path(Some(fake_bwrap_path)), None);
}
#[test]
fn system_bwrap_probe_times_out_without_reporting_a_warning() {
let fake_bwrap = write_fake_bwrap(
r#"#!/bin/sh
sleep 1
exit 0
"#,
);
let fake_bwrap_path: &Path = fake_bwrap.as_ref();
let started_at = Instant::now();
assert!(system_bwrap_has_user_namespace_access(
fake_bwrap_path,
Duration::from_millis(10),
));
assert!(started_at.elapsed() < Duration::from_millis(500));
}
#[test]
fn system_bwrap_probe_does_not_wait_for_descendants_holding_stderr_open() {
let fake_bwrap = write_fake_bwrap(
r#"#!/bin/sh
echo 'No permissions to create a new namespace' >&2
sleep 1 &
exit 1
"#,
);
let fake_bwrap_path: &Path = fake_bwrap.as_ref();
let started_at = Instant::now();
assert!(!system_bwrap_has_user_namespace_access(
fake_bwrap_path,
Duration::from_millis(100),
));
assert!(started_at.elapsed() < Duration::from_millis(500));
}
#[test]
fn detects_wsl1_proc_version_formats() {
assert!(proc_version_indicates_wsl1(
"Linux version 4.4.0-22621-Microsoft"
));
assert!(proc_version_indicates_wsl1(
"Linux version 5.15.0-microsoft-standard-WSL1"
));
assert!(proc_version_indicates_wsl1(
"Linux version 5.15.0-wsl-microsoft-standard-WSL1"
));
}
#[test]
fn does_not_treat_wsl2_or_native_linux_as_wsl1() {
assert!(!proc_version_indicates_wsl1(
"Linux version 6.6.87.2-microsoft-standard-WSL2"
));
assert!(!proc_version_indicates_wsl1(
"Linux version 6.6.87.2-wsl-microsoft-standard-WSL2"
));
assert!(!proc_version_indicates_wsl1(
"Linux version 4.19.104-microsoft-standard"
));
assert!(!proc_version_indicates_wsl1(
"Linux version 6.6.87.2-microsoft-standard-WSL3"
));
assert!(!proc_version_indicates_wsl1("Linux version 6.8.0"));
}
#[test]
fn finds_first_executable_bwrap_in_joined_search_path() {
let temp_dir = tempdir().expect("temp dir");
let cwd = temp_dir.path().join("cwd:with-colon");
let first_dir = temp_dir.path().join("first");
let second_dir = temp_dir.path().join("second");
std::fs::create_dir_all(&cwd).expect("create cwd");
std::fs::create_dir_all(&first_dir).expect("create first dir");
std::fs::create_dir_all(&second_dir).expect("create second dir");
std::fs::write(first_dir.join("bwrap"), "not executable").expect("write non-executable bwrap");
let expected_bwrap = write_named_fake_bwrap_in(&second_dir);
for search_paths in [
vec![first_dir, second_dir],
vec![PathBuf::from("../first"), PathBuf::from("../second")],
] {
let search_path = std::env::join_paths(search_paths).expect("join search path");
assert_eq!(
find_executable_in_search_paths(
"bwrap",
std::env::split_paths(&search_path),
&cwd,
&PermissionProfile::read_only().file_system_sandbox_policy(),
&cwd,
),
Some(expected_bwrap.clone())
);
}
}
#[test]
fn skips_workspace_local_bwrap_in_joined_search_path() {
let temp_dir = tempdir().expect("temp dir");
let cwd = temp_dir.path().join("cwd");
let trusted_dir = temp_dir.path().join("trusted");
std::fs::create_dir_all(&cwd).expect("create cwd");
std::fs::create_dir_all(&trusted_dir).expect("create trusted dir");
let _workspace_bwrap = write_named_fake_bwrap_in(&cwd);
let expected_bwrap = write_named_fake_bwrap_in(&trusted_dir);
let search_path = std::env::join_paths([cwd.clone(), trusted_dir]).expect("join search path");
assert_eq!(
find_executable_in_search_paths(
"bwrap",
std::env::split_paths(&search_path),
&cwd,
&PermissionProfile::read_only().file_system_sandbox_policy(),
&cwd,
),
Some(expected_bwrap)
);
}
#[test]
fn root_cwd_does_not_hide_system_bwrap_candidates() {
let temp_dir = tempdir().expect("temp dir");
let bin_dir = temp_dir.path().join("bin");
std::fs::create_dir_all(&bin_dir).expect("create bin dir");
let expected_bwrap = write_named_fake_bwrap_in(&bin_dir);
let search_path = std::env::join_paths([bin_dir]).expect("join search path");
assert_eq!(
find_executable_in_search_paths(
"bwrap",
std::env::split_paths(&search_path),
Path::new("/"),
&PermissionProfile::read_only().file_system_sandbox_policy(),
Path::new("/"),
),
Some(expected_bwrap)
);
assert_eq!(
find_executable_in_search_paths(
"bwrap",
std::env::split_paths(&search_path),
Path::new("/"),
&PermissionProfile::Disabled.file_system_sandbox_policy(),
Path::new("/"),
),
None,
);
}
#[test]
fn skips_bwrap_in_writable_roots_outside_command_cwd() {
let temp_dir = tempdir().expect("temp dir");
let workspace = temp_dir.path().join("workspace");
let cwd = workspace.join("service");
let workspace_bin = workspace.join("bin");
let extra_root = temp_dir.path().join("extra");
let trusted_dir = temp_dir.path().join("trusted");
for dir in [&cwd, &workspace_bin, &extra_root, &trusted_dir] {
std::fs::create_dir_all(dir).expect("create directory");
}
write_named_fake_bwrap_in(&workspace_bin);
write_named_fake_bwrap_in(&extra_root);
let expected_bwrap = write_named_fake_bwrap_in(&trusted_dir);
let writable_roots = vec![workspace, extra_root.clone()];
let policy = PermissionProfile::read_only()
.file_system_sandbox_policy()
.with_additional_writable_roots(
&cwd,
&writable_roots
.into_iter()
.map(|path| AbsolutePathBuf::try_from(path).unwrap())
.collect::<Vec<_>>(),
);
let search_paths = vec![workspace_bin, extra_root];
assert_eq!(
find_executable_in_search_paths("bwrap", search_paths.clone(), &cwd, &policy, &cwd),
None,
);
assert_eq!(
find_executable_in_search_paths(
"bwrap",
search_paths.into_iter().chain([trusted_dir]),
&cwd,
&policy,
&cwd,
),
Some(expected_bwrap),
);
}
#[test]
fn skips_bwrap_in_symlinked_writable_root() {
let temp_dir = tempdir().expect("temp dir");
let workspace = temp_dir.path().join("workspace");
let cwd = workspace.join("service");
let workspace_bin = workspace.join("bin");
let alias = temp_dir.path().join("alias");
std::fs::create_dir_all(&cwd).expect("create cwd");
std::fs::create_dir_all(&workspace_bin).expect("create bin");
std::os::unix::fs::symlink(&workspace, &alias).expect("create workspace alias");
write_named_fake_bwrap_in(&workspace_bin);
let policy = PermissionProfile::read_only()
.file_system_sandbox_policy()
.with_additional_writable_roots(&cwd, &[AbsolutePathBuf::try_from(alias).unwrap()]);
assert_eq!(
find_executable_in_search_paths("bwrap", [workspace_bin], &cwd, &policy, &cwd),
None,
);
}
#[test]
fn skips_writable_bwrap_symlink_to_read_only_target() {
let temp = tempdir().unwrap();
let bin = temp.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let system_binary = std::fs::canonicalize("/bin/true").unwrap();
std::os::unix::fs::symlink(&system_binary, bin.join("bwrap")).unwrap();
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(bin.as_path()).unwrap().into(),
FileSystemAccessMode::Write,
)]);
assert_eq!(
find_executable_in_search_paths("bwrap", [bin], Path::new("/"), &policy, Path::new("/")),
None,
);
}
#[test]
fn skips_bwrap_through_symlinked_path_directory_into_writable_root() {
let temp = tempdir().unwrap();
let workspace = temp.path().join("workspace");
let bin = workspace.join("bin");
let alias = temp.path().join("alias");
std::fs::create_dir_all(&bin).unwrap();
std::os::unix::fs::symlink(&workspace, &alias).unwrap();
let system_binary = std::fs::canonicalize("/bin/true").unwrap();
std::os::unix::fs::symlink(&system_binary, bin.join("bwrap")).unwrap();
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(workspace.as_path())
.unwrap()
.into(),
FileSystemAccessMode::Write,
)]);
assert_eq!(
find_executable_in_search_paths(
"bwrap",
[alias.join("bin")],
Path::new("/"),
&policy,
Path::new("/"),
),
None,
);
}
#[test]
fn full_disk_write_rejects_owned_bwrap_even_when_chmod_read_only() {
use std::os::unix::fs::PermissionsExt;
let temp = tempdir().unwrap();
let bin = temp.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let bwrap = write_named_fake_bwrap_in(&bin);
std::fs::set_permissions(&bwrap, std::fs::Permissions::from_mode(0o555)).unwrap();
let policy = PermissionProfile::Disabled.file_system_sandbox_policy();
assert_eq!(
find_executable_in_search_paths("bwrap", [bin], Path::new("/"), &policy, Path::new("/")),
None,
);
}
#[test]
fn read_only_bwrap_carveout_does_not_trust_a_replaceable_parent() {
let temp = tempdir().unwrap();
let bin = temp.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let bwrap = write_named_fake_bwrap_in(&bin);
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(temp.path()).unwrap().into(),
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(bwrap).unwrap().into(),
FileSystemAccessMode::Read,
),
]);
assert_eq!(
find_executable_in_search_paths("bwrap", [bin], Path::new("/"), &policy, Path::new("/")),
None,
);
}
#[test]
fn root_write_preserves_a_read_only_system_installation() {
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSpecialPath;
// Use a system executable as a discovery-only candidate. Never execute it.
let system_binary = std::fs::canonicalize("/bin/true").unwrap();
let system_program = system_binary.file_name().unwrap().to_str().unwrap();
let system_search_path = system_binary.parent().unwrap().to_path_buf();
let protected_root = system_binary
.ancestors()
.find(|path| path.parent() == Some(Path::new("/")))
.unwrap();
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(protected_root).unwrap().into(),
FileSystemAccessMode::Read,
),
]);
for policy in [
policy,
PermissionProfile::Disabled.file_system_sandbox_policy(),
] {
// Root can modify the system installation unless the policy protects it.
// SAFETY: geteuid has no preconditions.
let can_modify_system =
policy.has_full_disk_write_access() && unsafe { libc::geteuid() } == 0;
assert_eq!(
find_executable_in_search_paths(
system_program,
[system_search_path.clone()],
Path::new("/"),
&policy,
Path::new("/"),
),
(!can_modify_system).then(|| system_binary.clone()),
);
}
}
fn write_fake_bwrap(contents: &str) -> tempfile::TempPath {
write_fake_bwrap_in(
&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
contents,
)
}
fn write_fake_bwrap_in(dir: &Path, contents: &str) -> tempfile::TempPath {
use tempfile::NamedTempFile;
// Bazel can mount the OS temp directory `noexec`, so prefer the current
// working directory for fake executables and fall back to the default temp
// dir outside that environment.
let temp_file = NamedTempFile::new_in(dir)
.ok()
.unwrap_or_else(|| NamedTempFile::new().expect("temp file"));
let path = temp_file.into_temp_path();
// A sibling spawn may retain the temporary file's writable descriptor.
// Remove that inode before the helper creates the executable in its child.
std::fs::remove_file(&path).expect("remove empty temporary file");
codex_utils_cargo_bin::write_executable(&path, contents).expect("write fake bwrap");
path
}
fn write_named_fake_bwrap_in(dir: &Path) -> PathBuf {
use std::fs;
let path = dir.join("bwrap");
codex_utils_cargo_bin::write_executable(&path, "#!/bin/sh\n").expect("write fake bwrap");
fs::canonicalize(path).expect("canonicalize fake bwrap")
}

View File

@@ -0,0 +1,72 @@
use codex_protocol::exec_output::ExecToolCallOutput;
use crate::SandboxType;
/// We don't have a fully deterministic way to tell if our command failed
/// because of the sandbox - a command in the user's zshrc file might hit an
/// error, but the command itself might fail or succeed for other reasons.
/// For now, we conservatively check for well known command failure exit codes and
/// also look for common sandbox denial keywords in the command output.
///
/// This predicate is intentionally side-effect free. Callers that handle a
/// denial should record it where the relevant audit context is available.
pub fn is_likely_sandbox_denied(
sandbox_type: SandboxType,
exec_output: &ExecToolCallOutput,
) -> bool {
if sandbox_type == SandboxType::None || exec_output.exit_code == 0 {
return false;
}
if is_likely_executor_managed_sandbox_denied(exec_output) {
return true;
}
const QUICK_REJECT_EXIT_CODES: [i32; 3] = [2, 126, 127];
if QUICK_REJECT_EXIT_CODES.contains(&exec_output.exit_code) {
return false;
}
#[cfg(unix)]
{
const EXIT_CODE_SIGNAL_BASE: i32 = 128;
const SIGSYS_CODE: i32 = libc::SIGSYS;
if sandbox_type == SandboxType::LinuxSeccomp
&& exec_output.exit_code == EXIT_CODE_SIGNAL_BASE + SIGSYS_CODE
{
return true;
}
}
false
}
/// Detect executor-managed sandbox denials when its concrete backend is unknown.
pub fn is_likely_executor_managed_sandbox_denied(exec_output: &ExecToolCallOutput) -> bool {
if exec_output.exit_code == 0 {
return false;
}
const SANDBOX_DENIED_KEYWORDS: [&str; 7] = [
"operation not permitted",
"permission denied",
"read-only file system",
"seccomp",
"sandbox",
"landlock",
"failed to write file",
];
[
&exec_output.stderr.text,
&exec_output.stdout.text,
&exec_output.aggregated_output.text,
]
.into_iter()
.any(|section| {
let lower = section.to_lowercase();
SANDBOX_DENIED_KEYWORDS
.iter()
.any(|needle| lower.contains(needle))
})
}

View File

@@ -0,0 +1,115 @@
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use std::path::Path;
/// Basename used when the Codex executable self-invokes as the Linux sandbox
/// helper.
pub const CODEX_LINUX_SANDBOX_ARG0: &str = "codex-linux-sandbox";
pub fn allow_network_for_proxy(enforce_managed_network: bool) -> bool {
// When managed network requirements are active, request proxy-only
// networking from the Linux sandbox helper. Without managed requirements,
// preserve existing behavior.
enforce_managed_network
}
/// Converts the permission profile into the CLI invocation for
/// `codex-linux-sandbox`.
///
/// A managed context selects proxy isolation; a default context keeps its
/// restrictive policy when an older caller supplies no additional details.
///
/// The helper performs the actual sandboxing (bubblewrap by default + seccomp)
/// after parsing these arguments. The profile JSON flag is emitted before
/// helper feature flags so the argv order matches the helper's CLI shape. See
/// `docs/linux_sandbox.md` for the Linux semantics.
pub fn create_linux_sandbox_command_args_for_permission_profile(
command: Vec<String>,
command_cwd: &Path,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &Path,
use_legacy_landlock: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Vec<String> {
let permission_profile_json = serde_json::to_string(permission_profile)
.unwrap_or_else(|err| panic!("failed to serialize permission profile: {err}"));
let sandbox_policy_cwd = sandbox_policy_cwd
.to_str()
.unwrap_or_else(|| panic!("cwd must be valid UTF-8"))
.to_string();
let command_cwd = command_cwd
.to_str()
.unwrap_or_else(|| panic!("command cwd must be valid UTF-8"))
.to_string();
let mut linux_cmd: Vec<String> = vec![
"--sandbox-policy-cwd".to_string(),
sandbox_policy_cwd,
"--command-cwd".to_string(),
command_cwd,
"--permission-profile".to_string(),
permission_profile_json,
];
// Proxy-only networking requires bubblewrap's isolated network namespace.
if use_legacy_landlock && managed_network.is_none() {
linux_cmd.push("--use-legacy-landlock".to_string());
}
if let Some(managed_network) = managed_network {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push(
serde_json::to_string(managed_network)
.unwrap_or_else(|err| panic!("failed to serialize managed network context: {err}")),
);
}
linux_cmd.push("--".to_string());
linux_cmd.extend(command);
linux_cmd
}
/// Converts the sandbox cwd and execution options into the CLI invocation for
/// `codex-linux-sandbox`.
#[cfg_attr(not(test), allow(dead_code))]
fn create_linux_sandbox_command_args(
command: Vec<String>,
command_cwd: &Path,
sandbox_policy_cwd: &Path,
use_legacy_landlock: bool,
allow_network_for_proxy: bool,
) -> Vec<String> {
let command_cwd = command_cwd
.to_str()
.unwrap_or_else(|| panic!("command cwd must be valid UTF-8"))
.to_string();
let sandbox_policy_cwd = sandbox_policy_cwd
.to_str()
.unwrap_or_else(|| panic!("cwd must be valid UTF-8"))
.to_string();
let mut linux_cmd: Vec<String> = vec![
"--sandbox-policy-cwd".to_string(),
sandbox_policy_cwd,
"--command-cwd".to_string(),
command_cwd,
];
// Proxy-only networking requires bubblewrap's isolated network namespace.
if use_legacy_landlock && !allow_network_for_proxy {
linux_cmd.push("--use-legacy-landlock".to_string());
}
if allow_network_for_proxy {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push("{}".to_string());
}
// Separator so that command arguments starting with `-` are not parsed as
// options of the helper itself.
linux_cmd.push("--".to_string());
// Append the original tool command.
linux_cmd.extend(command);
linux_cmd
}
#[cfg(test)]
#[path = "landlock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,92 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn legacy_landlock_flag_is_included_when_requested() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let default_bwrap = create_linux_sandbox_command_args(
command.clone(),
command_cwd,
cwd,
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
);
assert_eq!(
default_bwrap.contains(&"--use-legacy-landlock".to_string()),
false
);
let legacy_landlock = create_linux_sandbox_command_args(
command,
command_cwd,
cwd,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ false,
);
assert_eq!(
legacy_landlock.contains(&"--use-legacy-landlock".to_string()),
true
);
}
#[test]
fn managed_context_takes_precedence_over_legacy_landlock() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
Some(&ManagedNetworkSandboxContext::default()),
);
assert_eq!(args.contains(&"--managed-network".to_string()), true);
assert_eq!(args.contains(&"--use-legacy-landlock".to_string()), false);
}
#[test]
fn permission_profile_flag_is_included() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
let permission_profile = PermissionProfile::read_only();
let args = create_linux_sandbox_command_args_for_permission_profile(
command,
command_cwd,
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
/*managed_network*/ None,
);
assert_eq!(
args.windows(2)
.any(|window| { window[0] == "--permission-profile" && !window[1].is_empty() }),
true
);
assert_eq!(
args.windows(2)
.any(|window| window[0] == "--command-cwd" && window[1] == "/tmp/link"),
true
);
}
#[test]
fn proxy_network_requires_managed_requirements() {
assert_eq!(
allow_network_for_proxy(/*enforce_managed_network*/ false),
false
);
assert_eq!(
allow_network_for_proxy(/*enforce_managed_network*/ true),
true
);
}

View File

@@ -0,0 +1,55 @@
//! Bind filesystem and network inputs for sandbox preparation on the execution host.
use std::io;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemPath;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
/// The authorized profile, resolved on the host that will enforce it.
#[derive(Debug)]
pub(super) struct PreparedLaunchPolicy {
pub(super) permissions: PermissionProfile,
}
impl PreparedLaunchPolicy {
/// An empty workspace list stays empty, even when the policy contains `:workspace_roots`.
pub(super) fn resolve(
permissions: PermissionProfile,
policy_cwd: &PathUri,
roots: Option<&[PathUri]>,
) -> io::Result<Self> {
let Some(roots) = roots else {
return Ok(Self { permissions });
};
native_path(policy_cwd, "sandbox policy cwd")?;
let workspace_roots = native_workspace_roots(roots)?;
let (file_system, network) = permissions.to_runtime_permissions();
for entry in &file_system.entries {
if let FileSystemPath::Path { path } = &entry.path {
native_path(path, "sandbox permission path")?;
}
}
let file_system =
file_system.materialize_project_roots_with_workspace_roots(&workspace_roots);
let permissions = PermissionProfile::from_runtime_permissions_with_enforcement(
permissions.enforcement(),
&file_system,
network,
);
Ok(Self { permissions })
}
}
pub(super) fn native_workspace_roots(roots: &[PathUri]) -> io::Result<Vec<AbsolutePathBuf>> {
roots
.iter()
.map(|root| native_path(root, "sandbox workspace root"))
.collect::<io::Result<Vec<_>>>()
}
fn native_path(path: &PathUri, field: &str) -> io::Result<AbsolutePathBuf> {
path.to_abs_path()
.map_err(|err| io::Error::new(err.kind(), format!("invalid {field}: {err}")))
}

View File

@@ -0,0 +1,109 @@
#[cfg(target_os = "linux")]
mod bwrap;
mod denial;
pub mod landlock;
mod linux_pid_namespace;
mod manager;
pub mod policy_transforms;
mod sandbox_integrity;
#[cfg(target_os = "macos")]
pub mod seatbelt;
mod spawn;
mod terminal_queries;
mod violation;
mod windows;
#[cfg(windows)]
mod windows_mxc;
#[cfg(target_os = "linux")]
pub use bwrap::find_executable_in_search_paths;
#[cfg(target_os = "linux")]
pub use bwrap::find_pre_sandbox_executable_in_path;
#[cfg(target_os = "linux")]
pub use bwrap::find_system_bwrap_in_path;
#[cfg(target_os = "linux")]
pub use bwrap::system_bwrap_warning;
pub use codex_mxc_sandbox::CODEX_WINDOWS_MXC_ARG1;
pub use codex_mxc_sandbox::is_available as windows_mxc_available;
pub use codex_mxc_sandbox::run_main as run_windows_mxc_main;
pub use codex_windows_sandbox::WindowsSandboxProxySettingsMode;
pub use denial::is_likely_executor_managed_sandbox_denied;
pub use denial::is_likely_sandbox_denied;
pub use linux_pid_namespace::LinuxSandboxPidNamespace;
pub use manager::SandboxCommand;
pub use manager::SandboxDirectSpawnTransformRequest;
pub use manager::SandboxExecRequest;
pub use manager::SandboxManager;
pub use manager::SandboxTransformError;
pub use manager::SandboxTransformRequest;
pub use manager::SandboxType;
pub use manager::SandboxablePreference;
pub use manager::compatibility_sandbox_policy_for_permission_profile;
pub use manager::get_platform_sandbox;
pub use manager::with_managed_mitm_ca_readable_root;
pub use sandbox_integrity::FileContentsChecker;
pub use sandbox_integrity::IntegrityFinding;
pub use sandbox_integrity::IntegrityFindingDetails;
pub use spawn::SpawnRequest;
pub use spawn::WindowsSandboxSpawnRequest;
pub use spawn::spawn_process;
pub use violation::FileSystemSandboxViolation;
pub use violation::FileSystemSandboxViolationReason;
pub use violation::NetworkSandboxViolation;
pub use violation::SandboxViolationBackend;
pub use violation::SandboxViolationEvent;
pub use violation::record_filesystem_sandbox_violation;
pub use violation::record_network_sandbox_violation;
pub use violation::record_sandbox_violation;
pub use windows::WindowsSandboxFilesystemOverrides;
pub use windows::permission_profile_supports_windows_restricted_token_sandbox;
pub use windows::resolve_windows_elevated_filesystem_overrides;
pub use windows::resolve_windows_restricted_token_filesystem_overrides;
pub use windows::windows_sandbox_uses_elevated_backend;
use codex_protocol::error::CodexErr;
#[cfg(not(target_os = "linux"))]
pub fn system_bwrap_warning(
_permission_profile: &codex_protocol::models::PermissionProfile,
_sandbox_policy_cwd: &std::path::Path,
) -> Option<String> {
None
}
impl From<SandboxTransformError> for CodexErr {
fn from(err: SandboxTransformError) -> Self {
match err {
error @ SandboxTransformError::InvalidPolicy(_)
| error @ SandboxTransformError::InvalidCommandCwd { .. }
| error @ SandboxTransformError::InvalidSandboxPolicyCwd { .. } => {
CodexErr::InvalidRequest(error.to_string())
}
SandboxTransformError::MissingLinuxSandboxExecutable => {
CodexErr::LandlockSandboxExecutableNotProvided
}
SandboxTransformError::EnvironmentNetworkProxy(message) => {
CodexErr::UnsupportedOperation(message)
}
SandboxTransformError::WindowsMxcPreparation(message) => {
CodexErr::UnsupportedOperation(message)
}
#[cfg(target_os = "macos")]
SandboxTransformError::SeatbeltPreparation(message) => {
CodexErr::UnsupportedOperation(message)
}
#[cfg(target_os = "linux")]
SandboxTransformError::Wsl1UnsupportedForBubblewrap => {
CodexErr::UnsupportedOperation(crate::bwrap::WSL1_BWRAP_WARNING.to_string())
}
#[cfg(not(target_os = "macos"))]
SandboxTransformError::SeatbeltUnavailable => CodexErr::UnsupportedOperation(
"seatbelt sandbox is only available on macOS".to_string(),
),
#[cfg(target_os = "windows")]
SandboxTransformError::WindowsSandboxPreparation(message) => {
CodexErr::UnsupportedOperation(message)
}
}
}
}

View File

@@ -0,0 +1,23 @@
//! Startup-owned Linux PID isolation policy, independent of request permissions.
/// Selects the PID namespace policy for Linux bubblewrap sandboxes.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LinuxSandboxPidNamespace {
/// Create a new PID namespace, retaining the legacy `/proc` mount fallback.
#[default]
Isolate,
/// Reuse the caller's PID namespace and `/proc`, allowing signals to other same-UID processes.
Inherit,
}
impl std::str::FromStr for LinuxSandboxPidNamespace {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value {
"isolate" => Ok(Self::Isolate),
"inherit" => Ok(Self::Inherit),
_ => Err("expected 'isolate' or 'inherit'".to_string()),
}
}
}

View File

@@ -0,0 +1,839 @@
use self::launch::PreparedLaunchPolicy;
use crate::LinuxSandboxPidNamespace;
#[cfg(windows)]
use crate::WindowsSandboxFilesystemOverrides;
#[cfg(target_os = "linux")]
use crate::bwrap::WSL1_BWRAP_WARNING;
use crate::landlock::CODEX_LINUX_SANDBOX_ARG0;
use crate::policy_transforms::effective_permission_profile;
use crate::policy_transforms::should_require_platform_sandbox;
#[cfg(target_os = "macos")]
use crate::seatbelt::MacosSeatbeltProfile;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::sandbox::SandboxOverride;
pub use codex_protocol::sandbox::SandboxType;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io;
use std::path::Path;
#[path = "launch.rs"]
pub(super) mod launch;
#[cfg(target_os = "windows")]
const WINDOWS_SANDBOX_WRAPPER_SETUP_ENV_ALLOWLIST: &[&str] = &[
"USERNAME",
"USERPROFILE",
// ShellExecuteExW needs SystemRoot to elevate the setup helper.
"SYSTEMROOT",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SandboxablePreference {
Auto,
Require,
Forbid,
}
pub fn get_platform_sandbox(windows_sandbox_enabled: bool) -> Option<SandboxType> {
if cfg!(target_os = "macos") {
Some(SandboxType::MacosSeatbelt)
} else if cfg!(target_os = "linux") {
Some(SandboxType::LinuxSeccomp)
} else if cfg!(target_os = "windows") {
if windows_sandbox_enabled {
Some(SandboxType::WindowsRestrictedToken)
} else {
None
}
} else {
None
}
}
pub fn with_managed_mitm_ca_readable_root(
permission_profile: PermissionProfile,
managed_mitm_ca_trust_bundle_path: Option<&AbsolutePathBuf>,
sandbox_policy_cwd: &Path,
) -> PermissionProfile {
let Some(managed_mitm_ca_trust_bundle_path) = managed_mitm_ca_trust_bundle_path else {
return permission_profile;
};
let (file_system_sandbox_policy, network_sandbox_policy) =
permission_profile.to_runtime_permissions();
let file_system_sandbox_policy = file_system_sandbox_policy.with_additional_readable_roots(
sandbox_policy_cwd,
std::slice::from_ref(managed_mitm_ca_trust_bundle_path),
);
PermissionProfile::from_runtime_permissions_with_enforcement(
permission_profile.enforcement(),
&file_system_sandbox_policy,
network_sandbox_policy,
)
}
#[derive(Debug)]
pub struct SandboxCommand {
pub program: OsString,
pub args: Vec<String>,
pub cwd: PathUri,
pub env: HashMap<String, String>,
pub managed_network: Option<ManagedNetworkSandboxContext>,
pub additional_permissions: Option<AdditionalPermissionProfile>,
}
/// A host-native launch request produced after the sandbox manager validates URI inputs.
/// Build this only at the execution boundary: in exec-server, or in its logical equivalent within
/// app-server. Orchestration and transport code should retain [`PathUri`] values and defer
/// conversion to native paths until this request is created.
#[derive(Clone, Debug)]
pub struct SandboxExecRequest {
/// Controller-selected override, retained for observations without altering the sandbox command.
pub sandbox_override: SandboxOverride,
pub command: Vec<String>,
pub cwd: PathUri,
pub sandbox_policy_cwd: PathUri,
pub env: HashMap<String, String>,
pub network: Option<NetworkProxy>,
pub network_environment_id: Option<String>,
pub sandbox: SandboxType,
// TODO(anp): Reconcile these backend copies with the supplied sandbox context
// (TurnEnvironment::sandbox_context for turns), preserving this launch snapshot.
pub windows_sandbox_level: WindowsSandboxLevel,
pub permission_profile: PermissionProfile,
pub arg0: Option<String>,
}
/// Bundled arguments for sandbox transformation.
///
/// This keeps call sites self-documenting when several fields are optional.
pub struct SandboxTransformRequest<'a> {
pub command: SandboxCommand,
pub permissions: &'a PermissionProfile,
/// Bind symbolic workspace rules to these executor roots. `None` means they are already resolved.
pub workspace_roots: Option<&'a [PathUri]>,
pub sandbox: SandboxType,
pub enforce_managed_network: bool,
pub environment_id: Option<&'a str>,
// TODO(viyatb): Evaluate switching this to Option<Arc<NetworkProxy>>
// to make shared ownership explicit across runtime/sandbox plumbing.
pub network: Option<&'a NetworkProxy>,
pub sandbox_policy_cwd: &'a PathUri,
pub sandbox_exe: Option<&'a Path>,
// TODO(anp): Reconcile these backend inputs with the supplied sandbox context
// (TurnEnvironment::sandbox_context for turns) so selection shares its authority.
pub use_legacy_landlock: bool,
pub windows_sandbox_level: WindowsSandboxLevel,
}
/// Bundled arguments for a sandbox transformation whose result will be spawned
/// directly from argv.
///
/// Direct-spawn callers will not run a later platform-specific launcher, so the
/// returned command must encode any sandbox wrapper it needs.
pub struct SandboxDirectSpawnTransformRequest<'a> {
pub transform: SandboxTransformRequest<'a>,
pub workspace_roots: &'a [AbsolutePathBuf],
pub windows_sandbox_proxy_settings_mode: codex_windows_sandbox::WindowsSandboxProxySettingsMode,
}
// TODO(anp): Revisit this preparation type once this module's PathUri migration is complete.
struct PendingSandboxedExecRequest {
native_command_cwd: AbsolutePathBuf,
native_sandbox_policy_cwd: AbsolutePathBuf,
effective_permission_profile: PermissionProfile,
}
impl PendingSandboxedExecRequest {
fn new(
command_cwd: &PathUri,
sandbox_policy_cwd: &PathUri,
effective_permission_profile: PermissionProfile,
managed_mitm_ca_trust_bundle_path: Option<&AbsolutePathBuf>,
) -> Result<Self, SandboxTransformError> {
// TODO(anp): Move PathUri conversion into the platform sandbox implementations.
let native_command_cwd = command_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidCommandCwd {
cwd: command_cwd.clone(),
source,
}
})?;
let native_sandbox_policy_cwd = sandbox_policy_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidSandboxPolicyCwd {
cwd: sandbox_policy_cwd.clone(),
source,
}
})?;
let effective_permission_profile = with_managed_mitm_ca_readable_root(
effective_permission_profile,
managed_mitm_ca_trust_bundle_path,
native_sandbox_policy_cwd.as_path(),
);
Ok(Self {
native_command_cwd,
native_sandbox_policy_cwd,
effective_permission_profile,
})
}
}
#[derive(Debug)]
pub enum SandboxTransformError {
InvalidPolicy(io::Error),
InvalidCommandCwd {
cwd: PathUri,
source: io::Error,
},
InvalidSandboxPolicyCwd {
cwd: PathUri,
source: io::Error,
},
MissingLinuxSandboxExecutable,
WindowsMxcPreparation(String),
EnvironmentNetworkProxy(String),
#[cfg(target_os = "macos")]
SeatbeltPreparation(String),
#[cfg(target_os = "linux")]
Wsl1UnsupportedForBubblewrap,
#[cfg(not(target_os = "macos"))]
SeatbeltUnavailable,
#[cfg(target_os = "windows")]
WindowsSandboxPreparation(String),
}
impl std::fmt::Display for SandboxTransformError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidPolicy(err) => err.fmt(f),
Self::InvalidCommandCwd { cwd, source } => {
write!(
f,
"command cwd URI `{cwd}` is not valid on this host: {source}"
)
}
Self::InvalidSandboxPolicyCwd { cwd, source } => write!(
f,
"sandbox policy cwd URI `{cwd}` is not valid on this host: {source}"
),
Self::MissingLinuxSandboxExecutable => {
write!(f, "missing codex-linux-sandbox executable path")
}
Self::WindowsMxcPreparation(err) => {
write!(f, "failed to prepare MXC sandbox: {err}")
}
Self::EnvironmentNetworkProxy(err) => {
write!(f, "failed to prepare environment network proxy: {err}")
}
#[cfg(target_os = "macos")]
Self::SeatbeltPreparation(err) => {
write!(f, "failed to prepare Seatbelt sandbox: {err}")
}
#[cfg(target_os = "linux")]
Self::Wsl1UnsupportedForBubblewrap => write!(f, "{WSL1_BWRAP_WARNING}"),
#[cfg(not(target_os = "macos"))]
Self::SeatbeltUnavailable => write!(f, "seatbelt sandbox is only available on macOS"),
#[cfg(target_os = "windows")]
Self::WindowsSandboxPreparation(err) => {
write!(f, "failed to prepare Windows sandbox: {err}")
}
}
}
}
impl std::error::Error for SandboxTransformError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::InvalidPolicy(source) => Some(source),
Self::InvalidCommandCwd { source, .. }
| Self::InvalidSandboxPolicyCwd { source, .. } => Some(source),
Self::MissingLinuxSandboxExecutable => None,
Self::WindowsMxcPreparation(_) => None,
Self::EnvironmentNetworkProxy(_) => None,
#[cfg(target_os = "macos")]
Self::SeatbeltPreparation(_) => None,
#[cfg(target_os = "linux")]
Self::Wsl1UnsupportedForBubblewrap => None,
#[cfg(not(target_os = "macos"))]
Self::SeatbeltUnavailable => None,
#[cfg(target_os = "windows")]
Self::WindowsSandboxPreparation(_) => None,
}
}
}
#[derive(Clone, Default)]
pub struct SandboxManager {
linux_sandbox_pid_namespace: LinuxSandboxPidNamespace,
#[cfg(target_os = "macos")]
seatbelt_profile: MacosSeatbeltProfile,
#[cfg(target_os = "macos")]
allowed_symlinked_codex_home: Option<AbsolutePathBuf>,
}
impl SandboxManager {
pub fn new() -> Self {
Self::default()
}
/// Creates a manager that applies the narrower runtime profile required by filesystem helpers.
pub fn for_file_system_helpers() -> Self {
Self {
linux_sandbox_pid_namespace: LinuxSandboxPidNamespace::default(),
#[cfg(target_os = "macos")]
seatbelt_profile: MacosSeatbeltProfile::FileSystemHelper,
#[cfg(target_os = "macos")]
allowed_symlinked_codex_home: None,
}
}
/// Applies a trusted executor startup policy, never a command or repository setting.
pub fn with_linux_sandbox_pid_namespace(mut self, mode: LinuxSandboxPidNamespace) -> Self {
self.linux_sandbox_pid_namespace = mode;
self
}
/// Allows otherwise-authorized writable roots beneath the opted-in user home
/// to follow symlinks, including targets outside that home.
#[cfg(target_os = "macos")]
pub fn with_allowed_symlinked_codex_home(
mut self,
allowed_symlinked_codex_home: Option<AbsolutePathBuf>,
) -> Self {
self.allowed_symlinked_codex_home = allowed_symlinked_codex_home;
self
}
pub fn select_initial(
&self,
permission_profile: &PermissionProfile,
pref: SandboxablePreference,
windows_sandbox_type: SandboxType,
has_managed_network_requirements: bool,
) -> SandboxType {
#[cfg(windows)]
crate::windows_mxc::record_availability_once();
if !self.should_sandbox(permission_profile, pref, has_managed_network_requirements) {
return SandboxType::None;
}
if cfg!(windows) && windows_sandbox_type == SandboxType::WindowsMxc {
return SandboxType::WindowsMxc;
}
get_platform_sandbox(windows_sandbox_type != SandboxType::None).unwrap_or(SandboxType::None)
}
/// Returns whether the request needs a sandbox, independently of whether
/// this host can provide a concrete sandbox implementation.
pub fn should_sandbox(
&self,
permission_profile: &PermissionProfile,
pref: SandboxablePreference,
has_managed_network_requirements: bool,
) -> bool {
match pref {
SandboxablePreference::Forbid => false,
SandboxablePreference::Require => true,
SandboxablePreference::Auto => {
let (file_system_policy, network_policy) =
permission_profile.to_runtime_permissions();
should_require_platform_sandbox(
&file_system_policy,
network_policy,
has_managed_network_requirements,
)
}
}
}
/// Prepare filesystem and network enforcement for a command on the execution host.
pub fn transform(
&self,
request: SandboxTransformRequest<'_>,
) -> Result<SandboxExecRequest, SandboxTransformError> {
#[cfg(windows)]
if request.sandbox == SandboxType::WindowsRestrictedToken
&& request.enforce_managed_network
&& request.windows_sandbox_level != WindowsSandboxLevel::Elevated
{
return Err(SandboxTransformError::WindowsSandboxPreparation(
"managed networking requires the elevated Windows sandbox backend".into(),
));
}
let backend = request.sandbox;
let command = request.command;
let managed_network = command
.managed_network
.filter(|_| request.enforce_managed_network || backend == SandboxType::MacosSeatbelt);
let managed_mitm_ca_trust_bundle_path = request
.network
.and_then(NetworkProxy::managed_mitm_ca_trust_bundle_path);
let permissions = effective_permission_profile(
request.permissions,
command.additional_permissions.as_ref(),
);
let policy = PreparedLaunchPolicy::resolve(
permissions,
request.sandbox_policy_cwd,
request.workspace_roots,
)
.map_err(SandboxTransformError::InvalidPolicy)?;
let mut argv = Vec::with_capacity(1 + command.args.len());
argv.push(command.program.to_string_lossy().into_owned());
argv.extend(command.args);
let mut exec = SandboxExecRequest {
sandbox_override: SandboxOverride::NoOverride,
command: argv,
cwd: command.cwd,
sandbox_policy_cwd: request.sandbox_policy_cwd.clone(),
env: command.env,
network: request.network.cloned(),
network_environment_id: request.environment_id.map(str::to_owned),
sandbox: backend,
windows_sandbox_level: request.windows_sandbox_level,
permission_profile: policy.permissions,
arg0: None,
};
if backend == SandboxType::None {
return Ok(exec);
}
let pending = PendingSandboxedExecRequest::new(
&exec.cwd,
&exec.sandbox_policy_cwd,
exec.permission_profile,
managed_mitm_ca_trust_bundle_path.as_ref(),
);
match backend {
SandboxType::None => unreachable!("native launch returned above"),
SandboxType::WindowsMxc => {
if !codex_mxc_sandbox::is_available() {
return Err(SandboxTransformError::WindowsMxcPreparation(
"native MXC is unavailable on this executor".into(),
));
}
let route = match managed_network {
None if request.enforce_managed_network => {
let proxy = request.network.ok_or_else(|| {
SandboxTransformError::WindowsMxcPreparation(
"managed networking requires an executor-local proxy".to_string(),
)
})?;
let prepared = proxy
.prepare_for_optional_environment(exec.env, request.environment_id)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
route => route,
};
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe = request.sandbox_exe.ok_or_else(|| {
SandboxTransformError::WindowsMxcPreparation(
"missing Codex executable path".into(),
)
})?;
let args = codex_mxc_sandbox::create_command_args(
codex_mxc_sandbox::CreateMxcCommandArgsParams {
command: std::mem::take(&mut exec.command),
permission_profile: &exec.permission_profile,
sandbox_policy_cwd: &pending.native_sandbox_policy_cwd,
managed_network: route.as_ref(),
env: &mut exec.env,
},
)
.map_err(|err| SandboxTransformError::WindowsMxcPreparation(err.to_string()))?;
exec.command = std::iter::once(exe.to_string_lossy().into_owned())
.chain(args)
.collect();
}
#[cfg(target_os = "macos")]
SandboxType::MacosSeatbelt => {
use crate::seatbelt::CreateSeatbeltCommandArgsParams;
use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use crate::seatbelt::SeatbeltPreparationError;
use crate::seatbelt::create_seatbelt_command_args_with_profile;
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let (file_system_sandbox_policy, network_sandbox_policy) =
exec.permission_profile.to_runtime_permissions();
let args = create_seatbelt_command_args_with_profile(
CreateSeatbeltCommandArgsParams {
command: std::mem::take(&mut exec.command),
file_system_sandbox_policy: &file_system_sandbox_policy,
network_sandbox_policy,
sandbox_policy_cwd: &pending.native_sandbox_policy_cwd,
enforce_managed_network: request.enforce_managed_network,
managed_network: managed_network.as_ref(),
environment_id: request.environment_id,
network: request.network,
extra_allow_unix_sockets: &[],
},
self.seatbelt_profile,
self.allowed_symlinked_codex_home.as_ref(),
)
.map_err(|err| match err {
SeatbeltPreparationError::FileSystem(message) => {
SandboxTransformError::SeatbeltPreparation(message)
}
SeatbeltPreparationError::EnvironmentNetworkProxy(message) => {
SandboxTransformError::EnvironmentNetworkProxy(message)
}
})?;
exec.command = std::iter::once(MACOS_PATH_TO_SEATBELT_EXECUTABLE.to_owned())
.chain(args)
.collect();
}
#[cfg(not(target_os = "macos"))]
SandboxType::MacosSeatbelt => return Err(SandboxTransformError::SeatbeltUnavailable),
SandboxType::LinuxSeccomp => {
let pending = pending?;
exec.permission_profile = pending.effective_permission_profile;
let exe = request
.sandbox_exe
.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
let route = match (
request.enforce_managed_network,
managed_network,
request.network,
) {
(false, _, _) => None,
(true, None, Some(proxy)) => {
let prepared = proxy
.prepare_for_optional_environment(exec.env, request.environment_id)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
exec.env = prepared.env;
Some(prepared.sandbox_context)
}
(true, context, _) => Some(context.unwrap_or_default()),
};
self.wrap_linux(
&mut exec,
(
&pending.native_command_cwd,
&pending.native_sandbox_policy_cwd,
),
exe,
request.use_legacy_landlock,
route.as_ref(),
)?;
}
SandboxType::WindowsRestrictedToken => {
exec.permission_profile = pending?.effective_permission_profile;
}
}
Ok(exec)
}
fn wrap_linux(
&self,
exec: &mut SandboxExecRequest,
(cwd, policy_cwd): (&AbsolutePathBuf, &AbsolutePathBuf),
exe: &Path,
use_legacy_landlock: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Result<(), SandboxTransformError> {
#[cfg(target_os = "linux")]
ensure_linux_bubblewrap_is_supported(
&exec.permission_profile.file_system_sandbox_policy(),
use_legacy_landlock,
managed_network.is_some(),
crate::bwrap::is_wsl1(),
)?;
let program = exe.to_string_lossy().into_owned();
let mut args = crate::landlock::create_linux_sandbox_command_args_for_permission_profile(
std::mem::take(&mut exec.command),
cwd,
&exec.permission_profile,
policy_cwd,
use_legacy_landlock,
managed_network,
);
// Only the startup opt-in requires a helper that understands PID inheritance.
if self.linux_sandbox_pid_namespace == LinuxSandboxPidNamespace::Inherit {
args.insert(0, "--inherit-pid-namespace".to_owned());
}
exec.command = std::iter::once(program.clone()).chain(args).collect();
let arg0 = if exe.file_name() == Some(OsStr::new(CODEX_LINUX_SANDBOX_ARG0)) {
&program
} else {
CODEX_LINUX_SANDBOX_ARG0
};
exec.arg0 = Some(arg0.to_owned());
Ok(())
}
pub fn transform_for_direct_spawn(
&self,
request: SandboxDirectSpawnTransformRequest<'_>,
) -> Result<SandboxExecRequest, SandboxTransformError> {
#[cfg(windows)]
{
self.transform_for_direct_spawn_with_codex_home(request, /*codex_home*/ None)
}
#[cfg(not(windows))]
{
self.transform(request.transform)
}
}
#[cfg(target_os = "windows")]
fn transform_for_direct_spawn_with_codex_home(
&self,
request: SandboxDirectSpawnTransformRequest<'_>,
codex_home: Option<&Path>,
) -> Result<SandboxExecRequest, SandboxTransformError> {
let roots = request.transform.workspace_roots;
let fallback_roots = request.workspace_roots;
let proxy_settings_mode = request.windows_sandbox_proxy_settings_mode;
let sandbox_exe = request.transform.sandbox_exe;
let mut request = self.transform(request.transform)?;
if request.sandbox != SandboxType::WindowsRestrictedToken {
return Ok(request);
}
let owned_codex_home;
let codex_home = if let Some(codex_home) = codex_home {
codex_home
} else {
owned_codex_home = codex_utils_home_dir::find_codex_home()
.map_err(|err| SandboxTransformError::WindowsSandboxPreparation(err.to_string()))?;
owned_codex_home.as_path()
};
let workspace_roots = roots
.map(launch::native_workspace_roots)
.transpose()
.map_err(SandboxTransformError::InvalidPolicy)?;
let sandbox_exe = sandbox_exe.ok_or_else(|| {
SandboxTransformError::WindowsSandboxPreparation(
"missing Codex executable path".to_string(),
)
})?;
wrap_windows_sandbox_exec_request_for_direct_spawn(
&mut request,
workspace_roots.as_deref().unwrap_or(fallback_roots),
codex_home,
sandbox_exe,
proxy_settings_mode,
)?;
Ok(request)
}
}
#[cfg(target_os = "windows")]
fn wrap_windows_sandbox_exec_request_for_direct_spawn(
request: &mut SandboxExecRequest,
workspace_roots: &[AbsolutePathBuf],
codex_home: &Path,
sandbox_exe: &Path,
proxy_settings_mode: codex_windows_sandbox::WindowsSandboxProxySettingsMode,
) -> Result<(), SandboxTransformError> {
// TODO(anp): Keep PathUri through the Windows sandbox wrapper boundary.
let native_cwd =
request
.cwd
.to_abs_path()
.map_err(|source| SandboxTransformError::InvalidCommandCwd {
cwd: request.cwd.clone(),
source,
})?;
let native_sandbox_policy_cwd = request.sandbox_policy_cwd.to_abs_path().map_err(|source| {
SandboxTransformError::InvalidSandboxPolicyCwd {
cwd: request.sandbox_policy_cwd.clone(),
source,
}
})?;
let Some(program) = request.command.first_mut() else {
return Err(SandboxTransformError::WindowsSandboxPreparation(
"sandbox command was empty".to_string(),
));
};
// transform() may have made the inner command a Codex helper. Only that
// helper needs materializing; an arbitrary workload such as cmd.exe does not.
if Path::new(program.as_str()) == sandbox_exe {
let helper = codex_windows_sandbox::resolve_exe_for_launch(sandbox_exe, codex_home);
*program = helper.to_string_lossy().into_owned();
}
let inner_command = std::mem::take(&mut request.command);
let proxy_enforced = request.network.is_some();
let network_proxy_restricting_sid = request
.network
.as_ref()
.map(|network| {
network
.network_proxy_restricting_sid(request.network_environment_id.as_deref())
.ok_or_else(|| {
SandboxTransformError::WindowsSandboxPreparation(
"managed Windows proxy route is missing its restricting SID".to_string(),
)
})
})
.transpose()?;
let overrides = WindowsSandboxFilesystemOverrides::resolve(
request.sandbox,
&request.permission_profile,
&native_sandbox_policy_cwd,
request.windows_sandbox_level,
&request.env,
)
.map_err(SandboxTransformError::WindowsSandboxPreparation)?;
let empty_paths: &[AbsolutePathBuf] = &[];
let read_roots_override = overrides
.as_ref()
.and_then(|overrides| overrides.read_roots_override.as_deref());
let read_roots_include_platform_defaults = overrides
.as_ref()
.is_some_and(|overrides| overrides.read_roots_include_platform_defaults);
let write_roots_override = overrides
.as_ref()
.and_then(|overrides| overrides.write_roots_override.as_deref());
let deny_read_paths_override = overrides.as_ref().map_or(empty_paths, |overrides| {
overrides.additional_deny_read_paths.as_slice()
});
let deny_write_paths_override = overrides.as_ref().map_or(empty_paths, |overrides| {
overrides.additional_deny_write_paths.as_slice()
});
let mut wrapper_args =
codex_windows_sandbox::create_windows_sandbox_command_args_for_permission_profile(
inner_command,
&native_cwd,
workspace_roots,
&mut request.env,
&request.permission_profile,
request.windows_sandbox_level,
proxy_enforced,
network_proxy_restricting_sid.as_deref(),
proxy_settings_mode,
read_roots_override,
read_roots_include_platform_defaults,
write_roots_override,
deny_read_paths_override,
deny_write_paths_override,
codex_home,
)
.map_err(|err| SandboxTransformError::WindowsSandboxPreparation(err.to_string()))?;
request.command = Vec::with_capacity(1 + wrapper_args.len());
// This outer process interprets Codex wrapper arguments, so it must be the
// supplied Codex executable even when the inner command is another program.
request
.command
.push(sandbox_exe.to_string_lossy().into_owned());
request.command.append(&mut wrapper_args);
request.sandbox = SandboxType::None;
request.arg0 = None;
add_windows_sandbox_wrapper_setup_env(&mut request.env);
Ok(())
}
#[cfg(target_os = "windows")]
fn add_windows_sandbox_wrapper_setup_env(env: &mut HashMap<String, String>) {
add_windows_sandbox_wrapper_setup_env_from_vars(
env,
std::env::vars_os(),
codex_windows_sandbox::registered_core_requested(),
);
}
#[cfg(target_os = "windows")]
fn add_windows_sandbox_wrapper_setup_env_from_vars(
env: &mut HashMap<String, String>,
vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
registered_core: bool,
) {
// This outer helper must use the parent's runtime selection, not shell-policy overrides.
env.retain(|key, _| !key.eq_ignore_ascii_case("CODEX_WINDOWS_REGISTERED_CORE"));
if registered_core {
env.insert("CODEX_WINDOWS_REGISTERED_CORE".into(), "1".into());
}
for (key, value) in vars {
let key = key.to_string_lossy().into_owned();
if !WINDOWS_SANDBOX_WRAPPER_SETUP_ENV_ALLOWLIST
.iter()
.any(|allowed| key.eq_ignore_ascii_case(allowed))
{
continue;
}
env.retain(|existing, _| !existing.eq_ignore_ascii_case(&key));
env.insert(key, value.to_string_lossy().into_owned());
}
}
pub fn compatibility_sandbox_policy_for_permission_profile(
permissions: &PermissionProfile,
cwd: &Path,
) -> SandboxPolicy {
permissions
.to_legacy_sandbox_policy(cwd)
.unwrap_or_else(|_| {
let (file_system_policy, network_policy) = permissions.to_runtime_permissions();
compatibility_workspace_write_policy(file_system_policy, network_policy, cwd)
})
}
fn compatibility_workspace_write_policy(
file_system_policy: FileSystemSandboxPolicy,
network_policy: NetworkSandboxPolicy,
cwd: &Path,
) -> SandboxPolicy {
let cwd_abs = AbsolutePathBuf::from_absolute_path(cwd).ok();
let writable_roots = file_system_policy
.get_writable_roots_with_cwd(cwd)
.into_iter()
.map(|root| root.root)
.filter(|root| cwd_abs.as_ref() != Some(root))
.collect();
let tmpdir_writable = std::env::var_os("TMPDIR")
.filter(|tmpdir| !tmpdir.is_empty())
.and_then(|tmpdir| {
AbsolutePathBuf::from_absolute_path(std::path::PathBuf::from(tmpdir)).ok()
})
.is_some_and(|tmpdir| {
file_system_policy.can_write_local_path_with_cwd(tmpdir.as_path(), cwd)
});
let slash_tmp = Path::new("/tmp");
let slash_tmp_writable = slash_tmp.is_absolute()
&& slash_tmp.is_dir()
&& file_system_policy.can_write_local_path_with_cwd(slash_tmp, cwd);
SandboxPolicy::WorkspaceWrite {
writable_roots,
network_access: network_policy.is_enabled(),
exclude_tmpdir_env_var: !tmpdir_writable,
exclude_slash_tmp: !slash_tmp_writable,
}
}
#[cfg(target_os = "linux")]
fn ensure_linux_bubblewrap_is_supported(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
use_legacy_landlock: bool,
allow_network_for_proxy: bool,
is_wsl1: bool,
) -> Result<(), SandboxTransformError> {
let requires_bubblewrap = allow_network_for_proxy
|| (!use_legacy_landlock && !file_system_sandbox_policy.has_full_disk_write_access());
if is_wsl1 && requires_bubblewrap {
return Err(SandboxTransformError::Wsl1UnsupportedForBubblewrap);
}
Ok(())
}
#[cfg(test)]
#[path = "manager_tests.rs"]
mod tests;

View File

@@ -0,0 +1,921 @@
use super::SandboxCommand;
#[cfg(windows)]
use super::SandboxDirectSpawnTransformRequest;
use super::SandboxManager;
use super::SandboxTransformRequest;
use super::SandboxType;
use super::SandboxablePreference;
use super::get_platform_sandbox;
use super::with_managed_mitm_ca_readable_root;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::NetworkPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use dunce::canonicalize;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use tempfile::TempDir;
#[test]
fn danger_full_access_defaults_to_no_sandbox_without_network_requirements() {
let manager = SandboxManager::new();
let sandbox = manager.select_initial(
&PermissionProfile::Disabled,
SandboxablePreference::Auto,
SandboxType::None,
/*has_managed_network_requirements*/ false,
);
assert_eq!(sandbox, SandboxType::None);
}
#[test]
fn danger_full_access_uses_platform_sandbox_with_network_requirements() {
let manager = SandboxManager::new();
let expected =
get_platform_sandbox(/*windows_sandbox_enabled*/ false).unwrap_or(SandboxType::None);
let sandbox = manager.select_initial(
&PermissionProfile::Disabled,
SandboxablePreference::Auto,
SandboxType::None,
/*has_managed_network_requirements*/ true,
);
assert_eq!(sandbox, expected);
}
#[test]
fn restricted_file_system_uses_platform_sandbox_without_managed_network() {
let manager = SandboxManager::new();
let expected =
get_platform_sandbox(/*windows_sandbox_enabled*/ false).unwrap_or(SandboxType::None);
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]),
NetworkSandboxPolicy::Enabled,
);
let sandbox = manager.select_initial(
&permissions,
SandboxablePreference::Auto,
SandboxType::None,
/*has_managed_network_requirements*/ false,
);
assert_eq!(sandbox, expected);
}
#[test]
fn explicit_mxc_only_overrides_the_windows_sandbox() {
let manager = SandboxManager::new();
let sandbox = manager.select_initial(
&PermissionProfile::read_only(),
SandboxablePreference::Auto,
SandboxType::WindowsMxc,
/*has_managed_network_requirements*/ false,
);
let expected = if cfg!(windows) {
SandboxType::WindowsMxc
} else {
get_platform_sandbox(/*windows_sandbox_enabled*/ false).unwrap_or(SandboxType::None)
};
assert_eq!(sandbox, expected);
}
#[test]
fn unsandboxed_transform_preserves_foreign_cwd_and_unrestricted_file_system_policy() {
let manager = SandboxManager::new();
let cwd_uri = if cfg!(windows) {
PathUri::parse("file:///workspace/remote").expect("POSIX path URI")
} else {
PathUri::parse("file:///C:/workspace/remote").expect("Windows path URI")
};
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::unrestricted(),
NetworkSandboxPolicy::Restricted,
);
let exec_request = manager
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: None,
additional_permissions: None,
},
permissions: &permissions,
workspace_roots: None,
sandbox: SandboxType::None,
enforce_managed_network: false,
environment_id: Some("remote"),
network: None,
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
.expect("transform");
assert_eq!(exec_request.cwd, cwd_uri);
assert_eq!(exec_request.sandbox_policy_cwd, cwd_uri);
assert_eq!(
exec_request.network_environment_id.as_deref(),
Some("remote")
);
assert_eq!(
exec_request.permission_profile.file_system_sandbox_policy(),
FileSystemSandboxPolicy::unrestricted()
);
assert_eq!(
exec_request.permission_profile.network_sandbox_policy(),
NetworkSandboxPolicy::Restricted
);
}
#[cfg(target_os = "macos")]
#[test]
fn symlinked_workspace_reports_seatbelt_preparation_error() {
use std::os::unix::fs::symlink;
let manager = SandboxManager::new();
let temp_dir = TempDir::new().expect("create temp dir");
let target = temp_dir.path().join("target");
let workspace = temp_dir.path().join("workspace");
std::fs::create_dir(&target).expect("create target");
symlink(&target, &workspace).expect("create symlinked workspace");
let workspace = AbsolutePathBuf::from_absolute_path(workspace).expect("absolute workspace");
let workspace_uri = PathUri::from_abs_path(&workspace);
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::workspace_write(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
),
NetworkSandboxPolicy::Restricted,
);
let error = manager
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: workspace_uri.clone(),
env: HashMap::new(),
managed_network: None,
additional_permissions: None,
},
permissions: &permissions,
workspace_roots: None,
sandbox: SandboxType::MacosSeatbelt,
enforce_managed_network: false,
environment_id: None,
network: None,
sandbox_policy_cwd: &workspace_uri,
sandbox_exe: None,
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
.expect_err("symlinked workspace should be rejected");
assert!(matches!(
&error,
super::SandboxTransformError::SeatbeltPreparation(message)
if message.contains("symlinked writable roots are not supported")
));
assert!(
!error.to_string().contains("network proxy"),
"filesystem error should not be attributed to network proxy: {error}"
);
}
#[test]
fn transform_additional_permissions_enable_network_for_external_sandbox() {
let manager = SandboxManager::new();
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
let cwd_uri = PathUri::from_abs_path(&cwd);
let permissions = PermissionProfile::External {
network: NetworkSandboxPolicy::Restricted,
};
let temp_dir = TempDir::new().expect("create temp dir");
let path = AbsolutePathBuf::from_absolute_path(
canonicalize(temp_dir.path()).expect("canonicalize temp dir"),
)
.expect("absolute temp dir");
let exec_request = manager
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: None,
additional_permissions: Some(AdditionalPermissionProfile {
network: Some(NetworkPermissions {
enabled: Some(true),
}),
file_system: Some(FileSystemPermissions::from_read_write_roots(
Some(vec![path]),
Some(Vec::new()),
)),
}),
},
permissions: &permissions,
workspace_roots: None,
sandbox: SandboxType::None,
enforce_managed_network: false,
environment_id: None,
network: None,
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
.expect("transform");
assert_eq!(
exec_request.permission_profile,
PermissionProfile::External {
network: NetworkSandboxPolicy::Enabled,
}
);
assert_eq!(
exec_request.permission_profile.network_sandbox_policy(),
NetworkSandboxPolicy::Enabled
);
}
#[test]
fn transform_additional_permissions_preserves_denied_entries() {
let manager = SandboxManager::new();
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
let cwd_uri = PathUri::from_abs_path(&cwd);
let temp_dir = TempDir::new().expect("create temp dir");
let workspace_root = AbsolutePathBuf::from_absolute_path(
canonicalize(temp_dir.path()).expect("canonicalize temp dir"),
)
.expect("absolute temp dir");
let allowed_path = workspace_root.join("allowed");
let denied_path = workspace_root.join("denied");
let denied = FileSystemSandboxEntry::new(denied_path.into(), FileSystemAccessMode::Deny);
let allowed = FileSystemSandboxEntry::new(allowed_path.into(), FileSystemAccessMode::Write);
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
FileSystemAccessMode::Read,
),
denied.clone(),
]),
NetworkSandboxPolicy::Restricted,
);
let workspace = PathUri::from_abs_path(&workspace_root);
let build_dir = FileSystemSandboxEntry::new(
workspace_root.join("build").into(),
FileSystemAccessMode::Write,
);
let read = FileSystemSandboxEntry::new(workspace_root.into(), FileSystemAccessMode::Read);
let additional = AdditionalPermissionProfile {
file_system: Some(FileSystemPermissions {
entries: vec![
allowed.clone(),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(Some("build".to_string())),
},
FileSystemAccessMode::Write,
),
],
..Default::default()
}),
..Default::default()
};
for (roots, expected_entries) in [
(
std::slice::from_ref(&workspace),
vec![read, denied.clone(), allowed.clone(), build_dir],
),
(&[][..], vec![denied, allowed]),
] {
let request = SandboxTransformRequest {
command: SandboxCommand {
program: "pwd".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: Default::default(),
managed_network: None,
additional_permissions: Some(additional.clone()),
},
permissions: &permissions,
workspace_roots: Some(roots),
sandbox: SandboxType::None,
enforce_managed_network: false,
network: None,
environment_id: None,
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: None,
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
};
let exec_request = manager.transform(request).expect("transform");
assert_eq!(
exec_request.permission_profile,
PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(expected_entries),
NetworkSandboxPolicy::Restricted,
)
);
}
}
#[test]
fn managed_mitm_ca_bundle_becomes_readable_for_restricted_sandbox() {
let cwd = TempDir::new().expect("create cwd");
let cwd =
AbsolutePathBuf::from_absolute_path(canonicalize(cwd.path()).expect("canonicalize cwd"))
.expect("absolute cwd");
let managed_bundle_dir = TempDir::new().expect("create managed bundle dir");
let managed_bundle_path =
AbsolutePathBuf::from_absolute_path(managed_bundle_dir.path().join("ca-bundle.pem"))
.expect("absolute managed bundle path");
let permission_profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: cwd.clone().into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]),
NetworkSandboxPolicy::Restricted,
);
let permission_profile = with_managed_mitm_ca_readable_root(
permission_profile,
Some(&managed_bundle_path),
cwd.as_path(),
);
let (file_system_sandbox_policy, _) = permission_profile.to_runtime_permissions();
assert_eq!(
file_system_sandbox_policy,
FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: cwd.into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: managed_bundle_path.into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
])
);
}
#[cfg(target_os = "linux")]
fn transform_linux_seccomp_request(
codex_linux_sandbox_exe: &std::path::Path,
mode: crate::LinuxSandboxPidNamespace,
) -> super::SandboxExecRequest {
let manager = SandboxManager::new().with_linux_sandbox_pid_namespace(mode);
let cwd = AbsolutePathBuf::current_dir().expect("current dir");
let cwd_uri = PathUri::from_abs_path(&cwd);
let permissions = PermissionProfile::Disabled;
manager
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: None,
additional_permissions: None,
},
permissions: &permissions,
workspace_roots: None,
sandbox: SandboxType::LinuxSeccomp,
enforce_managed_network: false,
environment_id: None,
network: None,
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: Some(codex_linux_sandbox_exe),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
.expect("transform")
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_rejects_linux_bubblewrap_path() {
let restricted_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]);
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&restricted_policy,
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ true,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
assert!(matches!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ true,
/*is_wsl1*/ true,
),
Err(super::SandboxTransformError::Wsl1UnsupportedForBubblewrap)
));
}
#[cfg(target_os = "linux")]
#[test]
fn wsl1_allows_non_bubblewrap_linux_paths() {
assert!(
super::ensure_linux_bubblewrap_is_supported(
&FileSystemSandboxPolicy::unrestricted(),
/*use_legacy_landlock*/ false,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
)
.is_ok()
);
let restricted_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
}]);
assert!(
super::ensure_linux_bubblewrap_is_supported(
&restricted_policy,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ false,
/*is_wsl1*/ true,
)
.is_ok()
);
}
#[cfg(target_os = "linux")]
#[test]
fn transform_linux_seccomp_preserves_helper_path_in_arg0_when_available() {
let codex_linux_sandbox_exe = std::path::PathBuf::from("/tmp/codex-linux-sandbox");
let exec_request = transform_linux_seccomp_request(
&codex_linux_sandbox_exe,
crate::LinuxSandboxPidNamespace::default(),
);
assert_eq!(
exec_request.arg0,
Some(codex_linux_sandbox_exe.to_string_lossy().into_owned())
);
}
#[cfg(target_os = "linux")]
#[test]
fn transform_linux_seccomp_uses_helper_alias_when_launcher_is_not_helper_path() {
let codex_linux_sandbox_exe = std::path::PathBuf::from("/tmp/codex");
for (mode, first_helper_arg) in [
(
crate::LinuxSandboxPidNamespace::Isolate,
"--sandbox-policy-cwd",
),
(
crate::LinuxSandboxPidNamespace::Inherit,
"--inherit-pid-namespace",
),
] {
let exec_request = transform_linux_seccomp_request(&codex_linux_sandbox_exe, mode);
assert_eq!(exec_request.arg0, Some("codex-linux-sandbox".to_string()));
assert_eq!(exec_request.command[1], first_helper_arg);
}
}
#[cfg(unix)]
#[tokio::test]
async fn linux_unix_socket_grant_uses_effective_managed_policy() -> anyhow::Result<()> {
use codex_network_proxy::ConfigReloader;
use codex_network_proxy::ConfigReloaderFuture;
use codex_network_proxy::ConfigState;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::NetworkProxyConstraints;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::build_config_state;
use std::sync::Arc;
struct TestConfigReloader;
impl ConfigReloader for TestConfigReloader {
fn source_label(&self) -> String {
"sandbox manager test config".to_string()
}
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
Box::pin(async { Ok(None) })
}
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
Box::pin(async { Err(anyhow::anyhow!("test config cannot reload")) })
}
}
let state = build_config_state(
NetworkProxyConfig {
enabled: true,
dangerously_allow_all_unix_sockets: Some(true),
..Default::default()
},
NetworkProxyConstraints::default(),
codex_utils_path_uri::Platform::native(),
)?;
let network = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
state,
Arc::new(TestConfigReloader),
)))
.managed_by_codex(/*managed_by_codex*/ false)
.build()
.await?;
let prepared =
network.prepare_for_optional_environment(HashMap::new(), /*environment_id*/ None)?;
let allow_all = prepared.sandbox_context;
let path_only = ManagedNetworkSandboxContext {
allow_unix_sockets: vec!["/tmp/daemon.sock".to_string()],
..Default::default()
};
let denied = ManagedNetworkSandboxContext::default();
let cwd = AbsolutePathBuf::current_dir()?;
let cwd_uri = PathUri::from_abs_path(&cwd);
let manager = SandboxManager::new();
for (label, context, live_proxy, enforce_managed_network, expected) in [
(
"missing policy stays managed with restrictive defaults",
None,
false,
true,
Some(denied.clone()),
),
(
"path grant stays restricted",
Some(path_only.clone()),
false,
true,
Some(path_only),
),
(
"prepared allow-all",
Some(allow_all.clone()),
false,
true,
Some(allow_all.clone()),
),
(
"prepared denial overrides live allow-all",
Some(denied.clone()),
true,
true,
Some(denied),
),
(
"live proxy fallback",
None,
true,
true,
Some(allow_all.clone()),
),
("no managed network", Some(allow_all), true, false, None),
] {
let request = manager.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: context,
additional_permissions: None,
},
permissions: &PermissionProfile::Disabled,
workspace_roots: None,
sandbox: SandboxType::LinuxSeccomp,
enforce_managed_network,
environment_id: None,
network: live_proxy.then_some(&network),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: Some(std::path::Path::new("/tmp/codex-linux-sandbox")),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})?;
let transported_context = request
.command
.windows(2)
.find(|args| args[0] == "--managed-network")
.map(|args| serde_json::from_str::<ManagedNetworkSandboxContext>(&args[1]))
.transpose()?;
assert_eq!(transported_context, expected, "{label}");
}
Ok(())
}
#[cfg(target_os = "windows")]
#[test]
fn transform_for_direct_spawn_windows_preserves_only_wrapper_setup_environment() {
let mut env = HashMap::from([
("Path".to_string(), r"C:\Windows\System32".to_string()),
("username".to_string(), "wrong-user".to_string()),
("UserProfile".to_string(), r"C:\wrong".to_string()),
("SYSTEMROOT".to_string(), r"C:\wrong".to_string()),
]);
super::add_windows_sandbox_wrapper_setup_env_from_vars(
&mut env,
[
("USERNAME", "alice"),
("USERPROFILE", r"C:\Users\alice"),
("SystemRoot", r"C:\Windows"),
("OPENAI_API_KEY", "secret"),
("HTTP_PROXY", "http://127.0.0.1:7890"),
]
.map(|(key, value)| {
(
std::ffi::OsString::from(key),
std::ffi::OsString::from(value),
)
}),
/*registered_core*/ false,
);
assert_eq!(
env,
HashMap::from([
("Path".to_string(), r"C:\Windows\System32".to_string()),
("USERNAME".to_string(), "alice".to_string()),
("USERPROFILE".to_string(), r"C:\Users\alice".to_string()),
("SystemRoot".to_string(), r"C:\Windows".to_string()),
])
);
}
#[cfg(target_os = "windows")]
#[test]
fn wrapper_runtime_selection_uses_the_parent_not_environment_overrides() {
for registered_core in [false, true] {
let mut env = HashMap::from([("codex_windows_registered_core".into(), "1".into())]);
super::add_windows_sandbox_wrapper_setup_env_from_vars(
&mut env,
[("CODEX_WINDOWS_REGISTERED_CORE".into(), "0".into())],
registered_core,
);
assert_eq!(
env,
if registered_core {
HashMap::from([("CODEX_WINDOWS_REGISTERED_CORE".into(), "1".into())])
} else {
HashMap::new()
}
);
}
}
#[cfg(target_os = "windows")]
#[test]
fn transform_for_direct_spawn_windows_materializes_inner_helper() {
let codex_home = tempfile::TempDir::new().expect("codex home");
let helper_dir = tempfile::TempDir::new().expect("helper dir");
let configured_helper = helper_dir.path().join("configured-codex-helper.exe");
std::fs::write(&configured_helper, b"helper").expect("write configured helper");
let cwd = AbsolutePathBuf::from_absolute_path(
canonicalize(helper_dir.path()).expect("canonical helper directory"),
)
.expect("absolute cwd");
let cwd_uri = PathUri::from_abs_path(&cwd);
let blocked = cwd.join("blocked");
std::fs::create_dir_all(blocked.as_path()).expect("create blocked path");
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
missing_path_behavior: None,
},
FileSystemSandboxEntry {
path: blocked.into(),
access: FileSystemAccessMode::Read,
missing_path_behavior: None,
},
]),
NetworkSandboxPolicy::Restricted,
);
let other_workspace = tempfile::TempDir::new().expect("other workspace");
let other_workspace_root = AbsolutePathBuf::from_absolute_path(
canonicalize(other_workspace.path()).expect("canonical other workspace"),
)
.expect("absolute other workspace");
let workspace_roots = [cwd, other_workspace_root];
let manager = SandboxManager::new();
let prepare = |roots, policy_cwd| {
manager
.transform_for_direct_spawn_with_codex_home(
SandboxDirectSpawnTransformRequest {
workspace_roots: workspace_roots.as_slice(),
windows_sandbox_proxy_settings_mode:
codex_windows_sandbox::WindowsSandboxProxySettingsMode::Preserve,
transform: SandboxTransformRequest {
command: SandboxCommand {
program: configured_helper.as_os_str().to_owned(),
args: vec!["--codex-run-as-fs-helper".to_string()],
cwd: cwd_uri.clone(),
env: HashMap::from([(
"Path".to_string(),
r"C:\Windows\System32".to_string(),
)]),
managed_network: None,
additional_permissions: None,
},
permissions: &permissions,
workspace_roots: roots,
sandbox: SandboxType::WindowsRestrictedToken,
enforce_managed_network: false,
environment_id: None,
network: None,
sandbox_policy_cwd: policy_cwd,
sandbox_exe: Some(configured_helper.as_path()),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
},
},
Some(codex_home.path()),
)
.expect("transform for direct spawn")
};
let exec_request = prepare(/*roots*/ None, &cwd_uri);
let inner_env_json = exec_request
.command
.windows(2)
.find(|args| args[0] == "--env-json")
.expect("inner command environment");
assert_eq!(
serde_json::from_str::<HashMap<String, String>>(&inner_env_json[1])
.expect("decode inner command environment"),
HashMap::from([("Path".to_string(), r"C:\Windows\System32".to_string())])
);
let separator_index = exec_request
.command
.iter()
.position(|arg| arg == "--")
.expect("wrapper argv separator");
let materialized_helper = std::path::PathBuf::from(&exec_request.command[separator_index + 1]);
assert_eq!(exec_request.sandbox, SandboxType::None);
assert_eq!(
exec_request.command.first(),
Some(&configured_helper.display().to_string())
);
assert!(
exec_request
.command
.iter()
.any(|arg| arg == "--run-as-windows-sandbox")
);
assert!(
exec_request
.command
.iter()
.any(|arg| arg == "--preserve-proxy-settings")
);
assert!(
exec_request
.command
.iter()
.any(|arg| arg == "--deny-write-paths-json")
);
assert_eq!(
exec_request.command[separator_index + 2],
"--codex-run-as-fs-helper"
);
let explicit_root = PathUri::from_abs_path(&workspace_roots[1]);
// The wrapper encodes the cwd for an empty root list. Its serialized policy must
// already have removed the workspace write grant.
for (request, expected_roots, expected_writes) in [
(&exec_request, &workspace_roots[..], None),
(
&prepare(Some(&[]), &cwd_uri),
&workspace_roots[..1],
Some([false, false]),
),
(
// The legacy workspace-write projection always includes its policy cwd.
// Anchor it at the grant and check the command cwd independently.
&prepare(Some(std::slice::from_ref(&explicit_root)), &explicit_root),
&workspace_roots[1..],
Some([false, true]),
),
] {
assert_eq!(
request
.command
.windows(2)
.filter_map(|args| {
(args[0] == "--workspace-root").then_some(std::path::PathBuf::from(&args[1]))
})
.collect::<Vec<_>>(),
expected_roots
.iter()
.map(|root| root.as_path().to_path_buf())
.collect::<Vec<_>>()
);
if let Some(expected_writes) = expected_writes {
let profile_json = request
.command
.windows(2)
.find(|args| args[0] == "--permission-profile")
.expect("serialized wrapper policy");
let policy = serde_json::from_str::<PermissionProfile>(&profile_json[1])
.expect("decode wrapper policy")
.file_system_sandbox_policy();
assert_eq!(
workspace_roots
.each_ref()
.map(|root| policy.can_write_local_path_with_cwd(root, &workspace_roots[0])),
expected_writes
);
}
}
assert_eq!(
materialized_helper
.parent()
.and_then(std::path::Path::file_name),
Some(std::ffi::OsStr::new(".sandbox-bin"))
);
assert!(materialized_helper.exists());
}
#[test]
fn restricted_token_preserves_read_only_carveouts_at_a_volume_root() -> anyhow::Result<()> {
let cwd = AbsolutePathBuf::current_dir()?;
let root = AbsolutePathBuf::from_absolute_path(cwd.ancestors().last().expect("volume root"))?;
// Exercise policy preparation without installing ACLs on the test host.
let read_only = root.join("codex-test-read-only");
let mut file_system = FileSystemSandboxPolicy::workspace_write(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
file_system.entries.push(FileSystemSandboxEntry::new(
read_only.clone().into(),
FileSystemAccessMode::Read,
));
let profile =
PermissionProfile::from_runtime_permissions(&file_system, NetworkSandboxPolicy::Restricted);
let overrides = crate::resolve_windows_restricted_token_filesystem_overrides(
SandboxType::WindowsRestrictedToken,
&profile,
&root,
WindowsSandboxLevel::RestrictedToken,
)
.expect("prepare volume-root workspace")
.expect("read-only child");
assert_eq!(overrides.additional_deny_write_paths, [read_only]);
Ok(())
}

View File

@@ -0,0 +1,670 @@
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::models::NetworkPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxKind;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::permissions::ReadDenyMatcher;
use codex_protocol::permissions::file_system_root;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use std::num::NonZeroUsize;
pub fn normalize_additional_permissions(
additional_permissions: AdditionalPermissionProfile,
) -> Result<AdditionalPermissionProfile, String> {
let network = additional_permissions
.network
.filter(|network| !network.is_empty());
let file_system = match additional_permissions.file_system {
Some(file_system) => {
let mut entries = Vec::with_capacity(file_system.entries.len());
let glob_scan_max_depth = file_system.glob_scan_max_depth;
for entry in file_system.entries {
if matches!(&entry.path, FileSystemPath::GlobPattern { .. })
&& entry.access != FileSystemAccessMode::Deny
{
return Err(
"glob file system permissions only support deny-read entries".to_string(),
);
}
if !entries.contains(&entry) {
entries.push(entry);
}
}
let file_system = FileSystemPermissions {
entries,
glob_scan_max_depth,
};
(!file_system.is_empty()).then_some(file_system)
}
None => None,
};
Ok(AdditionalPermissionProfile {
network,
file_system,
})
}
pub fn normalize_additional_permissions_with_context(
additional_permissions: AdditionalPermissionProfile,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<AdditionalPermissionProfile, String> {
let normalized = normalize_additional_permissions(additional_permissions)?;
if let Some(file_system) = normalized.file_system.as_ref() {
for entry in &file_system.entries {
let FileSystemPath::Path { path } = &entry.path else {
continue;
};
if path.infer_path_convention().is_none()
|| path.infer_path_convention() != context.cwd.infer_path_convention()
|| path.join(".").is_err()
{
return Err(format!(
"permission path `{path}` does not match executor cwd `{}`",
context.cwd
));
}
}
}
Ok(normalized)
}
/// Resolves cwd-dependent permission entries without filtering their authority.
///
/// Unlike intersection, this preserves narrower grants beneath denied paths.
pub fn materialize_additional_permissions_with_context(
mut additional_permissions: AdditionalPermissionProfile,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Result<AdditionalPermissionProfile, String> {
if let Some(file_system) = additional_permissions.file_system.as_mut() {
file_system.entries = materialize_context_dependent_entries(&file_system.entries, context)
.ok_or_else(|| format!("unable to resolve permission path in `{}`", context.cwd))?;
}
normalize_additional_permissions_with_context(additional_permissions, context)
}
pub fn merge_permission_profiles(
base: Option<&AdditionalPermissionProfile>,
permissions: Option<&AdditionalPermissionProfile>,
) -> Option<AdditionalPermissionProfile> {
let Some(permissions) = permissions else {
return base.cloned();
};
match base {
Some(base) => {
let network = match (base.network.as_ref(), permissions.network.as_ref()) {
(
Some(NetworkPermissions {
enabled: Some(true),
}),
_,
)
| (
_,
Some(NetworkPermissions {
enabled: Some(true),
}),
) => Some(NetworkPermissions {
enabled: Some(true),
}),
_ => None,
};
let file_system = match (base.file_system.as_ref(), permissions.file_system.as_ref()) {
(Some(base), Some(permissions)) => Some(FileSystemPermissions {
entries: merge_permission_entries(&base.entries, &permissions.entries),
glob_scan_max_depth: merge_glob_scan_max_depth(
&base.entries,
base.glob_scan_max_depth.map(usize::from),
&permissions.entries,
permissions.glob_scan_max_depth.map(usize::from),
)
.and_then(NonZeroUsize::new),
})
.filter(|file_system| !file_system.is_empty()),
(Some(base), None) => Some(base.clone()),
(None, Some(permissions)) => Some(permissions.clone()),
(None, None) => None,
};
Some(AdditionalPermissionProfile {
network,
file_system,
})
.filter(|permissions| !permissions.is_empty())
}
None => Some(permissions.clone()).filter(|permissions| !permissions.is_empty()),
}
}
pub fn intersect_permission_profiles_with_context(
requested: AdditionalPermissionProfile,
granted: AdditionalPermissionProfile,
context: &FileSystemSandboxPolicyContext<'_>,
) -> AdditionalPermissionProfile {
let file_system = requested
.file_system
.and_then(|requested_file_system| {
let granted_file_system = granted.file_system.unwrap_or_default();
let requested_entries =
materialize_context_dependent_entries(&requested_file_system.entries, context)?;
let granted_entries =
materialize_context_dependent_entries(&granted_file_system.entries, context)?;
let requested_policy = FileSystemSandboxPolicy::restricted(requested_entries.clone());
let requested_read_deny_matcher =
ReadDenyMatcher::from_context(&requested_policy, context);
let mut accepted_entries = Vec::new();
for entry in granted_entries.iter().filter(|entry| {
granted_file_system_entry_within_request(
&requested_file_system,
&requested_policy,
requested_read_deny_matcher.as_ref(),
entry,
context,
)
}) {
if !accepted_entries.contains(entry) {
accepted_entries.push(entry.clone());
}
}
let mut entries = accepted_entries.clone();
let requested_retained_deny_entries = retain_constraining_deny_entries(
&requested_entries,
&accepted_entries,
context,
&mut entries,
);
let granted_retained_deny_entries = retain_constraining_deny_entries(
&granted_entries,
&accepted_entries,
context,
&mut entries,
);
Some(FileSystemPermissions {
glob_scan_max_depth: merge_glob_scan_max_depth(
&requested_retained_deny_entries,
requested_file_system.glob_scan_max_depth.map(usize::from),
&granted_retained_deny_entries,
granted_file_system.glob_scan_max_depth.map(usize::from),
)
.and_then(NonZeroUsize::new),
entries,
})
})
.filter(|file_system| !file_system.is_empty());
let network = match (requested.network, granted.network) {
(
Some(NetworkPermissions {
enabled: Some(true),
}),
Some(NetworkPermissions {
enabled: Some(true),
}),
) => Some(NetworkPermissions {
enabled: Some(true),
}),
_ => None,
};
AdditionalPermissionProfile {
network,
file_system,
}
}
fn merge_glob_scan_max_depth(
left_entries: &[FileSystemSandboxEntry],
left_depth: Option<usize>,
right_entries: &[FileSystemSandboxEntry],
right_depth: Option<usize>,
) -> Option<usize> {
let left_depth = effective_glob_scan_depth(left_entries, left_depth);
let right_depth = effective_glob_scan_depth(right_entries, right_depth);
match (left_depth, right_depth) {
(Some(GlobScanDepth::Unbounded), _) | (_, Some(GlobScanDepth::Unbounded)) => None,
(Some(GlobScanDepth::Bounded(left)), Some(GlobScanDepth::Bounded(right))) => {
Some(left.max(right))
}
(Some(GlobScanDepth::Bounded(depth)), None)
| (None, Some(GlobScanDepth::Bounded(depth))) => Some(depth),
(None, None) => None,
}
}
fn effective_glob_scan_depth(
entries: &[FileSystemSandboxEntry],
depth: Option<usize>,
) -> Option<GlobScanDepth> {
entries
.iter()
.any(|entry| {
entry.access == FileSystemAccessMode::Deny
&& matches!(&entry.path, FileSystemPath::GlobPattern { .. })
})
.then_some(match depth {
Some(depth) => GlobScanDepth::Bounded(depth),
None => GlobScanDepth::Unbounded,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GlobScanDepth {
Bounded(usize),
Unbounded,
}
fn granted_file_system_entry_within_request(
requested: &FileSystemPermissions,
requested_policy: &FileSystemSandboxPolicy,
requested_read_deny_matcher: Option<&ReadDenyMatcher>,
granted_entry: &FileSystemSandboxEntry,
context: &FileSystemSandboxPolicyContext<'_>,
) -> bool {
if !granted_entry.access.can_read()
|| matches!(
&granted_entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::SlashTmp,
} if context.cwd.infer_path_convention() != Some(PathConvention::Posix)
)
{
return false;
}
if context.cwd.infer_path_convention() == Some(PathConvention::Windows)
&& is_root_entry(granted_entry)
&& !requested.entries.iter().any(|requested_entry| {
is_root_entry(requested_entry)
&& access_covers(requested_entry.access, granted_entry.access)
})
{
return false;
}
if let Some(path) = resolve_permission_path(&granted_entry.path, context) {
if path.infer_path_convention() != context.cwd.infer_path_convention()
|| requested_read_deny_matcher
.is_some_and(|matcher| matcher.is_read_denied_uri(&path, context))
{
return false;
}
return access_covers(
requested_policy.resolve_access(&path, context),
granted_entry.access,
);
}
requested.entries.iter().any(|requested_entry| {
access_covers(requested_entry.access, granted_entry.access)
&& requested_entry.path == granted_entry.path
})
}
fn retain_constraining_deny_entries(
source_entries: &[FileSystemSandboxEntry],
accepted_entries: &[FileSystemSandboxEntry],
context: &FileSystemSandboxPolicyContext<'_>,
output_entries: &mut Vec<FileSystemSandboxEntry>,
) -> Vec<FileSystemSandboxEntry> {
let mut retained_entries = Vec::new();
for entry in source_entries
.iter()
.filter(|entry| entry.access == FileSystemAccessMode::Deny)
{
if !deny_entry_constrains_accepted_grant(entry, accepted_entries, context) {
continue;
}
if !output_entries.contains(entry) {
output_entries.push(entry.clone());
}
retained_entries.push(entry.clone());
}
retained_entries
}
fn deny_entry_constrains_accepted_grant(
deny_entry: &FileSystemSandboxEntry,
accepted_entries: &[FileSystemSandboxEntry],
context: &FileSystemSandboxPolicyContext<'_>,
) -> bool {
accepted_entries
.iter()
.filter(|entry| entry.access.can_read())
.any(|entry| {
if is_root_entry(entry) {
return true;
}
let Some(grant_path) = resolve_permission_path(&entry.path, context) else {
return true;
};
match &deny_entry.path {
FileSystemPath::GlobPattern { pattern } => {
glob_static_prefix_path(pattern, context)
.is_none_or(|prefix| paths_overlap(&prefix, &grant_path))
}
FileSystemPath::Path { .. } | FileSystemPath::Special { .. } => {
resolve_permission_path(&deny_entry.path, context)
.is_none_or(|deny_path| paths_overlap(&deny_path, &grant_path))
}
}
})
}
fn glob_static_prefix_path(
pattern: &str,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Option<PathUri> {
let is_windows = context.cwd.infer_path_convention() == Some(PathConvention::Windows);
let (prefix, wildcard_in_segment) = match pattern.find(['*', '?', '[', ']']) {
Some(0) => return None,
Some(index) => {
let prefix = &pattern[..index];
(
prefix,
!(prefix.ends_with('/') || is_windows && prefix.ends_with('\\')),
)
}
None => (pattern, false),
};
let prefix = context.cwd.join(prefix).ok()?;
if wildcard_in_segment {
prefix.parent()
} else {
Some(prefix)
}
}
fn paths_overlap(left: &PathUri, right: &PathUri) -> bool {
left.overlaps(right).unwrap_or(true)
}
fn access_covers(requested: FileSystemAccessMode, granted: FileSystemAccessMode) -> bool {
match granted {
FileSystemAccessMode::Read => requested.can_read(),
FileSystemAccessMode::Write => requested.can_write(),
FileSystemAccessMode::Deny => false,
}
}
fn is_root_entry(entry: &FileSystemSandboxEntry) -> bool {
matches!(
&entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
}
)
}
fn materialize_cwd_dependent_entry(
entry: &FileSystemSandboxEntry,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Option<FileSystemSandboxEntry> {
match &entry.path {
FileSystemPath::GlobPattern { pattern } => {
let is_windows = context.cwd.infer_path_convention() == Some(PathConvention::Windows);
let home_relative = pattern
.strip_prefix("~/")
.or_else(|| (pattern == "~").then_some(""))
.or_else(|| is_windows.then(|| pattern.strip_prefix("~\\")).flatten());
let (root, pattern) = match home_relative {
Some(suffix) => (
context.user_home_dir?,
suffix.trim_start_matches(|separator| {
separator == '/' || is_windows && separator == '\\'
}),
),
None => (context.cwd, pattern.as_str()),
};
let path = root.join(pattern).ok()?;
let path = FileSystemPath::GlobPattern {
pattern: path.inferred_native_path_string(),
};
Some(FileSystemSandboxEntry {
path,
access: entry.access,
missing_path_behavior: entry.missing_path_behavior,
})
}
FileSystemPath::Path { .. } | FileSystemPath::Special { .. } => Some(entry.clone()),
}
}
fn resolve_permission_path(
path: &FileSystemPath,
context: &FileSystemSandboxPolicyContext<'_>,
) -> Option<PathUri> {
match path {
FileSystemPath::Path { path } => Some(path.clone()),
FileSystemPath::GlobPattern { .. } => None,
FileSystemPath::Special { value } => match value {
FileSystemSpecialPath::Root => file_system_root(context),
FileSystemSpecialPath::ProjectRoots { subpath } => {
let root = context.workspace_roots.first()?;
match subpath {
Some(subpath) => root.join(subpath).ok(),
None => Some(root.clone()),
}
}
FileSystemSpecialPath::Tmpdir => context.temporary_directories?.first().cloned(),
FileSystemSpecialPath::SlashTmp
if context.cwd.infer_path_convention() == Some(PathConvention::Posix) =>
{
context.cwd.join("/tmp").ok()
}
FileSystemSpecialPath::SlashTmp
| FileSystemSpecialPath::Minimal
| FileSystemSpecialPath::Unknown { .. } => None,
},
}
}
fn materialize_context_dependent_entries(
entries: &[FileSystemSandboxEntry],
context: &FileSystemSandboxPolicyContext<'_>,
) -> Option<Vec<FileSystemSandboxEntry>> {
let mut materialized = Vec::new();
for entry in entries {
match &entry.path {
FileSystemPath::Special {
value: FileSystemSpecialPath::ProjectRoots { .. },
} => {
let mut resolved = Vec::new();
for root in context.workspace_roots {
let mut root_context = *context;
root_context.workspace_roots = std::slice::from_ref(root);
let Some(path) = resolve_permission_path(&entry.path, &root_context) else {
if entry.access == FileSystemAccessMode::Deny {
return None;
}
continue;
};
resolved.push(materialized_path_entry(entry, path));
}
if entry.access == FileSystemAccessMode::Deny && resolved.is_empty() {
return None;
}
materialized.extend(resolved);
}
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
} => {
let Some(temporary_directories) = context.temporary_directories else {
if entry.access == FileSystemAccessMode::Deny {
return None;
}
materialized.push(entry.clone());
continue;
};
materialized.extend(
temporary_directories
.iter()
.cloned()
.map(|path| materialized_path_entry(entry, path)),
);
}
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
} => {
resolve_permission_path(&entry.path, context)?;
materialized.push(entry.clone());
}
_ => {
let Some(entry) = materialize_cwd_dependent_entry(entry, context) else {
if entry.access == FileSystemAccessMode::Deny {
return None;
}
continue;
};
materialized.push(entry);
}
}
}
Some(materialized)
}
fn materialized_path_entry(
entry: &FileSystemSandboxEntry,
path: PathUri,
) -> FileSystemSandboxEntry {
FileSystemSandboxEntry {
path: FileSystemPath::Path { path },
access: entry.access,
missing_path_behavior: entry.missing_path_behavior,
}
}
fn merge_permission_entries(
base: &[FileSystemSandboxEntry],
permissions: &[FileSystemSandboxEntry],
) -> Vec<FileSystemSandboxEntry> {
let mut merged = Vec::with_capacity(base.len() + permissions.len());
for entry in base.iter().chain(permissions.iter()) {
if !merged.contains(entry) {
merged.push(entry.clone());
}
}
merged
}
fn merge_file_system_policy_with_additional_permissions(
file_system_policy: &FileSystemSandboxPolicy,
additional_permissions: &FileSystemPermissions,
) -> FileSystemSandboxPolicy {
match file_system_policy.kind {
FileSystemSandboxKind::Restricted => {
let mut merged_policy = file_system_policy.clone();
for entry in &additional_permissions.entries {
if !merged_policy.entries.contains(entry) {
merged_policy.entries.push(entry.clone());
}
}
merged_policy.glob_scan_max_depth = merge_glob_scan_max_depth(
&file_system_policy.entries,
file_system_policy.glob_scan_max_depth,
&additional_permissions.entries,
additional_permissions.glob_scan_max_depth.map(usize::from),
);
merged_policy
}
FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => {
file_system_policy.clone()
}
}
}
pub fn effective_file_system_sandbox_policy(
file_system_policy: &FileSystemSandboxPolicy,
additional_permissions: Option<&AdditionalPermissionProfile>,
) -> FileSystemSandboxPolicy {
let Some(additional_permissions) = additional_permissions else {
return file_system_policy.clone();
};
let Some(file_system_permissions) = additional_permissions.file_system.as_ref() else {
return file_system_policy.clone();
};
if file_system_permissions.is_empty() {
file_system_policy.clone()
} else {
merge_file_system_policy_with_additional_permissions(
file_system_policy,
file_system_permissions,
)
}
}
fn merge_network_access(
base_network_access: bool,
additional_permissions: &AdditionalPermissionProfile,
) -> bool {
base_network_access
|| additional_permissions
.network
.as_ref()
.and_then(|network| network.enabled)
.unwrap_or(false)
}
pub fn effective_network_sandbox_policy(
network_policy: NetworkSandboxPolicy,
additional_permissions: Option<&AdditionalPermissionProfile>,
) -> NetworkSandboxPolicy {
if additional_permissions
.is_some_and(|permissions| merge_network_access(network_policy.is_enabled(), permissions))
{
NetworkSandboxPolicy::Enabled
} else if additional_permissions.is_some() {
NetworkSandboxPolicy::Restricted
} else {
network_policy
}
}
pub fn effective_permission_profile(
permission_profile: &PermissionProfile,
additional_permissions: Option<&AdditionalPermissionProfile>,
) -> PermissionProfile {
let (file_system_policy, network_policy) = permission_profile.to_runtime_permissions();
let effective_file_system_policy =
effective_file_system_sandbox_policy(&file_system_policy, additional_permissions);
let effective_network_policy =
effective_network_sandbox_policy(network_policy, additional_permissions);
PermissionProfile::from_runtime_permissions_with_enforcement(
permission_profile.enforcement(),
&effective_file_system_policy,
effective_network_policy,
)
}
pub fn should_require_platform_sandbox(
file_system_policy: &FileSystemSandboxPolicy,
network_policy: NetworkSandboxPolicy,
has_managed_network_requirements: bool,
) -> bool {
if has_managed_network_requirements {
return true;
}
if !network_policy.is_enabled() {
return !matches!(
file_system_policy.kind,
FileSystemSandboxKind::ExternalSandbox
);
}
match file_system_policy.kind {
FileSystemSandboxKind::Restricted => !file_system_policy.has_full_disk_write_access(),
FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => false,
}
}
#[cfg(test)]
#[path = "policy_transforms_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
//! Check declared policy access to an existing containment dependency's contents.
//! Callers own the dependency inventory, reporting, and enforcement. Filesystem
//! inspection resolves current objects; it does not assess ownership or OS ACLs.
use super::finding::IntegrityFinding;
use super::finding::IntegrityFindingDetails;
use super::policy::PreparedPolicy;
use super::policy::prepare_policy;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::fs;
use std::io;
/// Rebuild for each effective policy and executor filesystem snapshot.
pub struct FileContentsChecker {
policy: PreparedPolicy,
}
impl FileContentsChecker {
/// Takes the prepared executor policy: symbolic roots must be materialized,
/// and backend snapshot expansion of globs (including scan limits) must
/// already be reflected in its entries. Remaining globs use policy matching.
/// Callers must handle full-disk write access separately.
pub fn new(policy: &FileSystemSandboxPolicy, cwd: &AbsolutePathBuf) -> io::Result<Self> {
let mut policy = prepare_policy(policy, cwd)?;
let mut roots = Vec::new();
for mut root in policy.roots {
let Some(resolved_root) = resolve_existing(&root.root)? else {
continue;
};
if !fs::metadata(&resolved_root)?.is_dir() {
root.protected_metadata_names.clear();
}
// Resolve existing carveouts and protected metadata aliases while
// retaining missing paths unchanged.
let mut exclusions = Vec::new();
for path in root.read_only_subpaths.iter().cloned().chain(
root.protected_metadata_names
.iter()
.map(|name| root.root.join(name)),
) {
exclusions.push(resolve_existing(&path)?.unwrap_or(path));
}
root.root = resolved_root;
root.read_only_subpaths = exclusions;
roots.push(root);
}
policy.roots = roots;
Ok(Self { policy })
}
pub fn check(&self, target: &AbsolutePathBuf) -> io::Result<Option<IntegrityFinding>> {
match fs::metadata(target) {
Ok(metadata) if metadata.is_file() => {}
Ok(_) => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"containment dependency is not a file",
));
}
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
}
let resolved_target = target.canonicalize()?;
// Denying an alias does not establish protection of the resolved contents.
if self
.policy
.glob_denials
.as_ref()
.is_some_and(|matcher| matcher.is_local_path_read_denied(resolved_target.as_path()))
{
return Ok(None);
}
let write_roots: Vec<_> = self
.policy
.roots
.iter()
.filter(|root| root.is_path_writable(resolved_target.as_path()))
.map(|root| root.root.clone())
.collect();
Ok((!write_roots.is_empty()).then(|| IntegrityFinding {
target: target.clone(),
write_roots,
details: IntegrityFindingDetails::Contents { resolved_target },
}))
}
}
fn resolve_existing(path: &AbsolutePathBuf) -> io::Result<Option<AbsolutePathBuf>> {
match path.canonicalize() {
Ok(path) => Ok(Some(path)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
#[cfg(test)]
#[path = "contents_tests.rs"]
mod tests;

View File

@@ -0,0 +1,143 @@
//! Policy grants, denials, and current file identities used by the contents checker.
use super::*;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemAccessMode::Deny;
use codex_protocol::permissions::FileSystemAccessMode::Read;
use codex_protocol::permissions::FileSystemAccessMode::Write;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use pretty_assertions::assert_eq;
fn policy(entries: &[(&AbsolutePathBuf, FileSystemAccessMode)]) -> FileSystemSandboxPolicy {
FileSystemSandboxPolicy::restricted(
entries
.iter()
.map(|(path, access)| FileSystemSandboxEntry::new((*path).clone().into(), *access))
.collect(),
)
}
#[test]
fn contents_respect_write_grants_and_carveouts() -> io::Result<()> {
let directory = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let target = root.join("sandbox-helper");
fs::write(&target, "fixture")?;
for (entries, write_roots) in [
(vec![(&root, Write)], Some(vec![root.clone()])),
(vec![(&root, Write), (&target, Read)], None),
(
vec![(&root, Read), (&target, Write)],
Some(vec![target.clone()]),
),
(vec![(&root, Write), (&target, Deny)], None),
(
vec![(&root, Write), (&target, Write)],
Some(vec![root.clone(), target.clone()]),
),
] {
let checker = FileContentsChecker::new(&policy(&entries), &root)?;
assert_eq!(
checker.check(&target)?,
write_roots.map(|write_roots| IntegrityFinding {
target: target.clone(),
write_roots,
details: IntegrityFindingDetails::Contents {
resolved_target: target.clone(),
},
})
);
}
Ok(())
}
#[test]
fn deny_read_globs_protect_matching_contents_without_disabling_other_checks() -> io::Result<()> {
let directory = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let target = root.join("sandbox-helper");
let unrelated = root.join("other-helper");
fs::write(&target, "fixture")?;
fs::write(&unrelated, "fixture")?;
let mut policy = policy(&[(&root, Write)]);
policy.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: format!("{}/sandbox-*", root.display()),
},
Deny,
));
let checker = FileContentsChecker::new(&policy, &root)?;
assert_eq!(checker.check(&target)?, None);
assert_eq!(
checker.check(&unrelated)?,
Some(IntegrityFinding {
target: unrelated.clone(),
write_roots: vec![root],
details: IntegrityFindingDetails::Contents {
resolved_target: unrelated,
},
})
);
Ok(())
}
#[cfg(unix)]
#[test]
fn contents_follow_links_and_resolved_write_grants() -> io::Result<()> {
let directory = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let writable = root.join("workspace");
let destination = root.join("sandbox-helper");
let link = writable.join("helper-link");
fs::create_dir(&writable)?;
fs::write(&destination, "fixture")?;
std::os::unix::fs::symlink(&destination, &link)?;
let mut alias_denied = policy(&[(&root, Write)]);
alias_denied.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: format!("{}/helper-*", writable.display()),
},
Deny,
));
for (policy, expected) in [
(policy(&[(&writable, Write)]), None),
(policy(&[(&link, Write)]), Some(destination.clone())),
(policy(&[(&root, Write), (&link, Read)]), None),
(alias_denied, Some(root.clone())),
] {
let checker = FileContentsChecker::new(&policy, &root)?;
assert_eq!(
checker.check(&link)?,
expected.map(|write_root| IntegrityFinding {
target: link.clone(),
write_roots: vec![write_root],
details: IntegrityFindingDetails::Contents {
resolved_target: destination.clone(),
},
})
);
}
Ok(())
}
#[test]
fn protected_metadata_contents_remain_read_only() -> io::Result<()> {
let directory = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let target = root.join(".codex/config.toml");
fs::create_dir(root.join(".codex"))?;
fs::write(&target, "fixture")?;
let checker = FileContentsChecker::new(&policy(&[(&root, Write)]), &root)?;
assert_eq!(checker.check(&target)?, None);
Ok(())
}
#[test]
fn missing_target_has_no_contents_to_mutate() -> io::Result<()> {
let directory = tempfile::tempdir()?;
let root = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let checker = FileContentsChecker::new(&policy(&[(&root, Write)]), &root)?;
assert_eq!(checker.check(&root.join("missing"))?, None);
Ok(())
}

View File

@@ -0,0 +1,18 @@
//! Shared findings for policy-based containment integrity checks.
use codex_utils_absolute_path::AbsolutePathBuf;
/// A containment dependency and the effective write grants responsible for a finding.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IntegrityFinding {
pub target: AbsolutePathBuf,
pub write_roots: Vec<AbsolutePathBuf>,
pub details: IntegrityFindingDetails,
}
/// Evidence specific to the kind of containment weakness detected.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IntegrityFindingDetails {
/// The policy permits modifying an existing file's contents.
Contents { resolved_target: AbsolutePathBuf },
}

View File

@@ -0,0 +1,7 @@
mod contents;
mod finding;
mod policy;
pub use contents::FileContentsChecker;
pub use finding::IntegrityFinding;
pub use finding::IntegrityFindingDetails;

View File

@@ -0,0 +1,31 @@
//! Prepare policy grants and glob matching shared by containment integrity checks.
//! Each checker owns further filesystem resolution of these roots and carveouts.
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::ReadDenyMatcher;
use codex_protocol::protocol::WritableRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::io;
pub(super) struct PreparedPolicy {
pub roots: Vec<WritableRoot>,
pub glob_denials: Option<ReadDenyMatcher>,
}
pub(super) fn prepare_policy(
policy: &FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> io::Result<PreparedPolicy> {
// Writable roots already resolve precedence for exact-path rules.
let mut glob_policy = policy.clone();
glob_policy
.entries
.retain(|entry| matches!(entry.path, FileSystemPath::GlobPattern { .. }));
let glob_denials = ReadDenyMatcher::try_new_for_local_paths(&glob_policy, cwd.as_path())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
Ok(PreparedPolicy {
roots: policy.get_writable_roots_with_cwd(cwd.as_path()),
glob_denials,
})
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
(version 1)
; inspired by Chrome's sandbox policy:
; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
; https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/renderer.sb;l=64;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
; start with closed-by-default
(deny default)
; child processes inherit the policy of their parent
(allow process-exec)
(allow process-fork)
(allow signal (target same-sandbox))
; process-info
(allow process-info* (target same-sandbox))
(allow file-write-data
(require-all
(path "/dev/null")
(vnode-type CHARACTER-DEVICE)))
; sysctls permitted.
(allow sysctl-read
(sysctl-name "hw.activecpu")
(sysctl-name "hw.busfrequency_compat")
(sysctl-name "hw.byteorder")
(sysctl-name "hw.cacheconfig")
(sysctl-name "hw.cachelinesize_compat")
(sysctl-name "hw.cpufamily")
(sysctl-name "hw.cpufrequency_compat")
(sysctl-name "hw.cputype")
(sysctl-name "hw.l1dcachesize_compat")
(sysctl-name "hw.l1icachesize_compat")
(sysctl-name "hw.l2cachesize_compat")
(sysctl-name "hw.l3cachesize_compat")
(sysctl-name "hw.logicalcpu_max")
(sysctl-name "hw.machine")
(sysctl-name "hw.model")
(sysctl-name "hw.memsize")
(sysctl-name "hw.ncpu")
(sysctl-name "hw.nperflevels")
; Chrome locks these CPU feature detection down a bit more tightly,
; but mostly for fingerprinting concerns which isn't an issue for codex.
(sysctl-name-prefix "hw.optional.arm.")
(sysctl-name-prefix "hw.optional.armv8_")
(sysctl-name "hw.packages")
(sysctl-name "hw.pagesize_compat")
(sysctl-name "hw.pagesize")
(sysctl-name "hw.physicalcpu")
(sysctl-name "hw.physicalcpu_max")
(sysctl-name "hw.logicalcpu")
(sysctl-name "hw.cpufrequency")
(sysctl-name "hw.tbfrequency_compat")
(sysctl-name "hw.vectorunit")
(sysctl-name "machdep.cpu.brand_string")
(sysctl-name "kern.argmax")
(sysctl-name "kern.hostname")
(sysctl-name "kern.maxfilesperproc")
(sysctl-name "kern.maxproc")
(sysctl-name "kern.osproductversion")
(sysctl-name "kern.osrelease")
(sysctl-name "kern.ostype")
(sysctl-name "kern.osvariant_status")
(sysctl-name "kern.osversion")
(sysctl-name "kern.secure_kernel")
; Python's ProcessPoolExecutor queries this through sysconf(_SC_SEM_NSEMS_MAX).
(sysctl-name "kern.sysv.semmns")
(sysctl-name "kern.usrstack64")
(sysctl-name "kern.version")
(sysctl-name "sysctl.proc_cputype")
(sysctl-name "vm.loadavg")
(sysctl-name-prefix "hw.perflevel")
(sysctl-name-prefix "kern.proc.pgrp.")
(sysctl-name-prefix "kern.proc.pid.")
(sysctl-name-prefix "net.routetable.")
)
; Allow Java to read some CPU info. This is misclassified as a "write" because
; userspace passes a memory buffer to the sysctl, but conceptually it is a read.
(allow sysctl-write
(sysctl-name "kern.grade_cputype"))
; IOKit
(allow iokit-open
(iokit-registry-entry-class "RootDomainUserClient")
)
; needed to look up user info, see https://crbug.com/792228
(allow mach-lookup
(global-name "com.apple.system.opendirectoryd.libinfo")
)
; Needed for python multiprocessing on MacOS for the SemLock
(allow ipc-posix-sem)
; Needed for PyTorch/libomp on macOS to register OpenMP runtimes.
(allow ipc-posix-shm-read-data
ipc-posix-shm-write-create
ipc-posix-shm-write-unlink
(ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$"))
(allow mach-lookup
(global-name "com.apple.PowerManagement.control")
)
; allow openpty()
(allow pseudo-tty)
(allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))
(allow file-read* file-write*
(require-all
(regex #"^/dev/ttys[0-9]+")
(extension "com.apple.sandbox.pty")))
; PTYs created before entering seatbelt may lack the extension; allow ioctl
; on those slave ttys so interactive shells detect a TTY and remain functional.
(allow file-ioctl (regex #"^/dev/ttys[0-9]+"))

View File

@@ -0,0 +1,24 @@
//! Mandatory pathname and network protections for privileged daemon sockets.
//! Emit these after all grants, including implicit platform access.
use super::SeatbeltPreparationError;
use std::path::Path;
pub(super) fn protection_policy(directory: &Path) -> Result<String, SeatbeltPreparationError> {
let quoted = serde_json::to_string(&directory.to_string_lossy())
.map_err(|error| SeatbeltPreparationError::FileSystem(error.to_string()))?;
let mut rules = vec![format!(
"(deny file-read* file-write* (literal {quoted}) (subpath {quoted}))\n\
(deny network-outbound (remote unix-socket (subpath {quoted})))"
)];
// Moving an ancestor would relocate the entire protected subtree beyond
// both pathname rules. Only unlink is denied; sibling writes still work.
for ancestor in directory.ancestors().skip(/*n*/ 1) {
let quoted = serde_json::to_string(&ancestor.to_string_lossy())
.map_err(|error| SeatbeltPreparationError::FileSystem(error.to_string()))?;
rules.push(format!(
"(deny file-write-unlink (require-all (vnode-type DIRECTORY) (literal {quoted})))"
));
}
Ok(rules.join("\n"))
}

View File

@@ -0,0 +1,86 @@
use super::CreateSeatbeltCommandArgsParams;
use super::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use super::create_seatbelt_command_args;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::process::Command;
#[test]
fn daemon_sockets_are_denied_despite_network_and_tmp_write_grants() {
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
let private = tempfile::tempdir_in(&root).unwrap();
let workspace = tempfile::tempdir().unwrap();
let socket = private.path().join("rpc.sock");
let alias = workspace.path().join("alias.sock");
let unrelated = workspace.path().join("other.sock");
let _daemon = UnixListener::bind(&socket).unwrap();
let _other = UnixListener::bind(&unrelated).unwrap();
std::os::unix::fs::symlink(&socket, &alias).unwrap();
UnixStream::connect(&alias).expect("host can reach daemon");
let script = r#"
import os, socket, sys
for path in sys.argv[1:3]:
try:
socket.socket(socket.AF_UNIX).connect(path)
except OSError:
pass
else:
raise AssertionError('daemon reachable: ' + path)
try:
os.link(sys.argv[1], sys.argv[4] + '/hardlink')
except OSError:
pass
else:
raise AssertionError('daemon hardlink created')
socket.socket(socket.AF_UNIX).connect(sys.argv[3])
s = socket.socket(socket.AF_UNIX)
s.bind(sys.argv[4] + '/local.sock')
s.listen(1)
c = socket.socket(socket.AF_UNIX)
c.connect(sys.argv[4] + '/local.sock')
p, _ = s.accept()
c.sendall(b'ok')
assert p.recv(2) == b'ok'
"#;
let command = vec![
"/usr/bin/python3".to_string(),
"-c".to_string(),
script.to_string(),
socket.display().to_string(),
alias.display().to_string(),
unrelated.display().to_string(),
workspace.path().display().to_string(),
];
let policy = FileSystemSandboxPolicy::workspace_write(
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
/*exclude_tmpdir_env_var*/ false,
/*exclude_slash_tmp*/ false,
);
let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
command,
file_system_sandbox_policy: &policy,
network_sandbox_policy: NetworkSandboxPolicy::Enabled,
sandbox_policy_cwd: workspace.path(),
enforce_managed_network: false,
managed_network: None,
environment_id: None,
network: None,
extra_allow_unix_sockets: &[AbsolutePathBuf::from_absolute_path(root).unwrap()],
})
.unwrap();
let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE)
.args(args)
.env("CODEX_HOME", workspace.path())
.output()
.unwrap();
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}

View File

@@ -0,0 +1,256 @@
//! Exercise mutating fcntls through read-only descriptors in actual Seatbelt children.
#![cfg(target_os = "macos")]
use super::CreateSeatbeltCommandArgsParams;
use super::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use super::create_seatbelt_command_args;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use pretty_assertions::assert_eq;
use std::fs;
use std::fs::File;
use std::io;
use std::mem::size_of_val;
use std::os::fd::AsRawFd;
use std::os::macos::fs::MetadataExt;
use std::path::Path;
use std::process::Command;
const F_MAKECOMPRESSED: libc::c_int = 80;
const FIXTURE_ENV: &str = "CODEX_SEATBELT_FCNTL_FIXTURE";
const EXPECTATION_ENV: &str = "CODEX_SEATBELT_FCNTL_EXPECTATION";
const TRANSFER_UNSUPPORTED: &str = "F_TRANSFEREXTENTS positive control unsupported";
const FILES: [&str; 3] = ["canary", "workspace/donor", "receiver"];
#[derive(Debug, PartialEq, Eq)]
struct Snapshot {
bytes: Vec<u8>,
blocks: u64,
flags: u32,
modified: (i64, i64),
changed: (i64, i64),
}
fn snapshots(directory: &Path) -> Vec<Snapshot> {
FILES
.iter()
.map(|name| {
let path = directory.join(name);
let metadata = fs::metadata(&path).expect("canary metadata");
Snapshot {
bytes: fs::read(path).expect("canary contents"),
blocks: metadata.st_blocks(),
flags: metadata.st_flags(),
modified: (metadata.st_mtime(), metadata.st_mtime_nsec()),
changed: (metadata.st_ctime(), metadata.st_ctime_nsec()),
}
})
.collect()
}
#[test]
fn restricted_policies_deny_mutating_fcntls_through_read_only_descriptors() {
let policies = [
("allow", FileSystemSandboxPolicy::unrestricted()),
("deny", FileSystemSandboxPolicy::read_only()),
(
"deny",
FileSystemSandboxPolicy::workspace_write(
&[],
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
),
),
];
for (expectation, policy) in policies {
let fixture = tempfile::tempdir().expect("fixture directory");
let workspace = fixture.path().join("workspace");
fs::create_dir(&workspace).expect("workspace directory");
fs::write(fixture.path().join(FILES[0]), b"outside sandbox canary\n")
.expect("compression canary");
fs::write(fixture.path().join(FILES[2]), []).expect("extent receiver");
// Retain the parent's CLOEXEC descriptor until verification so closing
// the child cannot discard the donor's unused preallocation.
let donor = File::create(fixture.path().join(FILES[1])).expect("extent donor");
{
let mut allocation = libc::fstore_t {
fst_flags: libc::F_ALLOCATEALL,
fst_posmode: libc::F_PEOFPOSMODE,
fst_offset: 0,
fst_length: 65536,
fst_bytesalloc: 0,
};
// SAFETY: the variadic argument points to a live fstore_t for F_PREALLOCATE.
let result =
unsafe { libc::fcntl(donor.as_raw_fd(), libc::F_PREALLOCATE, &raw mut allocation) };
assert_eq!(
result,
0,
"preallocate donor: {}",
io::Error::last_os_error()
);
}
let before = snapshots(fixture.path());
assert!(
before[1].blocks > 0,
"control needs allocated extents beyond EOF"
);
let module = module_path!().split_once("::").expect("test module path").1;
let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
command: vec![
std::env::current_exe()
.expect("test executable")
.to_string_lossy()
.into_owned(),
"--exact".into(),
format!("{module}::fcntl_child"),
"--ignored".into(),
"--nocapture".into(),
],
file_system_sandbox_policy: &policy,
network_sandbox_policy: NetworkSandboxPolicy::Restricted,
sandbox_policy_cwd: &workspace,
enforce_managed_network: false,
managed_network: None,
environment_id: None,
network: None,
extra_allow_unix_sockets: &[],
})
.expect("generated Seatbelt arguments");
let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE)
.args(args)
.current_dir(&workspace)
.env(FIXTURE_ENV, fixture.path())
.env(EXPECTATION_ENV, expectation)
.output()
.expect("run Seatbelt child");
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success()
&& stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted")
{
eprintln!("skipping fcntl regression: nested Seatbelt unavailable");
return;
}
assert!(output.status.success(), "{expectation}: {output:?}");
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("fcntl probes completed"));
let after = snapshots(fixture.path());
if expectation == "allow" {
assert!(after[0].bytes.is_empty(), "positive control must truncate");
if stdout.contains(TRANSFER_UNSUPPORTED) {
assert_eq!(
&after[1..],
&before[1..],
"unsupported transfer must preserve both files"
);
} else {
assert!(
after[1].blocks < before[1].blocks,
"positive control must move extents"
);
assert!(
after[2].blocks > before[2].blocks,
"receiver must gain extents"
);
}
} else {
assert_eq!(
after, before,
"restricted policy must preserve all canaries"
);
}
drop(donor);
}
}
#[test]
#[ignore]
fn fcntl_child() {
let Some(directory) = std::env::var_os(FIXTURE_ENV) else {
return;
};
let directory = Path::new(&directory);
let expectation = std::env::var(EXPECTATION_ENV).expect("expected fcntl result");
// The positive control uses writable descriptors so it still works if the
// OS independently fixes mutation through read-only descriptors.
let files = FILES.map(|name| {
fs::OpenOptions::new()
.read(true)
.write(expectation == "allow")
.open(directory.join(name))
.expect("canary descriptor")
});
let expected_mode = if expectation == "allow" {
libc::O_RDWR
} else {
libc::O_RDONLY
};
for file in &files {
// SAFETY: these fcntls need only the live descriptor and no variadic argument.
assert!(unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFD) } >= 0);
assert_eq!(
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL) } & libc::O_ACCMODE,
expected_mode
);
}
if expectation == "deny" {
let error = fs::OpenOptions::new()
.write(true)
.open(directory.join(FILES[0]))
.expect_err("outside canary must be read-only");
assert_eq!(error.raw_os_error(), Some(libc::EPERM));
}
let mut attributes = libc::attrlist {
bitmapcount: 5,
reserved: 0,
commonattr: libc::ATTR_CMN_GEN_COUNT,
volattr: 0,
dirattr: 0,
fileattr: 0,
forkattr: 0,
};
let mut generation = [0_u32; 2];
// SAFETY: both buffers have the layout and size requested by fgetattrlist.
let result = unsafe {
libc::fgetattrlist(
files[0].as_raw_fd(),
(&raw mut attributes).cast(),
generation.as_mut_ptr().cast(),
size_of_val(&generation),
libc::FSOPT_ATTR_CMN_EXTENDED,
)
};
assert_eq!(
result,
0,
"generation query: {}",
io::Error::last_os_error()
);
assert_eq!(generation[0] as usize, size_of_val(&generation));
for (descriptor, selector, argument) in [
(files[0].as_raw_fd(), F_MAKECOMPRESSED, generation[1]),
(
files[1].as_raw_fd(),
libc::F_TRANSFEREXTENTS,
files[2].as_raw_fd() as u32,
),
] {
// SAFETY: these selectors take numeric arguments and all descriptors remain live.
let result = unsafe { libc::fcntl(descriptor, selector, argument) };
let error = io::Error::last_os_error().raw_os_error();
match expectation.as_str() {
"allow"
if selector == libc::F_TRANSFEREXTENTS
&& result == -1
&& matches!(error, Some(libc::EINVAL) | Some(libc::ENOTSUP)) =>
{
println!("{TRANSFER_UNSUPPORTED}");
}
"allow" => assert_eq!(result, 0, "fcntl {selector}: {error:?}"),
"deny" => assert_eq!((result, error), (-1, Some(libc::EPERM)), "fcntl {selector}"),
_ => panic!("invalid fcntl expectation: {expectation}"),
}
}
println!("fcntl probes completed");
}

View File

@@ -0,0 +1,31 @@
; when network access is enabled, these policies are added after those in seatbelt_base_policy.sbpl
; proxy-specific allow rules are injected by codex-core based on environment.
; Ref https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/network.sb;drc=f8f264d5e4e7509c913f4c60c2639d15905a07e4
; allow only safe AF_SYSTEM sockets used for local platform services.
(allow system-socket
(require-all
(socket-domain AF_SYSTEM)
(socket-protocol 2)
)
)
(allow mach-lookup
; Used by platform helpers that resolve user directory locations.
(global-name "com.apple.bsd.dirhelper")
(global-name "com.apple.system.opendirectoryd.membership")
; Communicate with the security server for TLS certificate information.
(global-name "com.apple.SecurityServer")
(global-name "com.apple.networkd")
(global-name "com.apple.ocspd")
(global-name "com.apple.trustd.agent")
; Read network configuration.
(global-name "com.apple.SystemConfiguration.DNSConfiguration")
(global-name "com.apple.SystemConfiguration.configd")
)
(allow sysctl-read
(sysctl-name-regex #"^net.routetable")
)

View File

@@ -0,0 +1,88 @@
//! Exercise managed network restrictions in an actual Seatbelt child.
#![cfg(target_os = "macos")]
use super::CreateSeatbeltCommandArgsParams;
use super::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use super::create_seatbelt_command_args;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use std::net::TcpListener;
use std::net::TcpStream;
use std::net::UdpSocket;
use std::process::Command;
use std::time::Duration;
#[test]
fn managed_local_binding_does_not_allow_external_dns() {
let workspace = tempfile::tempdir().expect("temporary workspace");
let proxy = TcpListener::bind("127.0.0.1:0").expect("proxy listener");
let proxy_address = proxy.local_addr().expect("proxy address");
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![proxy_address.port()],
allow_local_binding: true,
..Default::default()
};
let module = module_path!().split_once("::").expect("test module path").1;
let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
command: vec![
std::env::current_exe()
.expect("test executable")
.to_string_lossy()
.into_owned(),
"--exact".into(),
format!("{module}::external_dns_child"),
"--ignored".into(),
"--nocapture".into(),
],
file_system_sandbox_policy: &FileSystemSandboxPolicy::read_only(),
network_sandbox_policy: NetworkSandboxPolicy::Enabled,
sandbox_policy_cwd: workspace.path(),
enforce_managed_network: true,
managed_network: Some(&managed_network),
environment_id: None,
network: None,
extra_allow_unix_sockets: &[],
})
.expect("generated Seatbelt arguments");
let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE)
.args(args)
.env("CODEX_TEST_DNS_PROXY_ADDRESS", proxy_address.to_string())
.output()
.expect("run managed DNS probe");
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success()
&& stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted")
{
eprintln!("skipping DNS regression: nested Seatbelt unavailable");
return;
}
assert!(output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("DNS probes completed"));
}
#[test]
#[ignore = "executed by the parent test inside Seatbelt"]
fn external_dns_child() {
let Ok(proxy_address) = std::env::var("CODEX_TEST_DNS_PROXY_ADDRESS") else {
return;
};
TcpStream::connect(proxy_address).expect("managed proxy remains reachable");
let socket = UdpSocket::bind("0.0.0.0:0").expect("local binding remains allowed");
// TEST-NET needs no live DNS service. UDP connect checks the destination
// permission without sending a DNS query or depending on a server reply.
let udp = socket.connect("192.0.2.1:53");
let tcp =
TcpStream::connect_timeout(&"192.0.2.1:53".parse().unwrap(), Duration::from_millis(100));
for error in [udp.err(), tcp.err()] {
assert!(
error.as_ref().is_some_and(|error| matches!(
error.raw_os_error(),
Some(libc::EPERM | libc::EACCES)
)),
"external DNS must be denied by Seatbelt, got {error:?}",
);
}
println!("DNS probes completed");
}

View File

@@ -0,0 +1,8 @@
; Preferences IPC can expose data outside the filesystem read roots.
; Include this policy only when filesystem reads are unrestricted.
(allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs."))
(allow mach-lookup
(global-name "com.apple.cfprefsd.daemon")
(global-name "com.apple.cfprefsd.agent")
(local-name "com.apple.cfprefsd.agent"))
(allow user-preference-read)

View File

@@ -0,0 +1,188 @@
; macOS platform defaults included when a split filesystem policy requests `:minimal`.
; Read access to standard system paths
(allow file-read* file-test-existence
(subpath "/Library/Apple")
(subpath "/Library/Filesystems/NetFSPlugins")
(subpath "/Library/Preferences/Logging")
(subpath "/private/var/db/DarwinDirectory/local/recordStore.data")
(subpath "/private/var/db/timezone")
(subpath "/usr/lib")
(subpath "/usr/share")
(subpath "/Library/Preferences")
(subpath "/var/db")
(subpath "/private/var/db"))
; Map system frameworks + dylibs for loader.
(allow file-map-executable
(subpath "/Library/Apple/System/Library/Frameworks")
(subpath "/Library/Apple/System/Library/PrivateFrameworks")
(subpath "/Library/Apple/usr/lib")
(subpath "/System/Library/Extensions")
(subpath "/System/Library/Frameworks")
(subpath "/System/Library/PrivateFrameworks")
(subpath "/System/Library/SubFrameworks")
(subpath "/System/iOSSupport/System/Library/Frameworks")
(subpath "/System/iOSSupport/System/Library/PrivateFrameworks")
(subpath "/System/iOSSupport/System/Library/SubFrameworks")
(subpath "/usr/lib"))
; System Framework and AppKit resources
(allow file-read* file-test-existence
(subpath "/Library/Apple/System/Library/Frameworks")
(subpath "/Library/Apple/System/Library/PrivateFrameworks")
(subpath "/Library/Apple/usr/lib")
(subpath "/System/Library/Frameworks")
(subpath "/System/Library/PrivateFrameworks")
(subpath "/System/Library/SubFrameworks")
(subpath "/System/iOSSupport/System/Library/Frameworks")
(subpath "/System/iOSSupport/System/Library/PrivateFrameworks")
(subpath "/System/iOSSupport/System/Library/SubFrameworks")
(subpath "/usr/lib"))
; Allow guarded vnodes.
(allow system-mac-syscall (mac-policy-name "vnguard"))
; Determine whether a container is expected.
(allow system-mac-syscall
(require-all
(mac-policy-name "Sandbox")
(mac-syscall-number 67)))
; Allow resolution of standard system symlinks.
(allow file-read-metadata file-test-existence
(literal "/etc")
(literal "/tmp")
(literal "/var")
(literal "/private/etc/localtime"))
; Allow stat'ing of firmlink parent path components.
(allow file-read-metadata file-test-existence
(path-ancestors "/System/Volumes/Data/private"))
; Allow processes to get their current working directory.
(allow file-read* file-test-existence
(literal "/"))
; Allow FSIOC_CAS_BSDFLAGS as alternate chflags.
(allow system-fsctl (fsctl-command FSIOC_CAS_BSDFLAGS))
; Allow access to standard special files.
(allow file-read* file-test-existence
(literal "/dev/autofs_nowait")
(literal "/dev/random")
(literal "/dev/urandom")
(literal "/private/etc/master.passwd")
(literal "/private/etc/passwd")
(literal "/private/etc/protocols")
(literal "/private/etc/services"))
; Allow null/zero read/write.
(allow file-read* file-test-existence file-write-data
(literal "/dev/null")
(literal "/dev/zero"))
; Allow read/write access to the file descriptors.
(allow file-read-data file-test-existence file-write-data
(subpath "/dev/fd"))
; Provide access to debugger helpers.
(allow file-read* file-test-existence file-write-data file-ioctl
(literal "/dev/dtracehelper"))
; Allow reading standard config directories.
(allow file-read* (subpath "/etc"))
(allow file-read* (subpath "/private/etc"))
(allow file-read* file-test-existence
(literal "/System/Library/CoreServices")
(literal "/System/Library/CoreServices/.SystemVersionPlatform.plist")
(literal "/System/Library/CoreServices/SystemVersion.plist"))
; Some processes read /var metadata during startup.
(allow file-read-metadata (subpath "/var"))
(allow file-read-metadata (subpath "/private/var"))
; IOKit access for root domain services.
(allow iokit-open
(iokit-registry-entry-class "RootDomainUserClient"))
; macOS Standard library queries opendirectoryd at startup
(allow mach-lookup (global-name "com.apple.system.opendirectoryd.libinfo"))
; Allow IPC to analytics, logging, trust, and other system agents.
(allow mach-lookup
(global-name "com.apple.analyticsd")
(global-name "com.apple.analyticsd.messagetracer")
(global-name "com.apple.appsleep")
(global-name "com.apple.bsd.dirhelper")
(global-name "com.apple.diagnosticd")
(global-name "com.apple.dt.automationmode.reader")
(global-name "com.apple.espd")
(global-name "com.apple.logd")
(global-name "com.apple.logd.events")
(global-name "com.apple.secinitd")
(global-name "com.apple.system.DirectoryService.libinfo_v1")
(global-name "com.apple.system.logger")
(global-name "com.apple.system.notification_center")
(global-name "com.apple.system.opendirectoryd.membership")
(global-name "com.apple.trustd")
(global-name "com.apple.trustd.agent")
(global-name "com.apple.xpc.activity.unmanaged"))
; Allow IPC to the syslog socket for logging.
(allow network-outbound (literal "/private/var/run/syslog"))
; macOS Notifications
(allow ipc-posix-shm-read*
(ipc-posix-name "apple.shm.notification_center"))
; Regulatory domain support.
(allow file-read*
(literal "/private/var/db/eligibilityd/eligibility.plist"))
; Audio and power management services.
(allow mach-lookup (global-name "com.apple.audio.audiohald"))
(allow mach-lookup (global-name "com.apple.audio.AudioComponentRegistrar"))
(allow mach-lookup (global-name "com.apple.PowerManagement.control"))
; Allow reading the minimum system runtime so exec works.
(allow file-read-data (subpath "/bin"))
(allow file-read-metadata (subpath "/bin"))
(allow file-read-data (subpath "/sbin"))
(allow file-read-metadata (subpath "/sbin"))
(allow file-read-data (subpath "/usr/bin"))
(allow file-read-metadata (subpath "/usr/bin"))
(allow file-read-data (subpath "/usr/sbin"))
(allow file-read-metadata (subpath "/usr/sbin"))
(allow file-read-data (subpath "/usr/libexec"))
(allow file-read-metadata (subpath "/usr/libexec"))
(allow file-read* (subpath "/Library/Preferences"))
(allow file-read* (subpath "/opt/homebrew/lib"))
(allow file-read* (subpath "/usr/local/lib"))
; Terminal basics and device handles.
(allow file-read* (regex "^/dev/fd/(0|1|2)$"))
(allow file-write* (regex "^/dev/fd/(1|2)$"))
(allow file-read* file-write* (literal "/dev/null"))
(allow file-read* file-write* (literal "/dev/tty"))
(allow file-read-metadata (literal "/dev"))
(allow file-read-metadata (regex "^/dev/.*$"))
(allow file-read-metadata (literal "/dev/stdin"))
(allow file-read-metadata (literal "/dev/stdout"))
(allow file-read-metadata (literal "/dev/stderr"))
(allow file-read-metadata (regex "^/dev/tty[^/]*$"))
(allow file-read-metadata (regex "^/dev/pty[^/]*$"))
(allow file-read* file-write* (regex "^/dev/ttys[0-9]+$"))
(allow file-read* file-write* (literal "/dev/ptmx"))
(allow file-ioctl (regex "^/dev/ttys[0-9]+$"))
; Allow metadata traversal for firmlink parents.
(allow file-read-metadata (literal "/System/Volumes") (vnode-type DIRECTORY))
(allow file-read-metadata (literal "/System/Volumes/Data") (vnode-type DIRECTORY))
(allow file-read-metadata (literal "/System/Volumes/Data/Users") (vnode-type DIRECTORY))
; App sandbox extensions
(allow file-read* (extension "com.apple.app-sandbox.read"))
(allow file-read* file-write* (extension "com.apple.app-sandbox.read-write"))

View File

@@ -0,0 +1,80 @@
//! Lower implicit process scratch access through the normal Seatbelt exclusions.
//! Explicit restrictions and project metadata also constrain these broad grants.
use super::SeatbeltAccessRoot;
use super::SeatbeltPreparationError;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::PROTECTED_METADATA_PATH_NAMES;
use codex_protocol::permissions::ResolvedFileSystemPermissions;
use codex_protocol::protocol::WritableRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::path::Path;
pub(super) fn scratch_access_roots(
policy: &FileSystemSandboxPolicy,
cwd: &Path,
filesystem: &ResolvedFileSystemPermissions,
) -> Result<(Vec<SeatbeltAccessRoot>, Vec<WritableRoot>), SeatbeltPreparationError> {
let mut read_only = filesystem
.readable_roots
.iter()
.filter(|path| !policy.can_write_local_path_with_cwd(path.as_path(), cwd))
.cloned()
.collect::<Vec<_>>();
read_only.extend(filesystem.unreadable_roots.iter().cloned());
for root in &filesystem.writable_roots {
read_only.extend(root.read_only_subpaths.iter().cloned());
read_only.extend(
root.protected_metadata_names
.iter()
.map(|name| root.root.join(name)),
);
}
// Use the physical paths: /tmp and /var are trusted system aliases, and
// the normal lowerer binds both roots and exclusions in that namespace.
let scratch_paths = ["/private/tmp", "/private/var/tmp"]
.into_iter()
.map(AbsolutePathBuf::from_absolute_path)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| SeatbeltPreparationError::FileSystem(error.to_string()))?;
let mut scratch_policy = policy.clone();
scratch_policy.entries.extend(
scratch_paths.iter().map(|path| {
FileSystemSandboxEntry::new(path.clone().into(), FileSystemAccessMode::Write)
}),
);
let writes = scratch_policy
.get_writable_roots_with_cwd_preserving_mutable_paths(cwd)
.into_iter()
.filter(|root| scratch_paths.contains(&root.root))
.map(|mut root| {
// Retain normal logical-path exclusions (including symlink inodes).
// Explicit restrictions at or above a scratch root, and metadata
// belonging to narrower project roots, also constrain the default.
root.read_only_subpaths.extend(read_only.iter().cloned());
for name in PROTECTED_METADATA_PATH_NAMES {
if !root
.protected_metadata_names
.iter()
.any(|existing| existing == name)
&& !policy.can_write_local_path_with_cwd(root.root.join(*name).as_path(), cwd)
{
root.protected_metadata_names.push((*name).to_string());
}
}
root
})
.collect();
let reads = scratch_paths
.into_iter()
.map(|root| SeatbeltAccessRoot {
root,
excluded_subpaths: filesystem.unreadable_roots.clone(),
protected_metadata_names: Vec::new(),
})
.collect();
Ok((reads, writes))
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,237 @@
//! Check TLS trust-service access in applied Seatbelt policies without external network dependencies.
#![cfg(target_os = "macos")]
use super::CreateSeatbeltCommandArgsParams;
use super::MACOS_PATH_TO_SEATBELT_EXECUTABLE;
use super::create_seatbelt_command_args;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::net::TcpListener;
use std::net::TcpStream;
use std::process::Command;
use std::time::Duration;
const EXPECTATION_ENV: &str = "CODEX_SEATBELT_TLS_EXPECTATION";
const PROXY_ADDRESS_ENV: &str = "CODEX_SEATBELT_TLS_PROXY_ADDRESS";
const OTHER_ADDRESS_ENV: &str = "CODEX_SEATBELT_TLS_OTHER_ADDRESS";
const SANDBOX_FILTER_GLOBAL_NAME: libc::c_int = 2;
// These symbols are exported by libSystem, which Rust already links on macOS.
unsafe extern "C" {
static SANDBOX_CHECK_NO_REPORT: libc::c_int;
fn sandbox_check(
pid: libc::pid_t,
operation: *const libc::c_char,
filter: libc::c_int,
...
) -> libc::c_int;
}
#[test]
fn trust_evaluation_agent_access_follows_network_policy() {
let workspace = tempfile::tempdir().expect("temporary workspace");
let proxy = TcpListener::bind("127.0.0.1:0").expect("proxy listener");
let other = TcpListener::bind("127.0.0.1:0").expect("unapproved listener");
let proxy_address = proxy.local_addr().expect("proxy address");
let other_address = other.local_addr().expect("unapproved address");
let unix_sockets = [
AbsolutePathBuf::from_absolute_path(workspace.path().join("service.sock"))
.expect("absolute Unix socket path"),
];
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![proxy_address.port()],
..Default::default()
};
let missing_endpoint = ManagedNetworkSandboxContext::default();
let unix_only = ManagedNetworkSandboxContext {
allow_unix_sockets: vec![unix_sockets[0].to_string_lossy().into_owned()],
..Default::default()
};
let all_unix_sockets = ManagedNetworkSandboxContext {
dangerously_allow_all_unix_sockets: true,
..Default::default()
};
let local_binding = ManagedNetworkSandboxContext {
allow_local_binding: true,
..Default::default()
};
let module = module_path!().split_once("::").expect("test module path").1;
for (name, network_policy, managed_network, extra_unix_sockets, expectation) in [
(
"disabled",
NetworkSandboxPolicy::Restricted,
None,
&[][..],
"deny",
),
(
"enabled",
NetworkSandboxPolicy::Enabled,
None,
&[][..],
"allow",
),
(
"managed-proxy",
NetworkSandboxPolicy::Restricted,
Some(&managed_network),
&[][..],
"proxy",
),
(
"managed-proxy-overrides-enabled",
NetworkSandboxPolicy::Enabled,
Some(&managed_network),
&[][..],
"proxy",
),
(
"missing-endpoint",
NetworkSandboxPolicy::Restricted,
Some(&missing_endpoint),
&[][..],
"deny",
),
(
"missing-endpoint-overrides-enabled",
NetworkSandboxPolicy::Enabled,
Some(&missing_endpoint),
&[][..],
"deny",
),
(
"unix-only",
NetworkSandboxPolicy::Restricted,
None,
unix_sockets.as_slice(),
"deny",
),
(
"managed-unix-only",
NetworkSandboxPolicy::Restricted,
Some(&unix_only),
&[][..],
"deny",
),
(
"all-unix-sockets",
NetworkSandboxPolicy::Restricted,
Some(&all_unix_sockets),
&[][..],
"deny",
),
(
"local-binding",
NetworkSandboxPolicy::Restricted,
Some(&local_binding),
&[][..],
"allow",
),
(
"enabled-with-unix-socket",
NetworkSandboxPolicy::Enabled,
None,
unix_sockets.as_slice(),
"allow",
),
] {
let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
command: vec![
std::env::current_exe()
.expect("test executable")
.to_string_lossy()
.into_owned(),
"--exact".into(),
format!("{module}::trust_evaluation_agent_child"),
"--ignored".into(),
"--nocapture".into(),
],
file_system_sandbox_policy: &FileSystemSandboxPolicy::read_only(),
network_sandbox_policy: network_policy,
sandbox_policy_cwd: workspace.path(),
enforce_managed_network: managed_network.is_some(),
managed_network,
environment_id: None,
network: None,
extra_allow_unix_sockets: extra_unix_sockets,
})
.expect("generated Seatbelt arguments");
let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE)
.args(args)
.current_dir(workspace.path())
.env(EXPECTATION_ENV, expectation)
.env(PROXY_ADDRESS_ENV, proxy_address.to_string())
.env(OTHER_ADDRESS_ENV, other_address.to_string())
.output()
.expect("run Seatbelt trust-service probe");
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success()
&& stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted")
{
eprintln!("skipping trust-service regression: nested Seatbelt unavailable");
return;
}
assert!(output.status.success(), "{name}: {output:?}");
assert!(
String::from_utf8_lossy(&output.stdout).contains("trust-service probes completed"),
"{name}: child must execute the probes: {output:?}"
);
}
}
#[test]
#[ignore]
fn trust_evaluation_agent_child() {
let Ok(expectation) = std::env::var(EXPECTATION_ENV) else {
return;
};
let expected = match expectation.as_str() {
"allow" => ([true, false], [true, true]),
"proxy" => ([true, false], [true, false]),
"deny" => ([false, false], [false, false]),
_ => panic!("invalid trust-service expectation: {expectation}"),
};
// Query the applied policy, independent of whether the OS currently runs this service.
let access = [
c"com.apple.TrustEvaluationAgent",
c"com.apple.TrustEvaluationAgent.unrelated",
]
.map(|service| {
// SAFETY: GLOBAL_NAME takes one NUL-terminated service name; all pointers remain live.
let result = unsafe {
sandbox_check(
libc::getpid(),
c"mach-lookup".as_ptr(),
SANDBOX_FILTER_GLOBAL_NAME | SANDBOX_CHECK_NO_REPORT,
service.as_ptr(),
)
};
assert!(
result >= 0,
"sandbox_check failed for {service:?}: {result}"
);
result == 0
});
let connections = [PROXY_ADDRESS_ENV, OTHER_ADDRESS_ENV].map(|key| {
let address = std::env::var(key)
.expect("listener address")
.parse()
.expect("valid socket address");
match TcpStream::connect_timeout(&address, Duration::from_secs(1)) {
Ok(_) => true,
Err(error) => {
assert!(
matches!(error.raw_os_error(), Some(libc::EPERM | libc::EACCES)),
"expected sandbox denial connecting to {address}: {error}"
);
false
}
}
});
assert_eq!((access, connections), expected);
println!("trust-service probes completed");
}

View File

@@ -0,0 +1,142 @@
use std::collections::HashMap;
use std::path::Path;
use anyhow::Context;
use anyhow::Result;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_pty::SpawnedProcess;
use codex_utils_pty::TerminalSize;
use crate::SandboxType;
use crate::WindowsSandboxFilesystemOverrides;
use crate::WindowsSandboxProxySettingsMode;
use crate::terminal_queries::respond_to_terminal_queries;
/// Windows-specific inputs for an executor-native process spawn.
// TODO(anp): Reconcile the Windows backend copy with the supplied sandbox
// context (TurnEnvironment::sandbox_context for turns), preserving this launch snapshot.
pub struct WindowsSandboxSpawnRequest<'a> {
pub permission_profile: &'a PermissionProfile,
pub workspace_roots: &'a [AbsolutePathBuf],
pub windows_sandbox_level: WindowsSandboxLevel,
pub proxy_enforced: bool,
pub network_proxy_restricting_sid: Option<&'a str>,
pub proxy_settings_mode: WindowsSandboxProxySettingsMode,
pub filesystem_overrides: Option<&'a WindowsSandboxFilesystemOverrides>,
}
/// Executor-native process launch request shared by local and exec-server execution.
pub struct SpawnRequest<'a> {
pub command: &'a [String],
pub cwd: &'a Path,
pub env: &'a HashMap<String, String>,
pub arg0: &'a Option<String>,
pub sandbox: SandboxType,
pub windows_sandbox: Option<WindowsSandboxSpawnRequest<'a>>,
pub tty: bool,
pub stdin_open: bool,
pub inherited_fds: codex_utils_pty::ChildFds<'a>,
}
/// Spawn a process using the backend selected by the prepared sandbox request.
#[tracing::instrument(name = "codex.process.spawn", skip_all)]
pub async fn spawn_process(request: SpawnRequest<'_>) -> Result<SpawnedProcess> {
let tty = request.tty;
let finish_spawn = |spawned| {
if tty {
respond_to_terminal_queries(spawned)
} else {
spawned
}
};
if request.sandbox == SandboxType::WindowsRestrictedToken {
#[cfg(target_os = "windows")]
{
let windows = request
.windows_sandbox
.context("missing Windows sandbox spawn request")?;
let codex_home = codex_utils_home_dir::find_codex_home()
.context("windows sandbox: failed to resolve codex_home")?;
let empty_paths = &[];
let overrides = windows.filesystem_overrides;
return codex_windows_sandbox::spawn_windows_sandbox_session_for_level(
codex_windows_sandbox::WindowsSandboxSessionRequest {
permission_profile: windows.permission_profile,
workspace_roots: windows.workspace_roots,
codex_home: codex_home.as_path(),
command: request.command.to_vec(),
cwd: request.cwd,
env_map: request.env.clone(),
windows_sandbox_level: windows.windows_sandbox_level,
proxy_enforced: windows.proxy_enforced,
network_proxy_restricting_sid: windows
.network_proxy_restricting_sid
.map(str::to_owned),
proxy_settings_mode: windows.proxy_settings_mode,
timeout_ms: None,
read_roots_override: overrides
.and_then(|value| value.read_roots_override.as_deref()),
read_roots_include_platform_defaults: overrides
.is_some_and(|value| value.read_roots_include_platform_defaults),
write_roots_override: overrides
.and_then(|value| value.write_roots_override.as_deref()),
deny_read_paths_override: overrides.map_or(empty_paths, |value| {
value.additional_deny_read_paths.as_slice()
}),
deny_write_paths_override: overrides.map_or(empty_paths, |value| {
value.additional_deny_write_paths.as_slice()
}),
tty: request.tty,
stdin_open: request.stdin_open,
},
)
.await
.map(finish_spawn);
}
#[cfg(not(target_os = "windows"))]
anyhow::bail!("Windows sandbox process spawn is unavailable on this platform");
}
let (program, args) = request
.command
.split_first()
.context("missing program for process spawn")?;
let spawned = if tty {
codex_utils_pty::pty::spawn_process(
program,
args,
request.cwd,
request.env,
request.arg0,
TerminalSize::default(),
request.inherited_fds,
)
.await
} else if request.stdin_open {
codex_utils_pty::pipe::spawn_process(
program,
args,
request.cwd,
request.env,
request.arg0,
request.inherited_fds.as_slice(),
)
.await
} else {
codex_utils_pty::pipe::spawn_process_no_stdin(
program,
args,
request.cwd,
request.env,
request.arg0,
request.inherited_fds.as_slice(),
)
.await
};
spawned.map(finish_spawn)
}

View File

@@ -0,0 +1,104 @@
//! Answer a bounded set of blocking terminal queries without emulating a terminal.
use codex_utils_pty::SpawnedProcess;
use tokio::sync::mpsc;
// Each pair contains the query bytes and the response to write to stdin.
const QUERY_RESPONSES: [(&[u8], &[u8]); 3] = [
// Device status report: report that the terminal is operating normally.
(b"\x1b[5n", b"\x1b[0n"),
// Window-size query: report a 24-row, 80-column text area.
(b"\x1b[18t", b"\x1b[8;24;80t"),
// Cursor-position report: return row 1, column 1.
(b"\x1b[6n", b"\x1b[1;1R"),
];
const MAX_MODE_DIGITS: usize = 10;
const MAX_QUERY_BYTES: usize = MAX_MODE_DIGITS + 5;
#[derive(Default)]
struct TerminalQueryResponder {
pending: Vec<u8>,
}
impl TerminalQueryResponder {
fn process(&mut self, bytes: Vec<u8>) -> (Vec<u8>, Vec<u8>) {
if self.pending.is_empty() && !bytes.contains(&b'\x1b') {
return (bytes, Vec::new());
}
let mut output = Vec::with_capacity(bytes.len());
let mut responses = Vec::new();
for byte in bytes {
if self.pending.is_empty() && byte != b'\x1b' {
output.push(byte);
continue;
}
if byte == b'\x1b' {
output.append(&mut self.pending);
}
self.pending.push(byte);
if self.pending.len() == 1
|| self.pending.as_slice() == b"\x1b["
|| self.pending[1] == b'['
&& !(0x40..=0x7e).contains(&byte)
&& self.pending.len() < MAX_QUERY_BYTES
{
continue;
}
if let Some((_, response)) = QUERY_RESPONSES
.iter()
.find(|(query, _)| *query == self.pending.as_slice())
{
responses.extend_from_slice(response);
} else if let [b'\x1b', b'[', b'?', mode @ .., b'$', b'p'] = self.pending.as_slice()
&& !mode.is_empty()
&& mode.len() <= MAX_MODE_DIGITS
&& mode.iter().all(u8::is_ascii_digit)
{
// DEC private-mode query: report the requested mode as unrecognized.
responses.extend_from_slice(b"\x1b[?");
responses.extend_from_slice(mode);
responses.extend_from_slice(b";0$y");
} else {
output.append(&mut self.pending);
}
self.pending.clear();
}
(output, responses)
}
}
pub(crate) fn respond_to_terminal_queries(mut spawned: SpawnedProcess) -> SpawnedProcess {
let response_tx = spawned.session.writer_sender().downgrade();
let (output_tx, output_rx) = mpsc::channel(128);
let mut raw_output_rx = std::mem::replace(&mut spawned.stdout_rx, output_rx);
tokio::spawn(async move {
let mut responder = TerminalQueryResponder::default();
while let Some(bytes) = raw_output_rx.recv().await {
let (output, responses) = responder.process(bytes);
if !responses.is_empty()
&& let Some(writer) = response_tx.upgrade()
{
let _ = writer.send(responses).await;
}
if !output.is_empty() {
let _ = output_tx.send(output).await;
}
}
if !responder.pending.is_empty() {
let _ = output_tx.send(responder.pending).await;
}
});
spawned
}
#[cfg(test)]
#[path = "terminal_queries_tests.rs"]
mod tests;

View File

@@ -0,0 +1,104 @@
#[cfg(unix)]
use std::path::Path;
use std::time::Duration;
use codex_utils_pty::ProcessDriver;
use codex_utils_pty::SpawnedProcess;
use codex_utils_pty::spawn_from_driver;
use pretty_assertions::assert_eq;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
use super::respond_to_terminal_queries;
#[cfg(unix)]
use crate::SandboxType;
#[cfg(unix)]
use crate::SpawnRequest;
#[cfg(unix)]
use crate::spawn_process;
#[tokio::test]
async fn driver_backed_terminal_queries_are_answered() -> anyhow::Result<()> {
let (writer_tx, mut writer_rx) = mpsc::channel(8);
let (stdout_tx, stdout_rx) = broadcast::channel(8);
let (exit_tx, exit_rx) = oneshot::channel();
let spawned = respond_to_terminal_queries(spawn_from_driver(ProcessDriver {
writer_tx,
stdout_rx,
stderr_rx: None,
exit_rx,
terminator: None,
writer_handle: None,
resizer: None,
#[cfg(windows)]
tty: true,
}));
let SpawnedProcess {
session: _session,
mut stdout_rx,
..
} = spawned;
stdout_tx.send(b"before\x1b[".to_vec())?;
stdout_tx.send(b"5n\x1b[18t\x1b[6n\x1b[?1049$p\x1b[31mafter".to_vec())?;
let responses = timeout(Duration::from_secs(2), writer_rx.recv())
.await?
.ok_or_else(|| anyhow::anyhow!("terminal response channel closed"))?;
assert_eq!(responses, b"\x1b[0n\x1b[8;24;80t\x1b[1;1R\x1b[?1049;0$y");
drop(stdout_tx);
exit_tx.send(0).expect("send exit code");
let output = timeout(Duration::from_secs(2), async move {
let mut output = Vec::new();
while let Some(chunk) = stdout_rx.recv().await {
output.extend(chunk);
}
output
})
.await?;
assert_eq!(output, b"before\x1b[31mafter".to_vec());
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn direct_terminal_queries_are_answered() -> anyhow::Result<()> {
let script =
"stty -echo -icanon; printf 'alpha\\033[6n'; dd bs=1 count=6 2>/dev/null; printf '\\nok'";
let command = vec!["/bin/sh".to_string(), "-c".to_string(), script.to_string()];
let env = std::env::vars().collect();
let spawned = spawn_process(SpawnRequest {
command: &command,
cwd: Path::new("."),
env: &env,
arg0: &None,
sandbox: SandboxType::None,
windows_sandbox: None,
tty: true,
stdin_open: true,
inherited_fds: codex_utils_pty::ChildFds::Inherited(&[]),
})
.await?;
let SpawnedProcess {
session: _session,
mut stdout_rx,
exit_rx,
..
} = spawned;
let (code, output) = timeout(Duration::from_secs(5), async move {
let code = exit_rx.await?;
let mut output = Vec::new();
while let Some(chunk) = stdout_rx.recv().await {
output.extend(chunk);
}
anyhow::Ok((code, output))
})
.await??;
assert_eq!((code, output), (0, b"alpha\x1b[1;1R\r\nok".to_vec()));
Ok(())
}

View File

@@ -0,0 +1,300 @@
use crate::SandboxType;
use codex_network_proxy::BlockedRequest;
use codex_network_proxy::NetworkMode;
use codex_protocol::exec_output::ExecToolCallOutput;
use tracing::warn;
#[cfg(unix)]
const EXIT_CODE_SIGNAL_BASE: i32 = 128;
const OUTPUT_SNIPPET_MAX_CHARS: usize = 512;
const SANDBOX_DENIED_KEYWORDS: [(FileSystemSandboxViolationReason, &str); 7] = [
(
FileSystemSandboxViolationReason::OperationNotPermitted,
"operation not permitted",
),
(
FileSystemSandboxViolationReason::PermissionDenied,
"permission denied",
),
(
FileSystemSandboxViolationReason::ReadOnlyFileSystem,
"read-only file system",
),
(FileSystemSandboxViolationReason::PolicyDenied, "seccomp"),
(FileSystemSandboxViolationReason::PolicyDenied, "sandbox"),
(FileSystemSandboxViolationReason::PolicyDenied, "landlock"),
(
FileSystemSandboxViolationReason::FailedToWriteFile,
"failed to write file",
),
];
// Quick rejects: well-known non-sandbox shell exit codes.
// 2: misuse of shell builtins
// 126: permission denied
// 127: command not found
const QUICK_REJECT_EXIT_CODES: [i32; 3] = [2, 126, 127];
/// A normalized sandbox violation observed by Codex sandbox enforcement.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SandboxViolationEvent {
FileSystem(FileSystemSandboxViolation),
Network(NetworkSandboxViolation),
}
/// Enforcement backend that observed a sandbox violation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SandboxViolationBackend {
LinuxSandbox,
ManagedNetworkProxy,
Seatbelt,
WindowsSandbox,
WindowsMxc,
}
impl SandboxViolationBackend {
pub const fn as_str(self) -> &'static str {
match self {
Self::LinuxSandbox => "linux_sandbox",
Self::ManagedNetworkProxy => "managed_network_proxy",
Self::Seatbelt => "seatbelt",
Self::WindowsSandbox => "windows_sandbox",
Self::WindowsMxc => "windows_mxc",
}
}
}
/// A filesystem sandbox denial inferred from a sandboxed process result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileSystemSandboxViolation {
pub backend: SandboxViolationBackend,
pub reason: FileSystemSandboxViolationReason,
pub path: Option<String>,
pub output_snippet: String,
}
/// Normalized reasons used when classifying filesystem sandbox denials.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileSystemSandboxViolationReason {
OperationNotPermitted,
PermissionDenied,
ReadOnlyFileSystem,
PolicyDenied,
FailedToWriteFile,
SignalSyscall,
}
impl FileSystemSandboxViolationReason {
pub const fn as_str(self) -> &'static str {
match self {
Self::OperationNotPermitted => "operation_not_permitted",
Self::PermissionDenied => "permission_denied",
Self::ReadOnlyFileSystem => "read_only_file_system",
Self::PolicyDenied => "policy_denied",
Self::FailedToWriteFile => "failed_to_write_file",
Self::SignalSyscall => "sigsys",
}
}
}
/// A network sandbox denial reported by the managed network proxy.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NetworkSandboxViolation {
pub backend: SandboxViolationBackend,
pub host: String,
pub reason: String,
pub client: Option<String>,
pub method: Option<String>,
pub mode: Option<NetworkMode>,
pub protocol: String,
pub decision: Option<String>,
pub source: Option<String>,
pub port: Option<u16>,
pub timestamp: i64,
}
impl NetworkSandboxViolation {
pub fn from_blocked_request(blocked: &BlockedRequest) -> Self {
Self {
backend: SandboxViolationBackend::ManagedNetworkProxy,
host: blocked.host.clone(),
reason: blocked.reason.clone(),
client: blocked.client.clone(),
method: blocked.method.clone(),
mode: blocked.mode,
protocol: blocked.protocol.clone(),
decision: blocked.decision.clone(),
source: blocked.source.clone(),
port: blocked.port,
timestamp: blocked.timestamp,
}
}
}
/// Classify a sandboxed process result as a filesystem sandbox violation.
fn classify_filesystem_sandbox_violation(
sandbox_type: SandboxType,
exec_output: &ExecToolCallOutput,
) -> Option<FileSystemSandboxViolation> {
if exec_output.exit_code == 0 {
return None;
}
let backend = match sandbox_type {
SandboxType::None => return None,
SandboxType::MacosSeatbelt => SandboxViolationBackend::Seatbelt,
SandboxType::LinuxSeccomp => SandboxViolationBackend::LinuxSandbox,
SandboxType::WindowsRestrictedToken => SandboxViolationBackend::WindowsSandbox,
SandboxType::WindowsMxc => SandboxViolationBackend::WindowsMxc,
};
if let Some((reason, output)) = filesystem_reason_from_output(exec_output) {
return Some(FileSystemSandboxViolation {
backend,
reason,
path: extract_denied_path_from_text(output),
output_snippet: output_snippet(output),
});
}
if QUICK_REJECT_EXIT_CODES.contains(&exec_output.exit_code) {
return None;
}
#[cfg(unix)]
{
if sandbox_type == SandboxType::LinuxSeccomp
&& exec_output.exit_code == EXIT_CODE_SIGNAL_BASE + libc::SIGSYS
{
return Some(FileSystemSandboxViolation {
backend,
reason: FileSystemSandboxViolationReason::SignalSyscall,
path: None,
output_snippet: [
&exec_output.stderr.text,
&exec_output.stdout.text,
&exec_output.aggregated_output.text,
]
.into_iter()
.find(|section| !section.trim().is_empty())
.map_or_else(String::new, |section| output_snippet(section)),
});
}
}
None
}
/// Record a filesystem sandbox violation, returning the classified event when one was found.
pub fn record_filesystem_sandbox_violation(
sandbox_type: SandboxType,
exec_output: &ExecToolCallOutput,
) -> Option<FileSystemSandboxViolation> {
let violation = classify_filesystem_sandbox_violation(sandbox_type, exec_output)?;
record_sandbox_violation(&SandboxViolationEvent::FileSystem(violation.clone()));
Some(violation)
}
/// Record a network sandbox violation from a managed-proxy blocked request.
pub fn record_network_sandbox_violation(blocked: &BlockedRequest) -> NetworkSandboxViolation {
let violation = NetworkSandboxViolation::from_blocked_request(blocked);
record_sandbox_violation(&SandboxViolationEvent::Network(violation.clone()));
violation
}
/// Emit a sandbox violation to the tracing stack.
pub fn record_sandbox_violation(event: &SandboxViolationEvent) {
match event {
SandboxViolationEvent::FileSystem(violation) => {
let path = violation.path.as_deref().unwrap_or("unknown");
warn!(
"recorded sandbox violation: resource=filesystem backend={} reason={} path={}",
violation.backend.as_str(),
violation.reason.as_str(),
path
);
}
SandboxViolationEvent::Network(violation) => {
warn!(
"recorded sandbox violation: resource=network backend={} protocol={} host={} port={:?} reason={} method={:?} mode={:?} client={:?} decision={:?} source={:?}",
violation.backend.as_str(),
violation.protocol,
violation.host,
violation.port,
violation.reason,
violation.method,
violation.mode,
violation.client,
violation.decision,
violation.source
);
}
}
}
fn filesystem_reason_from_output(
exec_output: &ExecToolCallOutput,
) -> Option<(FileSystemSandboxViolationReason, &str)> {
[
&exec_output.stderr.text,
&exec_output.stdout.text,
&exec_output.aggregated_output.text,
]
.into_iter()
.find_map(|section| {
let section = section.as_str();
let lower = section.to_lowercase();
SANDBOX_DENIED_KEYWORDS
.iter()
.find_map(|(reason, needle)| lower.contains(needle).then_some(*reason))
.map(|reason| (reason, section))
})
}
fn extract_denied_path_from_text(text: &str) -> Option<String> {
const PATH_MARKERS: [&str; 3] = [
": operation not permitted",
": permission denied",
": read-only file system",
];
for line in text.lines() {
for marker in PATH_MARKERS {
let Some(marker_start) = line.match_indices(':').find_map(|(marker_start, _)| {
line.get(marker_start..)
.and_then(|suffix| suffix.get(..marker.len()))
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(marker))
.then_some(marker_start)
}) else {
continue;
};
let candidate_prefix = &line[..marker_start];
let candidate = candidate_prefix
.rsplit_once(": ")
.map_or(candidate_prefix, |(_, path)| path)
.trim()
.trim_matches('"')
.trim_matches('\'');
if candidate.starts_with('/')
|| candidate.starts_with("./")
|| candidate.starts_with("../")
{
return Some(candidate.to_string());
}
}
}
None
}
fn output_snippet(output: &str) -> String {
output
.trim()
.chars()
.take(OUTPUT_SNIPPET_MAX_CHARS)
.collect()
}
#[cfg(test)]
#[path = "violation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,237 @@
use super::*;
use codex_network_proxy::BlockedRequest;
use codex_network_proxy::BlockedRequestArgs;
use codex_network_proxy::NetworkMode;
use codex_protocol::exec_output::ExecToolCallOutput;
use codex_protocol::exec_output::StreamOutput;
use pretty_assertions::assert_eq;
use std::time::Duration;
fn make_exec_output(
exit_code: i32,
stdout: &str,
stderr: &str,
aggregated: &str,
) -> ExecToolCallOutput {
ExecToolCallOutput {
exit_code,
stdout: StreamOutput::new(stdout.to_string()),
stderr: StreamOutput::new(stderr.to_string()),
aggregated_output: StreamOutput::new(aggregated.to_string()),
duration: Duration::from_millis(1),
timed_out: false,
}
}
#[test]
fn classifies_legacy_denial_keywords() {
for keyword in [
"operation not permitted",
"permission denied",
"read-only file system",
"seccomp",
"sandbox",
"landlock",
"failed to write file",
] {
let output = make_exec_output(/*exit_code*/ 1, "", keyword, "");
assert!(
classify_filesystem_sandbox_violation(SandboxType::LinuxSeccomp, &output).is_some(),
"{keyword}"
);
}
}
#[test]
fn normalizes_backend_keywords_as_policy_denied() {
for keyword in ["seccomp", "sandbox", "landlock"] {
let output = make_exec_output(/*exit_code*/ 1, "", keyword, "");
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::LinuxSeccomp, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::LinuxSandbox,
reason: FileSystemSandboxViolationReason::PolicyDenied,
path: None,
output_snippet: keyword.to_string(),
})
);
}
}
#[test]
fn preserves_legacy_denial_ordering() {
let quick_reject_without_keyword =
make_exec_output(/*exit_code*/ 127, "", "command not found", "");
let quick_reject_with_keyword =
make_exec_output(/*exit_code*/ 127, "", "Permission denied", "");
let zero_exit_with_keyword =
make_exec_output(/*exit_code*/ 0, "", "Operation not permitted", "");
let non_sandbox_with_keyword =
make_exec_output(/*exit_code*/ 1, "", "Operation not permitted", "");
assert!(
classify_filesystem_sandbox_violation(
SandboxType::LinuxSeccomp,
&quick_reject_without_keyword
)
.is_none()
);
assert!(
classify_filesystem_sandbox_violation(
SandboxType::LinuxSeccomp,
&quick_reject_with_keyword
)
.is_some()
);
assert!(
classify_filesystem_sandbox_violation(SandboxType::LinuxSeccomp, &zero_exit_with_keyword)
.is_none()
);
assert!(
classify_filesystem_sandbox_violation(SandboxType::None, &non_sandbox_with_keyword)
.is_none()
);
}
#[test]
fn classifies_filesystem_violation_with_path() {
let output = make_exec_output(
/*exit_code*/ 1,
"",
"bash: /private/tmp/denied: Operation not permitted",
"",
);
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::MacosSeatbelt, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::Seatbelt,
reason: FileSystemSandboxViolationReason::OperationNotPermitted,
path: Some("/private/tmp/denied".to_string()),
output_snippet: "bash: /private/tmp/denied: Operation not permitted".to_string(),
})
);
}
#[test]
fn classifies_filesystem_violation_with_unicode_before_marker() {
let output = make_exec_output(
/*exit_code*/ 1,
"",
"bash: /private/tmp/\u{130}-denied: Operation not permitted",
"",
);
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::MacosSeatbelt, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::Seatbelt,
reason: FileSystemSandboxViolationReason::OperationNotPermitted,
path: Some("/private/tmp/\u{130}-denied".to_string()),
output_snippet: "bash: /private/tmp/\u{130}-denied: Operation not permitted"
.to_string(),
})
);
}
#[test]
fn classifies_filesystem_violation_from_aggregated_output() {
let output = make_exec_output(
/*exit_code*/ 101,
"",
"",
"cargo failed: Read-only file system when writing target",
);
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::MacosSeatbelt, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::Seatbelt,
reason: FileSystemSandboxViolationReason::ReadOnlyFileSystem,
path: None,
output_snippet: "cargo failed: Read-only file system when writing target".to_string(),
})
);
}
#[test]
fn keeps_output_snippet_on_the_stream_that_matched() {
let output = make_exec_output(
/*exit_code*/ 1,
"bash: /private/tmp/denied: Permission denied",
"unrelated warning",
"unrelated warning\nbash: /private/tmp/denied: Permission denied",
);
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::MacosSeatbelt, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::Seatbelt,
reason: FileSystemSandboxViolationReason::PermissionDenied,
path: Some("/private/tmp/denied".to_string()),
output_snippet: "bash: /private/tmp/denied: Permission denied".to_string(),
})
);
}
#[cfg(unix)]
#[test]
fn classifies_linux_sigsys_exit() {
let output = make_exec_output(
/*exit_code*/ EXIT_CODE_SIGNAL_BASE + libc::SIGSYS,
"",
"",
"",
);
assert_eq!(
classify_filesystem_sandbox_violation(SandboxType::LinuxSeccomp, &output),
Some(FileSystemSandboxViolation {
backend: SandboxViolationBackend::LinuxSandbox,
reason: FileSystemSandboxViolationReason::SignalSyscall,
path: None,
output_snippet: String::new(),
})
);
}
#[test]
fn does_not_classify_non_sandbox_mode() {
let output = make_exec_output(/*exit_code*/ 1, "", "Operation not permitted", "");
assert!(classify_filesystem_sandbox_violation(SandboxType::None, &output).is_none());
}
#[test]
fn converts_blocked_request_to_network_violation() {
let blocked = BlockedRequest::new(BlockedRequestArgs {
host: "example.com".to_string(),
reason: "not_allowed".to_string(),
client: Some("curl".to_string()),
method: Some("CONNECT".to_string()),
mode: Some(NetworkMode::Limited),
protocol: "https".to_string(),
decision: Some("block".to_string()),
source: Some("policy".to_string()),
port: Some(443),
});
assert_eq!(
NetworkSandboxViolation::from_blocked_request(&blocked),
NetworkSandboxViolation {
backend: SandboxViolationBackend::ManagedNetworkProxy,
host: "example.com".to_string(),
reason: "not_allowed".to_string(),
client: Some("curl".to_string()),
method: Some("CONNECT".to_string()),
mode: Some(NetworkMode::Limited),
protocol: "https".to_string(),
decision: Some("block".to_string()),
source: Some("policy".to_string()),
port: Some(443),
timestamp: blocked.timestamp,
}
);
}

View File

@@ -0,0 +1,410 @@
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemPolicyProjection;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::protocol::WritableRoot;
use codex_utils_absolute_path::AbsolutePathBuf;
use crate::SandboxType;
use crate::compatibility_sandbox_policy_for_permission_profile;
/// Resolved filesystem overrides for the Windows sandbox backends.
///
/// The elevated Windows backend consumes extra deny-read paths plus explicit
/// read and write roots during setup/refresh. The unelevated restricted-token
/// backend only consumes extra deny-write carveouts on top of the legacy
/// `WorkspaceWrite` allow set. Read-root overrides are layered on top of the
/// baseline helper roots that the elevated setup path needs to launch the
/// sandboxed command; split policies that opt into platform defaults carry
/// that explicitly with the override.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowsSandboxFilesystemOverrides {
pub read_roots_override: Option<Vec<PathBuf>>,
pub read_roots_include_platform_defaults: bool,
pub write_roots_override: Option<Vec<PathBuf>>,
pub additional_deny_read_paths: Vec<AbsolutePathBuf>,
pub additional_deny_write_paths: Vec<AbsolutePathBuf>,
}
impl WindowsSandboxFilesystemOverrides {
/// Resolve filesystem overrides for the selected Windows sandbox using the child's environment.
pub fn resolve(
sandbox: SandboxType,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &AbsolutePathBuf,
windows_sandbox_level: WindowsSandboxLevel,
workload_env: &HashMap<String, String>,
) -> Result<Option<Self>, String> {
let use_elevated = windows_sandbox_uses_elevated_backend(windows_sandbox_level);
if use_elevated {
resolve_windows_elevated_filesystem_overrides(
sandbox,
permission_profile,
sandbox_policy_cwd,
use_elevated,
workload_env,
)
} else {
resolve_windows_restricted_token_filesystem_overrides(
sandbox,
permission_profile,
sandbox_policy_cwd,
windows_sandbox_level,
)
}
}
}
pub fn windows_sandbox_uses_elevated_backend(sandbox_level: WindowsSandboxLevel) -> bool {
matches!(sandbox_level, WindowsSandboxLevel::Elevated)
}
pub fn permission_profile_supports_windows_restricted_token_sandbox(
permission_profile: &PermissionProfile,
) -> bool {
match permission_profile {
PermissionProfile::Managed { file_system, .. } => {
!file_system.to_sandbox_policy().has_full_disk_write_access()
}
PermissionProfile::Disabled | PermissionProfile::External { .. } => false,
}
}
pub fn resolve_windows_restricted_token_filesystem_overrides(
sandbox: SandboxType,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &AbsolutePathBuf,
windows_sandbox_level: WindowsSandboxLevel,
) -> std::result::Result<Option<WindowsSandboxFilesystemOverrides>, String> {
if sandbox != SandboxType::WindowsRestrictedToken
|| windows_sandbox_level == WindowsSandboxLevel::Elevated
{
return Ok(None);
}
let (mut file_system_sandbox_policy, network_sandbox_policy) =
permission_profile.to_runtime_permissions();
let needs_direct_runtime_enforcement = file_system_sandbox_policy
.needs_direct_runtime_enforcement(network_sandbox_policy, sandbox_policy_cwd);
if permission_profile_supports_windows_restricted_token_sandbox(permission_profile)
&& !needs_direct_runtime_enforcement
{
return Ok(None);
}
if !permission_profile_supports_windows_restricted_token_sandbox(permission_profile) {
let permission_profile_name = permission_profile_display_name(permission_profile);
return Err(format!(
"windows sandbox backend cannot enforce file_system={:?}, network={network_sandbox_policy:?}, permission_profile={permission_profile_name}; refusing to run unsandboxed",
file_system_sandbox_policy.kind,
));
}
// Windows protects existing metadata paths through the legacy writable root
// projection. Do not turn skip-missing entries into newly-created
// deny-write sentinels.
file_system_sandbox_policy.remove_skip_missing_path_entries();
// The restricted-token backend can still enforce split write restrictions,
// but its WRITE_RESTRICTED token does not make capability SID deny-read ACEs
// participate in read access checks. Read restrictions therefore require the
// elevated backend, even when the filesystem root remains readable.
if !windows_policy_has_root_read_access(&file_system_sandbox_policy, sandbox_policy_cwd) {
return Err(
"windows unelevated restricted-token sandbox cannot enforce split filesystem read restrictions directly; refusing to run unsandboxed"
.to_string(),
);
}
let resolved = file_system_sandbox_policy
.resolve_for_enforcement(sandbox_policy_cwd, FileSystemPolicyProjection::Native)
.map_err(|err| err.to_string())?;
let additional_deny_read_paths =
codex_windows_sandbox::expand_windows_deny_read_paths(&resolved, sandbox_policy_cwd)?;
if !additional_deny_read_paths.is_empty() {
return Err(
"windows unelevated restricted-token sandbox cannot enforce deny-read restrictions directly; refusing to run unsandboxed"
.to_string(),
);
}
let legacy_projection = compatibility_sandbox_policy_for_permission_profile(
permission_profile,
sandbox_policy_cwd.as_path(),
);
let legacy_writable_roots = legacy_projection.get_writable_roots_with_cwd(sandbox_policy_cwd);
let split_writable_roots = resolved.writable_roots;
let legacy_root_paths: BTreeSet<PathBuf> = legacy_writable_roots
.iter()
.map(|root| normalize_windows_override_path(root.root.as_path()))
.collect::<std::result::Result<_, _>>()?;
let split_root_paths: BTreeSet<PathBuf> = split_writable_roots
.iter()
.map(|root| normalize_windows_override_path(root.root.as_path()))
.collect::<std::result::Result<_, _>>()?;
if legacy_root_paths != split_root_paths {
return Err(
"windows unelevated restricted-token sandbox cannot enforce split writable root sets directly; refusing to run unsandboxed"
.to_string(),
);
}
if has_reopened_writable_descendant(&split_writable_roots) {
return Err(
"windows unelevated restricted-token sandbox cannot reopen writable descendants under read-only carveouts directly; refusing to run unsandboxed"
.to_string(),
);
}
let mut additional_deny_write_paths = BTreeSet::new();
for split_root in &split_writable_roots {
let split_root_path = normalize_windows_override_path(split_root.root.as_path())?;
let Some(legacy_root) = legacy_writable_roots.iter().find(|candidate| {
normalize_windows_override_path(candidate.root.as_path())
.is_ok_and(|candidate_path| candidate_path == split_root_path)
}) else {
return Err(
"windows unelevated restricted-token sandbox cannot enforce split writable root sets directly; refusing to run unsandboxed"
.to_string(),
);
};
for read_only_subpath in &split_root.read_only_subpaths {
if !legacy_root
.read_only_subpaths
.iter()
.any(|candidate| candidate == read_only_subpath)
{
additional_deny_write_paths.insert(normalize_windows_override_path(
read_only_subpath.as_path(),
)?);
}
}
}
if additional_deny_read_paths.is_empty() && additional_deny_write_paths.is_empty() {
return Ok(None);
}
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_override: None,
read_roots_include_platform_defaults: false,
write_roots_override: None,
additional_deny_read_paths,
additional_deny_write_paths: additional_deny_write_paths
.into_iter()
.map(|path| AbsolutePathBuf::from_absolute_path(path).map_err(|err| err.to_string()))
.collect::<std::result::Result<_, _>>()?,
}))
}
pub fn resolve_windows_elevated_filesystem_overrides(
sandbox: SandboxType,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &AbsolutePathBuf,
use_windows_elevated_backend: bool,
workload_env: &HashMap<String, String>,
) -> std::result::Result<Option<WindowsSandboxFilesystemOverrides>, String> {
if sandbox != SandboxType::WindowsRestrictedToken || !use_windows_elevated_backend {
return Ok(None);
}
let (mut file_system_sandbox_policy, network_sandbox_policy) =
permission_profile.to_runtime_permissions();
if !permission_profile_supports_windows_restricted_token_sandbox(permission_profile) {
let permission_profile_name = permission_profile_display_name(permission_profile);
return Err(format!(
"windows sandbox backend cannot enforce file_system={:?}, network={network_sandbox_policy:?}, permission_profile={permission_profile_name}; refusing to run unsandboxed",
file_system_sandbox_policy.kind,
));
}
// Windows protects existing metadata paths through the legacy writable root
// projection. Do not turn skip-missing entries into newly-created
// deny-write sentinels.
file_system_sandbox_policy.remove_skip_missing_path_entries();
#[cfg(target_os = "windows")]
codex_windows_sandbox::resolve_workload_temp_paths(
&mut file_system_sandbox_policy,
workload_env,
);
#[cfg(not(target_os = "windows"))]
let _ = workload_env;
let resolved = file_system_sandbox_policy
.resolve_for_enforcement(sandbox_policy_cwd, FileSystemPolicyProjection::Native)
.map_err(|err| err.to_string())?;
let additional_deny_read_paths =
codex_windows_sandbox::expand_windows_deny_read_paths(&resolved, sandbox_policy_cwd)?;
let split_writable_roots = resolved.writable_roots;
if has_reopened_writable_descendant(&split_writable_roots) {
return Err(
"windows elevated sandbox cannot reopen writable descendants under read-only carveouts directly; refusing to run unsandboxed"
.to_string(),
);
}
let needs_direct_runtime_enforcement = file_system_sandbox_policy
.needs_direct_runtime_enforcement(network_sandbox_policy, sandbox_policy_cwd);
let has_explicit_write_carveouts = split_writable_roots.iter().any(|writable_root| {
writable_root.read_only_subpaths.iter().any(|path| {
file_system_sandbox_policy.has_explicit_non_write_entry_for_local_path_with_cwd(
path.as_path(),
sandbox_policy_cwd,
)
})
});
let normalize_path = |path: PathBuf| dunce::canonicalize(&path).unwrap_or(path);
let legacy_projection = compatibility_sandbox_policy_for_permission_profile(
permission_profile,
sandbox_policy_cwd.as_path(),
);
let legacy_writable_roots = legacy_projection.get_writable_roots_with_cwd(sandbox_policy_cwd);
let legacy_root_paths: BTreeSet<PathBuf> = legacy_writable_roots
.iter()
.map(|root| normalize_path(root.root.to_path_buf()))
.collect();
let split_readable_roots: Vec<PathBuf> = resolved
.readable_roots
.into_iter()
.map(AbsolutePathBuf::into_path_buf)
.map(&normalize_path)
.collect();
let split_root_paths: Vec<PathBuf> = split_writable_roots
.iter()
.map(|root| normalize_path(root.root.to_path_buf()))
.collect();
let split_root_path_set: BTreeSet<PathBuf> = split_root_paths.iter().cloned().collect();
// `has_full_disk_read_access()` is intentionally false when deny-read
// entries exist. For Windows setup overrides, the important question is
// whether the baseline still reads from the filesystem root and only needs
// additional deny ACLs layered on top.
let split_has_root_read_access =
windows_policy_has_root_read_access(&file_system_sandbox_policy, sandbox_policy_cwd);
let read_roots_override = if split_has_root_read_access {
None
} else {
Some(split_readable_roots)
};
let write_roots_override = if split_root_path_set == legacy_root_paths {
None
} else {
Some(split_root_paths)
};
let additional_deny_write_paths = if needs_direct_runtime_enforcement
|| has_explicit_write_carveouts
{
let mut deny_paths = BTreeSet::new();
for writable_root in &split_writable_roots {
let writable_root_path = normalize_path(writable_root.root.to_path_buf());
let legacy_root = legacy_writable_roots.iter().find(|candidate| {
normalize_path(candidate.root.to_path_buf()) == writable_root_path
});
for read_only_subpath in &writable_root.read_only_subpaths {
let read_only_subpath_suffix = read_only_subpath
.as_path()
.strip_prefix(writable_root.root.as_path())
.ok();
let already_denied_by_legacy = legacy_root.is_some_and(|legacy_root| {
legacy_root.read_only_subpaths.iter().any(|candidate| {
candidate
.as_path()
.strip_prefix(legacy_root.root.as_path())
.ok()
== read_only_subpath_suffix
})
});
let explicitly_configured = file_system_sandbox_policy
.has_explicit_non_write_entry_for_local_path_with_cwd(
read_only_subpath.as_path(),
sandbox_policy_cwd,
);
if explicitly_configured || !already_denied_by_legacy {
deny_paths.insert(normalize_path(read_only_subpath.to_path_buf()));
}
}
}
deny_paths
.into_iter()
.map(|path| AbsolutePathBuf::from_absolute_path(path).map_err(|err| err.to_string()))
.collect::<std::result::Result<_, _>>()?
} else {
Vec::new()
};
if read_roots_override.is_none()
&& write_roots_override.is_none()
&& additional_deny_read_paths.is_empty()
&& additional_deny_write_paths.is_empty()
{
return Ok(None);
}
Ok(Some(WindowsSandboxFilesystemOverrides {
read_roots_include_platform_defaults: read_roots_override.is_some()
&& resolved.include_platform_defaults,
read_roots_override,
write_roots_override,
additional_deny_read_paths,
additional_deny_write_paths,
}))
}
fn normalize_windows_override_path(path: &Path) -> std::result::Result<PathBuf, String> {
AbsolutePathBuf::from_absolute_path(dunce::simplified(path))
.map(AbsolutePathBuf::into_path_buf)
.map_err(|err| err.to_string())
}
fn windows_policy_has_root_read_access(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
cwd: &AbsolutePathBuf,
) -> bool {
let Some(root) = cwd.as_path().ancestors().last() else {
return false;
};
file_system_sandbox_policy.can_read_local_path_with_cwd(root, cwd.as_path())
}
fn permission_profile_display_name(permission_profile: &PermissionProfile) -> &'static str {
match permission_profile {
PermissionProfile::Managed { .. } => "Managed",
PermissionProfile::Disabled => "Disabled",
PermissionProfile::External { .. } => "External",
}
}
fn has_reopened_writable_descendant(writable_roots: &[WritableRoot]) -> bool {
writable_roots.iter().any(|writable_root| {
writable_root
.read_only_subpaths
.iter()
.any(|read_only_subpath| {
writable_roots.iter().any(|candidate| {
candidate.root.as_path() != writable_root.root.as_path()
&& candidate
.root
.as_path()
.starts_with(read_only_subpath.as_path())
})
})
})
}
#[cfg(all(test, target_os = "windows"))]
#[path = "windows_tests.rs"]
mod tests;

View File

@@ -0,0 +1,22 @@
//! Native Windows MXC capability discovery and availability metrics.
//! Probing is cached upstream; reporting happens at most once per process.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
static AVAILABILITY_RECORDED: AtomicBool = AtomicBool::new(false);
pub(super) fn record_availability_once() {
// Probe actual PSEC create/close support; symbol presence alone also
// succeeds on transitional Windows builds where MXC is not enabled.
let available = codex_mxc_sandbox::is_available();
if let Some(metrics) = codex_otel::global()
&& !AVAILABILITY_RECORDED.swap(true, Ordering::Relaxed)
{
let _ = metrics.counter(
"codex.windows_mxc.available",
/*inc*/ 1,
&[("available", if available { "true" } else { "false" })],
);
}
}

View File

@@ -0,0 +1,58 @@
//! Windows temp override behavior not covered by a successful child launch.
use super::*;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use pretty_assertions::assert_eq;
#[test]
fn elevated_non_write_temp_never_grants_write_access() {
let dir = tempfile::TempDir::new().unwrap();
let cwd = AbsolutePathBuf::from_absolute_path(dir.path().join("work")).unwrap();
let temp = dir.path().join("temp");
std::fs::create_dir_all(cwd.as_path()).unwrap();
std::fs::create_dir_all(&temp).unwrap();
let env = HashMap::from([("Temp".into(), temp.to_string_lossy().into_owned())]);
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
let profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
access,
),
]),
NetworkSandboxPolicy::Restricted,
);
let overrides = resolve_windows_elevated_filesystem_overrides(
SandboxType::WindowsRestrictedToken,
&profile,
&cwd,
true,
&env,
)
.unwrap();
let write_roots = overrides
.as_ref()
.and_then(|o| o.write_roots_override.as_ref());
assert!(write_roots.is_none_or(Vec::is_empty));
if access == FileSystemAccessMode::Deny {
assert_eq!(
overrides.unwrap().additional_deny_read_paths,
vec![
AbsolutePathBuf::from_absolute_path(dunce::canonicalize(&temp).unwrap())
.unwrap(),
]
);
}
}
}