Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,87 @@
#![cfg(target_os = "linux")]
use akode_linux_sandbox::BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE;
use akode_protocol::models::PermissionProfile;
use akode_utils_cargo_bin::copy_executable;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
#[test]
fn bazel_build_rejects_tampered_bundled_bwrap() {
// Cargo embeds the bundled bwrap digest only in release builds.
if option_env!("BAZEL_PACKAGE").is_none() {
return;
}
let bwrap_runfile =
std::env::var("CARGO_BIN_EXE_bwrap").expect("Bazel should provide the bwrap runfile");
let runfiles_dir =
std::env::var_os("TEST_SRCDIR").expect("Bazel should provide its runfiles directory");
let bwrap_binary = PathBuf::from(runfiles_dir).join(bwrap_runfile);
let original_bwrap_bytes =
std::fs::read(&bwrap_binary).expect("built bwrap should be readable");
let package = tempfile::tempdir().expect("package directory should be created");
let resources = package.path().join("akode-resources");
std::fs::create_dir(&resources).expect("package resource directory should be created");
let sandbox_binary = package.path().join("akode-linux-sandbox");
copy_executable(
Path::new(env!("CARGO_BIN_EXE_codex-linux-sandbox")),
&sandbox_binary,
)
.expect("sandbox binary should be copied into the package");
let bundled_bwrap = resources.join("bwrap");
copy_executable(&bwrap_binary, &bundled_bwrap)
.expect("built bwrap should be copied into the package");
let permission_profile = serde_json::to_string(&PermissionProfile::read_only())
.expect("read-only permission profile should serialize");
let run_sandbox = || {
Command::new(&sandbox_binary)
.arg("--sandbox-policy-cwd")
.arg(package.path())
.arg("--permission-profile")
.arg(&permission_profile)
.arg("--no-proc")
.arg("--")
.arg("/bin/true")
.env_clear()
.env("PATH", package.path())
.output()
.expect("sandbox binary should start")
};
let original_output = run_sandbox();
assert_ne!(
original_output.status.code(),
Some(BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE),
"sandbox should accept the digest of the unmodified bundled bwrap"
);
std::fs::remove_file(&bundled_bwrap).expect("read-only bundled bwrap should be replaceable");
let mut tampered_bwrap_bytes = original_bwrap_bytes;
tampered_bwrap_bytes.push(0);
// Write data to a separate inode, then publish it through the descriptor-safe helper.
let tampered_data = package.path().join("tampered-bwrap-data");
std::fs::write(&tampered_data, &tampered_bwrap_bytes)
.expect("modified bwrap data should be written");
copy_executable(&tampered_data, &bundled_bwrap)
.expect("modified bwrap should be copied into the package");
let bwrap_permissions = std::fs::metadata(&bwrap_binary)
.expect("built bwrap metadata should be readable")
.permissions();
std::fs::set_permissions(&bundled_bwrap, bwrap_permissions)
.expect("bundled bwrap should remain executable");
let tampered_output = run_sandbox();
assert_eq!(
tampered_output.status.code(),
Some(BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE),
"sandbox should reject the tampered bundled bwrap"
);
}

View File

@@ -0,0 +1,134 @@
//! Writable PATH candidates must never run while constructing the sandbox.
#![cfg(target_os = "linux")]
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cargo_bin::cargo_bin;
use akode_utils_cargo_bin::write_executable;
use pretty_assertions::assert_eq;
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
#[test]
fn child_workdir_does_not_probe_or_launch_writable_parent_bwrap() {
// Bazel can mount the default temp directory noexec.
let temp = tempfile::tempdir_in(std::env::current_dir().expect("current directory"))
.or_else(|_| tempfile::tempdir())
.expect("create fixture");
let workspace = temp.path().join("workspace");
let cwd = workspace.join("service");
let bin = workspace.join("bin");
let marker = temp.path().join("outside-workspace");
std::fs::create_dir_all(&cwd).expect("create cwd");
std::fs::create_dir_all(&bin).expect("create bin");
let fake_bwrap = bin.join("bwrap");
std::fs::write(
&fake_bwrap,
"#!/bin/sh\n: > \"$BWRAP_PROBE_MARKER\"\nprintf '%s\\n' '--as-pid-1 --perms --argv0 --ro-bind-fd'\n",
)
.expect("write fake bwrap");
std::fs::set_permissions(&fake_bwrap, std::fs::Permissions::from_mode(0o755))
.expect("make fake bwrap executable");
let policy = PermissionProfile::read_only()
.file_system_sandbox_policy()
.with_additional_writable_roots(
&workspace,
&[AbsolutePathBuf::try_from(workspace.clone()).expect("absolute workspace")],
);
let profile =
PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted);
let profile_json = serde_json::to_string(&profile).expect("serialize profile");
let trusted_path = std::env::var_os("PATH").expect("PATH is set");
let run = |search_path: &std::ffi::OsStr, script: &str| {
Command::new(cargo_bin("akode-linux-sandbox").expect("resolve sandbox binary"))
.arg("--sandbox-policy-cwd")
.arg(&workspace)
.arg("--command-cwd")
.arg(&cwd)
.arg("--permission-profile")
.arg(&profile_json)
.args(["--", "/bin/sh", "-c", script])
.current_dir(&cwd)
.env("PATH", search_path)
.env("BWRAP_PROBE_MARKER", &marker)
.output()
.expect("run sandbox")
};
let baseline = run(&trusted_path, "printf sandboxed");
let stderr = String::from_utf8_lossy(&baseline.stderr);
if !baseline.status.success()
&& [
"bubblewrap is unavailable",
"No permissions to create a new namespace",
"setting up uid map: Permission denied",
]
.iter()
.any(|message| stderr.contains(message))
{
eprintln!(
"sandbox unavailable: {}",
String::from_utf8_lossy(&baseline.stderr)
);
return;
}
assert_eq!(baseline.status.success(), true, "{baseline:?}");
let denied_write = run(&trusted_path, ": > \"$BWRAP_PROBE_MARKER\"");
assert_eq!(denied_write.status.success(), false, "{denied_write:?}");
assert!(
!marker.exists(),
"sandbox must deny the outside-workspace write"
);
let hostile_path = std::env::join_paths(
[bin]
.into_iter()
.chain(std::env::split_paths(&trusted_path)),
)
.expect("join PATH");
let output = run(&hostile_path, "printf sandboxed");
assert!(!marker.exists(), "writable bwrap ran before confinement");
assert_eq!(output.status.success(), true, "{output:?}");
assert_eq!(output.stdout, b"sandboxed");
}
#[test]
fn full_disk_write_with_managed_network_does_not_probe_writable_bwrap() {
let temp = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();
let bin = temp.path().join("bin");
let cwd = temp.path().join("cwd");
std::fs::create_dir(&bin).unwrap();
std::fs::create_dir(&cwd).unwrap();
let bwrap = bin.join("bwrap");
write_executable(&bwrap, "#!/bin/sh\n: > \"$BWRAP_PROBE_MARKER\"\nexit 1\n").unwrap();
let run = |profile: &PermissionProfile, marker: &std::path::Path| {
Command::new(cargo_bin("akode-linux-sandbox").expect("resolve sandbox binary"))
.arg("--sandbox-policy-cwd")
.arg(&cwd)
.arg("--permission-profile")
.arg(serde_json::to_string(profile).unwrap())
.args(["--managed-network", "{}", "--", "/bin/true"])
.current_dir(&cwd)
.env_clear()
.env("PATH", &bin)
.env("HTTP_PROXY", "http://127.0.0.1:9")
.env("BWRAP_PROBE_MARKER", marker)
.output()
.unwrap()
};
// Confirm this host reaches the capability probe without needing working
// namespaces or bundled bubblewrap. Both invocations use managed networking.
let control_marker = temp.path().join("control");
let control = run(&PermissionProfile::read_only(), &control_marker);
assert!(
control_marker.exists(),
"probe was not reached: {control:?}"
);
let marker = temp.path().join("unrestricted");
let output = run(&PermissionProfile::Disabled, &marker);
assert!(
!marker.exists(),
"writable bwrap ran before network confinement: {output:?}"
);
}

