use crate::adapter::API_KEY_VARIABLES;
use crate::config::{Config, Sandbox};
use anyhow::{bail, Result};
use std::{ffi::OsStr, path::Path, process::Command};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Support {
Enforced,
Unchecked(String),
Unavailable(String),
Boundary(String),
}
impl Support {
pub fn is_enforced(&self) -> bool {
matches!(self, Self::Enforced | Self::Boundary(_))
}
pub fn switches_on(&self) -> bool {
matches!(self, Self::Enforced)
}
fn reason(&self) -> &str {
match self {
Self::Enforced => "",
Self::Unchecked(reason) | Self::Unavailable(reason) | Self::Boundary(reason) => reason,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Bwrap {
Missing,
Broken(String),
Works,
}
impl Bwrap {
fn works(&self) -> bool {
matches!(self, Self::Works)
}
}
pub fn probe_bwrap(cwd: &Path) -> Bwrap {
use std::sync::OnceLock;
static RESULT: OnceLock<Bwrap> = OnceLock::new();
RESULT
.get_or_init(|| {
let Some(path) = crate::process::resolve(OsStr::new("bwrap"), cwd) else {
return Bwrap::Missing;
};
let output = crate::process::run(
Command::new(path).current_dir(cwd).args([
"--ro-bind",
"/",
"/",
"--unshare-all",
"--die-with-parent",
"true",
]),
None,
Some(10),
);
match output {
Ok(output) if output.status.success() => Bwrap::Works,
Ok(output) => {
let text = String::from_utf8_lossy(&output.stderr);
Bwrap::Broken(
text.lines()
.next()
.unwrap_or("it exited with an error")
.trim()
.to_owned(),
)
}
Err(error) => Bwrap::Broken(format!("{error:#}")),
}
})
.clone()
}
fn bwrap_problem(bwrap: &Bwrap) -> String {
match bwrap {
Bwrap::Works => String::new(),
Bwrap::Missing => "bubblewrap (bwrap) is not on PATH".into(),
Bwrap::Broken(detail) => format!(
"bubblewrap is installed but cannot start here ({detail}); if this is Ubuntu 24.04, an AppArmor rule may be blocking unprivileged user namespaces"
),
}
}
pub fn claude_support(cwd: &Path) -> Support {
let socat = crate::process::resolve(OsStr::new("socat"), cwd).is_some();
claude_support_for(
std::env::consts::OS,
&probe_bwrap(cwd),
socat,
crate::platform::boundary_is_container(),
)
}
pub fn codex_support(cwd: &Path) -> Support {
codex_support_for(
std::env::consts::OS,
&probe_bwrap(cwd),
crate::platform::boundary_is_container(),
)
}
fn container_boundary() -> Support {
Support::Boundary(
"the run is inside a container that is the boundary (AGENGO_BOUNDARY=container)".into(),
)
}
fn codex_support_for(os: &str, bwrap: &Bwrap, container: bool) -> Support {
match os {
"macos" | "windows" => Support::Enforced,
"linux" if bwrap.works() => Support::Enforced,
"linux" if container => container_boundary(),
"linux" => Support::Unchecked(format!(
"{}; Codex's sandbox on Linux uses bubblewrap (`sudo apt-get install bubblewrap`) and without it falls back to a helper that needs user namespaces, which agengo cannot check",
bwrap_problem(bwrap)
)),
other => Support::Unchecked(format!("agengo does not know whether Codex's sandbox works on {other}")),
}
}
fn claude_support_for(os: &str, bwrap: &Bwrap, socat: bool, container: bool) -> Support {
match os {
"macos" => Support::Enforced,
"linux" if bwrap.works() && socat => Support::Enforced,
"linux" if container => container_boundary(),
"linux" => {
let mut problems = Vec::new();
if !bwrap.works() {
problems.push(bwrap_problem(bwrap));
}
if !socat {
problems.push("socat is not on PATH".into());
}
Support::Unavailable(format!(
"Claude Code's sandbox cannot run here: {} (for example `sudo apt-get install bubblewrap socat`)",
problems.join("; ")
))
}
"windows" => Support::Unavailable(
"Claude Code has no sandbox on native Windows; use WSL2, or run agengo in a container or VM".into(),
),
other => Support::Unavailable(format!("Claude Code's sandbox is not supported on {other}")),
}
}
pub fn check(mode: Sandbox, agent: &str, support: &Support) -> Result<()> {
if mode == Sandbox::Off || support.is_enforced() {
return Ok(());
}
if mode == Sandbox::Strict {
bail!(
"--sandbox strict needs an agent whose sandbox agengo can enforce, and {agent} is not one here: {}. Fix that, run agengo in a container or VM and use --sandbox auto, or use --sandbox off.",
support.reason()
);
}
note_once(agent, support.reason());
Ok(())
}
fn note_once(agent: &str, reason: &str) {
use std::sync::Mutex;
static SAID: Mutex<Vec<String>> = Mutex::new(Vec::new());
if let Ok(mut said) = SAID.lock() {
if !said.iter().any(|name| name == agent) {
said.push(agent.to_owned());
eprintln!("agengo: note: {agent} runs without an OS sandbox from agengo ({reason})");
}
}
}
const KEPT: &[&str] = &[
"PATH",
"HOME",
"USER",
"LOGNAME",
"SHELL",
"LANG",
"LANGUAGE",
"TERM",
"COLORTERM",
"NO_COLOR",
"TMPDIR",
"TMP",
"TEMP",
"TZ",
"PWD",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
"REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE",
"HTTP_PROXY",
"HTTPS_PROXY",
"NO_PROXY",
"ALL_PROXY",
"CARGO_HOME",
"RUSTUP_HOME",
"GOPATH",
"GOROOT",
"JAVA_HOME",
"VIRTUAL_ENV",
"NVM_DIR",
"SYSTEMROOT",
"COMSPEC",
"PATHEXT",
"USERPROFILE",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMFILES",
"WINDIR",
"DISPLAY",
"WAYLAND_DISPLAY",
];
const KEPT_PREFIXES: &[&str] = &[
"LC_",
"XDG_",
"CLAUDE",
"CODEX",
"ANTIGRAVITY",
"AGY_",
"ANTHROPIC_",
"OPENAI_",
"GEMINI_",
"AGENGO_",
];
fn kept(
vars: impl Iterator<Item = (String, String)>,
extra: &[String],
api_keys: bool,
) -> Vec<(String, String)> {
vars.filter(|(name, _)| {
let upper = name.to_ascii_uppercase();
if extra.iter().any(|wanted| wanted.eq_ignore_ascii_case(name)) {
return true;
}
if API_KEY_VARIABLES.contains(&upper.as_str()) {
return api_keys;
}
KEPT.contains(&upper.as_str())
|| KEPT_PREFIXES.iter().any(|prefix| upper.starts_with(prefix))
})
.collect()
}
pub fn filter_env(command: &mut Command, extra: &[String]) {
command
.env_clear()
.envs(kept(std::env::vars(), extra, true));
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
Setup,
Check,
}
const SECRET_PATHS: &[&str] = &[
".ssh",
".aws",
".gnupg",
".kube",
".docker",
".azure",
".config/gh",
".config/gcloud",
".netrc",
".git-credentials",
];
const CACHE_PATHS: &[&str] = &[".cargo", ".npm", ".cache"];
fn plan_sandbox_unavailable(cwd: &Path) -> Option<String> {
plan_sandbox_unavailable_for(std::env::consts::OS, &probe_bwrap(cwd))
}
fn plan_sandbox_unavailable_for(os: &str, bwrap: &Bwrap) -> Option<String> {
match (os, bwrap) {
("linux", Bwrap::Works) => None,
("linux", other) => Some(format!(
"plan commands cannot be sandboxed: {} (`sudo apt-get install bubblewrap`)",
bwrap_problem(other)
)),
(other, _) => Some(format!(
"plan commands cannot be sandboxed on {other} yet; run agengo on Linux or WSL2, or in a container"
)),
}
}
fn bwrap_args(
worktree: &Path,
git_dir: Option<&Path>,
git_common_dir: Option<&Path>,
home: Option<&Path>,
exists: &dyn Fn(&Path) -> bool,
network: bool,
extra_write: &[String],
) -> Vec<String> {
let text = |path: &Path| path.to_string_lossy().into_owned();
let mut args: Vec<String> = [
"--ro-bind",
"/",
"/",
"--dev",
"/dev",
"--proc",
"/proc",
"--tmpfs",
"/tmp",
"--die-with-parent",
"--new-session",
]
.iter()
.map(|part| (*part).to_owned())
.collect();
if let Some(common) = git_common_dir.filter(|common| common.starts_with("/tmp")) {
args.extend(["--ro-bind".into(), text(common), text(common)]);
}
let mut bind = |path: &Path| {
args.extend(["--bind".into(), text(path), text(path)]);
};
bind(worktree);
if let Some(git_dir) = git_dir {
bind(git_dir);
}
if let Some(home) = home {
for name in CACHE_PATHS {
let path = home.join(name);
if exists(&path) {
bind(&path);
}
}
}
for wanted in extra_write {
let path = match (wanted.strip_prefix("~/"), home) {
(Some(rest), Some(home)) => home.join(rest),
_ => Path::new(wanted).to_path_buf(),
};
if exists(&path) {
bind(&path);
}
}
if let Some(home) = home {
for name in SECRET_PATHS {
let path = home.join(name);
if !exists(&path) {
continue;
}
if path.is_dir() {
args.extend(["--tmpfs".into(), text(&path)]);
} else {
args.extend(["--ro-bind".into(), "/dev/null".into(), text(&path)]);
}
}
}
if !network {
args.push("--unshare-net".into());
}
args.extend(["--chdir".into(), text(worktree), "--".into()]);
args
}
pub fn plan_command(
command: &[String],
cwd: &Path,
config: &Config,
phase: Phase,
) -> Result<Command> {
let unavailable = if config.sandbox == Sandbox::Off {
None
} else {
plan_sandbox_unavailable(cwd)
};
if unavailable.is_some() && crate::platform::boundary_is_container() {
let mut result = crate::process::argv(command, cwd)?;
let vars = kept(std::env::vars(), &config.sandbox_env, false);
result.env_clear().envs(vars);
return Ok(result);
}
plan_command_with(command, cwd, config, phase, unavailable)
}
fn plan_command_with(
command: &[String],
cwd: &Path,
config: &Config,
phase: Phase,
unavailable: Option<String>,
) -> Result<Command> {
let mut result = crate::process::argv(command, cwd)?;
if config.sandbox == Sandbox::Off {
return Ok(result);
}
let vars = kept(std::env::vars(), &config.sandbox_env, false);
if let Some(reason) = unavailable {
if config.sandbox == Sandbox::Strict {
bail!("--sandbox strict cannot confine a plan command here: {reason}");
}
note_once("plan commands", &reason);
result.env_clear().envs(vars);
return Ok(result);
}
let git_dir = crate::process::run(
Command::new("git")
.current_dir(cwd)
.args(["rev-parse", "--absolute-git-dir"]),
None,
Some(10),
)
.ok()
.filter(|output| output.status.success())
.map(|output| std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()));
let git_common_dir = crate::process::run(
Command::new("git").current_dir(cwd).args([
"rev-parse",
"--path-format=absolute",
"--git-common-dir",
]),
None,
Some(10),
)
.ok()
.filter(|output| output.status.success())
.map(|output| std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()));
let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
let network = phase == Phase::Setup || config.sandbox_check_network;
let worktree = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
let mut wrapped = Command::new("bwrap");
wrapped
.args(bwrap_args(
&worktree,
git_dir.as_deref(),
git_common_dir.as_deref(),
home.as_deref(),
&|path| path.exists(),
network,
&config.sandbox_write,
))
.arg(result.get_program())
.args(result.get_args())
.current_dir(cwd)
.env_clear()
.envs(vars);
Ok(wrapped)
}
#[cfg(test)]
mod tests {
use super::*;
fn vars(names: &[&str]) -> Vec<(String, String)> {
names
.iter()
.map(|n| ((*n).to_owned(), "x".to_owned()))
.collect()
}
#[test]
fn secrets_stay_out_unless_listed() {
let all = vars(&[
"PATH",
"HOME",
"GITHUB_TOKEN",
"AWS_SECRET_ACCESS_KEY",
"NPM_TOKEN",
"LC_ALL",
"CLAUDE_CODE_OAUTH_TOKEN",
"CODEX_HOME",
"OPENAI_API_KEY",
"Path",
]);
let names = |extra: &[String]| -> Vec<String> {
kept(all.clone().into_iter(), extra, true)
.into_iter()
.map(|(name, _)| name)
.collect()
};
let plain = names(&[]);
for wanted in [
"PATH",
"HOME",
"LC_ALL",
"CLAUDE_CODE_OAUTH_TOKEN",
"CODEX_HOME",
"Path",
] {
assert!(plain.contains(&wanted.to_owned()), "{wanted} is dropped");
}
for secret in ["GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY", "NPM_TOKEN"] {
assert!(!plain.contains(&secret.to_owned()), "{secret} is passed");
}
assert!(plain.contains(&"OPENAI_API_KEY".to_owned()));
assert!(names(&["github_token".to_owned()]).contains(&"GITHUB_TOKEN".to_owned()));
let no_keys: Vec<String> = kept(all.clone().into_iter(), &[], false)
.into_iter()
.map(|(name, _)| name)
.collect();
assert!(!no_keys.contains(&"OPENAI_API_KEY".to_owned()));
assert!(no_keys.contains(&"PATH".to_owned()));
}
fn broken() -> Bwrap {
Bwrap::Broken("bwrap: No permissions to create new namespace".into())
}
#[test]
fn claude_sandbox_support_by_platform() {
let works = Bwrap::Works;
assert!(claude_support_for("macos", &Bwrap::Missing, false, false).is_enforced());
assert!(claude_support_for("linux", &works, true, false).is_enforced());
let missing = claude_support_for("linux", &works, false, false);
assert!(
missing.reason().contains("socat is not on PATH"),
"{missing:?}"
);
assert!(claude_support_for("windows", &works, true, false)
.reason()
.contains("WSL2"));
}
#[test]
fn a_bwrap_that_is_installed_but_cannot_start_is_not_a_sandbox() {
let support = claude_support_for("linux", &broken(), true, false);
assert!(!support.is_enforced(), "{support:?}");
assert!(
support.reason().contains("cannot start here"),
"{support:?}"
);
assert!(support
.reason()
.contains("No permissions to create new namespace"));
assert!(support.reason().contains("AppArmor"));
let codex = codex_support_for("linux", &broken(), false);
assert!(!codex.is_enforced(), "{codex:?}");
let plan = plan_sandbox_unavailable_for("linux", &broken()).unwrap();
assert!(plan.contains("cannot start here"), "{plan}");
}
#[test]
fn a_container_boundary_satisfies_strict_without_switching_the_agent_sandbox_on() {
for bwrap in [Bwrap::Missing, broken()] {
let claude = claude_support_for("linux", &bwrap, false, true);
assert!(matches!(claude, Support::Boundary(_)), "{claude:?}");
assert!(claude.is_enforced());
assert!(!claude.switches_on());
assert!(check(Sandbox::Strict, "claude", &claude).is_ok());
let codex = codex_support_for("linux", &bwrap, true);
assert!(matches!(codex, Support::Boundary(_)), "{codex:?}");
}
let both = claude_support_for("linux", &Bwrap::Works, true, true);
assert!(both.switches_on());
assert!(!claude_support_for("windows", &Bwrap::Missing, false, true).is_enforced());
}
#[test]
fn codex_sandbox_support_by_platform() {
assert!(codex_support_for("windows", &Bwrap::Missing, false).is_enforced());
assert!(codex_support_for("macos", &Bwrap::Missing, false).is_enforced());
assert!(codex_support_for("linux", &Bwrap::Works, false).is_enforced());
assert!(!codex_support_for("linux", &Bwrap::Missing, false).is_enforced());
assert!(codex_support_for("linux", &Bwrap::Missing, false)
.reason()
.contains("bubblewrap"));
}
#[test]
fn strict_refuses_what_cannot_be_enforced_and_auto_does_not() {
let cannot = Support::Unavailable("no sandbox here".into());
assert!(check(Sandbox::Off, "agy", &cannot).is_ok());
assert!(check(Sandbox::Auto, "agy", &cannot).is_ok());
assert!(check(Sandbox::Strict, "claude", &Support::Enforced).is_ok());
let error = check(Sandbox::Strict, "agy", &cannot)
.unwrap_err()
.to_string();
assert!(
error.contains("agy") && error.contains("no sandbox here"),
"{error}"
);
}
#[cfg(unix)]
#[test]
fn plan_commands_get_the_short_environment_only_when_asked() -> Result<()> {
let dir = tempfile::tempdir()?;
let run = |sandbox| -> Result<String> {
let config = Config {
sandbox,
..Config::default()
};
let mut command = plan_command_with(
&["env".to_owned()],
dir.path(),
&config,
Phase::Check,
Some("no wrapper in this test".into()),
)?;
Ok(String::from_utf8(command.output()?.stdout)?)
};
assert!(run(Sandbox::Off)?.contains("CARGO_MANIFEST_DIR="));
let env = run(Sandbox::Auto)?;
assert!(env.contains("PATH="));
assert!(!env.contains("CARGO_MANIFEST_DIR="), "{env}");
Ok(())
}
#[test]
#[cfg(unix)]
fn bwrap_confines_writes_hides_secrets_and_closes_the_network() {
let exists = |path: &Path| {
matches!(
path.to_str(),
Some("/home/u/.cargo" | "/home/u/.ssh" | "/home/u/.netrc" | "/home/u/data")
)
};
let args = bwrap_args(
Path::new("/work/wt"),
Some(Path::new("/repo/.git/worktrees/wt")),
Some(Path::new("/tmp/r/.git")),
Some(Path::new("/home/u")),
&exists,
false,
&["~/data".to_owned(), "~/missing".to_owned()],
);
let joined = args.join(" ");
assert!(joined.starts_with("--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp"));
for wanted in [
"--tmpfs /tmp --die-with-parent --new-session --ro-bind /tmp/r/.git /tmp/r/.git --bind /work/wt /work/wt",
"--bind /repo/.git/worktrees/wt /repo/.git/worktrees/wt",
"--bind /home/u/.cargo /home/u/.cargo",
"--bind /home/u/data /home/u/data",
"--ro-bind /dev/null /home/u/.netrc",
"--unshare-net",
"--chdir /work/wt --",
] {
assert!(joined.contains(wanted), "{wanted} missing from {joined}");
}
assert!(!joined.contains("/home/u/missing"));
assert!(
!joined.contains("--bind /home/u/.ssh"),
"secrets are hidden, not bound"
);
assert_eq!(args.last().map(String::as_str), Some("--"));
let open = bwrap_args(Path::new("/work/wt"), None, None, None, &exists, true, &[]);
assert!(!open.contains(&"--unshare-net".to_owned()));
}
#[test]
#[cfg(unix)]
fn plan_commands_run_through_bwrap_and_strict_refuses_without_it() -> Result<()> {
let dir = tempfile::tempdir()?;
let config = |sandbox| Config {
sandbox,
..Config::default()
};
let command = ["make".to_owned(), "test".to_owned()];
let wrapped = plan_command_with(
&command,
dir.path(),
&config(Sandbox::Auto),
Phase::Check,
None,
)?;
assert_eq!(wrapped.get_program(), "bwrap");
let args: Vec<_> = wrapped
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
assert!(
args.contains(&"--unshare-net".to_owned()),
"checks have no network"
);
assert_eq!(&args[args.len() - 3..], ["--", "make", "test"]);
let setup = plan_command_with(
&command,
dir.path(),
&config(Sandbox::Auto),
Phase::Setup,
None,
)?;
assert!(
!setup.get_args().any(|a| a == "--unshare-net"),
"setup keeps the network"
);
let plain = plan_command_with(
&command,
dir.path(),
&config(Sandbox::Off),
Phase::Check,
None,
)?;
assert_eq!(plain.get_program(), "make");
let error = plan_command_with(
&command,
dir.path(),
&config(Sandbox::Strict),
Phase::Check,
Some("no bwrap".into()),
)
.unwrap_err()
.to_string();
assert!(error.contains("no bwrap"), "{error}");
assert!(plan_sandbox_unavailable_for("linux", &Bwrap::Works).is_none());
assert!(plan_sandbox_unavailable_for("linux", &Bwrap::Missing)
.unwrap()
.contains("bubblewrap"));
assert!(plan_sandbox_unavailable_for("windows", &Bwrap::Works)
.unwrap()
.contains("windows"));
Ok(())
}
#[cfg(target_os = "linux")]
#[test]
#[ignore = "needs bubblewrap"]
fn real_bwrap_confines_a_plan_command() -> Result<()> {
let git = |dir: &Path, args: &[&str]| -> Result<()> {
let status = Command::new("git")
.current_dir(dir)
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.status()?;
anyhow::ensure!(status.success(), "git {args:?} failed");
Ok(())
};
let dir = tempfile::tempdir()?;
let repo = dir.path().join("repo");
let worktree = dir.path().join("wt");
std::fs::create_dir(&repo)?;
git(&repo, &["init", "-q"])?;
git(&repo, &["commit", "-q", "--allow-empty", "-m", "first"])?;
git(
&repo,
&[
"worktree",
"add",
"-q",
worktree.to_str().unwrap(),
"-b",
"t1",
],
)?;
let outside =
std::path::PathBuf::from(std::env::var("HOME")?).join("agengo-bwrap-outside.txt");
let script = format!(
"echo in > inside.txt; echo inside=$?; \
echo out > '{outside}' 2>/dev/null; echo outside=$?; \
curl -s -m 3 -o /dev/null https://example.com; echo net=$?; \
git status --short >/dev/null; echo gitstatus=$?",
outside = outside.display()
);
let command = ["sh".to_owned(), "-c".to_owned(), script];
let run = |phase| -> Result<String> {
let config = Config {
sandbox: Sandbox::Auto,
..Config::default()
};
let mut wrapped = plan_command(&command, &worktree, &config, phase)?;
Ok(String::from_utf8(wrapped.output()?.stdout)?)
};
let check = run(Phase::Check)?;
assert!(check.contains("inside=0"), "{check}");
assert!(
!check.contains("outside=0"),
"wrote outside the worktree: {check}"
);
assert!(!check.contains("net=0"), "reached the network: {check}");
assert!(check.contains("gitstatus=0"), "{check}");
assert!(worktree.join("inside.txt").exists());
assert!(!outside.exists());
Ok(())
}
}