claude_cli: run claude inside the sandbox, outside only after the user allows it

This commit is contained in:
hermes committed 2026-10-16 20:29:15 +00:00
1 parent f519374312
commit 3756c12357
3 files changed
+173 -2

No files matched your search

+54 -1
View File
@@ -87,7 +87,7 @@ impl Default for Cfg {
}
}
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Sandbox {
backend: Backend,
network: bool,
@@ -124,6 +124,24 @@ pub fn command(program: impl AsRef<OsStr>) -> tokio::process::Command {
}
}
/// Per-program additions to the sandbox policy (see [`command_with`]).
#[derive(Default, Debug, Clone)]
pub struct Extra {
pub ro: Vec<PathBuf>,
pub rw: Vec<PathBuf>,
pub network: bool,
/// more env patterns (same syntax as `env_allow`)
pub env: Vec<String>,
}
/// Like [`command`], with extra paths / network / env for this one program. Plain command when off.
pub fn command_with(program: impl AsRef<OsStr>, x: &Extra) -> tokio::process::Command {
match active() {
Some(sb) => sb.with(x).command(program.as_ref()),
None => tokio::process::Command::new(program),
}
}
/// Error if the file tools may not read `p`.
pub fn guard_read(p: &Path) -> Result<(), String> {
active().map_or(Ok(()), |sb| sb.guard_read(p))
@@ -241,6 +259,18 @@ impl Sandbox {
})
}
fn with(&self, x: &Extra) -> Sandbox {
let mut s = self.clone();
let keep = |v: &[PathBuf]| -> Vec<PathBuf> {
v.iter().filter(|p| p.exists()).map(|p| canon(p)).collect()
};
s.ro.extend(keep(&x.ro));
s.rw.extend(keep(&x.rw));
s.network |= x.network;
s.env_allow.extend(x.env.iter().cloned());
s
}
pub fn describe(&self) -> String {
format!(
"{}, network {}",
@@ -508,4 +538,27 @@ mod tests {
let o = run("echo ${CARGO_MANIFEST_DIR:-unset}".into()).await;
assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "unset");
}
#[test]
fn extra_adds_paths_network_env() {
let d = tempfile::tempdir().unwrap();
let (ro, rw) = (d.path().join("ro"), d.path().join("rw"));
std::fs::create_dir_all(&ro).unwrap();
std::fs::create_dir_all(&rw).unwrap();
let x = Extra {
ro: vec![ro.clone(), "/nonexistent-x".into()],
rw: vec![rw.clone()],
network: true,
env: vec!["CLAUDE_*".into()],
};
let s = sb(Backend::Bwrap, false).with(&x);
let a = s.bwrap_args().join(" ");
assert!(a.contains("--share-net") && !a.contains("nonexistent"));
assert!(a.contains(&format!("--bind {0} {0}", canon(&rw).display())));
assert!(s.env_ok("CLAUDE_CONFIG") && !sb(Backend::Bwrap, false).env_ok("CLAUDE_CONFIG"));
assert!(
!s.network || !sb(Backend::Bwrap, false).network,
"base unchanged"
);
}
}