Stop --chdir from binding the working directory read-write

This commit is contained in:
2026-11-17 20:37:01 +01:00
parent 352ead2bf5
commit 4b801f811e
8 changed files with 72 additions and 21 deletions
+5 -1
View File
@@ -6,7 +6,7 @@ Sandbox agentic coding assistants with [bubblewrap](https://github.com/container
### Whitelist ### Whitelist
Tight sandbox for normal agent coding tasks. Only explicitly listed paths are visible — system binaries, libraries, a subset of `/etc`, `/sys` (all read-only), synthetic `/dev`, private `/proc`, `/tmp`, `/run`, and the working directory (read-write). Everything else is invisible. Whitelist always runs with hardening on (see below). Tight sandbox for normal agent coding tasks. Only explicitly listed paths are visible — system binaries, libraries, a subset of `/etc`, `/sys` (all read-only), synthetic `/dev`, private `/proc`, `/tmp` and `/run`. Everything else is invisible, including the working directory: bind it with `--rw .` (or `rw = ["$PWD"]` in the config). Whitelist always runs with hardening on (see below).
### Blacklist ### Blacklist
@@ -82,6 +82,10 @@ Every sandbox contains a read-only `/run/agent-sandbox/bwrap-args` holding the e
A user `--rw`/`--ro` targeting `/run/agent-sandbox` overrides the directory, like any other built-in path. A user `--rw`/`--ro` targeting `/run/agent-sandbox` overrides the directory, like any other built-in path.
## Working directory
The sandbox starts in the directory agent-sandbox was launched from, or in `--chdir PATH` (`chdir` in the config). Neither makes that directory visible or writable; only `--ro` and `--rw` do. If nothing binds it, bwrap refuses to start with `Can't chdir to PATH: No such file or directory`.
## Escape hatches ## Escape hatches
When the agent needs access to something the sandbox blocks, use `--rw` or `--ro` for paths and `--setenv`/`--unsetenv` for env vars. User overrides always win over the built-in policies. When the agent needs access to something the sandbox blocks, use `--rw` or `--ro` for paths and `--setenv`/`--unsetenv` for env vars. User overrides always win over the built-in policies.
+2 -1
View File
@@ -20,7 +20,7 @@ whitelist = true
# seccomp = false # default: true # seccomp = false # default: true
# env-filter = false # default: true # env-filter = false # default: true
# dry-run = true # dry-run = true
# chdir = "~/projects/my-repo" # chdir = "~/projects/my-repo" # only sets the working directory; bind it with ro/rw
ro = [ ro = [
"~/.config/agents", "~/.config/agents",
@@ -29,6 +29,7 @@ ro = [
# "/host/path:/sandbox/path", # SRC:DST -> mount host SRC at a different target # "/host/path:/sandbox/path", # SRC:DST -> mount host SRC at a different target
] ]
rw = [ rw = [
"$PWD", # the directory agent-sandbox was launched from
"~/.cargo", "~/.cargo",
"~/.rustup", "~/.rustup",
] ]
+1 -1
View File
@@ -79,7 +79,7 @@ pub struct Args {
#[arg(long = "persistent-key", value_name = "LABEL")] #[arg(long = "persistent-key", value_name = "LABEL")]
pub persistent_key: Option<String>, pub persistent_key: Option<String>,
/// Working directory inside the sandbox (default: current directory) /// Working directory inside the sandbox (default: current directory); bind it with --ro or --rw
#[arg(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub chdir: Option<PathBuf>, pub chdir: Option<PathBuf>,
-7
View File
@@ -71,7 +71,6 @@ fn build_command(
for spec in &config.extra_ro { for spec in &config.extra_ro {
add_ro_bind(&mut cmd, spec)?; add_ro_bind(&mut cmd, spec)?;
} }
add_rw_bind_path(&mut cmd, &config.chdir)?;
for spec in &config.extra_rw { for spec in &config.extra_rw {
add_rw_bind(&mut cmd, spec)?; add_rw_bind(&mut cmd, spec)?;
} }
@@ -307,12 +306,6 @@ fn add_ro_bind(cmd: &mut Command, spec: &BindSpec) -> Result<(), SandboxError> {
Ok(()) Ok(())
} }
fn add_rw_bind_path(cmd: &mut Command, path: &Path) -> Result<(), SandboxError> {
let source = resolve_bind_source(path)?;
cmd.arg("--bind").arg(source).arg(path);
Ok(())
}
fn resolve_bind_source(path: &Path) -> Result<PathBuf, SandboxError> { fn resolve_bind_source(path: &Path) -> Result<PathBuf, SandboxError> {
std::fs::canonicalize(path).map_err(|_| SandboxError::PathMissing(path.to_path_buf())) std::fs::canonicalize(path).map_err(|_| SandboxError::PathMissing(path.to_path_buf()))
} }
+3
View File
@@ -66,11 +66,14 @@ impl Sandbox {
fn build(prefix: &[&str], extra_args: &[&str], guard: Option<HostGlobsGuard>) -> Self { fn build(prefix: &[&str], extra_args: &[&str], guard: Option<HostGlobsGuard>) -> Self {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_agent-sandbox")); let mut cmd = Command::new(env!("CARGO_BIN_EXE_agent-sandbox"));
cmd.args(prefix); cmd.args(prefix);
cmd.args(LAUNCH_DIR_WRITABLE);
cmd.args(extra_args); cmd.args(extra_args);
Self { cmd, _guard: guard } Self { cmd, _guard: guard }
} }
} }
const LAUNCH_DIR_WRITABLE: [&str; 2] = ["--rw", "."];
fn scan_guard_for(extra_args: &[&str]) -> Option<HostGlobsGuard> { fn scan_guard_for(extra_args: &[&str]) -> Option<HostGlobsGuard> {
extra_args extra_args
.contains(&"--blacklist") .contains(&"--blacklist")
+2 -1
View File
@@ -171,9 +171,10 @@ fn interrupt_during_grace_period_kills_child_processes_at_once() {
} }
fn spawn_sandbox(args: &[&str], dir: &Path, script: &str) -> (Sandbox, Child) { fn spawn_sandbox(args: &[&str], dir: &Path, script: &str) -> (Sandbox, Child) {
let dir = dir.to_str().unwrap();
let mut sandbox = Sandbox::new(args); let mut sandbox = Sandbox::new(args);
let child = sandbox let child = sandbox
.args(["--chdir", dir.to_str().unwrap(), "--", "sh", "-c", script]) .args(["--rw", dir, "--chdir", dir, "--", "sh", "-c", script])
.stdout(Stdio::null()) .stdout(Stdio::null())
.spawn() .spawn()
.expect("agent-sandbox binary failed to execute"); .expect("agent-sandbox binary failed to execute");
+57 -8
View File
@@ -28,19 +28,65 @@ impl Drop for CleanupPath {
} }
} }
#[test] #[test]
fn cwd_is_writable() { fn chdir_alone_makes_nothing_visible() {
let _cleanup = CleanupPath::new("./sandbox_canary"); let dir = TempDir::new().unwrap();
let dir_str = dir.path().to_str().unwrap();
let output = Sandbox::new(&[]) let output = Sandbox::new(&["--chdir", dir_str])
.args(["--", "bash", "-c", "touch ./sandbox_canary && echo ok"]) .args(["--", "true"])
.output()
.expect("agent-sandbox binary failed to execute");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "chdir into an unbound path ran");
assert!(
stderr.contains(&format!(
"Can't chdir to {dir_str}: No such file or directory"
)),
"expected bwrap's chdir error, got: {stderr}"
);
}
#[test]
fn chdir_under_ro_is_read_only() {
let dir = TempDir::new().unwrap();
let dir_str = dir.path().to_str().unwrap();
let output = Sandbox::new(&["--ro", dir_str, "--chdir", dir_str])
.args([
"--",
"bash",
"-c",
"touch canary 2>/dev/null || echo readonly",
])
.output() .output()
.expect("agent-sandbox binary failed to execute"); .expect("agent-sandbox binary failed to execute");
let stdout = String::from_utf8_lossy(&output.stdout); let stdout = String::from_utf8_lossy(&output.stdout);
assert!( assert!(
stdout.contains("ok"), stdout.contains("readonly"),
"expected 'ok' in stdout, got: {stdout}" "expected 'readonly' in stdout, got: {stdout}, stderr: {}",
String::from_utf8_lossy(&output.stderr)
); );
assert!(!dir.path().join("canary").exists());
}
#[test]
fn chdir_under_rw_is_writable() {
let dir = TempDir::new().unwrap();
let dir_str = dir.path().to_str().unwrap();
let output = Sandbox::new(&["--rw", dir_str, "--chdir", dir_str])
.args(["--", "touch", "canary"])
.output()
.expect("agent-sandbox binary failed to execute");
assert!(
output.status.success(),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(dir.path().join("canary").exists());
} }
#[test] #[test]
@@ -647,7 +693,7 @@ fn persistent_tmp_resumes_with_explicit_key_matching_derived_hash() {
let _cleanup_tmp = CleanupPath::new(format!("/tmp/agent-sandbox-{key}")); let _cleanup_tmp = CleanupPath::new(format!("/tmp/agent-sandbox-{key}"));
let _cleanup_var = CleanupPath::new(format!("/var/tmp/agent-sandbox-{key}")); let _cleanup_var = CleanupPath::new(format!("/var/tmp/agent-sandbox-{key}"));
let writer = Sandbox::new(&["--persistent-tmp", "--chdir", chdir_str]) let writer = Sandbox::new(&["--persistent-tmp", "--ro", chdir_str, "--chdir", chdir_str])
.args(["--", "bash", "-c", "echo persisted > /tmp/canary"]) .args(["--", "bash", "-c", "echo persisted > /tmp/canary"])
.output() .output()
.expect("write run failed"); .expect("write run failed");
@@ -660,12 +706,15 @@ fn persistent_tmp_resumes_with_explicit_key_matching_derived_hash() {
// Second run: different chdir (would have derived a different hash) plus an // Second run: different chdir (would have derived a different hash) plus an
// extra flag, but an explicit key pinning the same host directory. // extra flag, but an explicit key pinning the same host directory.
let other_chdir = TempDir::new().unwrap(); let other_chdir = TempDir::new().unwrap();
let other_chdir_str = other_chdir.path().to_str().unwrap();
let reader = Sandbox::new(&[ let reader = Sandbox::new(&[
"--persistent-tmp", "--persistent-tmp",
"--persistent-key", "--persistent-key",
&key, &key,
"--ro",
other_chdir_str,
"--chdir", "--chdir",
other_chdir.path().to_str().unwrap(), other_chdir_str,
"--unshare-net", "--unshare-net",
]) ])
.args(["--", "cat", "/tmp/canary"]) .args(["--", "cat", "/tmp/canary"])
+2 -2
View File
@@ -65,7 +65,7 @@ fn chdir_override() {
let dir = TempDir::new().expect("failed to create temp dir"); let dir = TempDir::new().expect("failed to create temp dir");
let dir_str = dir.path().to_str().unwrap(); let dir_str = dir.path().to_str().unwrap();
let output = Sandbox::new(&["--chdir", dir_str]) let output = Sandbox::new(&["--ro", dir_str, "--chdir", dir_str])
.args(["--", "bash", "-c", "pwd"]) .args(["--", "bash", "-c", "pwd"])
.output() .output()
.expect("agent-sandbox binary failed to execute"); .expect("agent-sandbox binary failed to execute");
@@ -82,7 +82,7 @@ fn chdir_under_hardened_tmp() {
let dir = TempDir::new().expect("failed to create temp dir"); let dir = TempDir::new().expect("failed to create temp dir");
let dir_str = dir.path().to_str().unwrap(); let dir_str = dir.path().to_str().unwrap();
let output = Sandbox::new(&["--hardened", "--chdir", dir_str]) let output = Sandbox::new(&["--hardened", "--rw", dir_str, "--chdir", dir_str])
.args(["--", "bash", "-c", "pwd && touch ./ok && echo done"]) .args(["--", "bash", "-c", "pwd && touch ./ok && echo done"])
.output() .output()
.expect("agent-sandbox binary failed to execute"); .expect("agent-sandbox binary failed to execute");