View File

@@ -0,0 +1,359 @@
use super::*;
use pretty_assertions::assert_eq;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
#[tokio::test]
async fn private_tmp_mount_preserves_daemon_socket_isolation() {
if should_skip_bwrap_tests().await {
return;
}
// The parent owns cleanup after the child's disposable mount namespace exits.
let private = tempfile::tempdir_in("/tmp").unwrap();
let test_executable = std::env::current_exe().unwrap();
// Keep both executables available after the original /tmp is hidden.
akode_utils_cargo_bin::copy_executable(&test_executable, &private.path().join("test")).unwrap();
akode_utils_cargo_bin::copy_executable(
&codex_linux_sandbox_exe(),
&private.path().join("sandbox"),
)
.unwrap();
let (_, test_module) = module_path!().split_once("::").unwrap();
let fixture_test = format!("{test_module}::private_tmp_fixture");
// Mount setup needs capabilities, which bubblewrap only accepts as namespace root.
let output = tokio::process::Command::new("unshare")
.args([
"--user",
"--map-root-user",
"--mount",
"--propagation",
"private",
"--",
])
.arg(test_executable)
.args([
"--exact",
&fixture_test,
"--ignored",
"--nocapture",
"--test-threads=1",
])
.env("AKODE_TEST_PRIVATE_TMP", private.path())
.kill_on_drop(true)
.output()
.await
.unwrap();
if output.status.code() == Some(77)
|| String::from_utf8_lossy(&output.stderr).starts_with("unshare:")
{
eprintln!("skipping private tmp test: user/mount namespaces are unavailable");
return;
}
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-validated"));
}
#[test]
#[ignore = "invoked inside a disposable mount namespace"]
fn private_tmp_fixture() {
let Some(private) = std::env::var_os("AKODE_TEST_PRIVATE_TMP") else {
return;
};
let mount = std::process::Command::new("mount")
.arg("--bind")
.arg(private)
.arg("/tmp")
.output()
.unwrap();
if !mount.status.success() {
std::process::exit(/*code*/ 77);
}
// Namespace mounts have non-path roots such as `net:[inode]`. An unrelated
// one must not stop startup or disable the socket-isolation checks below.
let namespace = "/tmp/network-namespace";
std::fs::File::create(namespace).unwrap();
let mount = std::process::Command::new("mount")
.args(["--bind", "/proc/self/ns/net", namespace])
.output()
.unwrap();
assert!(mount.status.success(), "{mount:?}");
let root = akode_uds::prepare_shared_daemon_socket_directory().unwrap();
let endpoint = root.join("rpc.sock");
let _daemon = UnixListener::bind(&endpoint).unwrap();
let _other = UnixListener::bind("/tmp/other.sock").unwrap();
UnixStream::connect(&endpoint).expect("host can reach daemon");
let profile = PermissionProfile::workspace_write_with(
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
NetworkSandboxPolicy::Enabled,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let mut command = std::process::Command::new("/tmp/sandbox");
command
.args(["--sandbox-policy-cwd", "/tmp", "--permission-profile"])
.arg(serde_json::to_string(&profile).unwrap())
.arg("--")
.current_dir("/tmp");
let (_, test_module) = module_path!().split_once("::").unwrap();
let client_test = format!("{test_module}::private_tmp_client");
command
.args([
"/tmp/test",
"--exact",
&client_test,
"--ignored",
"--nocapture",
"--test-threads=1",
])
.env("AKODE_TEST_DAEMON_SOCKET", &endpoint)
.env("TMPDIR", "/tmp");
let output = command.output().unwrap();
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
// Devboxes expose their temporary volume through both /tmp and /build/tmp.
// An ancestor alias must receive the same socket mask without hiding other files.
std::fs::create_dir("/tmp/build").unwrap();
let mount = std::process::Command::new("mount")
.args(["--bind", "/tmp", "/tmp/build"])
.output()
.unwrap();
assert!(mount.status.success(), "{mount:?}");
let alias_endpoint = PathBuf::from("/tmp/build")
.join(root.file_name().unwrap())
.join("rpc.sock");
UnixStream::connect(&alias_endpoint).expect("host can reach ancestor alias");
command
.env("AKODE_TEST_DAEMON_ALIAS_SOCKET", &alias_endpoint)
.env("AKODE_TEST_OTHER_ALIAS_SOCKET", "/tmp/build/other.sock");
let output = command.output().unwrap();
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
// Rebinding the synthetic-mount registry must preserve masks for aliases
// beneath it, even when the surrounding /tmp is writable.
let registry_alias = PathBuf::from(format!(
"/tmp/codex-bwrap-synthetic-mount-targets-{}/view",
unsafe { libc::geteuid() }
));
std::fs::create_dir_all(&registry_alias).unwrap();
let mount = std::process::Command::new("mount")
.args(["--bind", "/tmp"])
.arg(&registry_alias)
.output()
.unwrap();
assert!(mount.status.success(), "{mount:?}");
let alias_endpoint = registry_alias
.join(root.file_name().unwrap())
.join("rpc.sock");
UnixStream::connect(&alias_endpoint).expect("host can reach registry alias");
command
.env("AKODE_TEST_DAEMON_ALIAS_SOCKET", &alias_endpoint)
.env(
"AKODE_TEST_OTHER_ALIAS_SOCKET",
registry_alias.join("other.sock"),
);
let output = command.output().unwrap();
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
// A real alias below the private mount must still prevent startup.
std::fs::create_dir("/tmp/alias").unwrap();
let mount = std::process::Command::new("mount")
.arg("--bind")
.arg(&root)
.arg("/tmp/alias")
.output()
.unwrap();
assert!(mount.status.success(), "{mount:?}");
UnixStream::connect("/tmp/alias/rpc.sock").expect("host can reach alias");
let output = command.output().unwrap();
assert!(!output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stderr).contains("unsupported host mount"));
assert!(!String::from_utf8_lossy(&output.stdout).contains("private-tmp-client-started"));
println!("private-tmp-validated");
}
#[test]
#[ignore = "invoked inside the private tmp sandbox"]
fn private_tmp_client() {
let Some(endpoint) = std::env::var_os("AKODE_TEST_DAEMON_SOCKET") else {
return;
};
println!("private-tmp-client-started");
assert!(UnixStream::connect(endpoint).is_err(), "daemon reachable");
UnixStream::connect("/tmp/other.sock").expect("unrelated socket reachable");
if let Some(alias) = std::env::var_os("AKODE_TEST_DAEMON_ALIAS_SOCKET") {
assert!(
UnixStream::connect(alias).is_err(),
"daemon alias reachable"
);
UnixStream::connect(std::env::var_os("AKODE_TEST_OTHER_ALIAS_SOCKET").unwrap())
.expect("unrelated alias socket reachable");
}
println!("private-tmp-isolated");
}
#[tokio::test]
async fn daemon_socket_bind_mount_alias_rejects_sandbox_startup() {
if should_skip_bwrap_tests().await {
return;
}
let root = akode_uds::prepare_shared_daemon_socket_directory().unwrap();
let private = tempfile::tempdir_in(&root).unwrap();
let alias = tempfile::tempdir().unwrap();
let _listener = UnixListener::bind(private.path().join("rpc.sock")).unwrap();
let profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::read_only(),
NetworkSandboxPolicy::Enabled,
);
let script = r#"
import pathlib, socket, subprocess, sys
root, alias, endpoint, helper, profile = sys.argv[1:]
mount = subprocess.run(['mount', '--bind', root, alias], capture_output=True)
if mount.returncode:
sys.exit(77)
try:
socket.socket(socket.AF_UNIX).connect(str(pathlib.Path(alias) / endpoint))
result = subprocess.run([helper, '--sandbox-policy-cwd', '/', '--permission-profile', profile,
'--', 'sh', '-c', 'echo command-started'], capture_output=True)
assert result.returncode != 0, result
assert b'unsupported host mount' in result.stderr, result
assert b'command-started' not in result.stdout, result
finally:
subprocess.run(['umount', alias], check=True)
"#;
let output = tokio::process::Command::new("unshare")
.args([
"--user",
"--map-current-user",
"--keep-caps",
"--mount",
"--propagation",
"private",
"--",
])
.args(["python3", "-c", script])
.arg(&root)
.arg(alias.path())
.arg(private.path().strip_prefix(&root).unwrap().join("rpc.sock"))
.arg(codex_linux_sandbox_exe())
.arg(serde_json::to_string(&profile).unwrap())
.kill_on_drop(true)
.output()
.await;
let Ok(output) = output else {
eprintln!("skipping bind-mount test: unshare is unavailable");
return;
};
if output.status.code() == Some(77)
|| String::from_utf8_lossy(&output.stderr).starts_with("unshare:")
{
eprintln!("skipping bind-mount test: user/mount namespaces are unavailable");
return;
}
assert_eq!(output.status.code(), Some(0), "{output:?}");
}
#[tokio::test]
async fn daemon_sockets_are_hidden_with_network_and_tmp_write_grants() {
if should_skip_bwrap_tests().await {
return;
}
let root = akode_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 directory_fd = std::fs::File::open(private.path()).unwrap();
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], sys.argv[2], '/proc/' + sys.argv[5] + '/root' + sys.argv[1]]:
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'
os.unlink(sys.argv[4] + '/local.sock')
# Main already hides procfs when isolating WSL interop.
if sys.argv[6] == 'host-proc' and not os.path.isdir('/run/WSL'):
assert os.path.isfile('/proc/self/status')
assert os.path.isdir('/proc/' + sys.argv[5])
for name in ['root', 'cwd', 'fd/' + sys.argv[7]]:
try:
os.readlink('/proc/' + sys.argv[5] + '/' + name)
except PermissionError:
pass
else:
raise AssertionError('host process link accessible: ' + name)
"#;
let profile = PermissionProfile::workspace_write_with(
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
NetworkSandboxPolicy::Enabled,
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ false,
);
let mut env = create_env_from_core_vars();
env.insert(
"AKODE_HOME".to_string(),
workspace.path().display().to_string(),
);
env.insert("TMPDIR".to_string(), workspace.path().display().to_string());
// Inherited procfs remains useful in containers that prohibit a fresh mount.
// Its host-process magic links must still respect the user namespace boundary.
for proc_mode in ["fresh-proc", "host-proc"] {
let mut command = tokio::process::Command::new(codex_linux_sandbox_exe());
command
.arg("--sandbox-policy-cwd")
.arg(workspace.path())
.arg("--permission-profile")
.arg(serde_json::to_string(&profile).unwrap())
.envs(&env)
.current_dir(workspace.path());
if proc_mode == "host-proc" {
command.arg("--no-proc");
}
let output = command
.args([
"--",
"python3",
"-c",
script,
socket.to_str().unwrap(),
alias.to_str().unwrap(),
unrelated.to_str().unwrap(),
workspace.path().to_str().unwrap(),
&std::process::id().to_string(),
proc_mode,
&directory_fd.as_raw_fd().to_string(),
])
.kill_on_drop(true)
.output()
.await
.unwrap();
assert_eq!(output.status.code(), Some(0), "{output:?}");
}
}

View File

@@ -0,0 +1,251 @@
//! Multiple denied files must not prevent sandbox startup or expose protected contents.
use super::LONG_TIMEOUT_MS;
use super::codex_linux_sandbox_exe;
use super::create_env_from_core_vars;
use super::run_cmd_result_with_permission_profile_for_cwd;
use super::should_skip_bwrap_tests;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_cargo_bin::write_executable;
use pretty_assertions::assert_eq;
enum DeniedFileRules {
ExactPaths,
Globs,
GlobsFromRoot,
GlobsWithProtectedRg,
GlobsWithoutRg,
}
#[test_case::test_case(DeniedFileRules::ExactPaths; "exact_paths")]
#[test_case::test_case(DeniedFileRules::Globs; "globs")]
#[test_case::test_case(DeniedFileRules::GlobsFromRoot; "globs_from_root")]
#[test_case::test_case(DeniedFileRules::GlobsWithProtectedRg; "globs_with_protected_rg")]
#[test_case::test_case(DeniedFileRules::GlobsWithoutRg; "globs_without_rg")]
#[tokio::test]
async fn sandbox_starts_with_multiple_denied_files(rules: DeniedFileRules) {
if should_skip_bwrap_tests().await {
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
return;
}
let use_controlled_rg_path = matches!(
rules,
DeniedFileRules::GlobsWithProtectedRg | DeniedFileRules::GlobsWithoutRg
);
let temp = if use_controlled_rg_path {
// Bazel can mount the default temp directory noexec.
tempfile::tempdir_in(std::env::current_dir().expect("current directory"))
.or_else(|_| tempfile::tempdir())
} else {
tempfile::tempdir()
}
.expect("tempdir");
let workspace = AbsolutePathBuf::try_from(temp.path()).expect("absolute workspace");
std::fs::create_dir(workspace.join("nested")).expect("create nested directory");
std::fs::write(workspace.join("AGENTS.md"), "project instructions\n")
.expect("write allowed instructions");
let denied_files = [
(workspace.join("one.key"), "dummy first key"),
(workspace.join("nested/two.key"), "dummy second key"),
(workspace.join(".env.local"), "dummy environment"),
(workspace.join("nested/.env"), "dummy nested environment"),
(workspace.join("#report-1.csv"), "dummy report"),
(workspace.join("!report.csv"), "dummy literal bang report"),
(workspace.join("notes.txt "), "dummy spaced filename"),
(workspace.join("root-only.cfg"), "dummy root configuration"),
];
for (path, contents) in &denied_files {
std::fs::write(path, contents).expect("write denied dummy file");
}
for path in ["notes.txt", "nested/allowed.cfg"] {
std::fs::write(workspace.join(path), "public").expect("write allowed file");
}
std::os::unix::fs::symlink("AGENTS.md", workspace.join("relative.key"))
.expect("relative file symlink");
std::os::unix::fs::symlink(workspace.join("AGENTS.md"), workspace.join("absolute.key"))
.expect("absolute file symlink");
let sandbox_helper = codex_linux_sandbox_exe();
let helper_dir = AbsolutePathBuf::try_from(sandbox_helper.parent().expect("helper parent"))
.expect("absolute helper directory");
let mut entries = vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Minimal,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(helper_dir.into(), FileSystemAccessMode::Read),
FileSystemSandboxEntry::new(workspace.clone().into(), FileSystemAccessMode::Write),
];
let mut env = create_env_from_core_vars();
// User config must not suppress the files used to construct deny masks.
let rg_config = workspace.join("ripgrep.conf");
std::fs::write(rg_config.as_path(), "--quiet\n").expect("write ripgrep config");
env.insert(
"RIPGREP_CONFIG_PATH".to_string(),
rg_config.to_str().expect("UTF-8 config path").to_string(),
);
let rg_fixture = if use_controlled_rg_path {
let fixture = tempfile::tempdir_in(temp.path().parent().expect("workspace parent"))
.expect("rg fixture");
write_executable(
workspace.join("rg").as_path(),
"#!/bin/sh\n: > \"$AKODE_TEST_REJECTED_RG_MARKER\"\nexit 0\n",
)
.expect("write workspace rg fixture");
if matches!(rules, DeniedFileRules::GlobsWithProtectedRg) {
write_executable(
&fixture.path().join("rg"),
r#"#!/bin/sh
: > "$AKODE_TEST_PROTECTED_RG_MARKER"
printf '%s\000' "$AKODE_TEST_DENIED_PATH_0" "$AKODE_TEST_DENIED_PATH_1" "$AKODE_TEST_DENIED_PATH_2"
"#,
)
.expect("write protected rg fixture");
}
// Keep bubblewrap available without adding an unrelated rg to the test PATH.
if let Some(bwrap) = akode_sandboxing::find_system_bwrap_in_path(
&PermissionProfile::read_only().file_system_sandbox_policy(),
&std::env::current_dir().expect("current directory"),
) {
std::os::unix::fs::symlink(bwrap, fixture.path().join("bwrap"))
.expect("link system bubblewrap");
}
env.insert(
"PATH".to_string(),
std::env::join_paths([workspace.as_path(), fixture.path()])
.expect("join PATH")
.into_string()
.expect("UTF-8 PATH"),
);
for (name, path) in [
(
"AKODE_TEST_REJECTED_RG_MARKER",
fixture.path().join("rejected-rg-ran"),
),
(
"AKODE_TEST_PROTECTED_RG_MARKER",
fixture.path().join("protected-rg-ran"),
),
("AKODE_TEST_DENIED_PATH_0", denied_files[0].0.to_path_buf()),
("AKODE_TEST_DENIED_PATH_1", denied_files[1].0.to_path_buf()),
("AKODE_TEST_DENIED_PATH_2", denied_files[2].0.to_path_buf()),
] {
env.insert(
name.to_string(),
path.to_str().expect("UTF-8 fixture path").to_string(),
);
}
Some(fixture)
} else {
None
};
match rules {
DeniedFileRules::ExactPaths => {
entries.extend(denied_files.iter().map(|(path, _)| {
FileSystemSandboxEntry::new(path.clone().into(), FileSystemAccessMode::Deny)
}));
}
DeniedFileRules::Globs
| DeniedFileRules::GlobsFromRoot
| DeniedFileRules::GlobsWithProtectedRg
| DeniedFileRules::GlobsWithoutRg => {
for suffix in [
"**/*.key",
"**/.env.local",
"nest*/.env",
"#report-*.csv",
"!*.csv",
"*.txt ",
"*.cfg",
] {
entries.push(FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: format!("{}/{suffix}", workspace.display()),
},
FileSystemAccessMode::Deny,
));
}
}
}
let permission_profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(entries),
NetworkSandboxPolicy::Enabled,
);
let output = run_cmd_result_with_permission_profile_for_cwd(
&[
"/bin/sh",
"-c",
r#"set -eu
cd "$1"
/bin/cat AGENTS.md
for blocked in one.key nested/two.key .env.local nested/.env '#report-1.csv' '!report.csv' 'notes.txt ' root-only.cfg; do
if (: < "$blocked") 2>/dev/null; then
printf 'read unexpectedly allowed: %s\n' "$blocked" >&2
exit 10
fi
if (printf changed > "$blocked") 2>/dev/null; then
printf 'write unexpectedly allowed: %s\n' "$blocked" >&2
exit 11
fi
done
for allowed in notes.txt nested/allowed.cfg; do
test "$(/bin/cat "$allowed")" = public
done
for alias in relative.key absolute.key; do
test "$(/bin/cat "$alias")" = 'project instructions'
done
printf 'allowed\n' > allowed.txt
/bin/cat allowed.txt
"#,
"sh",
workspace.to_str().expect("UTF-8 workspace"),
],
if matches!(rules, DeniedFileRules::GlobsFromRoot) {
AbsolutePathBuf::try_from("/").expect("absolute root")
} else {
workspace.clone()
},
permission_profile,
env,
LONG_TIMEOUT_MS,
/*use_legacy_landlock*/ false,
)
.await
.expect("sandbox should start with multiple denied files");
assert_eq!(
(output.exit_code, output.stdout.text, output.stderr.text),
(
0,
"project instructions\nallowed\n".to_string(),
String::new()
)
);
assert_eq!(
std::fs::read_to_string(workspace.join("allowed.txt")).expect("read allowed file"),
"allowed\n"
);
for (path, contents) in &denied_files {
assert_eq!(
std::fs::read_to_string(path).expect("read host dummy file"),
*contents
);
}
if let Some(fixture) = rg_fixture {
assert!(
!fixture.path().join("rejected-rg-ran").exists(),
"writable rg ran before confinement"
);
assert!(!fixture.path().join("protected-rg-ran").exists());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,191 @@
//! Explicit Unix-socket grants preserve managed-proxy network isolation.
use super::*;
use akode_network_proxy::ConfigReloader;
use akode_network_proxy::ConfigReloaderFuture;
use akode_network_proxy::ConfigState;
use akode_network_proxy::NetworkProxy;
use akode_network_proxy::NetworkProxyConfig;
use akode_network_proxy::NetworkProxyConstraints;
use akode_network_proxy::NetworkProxyState;
use akode_network_proxy::build_config_state;
use pretty_assertions::assert_eq;
use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream;
use std::sync::Arc;
struct TestConfigReloader(ConfigState);
impl ConfigReloader for TestConfigReloader {
fn source_label(&self) -> String {
"managed proxy Unix socket test".to_string()
}
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
Box::pin(async { Ok(None) })
}
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
Box::pin(async { Ok(self.0.clone()) })
}
}
#[tokio::test]
async fn managed_proxy_allow_all_unix_sockets_preserves_network_isolation() {
if let Some(reason) = managed_proxy_skip_reason().await {
eprintln!("skipping managed proxy Unix socket test: {reason}");
return;
}
if !Command::new("python3")
.arg("--version")
.output()
.await
.is_ok_and(|output| output.status.success())
{
eprintln!("skipping managed proxy Unix socket test: python3 is unavailable");
return;
}
let temp = tempfile::tempdir().expect("socket directory");
let socket_path = temp.path().join("daemon.sock");
let listener = UnixListener::bind(&socket_path).expect("host Unix listener");
let mut control = UnixStream::connect(&socket_path).expect("host Unix control connection");
let (mut control_peer, _) = listener.accept().expect("accept host Unix control");
control.write_all(b"ok").expect("write host control");
let mut control_payload = [0; 2];
control_peer
.read_exact(&mut control_payload)
.expect("read host control");
assert_eq!(control_payload, *b"ok");
// Use another loopback address so the namespace's proxy listener cannot
// collide with this host-only endpoint even if it selects the same port.
let tcp_listener =
TcpListener::bind((Ipv4Addr::new(127, 0, 0, 2), 0)).expect("host TCP listener");
let tcp_addr = tcp_listener.local_addr().expect("host TCP address");
let _tcp_control = TcpStream::connect(tcp_addr).expect("host TCP control connection");
let _tcp_peer = tcp_listener.accept().expect("accept host TCP control");
listener
.set_nonblocking(true)
.expect("nonblocking listener");
let server = std::thread::spawn(move || {
let deadline = Instant::now() + OPERATION_TIMEOUT * 2;
loop {
match listener.accept() {
Ok((mut stream, _)) => {
stream
.set_read_timeout(Some(OPERATION_TIMEOUT))
.expect("set Unix read timeout");
let mut request = [0; 4];
stream.read_exact(&mut request).expect("read Unix request");
assert_eq!(request, *b"ping");
stream.write_all(b"pong").expect("write Unix response");
break;
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
assert!(Instant::now() < deadline, "Unix request timed out");
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => panic!("accept Unix request: {error}"),
}
}
});
let probe = r#"
import errno, socket, sys
path, port, mode = sys.argv[1:]
try:
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
except OSError as error:
assert mode == 'deny' and error.errno == errno.EPERM, error
else:
assert mode == 'allow', 'Unix socket unexpectedly allowed'
with client:
client.settimeout(2)
client.connect(path)
client.sendall(b'ping')
assert client.recv(4, socket.MSG_WAITALL) == b'pong'
for address in [('127.0.0.2', int(port)), ('192.0.2.1', 80)]:
try:
connection = socket.create_connection(address, timeout=0.5)
except OSError:
pass
else:
connection.close()
raise AssertionError(('direct network unexpectedly allowed', address))
for family in (socket.AF_NETLINK, getattr(socket, 'AF_VSOCK', 40)):
try:
unexpected = socket.socket(family, socket.SOCK_STREAM)
except OSError as error:
assert error.errno == errno.EPERM, (family, error)
else:
unexpected.close()
raise AssertionError(('socket family unexpectedly allowed', family))
"#;
let cwd = std::env::current_dir().expect("current directory");
for (label, dangerously_allow_all_unix_sockets, allow_path) in [
("default denial", false, false),
("path grant stays restricted", false, true),
("explicit allow-all", true, false),
] {
let mut env = create_env_from_core_vars();
strip_proxy_env(&mut env);
let mut config = NetworkProxyConfig {
enabled: true,
proxy_url: "http://127.0.0.1:9".to_string(),
dangerously_allow_all_unix_sockets: Some(dangerously_allow_all_unix_sockets),
..Default::default()
};
if allow_path {
config.set_allow_unix_sockets(vec![socket_path.to_string_lossy().into_owned()]);
}
let state = build_config_state(
config,
NetworkProxyConstraints::default(),
akode_network_proxy::Platform::native(),
)
.expect("valid managed network configuration");
let network = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
state.clone(),
Arc::new(TestConfigReloader(state)),
)))
.managed_by_codex(/*managed_by_codex*/ false)
.build()
.await
.expect("build managed network proxy");
let prepared = network
.prepare_for_optional_environment(env, /*environment_id*/ None)
.expect("prepare managed network policy");
let mut command = Command::new(env!("CARGO_BIN_EXE_codex-linux-sandbox"));
command
.arg("--sandbox-policy-cwd")
.arg(&cwd)
.arg("--permission-profile")
.arg(serde_json::to_string(&PermissionProfile::Disabled).unwrap())
.arg("--managed-network")
.arg(serde_json::to_string(&prepared.sandbox_context).unwrap())
.args(["--", "python3", "-c", probe])
.arg(&socket_path)
.arg(tcp_addr.port().to_string())
.arg(if dangerously_allow_all_unix_sockets {
"allow"
} else {
"deny"
})
.env_clear()
.envs(prepared.env)
.kill_on_drop(true);
let output = tokio::time::timeout(OPERATION_TIMEOUT, command.output())
.await
.expect("Unix socket probe timed out")
.expect("Unix socket probe should execute");
assert!(
output.status.success(),
"{label}; stderr={}",
String::from_utf8_lossy(&output.stderr)
);
}
server.join().expect("Unix server should finish");
}

View File

@@ -0,0 +1,5 @@
// Aggregates all former standalone integration tests as modules.
mod bundled_bwrap;
mod bwrap_path;
mod managed_proxy;
mod sandbox;

View File

@@ -0,0 +1,204 @@
//! Mounts for writable roots must preserve read-only metadata protections.
use super::LONG_TIMEOUT_MS;
use super::create_env_from_core_vars;
use super::run_cmd_result_with_cwd_and_writable_roots;
use super::run_cmd_result_with_permission_profile_for_cwd;
use super::should_skip_bwrap_tests;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
enum RootLayout {
Directory,
Symlink,
}
#[test_case::test_case(RootLayout::Directory, ""; "home_cwd")]
#[test_case::test_case(RootLayout::Directory, ".akode/visualizations/thread"; "visualization_cwd")]
#[test_case::test_case(RootLayout::Symlink, ""; "symlink_home_cwd")]
#[test_case::test_case(RootLayout::Symlink, ".akode/visualizations/thread"; "symlink_visualization_cwd")]
#[tokio::test]
async fn sandbox_starts_with_nested_writable_metadata(layout: RootLayout, relative_cwd: &str) {
if should_skip_bwrap_tests().await {
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
return;
}
let temp = tempfile::tempdir().expect("tempdir");
let home =
AbsolutePathBuf::from_absolute_path(temp.path().join("home")).expect("absolute home");
match layout {
RootLayout::Directory => std::fs::create_dir(&home).expect("create home"),
RootLayout::Symlink => {
let target = temp.path().join("real-home");
std::fs::create_dir(&target).expect("create real home");
std::os::unix::fs::symlink(target, &home).expect("create home alias");
}
}
let codex_home = home.join(".akode");
let visualization = codex_home.join("visualizations/thread");
std::fs::create_dir_all(&visualization).expect("create visualization directory");
let protected_file = codex_home.join("config.toml");
std::fs::write(&protected_file, "unchanged").expect("write protected config");
let mut entries = vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
),
FileSystemSandboxEntry::new(home.clone().into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(codex_home.clone().into(), FileSystemAccessMode::Read),
FileSystemSandboxEntry::new(visualization.clone().into(), FileSystemAccessMode::Write),
];
// Remote clients expand generated workspace metadata rules to concrete
// paths, including paths that do not yet exist on the executor.
for name in [".git", ".agents", ".akode", ".aws"] {
entries.push(FileSystemSandboxEntry::skip_missing_path(
visualization.join(name).into(),
FileSystemAccessMode::Read,
));
}
let permission_profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(entries),
NetworkSandboxPolicy::Enabled,
);
let script = r#"
set -eu
workspace="$1"
visualization="$2"
printf home > "$workspace/allowed.txt"
printf visualization > "$visualization/allowed.txt"
if (rm "$workspace") 2>/dev/null; then
exit 13
fi
if (printf changed > "$workspace/.akode/config.toml") 2>/dev/null; then
exit 10
fi
if (touch "$workspace/.akode/forbidden.txt") 2>/dev/null; then
exit 11
fi
for name in .git .agents .akode .aws; do
test -d "$visualization/$name"
if (touch "$visualization/$name/forbidden.txt") 2>/dev/null; then
exit 12
fi
done
printf nested-metadata-protected
"#;
let output = run_cmd_result_with_permission_profile_for_cwd(
&[
"/bin/sh",
"-c",
script,
"nested-metadata-test",
home.to_str().expect("UTF-8 home"),
visualization
.to_str()
.expect("UTF-8 visualization directory"),
],
home.join(relative_cwd),
permission_profile,
create_env_from_core_vars(),
LONG_TIMEOUT_MS,
/*use_legacy_landlock*/ false,
)
.await
.expect("nested writable root should start under bubblewrap");
assert_eq!(
(output.exit_code, output.stdout.text, output.stderr.text),
(0, "nested-metadata-protected".to_string(), String::new())
);
for (path, expected) in [
(home.join("allowed.txt"), "home"),
(visualization.join("allowed.txt"), "visualization"),
(protected_file, "unchanged"),
] {
assert_eq!(std::fs::read_to_string(path).expect("read file"), expected);
}
for name in [".git", ".agents", ".akode", ".aws"] {
assert!(
!visualization.join(name).exists(),
"temporary {name} mountpoint should be cleaned up"
);
}
}
#[test_case::test_case(RootLayout::Directory; "direct")]
#[test_case::test_case(RootLayout::Symlink; "alias_outside_writable_roots")]
#[tokio::test]
async fn workspace_write_protects_resolved_gitdir_in_another_writable_root(layout: RootLayout) {
if should_skip_bwrap_tests().await {
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
return;
}
let temp = tempfile::tempdir().expect("tempdir");
// Roots at the same depth keep the workspace mount before the additional writable root.
let workspace = temp.path().join("workspace");
let writable = temp.path().join("writable");
let gitdir = writable.join("gitdir");
std::fs::create_dir(&workspace).expect("create workspace");
std::fs::create_dir_all(gitdir.join("hooks")).expect("create Git hooks directory");
let pointer_target = match layout {
RootLayout::Directory => gitdir.clone(),
RootLayout::Symlink => {
let aliases = temp.path().join("readonly-aliases");
std::fs::create_dir(&aliases).expect("create aliases directory");
let alias = aliases.join("repo");
std::os::unix::fs::symlink(&writable, &alias).expect("create gitdir alias");
alias.join("gitdir")
}
};
std::fs::write(
workspace.join(".git"),
format!("gitdir: {}\n", pointer_target.display()),
)
.expect("write Git pointer");
let hook = gitdir.join("hooks/pre-commit");
std::fs::write(&hook, "unchanged").expect("write Git hook");
let script = r#"
set -eu
printf allowed > "$1/allowed.txt"
if (printf changed > "$1/gitdir/hooks/pre-commit") 2>/dev/null; then
exit 10
fi
"#;
let output = run_cmd_result_with_cwd_and_writable_roots(
&[
"/bin/sh",
"-c",
script,
"resolved-gitdir-test",
writable.to_str().expect("UTF-8 writable root"),
],
&workspace,
std::slice::from_ref(&writable),
LONG_TIMEOUT_MS,
/*use_legacy_landlock*/ false,
/*network_access*/ true,
)
.await
.expect("sandboxed command should complete");
assert_eq!(
(output.exit_code, output.stdout.text, output.stderr.text),
(0, String::new(), String::new())
);
for (path, expected) in [
(writable.join("allowed.txt"), "allowed"),
(hook, "unchanged"),
] {
assert_eq!(std::fs::read_to_string(path).expect("read file"), expected);
}
}

View File

@@ -0,0 +1,174 @@
//! Approved root metadata writes must not remount targets hidden by executor-side denials.
use super::codex_linux_sandbox_exe;
use super::should_skip_bwrap_tests;
use akode_protocol::models::PermissionProfile;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSandboxPolicyContext;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::fs;
use std::process::Command;
#[tokio::test]
async fn root_metadata_symlinks_cannot_reopen_approved_denials() {
if should_skip_bwrap_tests().await {
return;
}
let Some(bwrap) = akode_sandboxing::find_system_bwrap_in_path(
&PermissionProfile::read_only().file_system_sandbox_policy(),
&std::env::current_dir().expect("current directory"),
) else {
eprintln!("skipping root metadata test: system bubblewrap is unavailable");
return;
};
let fixture = tempfile::tempdir_in("/tmp").unwrap();
let work = fixture.path().join("work");
let private = fixture.path().join("private");
fs::create_dir_all(work.join("public")).unwrap();
fs::create_dir_all(private.join("reopened")).unwrap();
fs::write(work.join("public/secret"), "outside").unwrap();
fs::write(private.join("reopened/secret"), "private").unwrap();
fs::write(private.join("sibling"), "sibling").unwrap();
akode_utils_cargo_bin::copy_executable(&codex_linux_sandbox_exe(), &work.join("sandbox"))
.unwrap();
let path_entry = |path: &str, access| {
FileSystemSandboxEntry::new(
AbsolutePathBuf::from_absolute_path(path).unwrap().into(),
access,
)
};
let cwd = AbsolutePathBuf::from_absolute_path("/tmp").unwrap().into();
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: None,
temporary_directories: Some(&[]),
};
let approved = |denied| {
let mut policy = FileSystemSandboxPolicy::read_only();
policy
.entries
.push(path_entry(denied, FileSystemAccessMode::Deny));
policy.for_approved_command(&context)
};
let run = |policy: &FileSystemSandboxPolicy,
private_mount: &str,
codex_target: &str,
script: &str| {
let profile =
PermissionProfile::from_runtime_permissions(policy, NetworkSandboxPolicy::Enabled);
let mut command = Command::new(&bwrap);
command
.args("--unshare-user --uid 0 --gid 0 --die-with-parent --tmpfs /".split_whitespace());
command.args(
"--ro-bind /usr /usr --ro-bind /etc /etc --proc /proc --dev /dev".split_whitespace(),
);
command.args("--dir /run --dir /.agents --symlink /private-link /.git".split_whitespace());
command.args(["--symlink", codex_target, "/.akode"]);
command.args(["--symlink", "/private/reopened", "/private-link"]);
for path in ["/bin", "/sbin", "/lib", "/lib64"] {
if let Ok(metadata) = fs::symlink_metadata(path) {
if metadata.file_type().is_symlink() {
command
.arg("--symlink")
.arg(fs::read_link(path).unwrap())
.arg(path);
} else {
command.args(["--ro-bind", path, path]);
}
}
}
command.arg("--bind").arg(&work).arg("/tmp");
command.arg("--bind").arg(&private).arg(private_mount);
if private_mount != "/private" {
command.args(["--symlink", private_mount, "/private"]);
}
command.args(
"--chdir /tmp --setenv TMPDIR /tmp --setenv PATH /usr/bin:/bin".split_whitespace(),
);
command.args(
"-- /tmp/sandbox --sandbox-policy-cwd /tmp --permission-profile".split_whitespace(),
);
command.arg(serde_json::to_string(&profile).unwrap());
command.args(["--", "/bin/sh", "-c", script]);
command.output().unwrap()
};
let private_denied = approved("/private");
let script = r#"
set -eu
if cat /private/reopened/secret >/dev/null 2>&1 ||
cat /.akode/secret >/dev/null 2>&1 || cat /.git/secret >/dev/null 2>&1; then exit 21; fi
if (printf bad > /.akode/changed) 2>/dev/null; then exit 22; fi
printf good > /.agents/allowed
printf good > /tmp/marker
printf 'root-metadata-denials-held\n'
"#;
let output = run(&private_denied, "/private", "/private/reopened", script);
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.starts_with("bwrap: Creating new namespace failed")
|| stderr.contains("No permissions to create a new namespace")
|| stderr.contains("setting up uid map")
{
eprintln!("skipping root metadata test: {stderr}");
return;
}
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert_eq!(output.stdout, b"root-metadata-denials-held\n");
assert_eq!(fs::read_to_string(work.join("marker")).unwrap(), "good");
assert!(!private.join("reopened/changed").exists());
let script = r#"
set -eu
printf safe > /.akode/allowed
if cat /.git/secret >/dev/null 2>&1; then exit 23; fi
"#;
let output = run(&private_denied, "/private", "/tmp/public", script);
assert_eq!(output.status.code(), Some(0), "{output:?}");
assert_eq!(
fs::read_to_string(work.join("public/allowed")).unwrap(),
"safe"
);
let script = r#"
set -eu
rm /private
ln -s /tmp/public /private
cat /.akode/secret
"#;
let output = run(&private_denied, "/real-private", "/private", script);
assert!(!output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stderr).contains(
"cannot enforce sandbox deny-read path /private because it crosses writable symlink /private"
), "{output:?}");
assert!(output.stdout.is_empty(), "{output:?}");
let mut reopened = private_denied;
reopened
.entries
.push(path_entry("/private/reopened", FileSystemAccessMode::Write));
let script = r#"
set -eu
test "$(cat /.akode/secret)" = private
if cat /private/sibling >/dev/null 2>&1; then exit 24; fi
"#;
let output = run(&reopened, "/private", "/private/reopened", script);
assert_eq!(output.status.code(), Some(0), "{output:?}");
let output = run(
&approved("/.akode/secret"),
"/private",
"/private/reopened",
"true",
);
assert!(!output.status.success(), "{output:?}");
assert!(String::from_utf8_lossy(&output.stderr).contains(
"cannot enforce sandbox deny-read path /.akode/secret because it crosses writable symlink /.akode"
), "{output:?}");
assert!(output.stdout.is_empty(), "{output:?}");
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,80 @@
//! WSLg runtime coverage for the duplicate-view mask and procfs fallback.
use super::NETWORK_TIMEOUT_MS;
use super::codex_linux_sandbox_exe;
use super::should_skip_bwrap_tests;
use akode_protocol::models::PermissionProfile;
use pretty_assertions::assert_eq;
use std::os::unix::fs::MetadataExt as _;
use std::time::Duration;
#[tokio::test]
async fn wslg_duplicate_view_is_masked_with_and_without_fresh_procfs() {
let root = std::fs::metadata("/").expect("inspect root");
let has_wslg_root = std::fs::symlink_metadata("/mnt/wslg/distro").is_ok_and(|metadata| {
metadata.is_dir() && (metadata.dev(), metadata.ino()) == (root.dev(), root.ino())
});
if !has_wslg_root || should_skip_bwrap_tests().await {
eprintln!("skipping WSLg test: WSLg or bwrap prerequisites are unavailable");
return;
}
let workspace = tempfile::tempdir().expect("create workspace");
let allowed = workspace.path().join("allowed.txt");
std::fs::write(&allowed, "allowed\n").expect("write allowed fixture");
let profile = serde_json::to_string(&PermissionProfile::read_only())
.expect("serialize read-only profile");
for no_proc in [false, true] {
let mut command = tokio::process::Command::new(codex_linux_sandbox_exe());
command
.arg("--sandbox-policy-cwd")
.arg(workspace.path())
.args(["--permission-profile", &profile]);
if no_proc {
command.arg("--no-proc");
}
// Inspect the protection itself, without accessing data through the alias.
let script = if no_proc {
"stat -c %a /mnt/wslg/distro && stat -f -c %T /mnt/wslg/distro && cat \"$1\" && test ! -e /proc/1"
} else {
"stat -c %a /mnt/wslg/distro && stat -f -c %T /mnt/wslg/distro && cat \"$1\""
};
let output = tokio::time::timeout(
Duration::from_millis(NETWORK_TIMEOUT_MS),
command
.args(["--", "/bin/sh", "-c", script, "sh"])
.arg(&allowed)
.kill_on_drop(true)
.output(),
)
.await
.expect("WSLg sandbox check should finish")
.expect("sandbox helper should start");
assert!(
output.status.success(),
"WSLg mask check failed (no_proc={no_proc}): {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(output.stdout, b"0\ntmpfs\nallowed\n");
}
// Exercise the public helper boundary: production wraps the requested
// executable in another helper command before constructing bwrap args.
let output = tokio::process::Command::new(codex_linux_sandbox_exe())
.arg("--sandbox-policy-cwd")
.arg(workspace.path())
.args([
"--permission-profile",
&profile,
"--",
"/mnt/wslg/distro/bin/true",
])
.output()
.await
.expect("sandbox helper should start");
assert_eq!(output.status.code(), Some(1));
assert_eq!(
String::from_utf8(output.stderr).expect("UTF-8 diagnostic"),
"error building bubblewrap command: Fatal error: restricted sandboxes do not support paths under /mnt/wslg/distro: /mnt/wslg/distro/bin/true; use the corresponding path under the primary filesystem root instead\n"
);
}