Optional sandbox for bash, LSP servers and lens/test runners (bwrap, seatbelt)
This commit is contained in:
1 parent
d3390a823d
commit
8e7c0bb89a
11 files changed
+586
-17
No files matched your search
@@ -11,6 +11,7 @@ mod mask;
|
||||
pub mod memory;
|
||||
pub mod nudge;
|
||||
pub mod permit;
|
||||
pub mod sandbox;
|
||||
pub mod session;
|
||||
pub mod stats;
|
||||
pub mod subagent;
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
//! Optional sandbox for child processes (bash, LSP servers, lens runners, test runners).
|
||||
//!
|
||||
//! Every sandboxed spawn goes through [`command`], a drop-in for `Command::new`. With the sandbox
|
||||
//! off it is a plain `Command::new`; on, it returns a command that runs the program under
|
||||
//! `bwrap` (Linux) or `sandbox-exec` (macOS): filesystem read-only except the project dir and
|
||||
//! `rw`, `$HOME` hidden except `ro`/`rw`, no network unless `network`, environment filtered.
|
||||
//! The hx process itself (LLM API, OAuth tokens) stays outside. File tools call [`guard_read`] /
|
||||
//! [`guard_write`] because they run in-process.
|
||||
//!
|
||||
//! ponytail: one policy for all children, no per-call network opt-in; add when a tool needs it.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Mode {
|
||||
#[default]
|
||||
Off,
|
||||
On,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Backend {
|
||||
#[default]
|
||||
Auto,
|
||||
Bwrap,
|
||||
Seatbelt,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Cfg {
|
||||
/// off (default) | on
|
||||
pub mode: Mode,
|
||||
/// auto (default) | bwrap | seatbelt
|
||||
pub backend: Backend,
|
||||
/// network for sandboxed children (default false)
|
||||
pub network: bool,
|
||||
/// extra writable paths (the project dir is always writable); `~` expands
|
||||
pub rw: Vec<String>,
|
||||
/// extra readable paths under `$HOME` (which is otherwise hidden); `~` expands
|
||||
pub ro: Vec<String>,
|
||||
/// env vars passed to children; a trailing `*` matches a prefix
|
||||
pub env_allow: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for Cfg {
|
||||
fn default() -> Self {
|
||||
let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect();
|
||||
Cfg {
|
||||
mode: Mode::Off,
|
||||
backend: Backend::Auto,
|
||||
network: false,
|
||||
rw: s(&["~/.cargo/registry", "~/.cargo/git"]),
|
||||
ro: s(&[
|
||||
"~/.cargo",
|
||||
"~/.rustup",
|
||||
"~/.local",
|
||||
"~/.nvm",
|
||||
"~/.npm",
|
||||
"~/.pyenv",
|
||||
"~/.gitconfig",
|
||||
"~/.config/git",
|
||||
]),
|
||||
env_allow: s(&[
|
||||
"PATH",
|
||||
"HOME",
|
||||
"USER",
|
||||
"LOGNAME",
|
||||
"SHELL",
|
||||
"TERM",
|
||||
"LANG",
|
||||
"LC_*",
|
||||
"TMPDIR",
|
||||
"CARGO_*",
|
||||
"RUST*",
|
||||
"NIX_*",
|
||||
"NODE_PATH",
|
||||
"GOPATH",
|
||||
"GOROOT",
|
||||
"VIRTUAL_ENV",
|
||||
]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Sandbox {
|
||||
backend: Backend,
|
||||
network: bool,
|
||||
home: PathBuf,
|
||||
cwd: PathBuf,
|
||||
rw: Vec<PathBuf>,
|
||||
ro: Vec<PathBuf>,
|
||||
env_allow: Vec<String>,
|
||||
}
|
||||
|
||||
static SANDBOX: OnceLock<Option<Sandbox>> = OnceLock::new();
|
||||
|
||||
/// Call once at startup. Errors (never silently falls back) if `mode = on` and no backend works.
|
||||
pub fn init(cfg: &Cfg, cwd: &Path) -> Result<(), String> {
|
||||
let sb = if cfg.mode == Mode::On {
|
||||
Some(Sandbox::new(cfg, cwd)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
SANDBOX
|
||||
.set(sb)
|
||||
.map_err(|_| "sandbox already initialised".into())
|
||||
}
|
||||
|
||||
pub fn active() -> Option<&'static Sandbox> {
|
||||
SANDBOX.get().and_then(Option::as_ref)
|
||||
}
|
||||
|
||||
/// Drop-in for `tokio::process::Command::new` that applies the sandbox when it is on.
|
||||
pub fn command(program: impl AsRef<OsStr>) -> tokio::process::Command {
|
||||
match active() {
|
||||
Some(sb) => sb.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))
|
||||
}
|
||||
|
||||
/// Error if the file tools may not write `p`.
|
||||
pub fn guard_write(p: &Path) -> Result<(), String> {
|
||||
active().map_or(Ok(()), |sb| sb.guard_write(p))
|
||||
}
|
||||
|
||||
fn expand(home: &Path, s: &str) -> PathBuf {
|
||||
match s.strip_prefix("~/") {
|
||||
Some(r) => home.join(r),
|
||||
None if s == "~" => home.to_path_buf(),
|
||||
None => PathBuf::from(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical path of `p`, or of its nearest existing ancestor plus the rest (for new files).
|
||||
fn canon(p: &Path) -> PathBuf {
|
||||
// lexical `..`/`.` removal first, so a non-existent prefix cannot hide an escape
|
||||
let mut norm = PathBuf::new();
|
||||
for c in p.components() {
|
||||
match c {
|
||||
std::path::Component::ParentDir => {
|
||||
norm.pop();
|
||||
}
|
||||
std::path::Component::CurDir => {}
|
||||
c => norm.push(c),
|
||||
}
|
||||
}
|
||||
let p = norm.as_path();
|
||||
let mut rest = vec![];
|
||||
let mut cur = p;
|
||||
loop {
|
||||
if let Ok(c) = cur.canonicalize() {
|
||||
return rest.iter().rev().fold(c, |a, s| a.join(s));
|
||||
}
|
||||
match (cur.parent(), cur.file_name()) {
|
||||
(Some(par), Some(n)) => {
|
||||
rest.push(n.to_owned());
|
||||
cur = par;
|
||||
}
|
||||
_ => return p.to_path_buf(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Probe: can this backend run `true` with a read-only root?
|
||||
fn probe(b: Backend) -> Result<(), String> {
|
||||
let (bin, args): (&str, Vec<String>) = match b {
|
||||
Backend::Bwrap => (
|
||||
"bwrap",
|
||||
[
|
||||
"--ro-bind",
|
||||
"/",
|
||||
"/",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--unshare-all",
|
||||
"--",
|
||||
"true",
|
||||
]
|
||||
.map(String::from)
|
||||
.into(),
|
||||
),
|
||||
_ => (
|
||||
"sandbox-exec",
|
||||
["-p", "(version 1)(allow default)", "true"]
|
||||
.map(String::from)
|
||||
.into(),
|
||||
),
|
||||
};
|
||||
match std::process::Command::new(bin).args(&args).output() {
|
||||
Ok(o) if o.status.success() => Ok(()),
|
||||
Ok(o) => Err(format!(
|
||||
"`{bin}` cannot create a sandbox here: {}",
|
||||
String::from_utf8_lossy(&o.stderr).trim()
|
||||
)),
|
||||
Err(e) => Err(format!("`{bin}` not usable: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox {
|
||||
fn new(cfg: &Cfg, cwd: &Path) -> Result<Self, String> {
|
||||
let backend = match cfg.backend {
|
||||
Backend::Auto if cfg!(target_os = "macos") => Backend::Seatbelt,
|
||||
Backend::Auto => Backend::Bwrap,
|
||||
b => b,
|
||||
};
|
||||
probe(backend).map_err(|e| {
|
||||
format!("sandbox = on but {e}. Install bubblewrap (Linux), or set sandbox mode = \"off\" / pass --no-sandbox.")
|
||||
})?;
|
||||
let home: PathBuf = std::env::var_os("HOME").map(Into::into).unwrap_or_default();
|
||||
let paths = |v: &[String]| -> Vec<PathBuf> {
|
||||
v.iter()
|
||||
.map(|s| expand(&home, s))
|
||||
.filter(|p| p.exists())
|
||||
.map(|p| canon(&p))
|
||||
.collect()
|
||||
};
|
||||
let mut ro = paths(&cfg.ro);
|
||||
let skills = crate::context::hx_home().join("skills");
|
||||
if skills.exists() {
|
||||
ro.push(canon(&skills));
|
||||
}
|
||||
Ok(Sandbox {
|
||||
backend,
|
||||
network: cfg.network,
|
||||
home: canon(&home),
|
||||
cwd: canon(cwd),
|
||||
rw: paths(&cfg.rw),
|
||||
ro,
|
||||
env_allow: cfg.env_allow.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn describe(&self) -> String {
|
||||
format!(
|
||||
"{}, network {}",
|
||||
match self.backend {
|
||||
Backend::Seatbelt => "seatbelt",
|
||||
_ => "bwrap",
|
||||
},
|
||||
if self.network { "on" } else { "off" }
|
||||
)
|
||||
}
|
||||
|
||||
fn tmp_dirs() -> Vec<PathBuf> {
|
||||
let mut v = vec![canon(Path::new("/tmp"))];
|
||||
v.push(canon(&std::env::temp_dir()));
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
fn writable(&self) -> Vec<PathBuf> {
|
||||
let mut v = vec![self.cwd.clone()];
|
||||
v.extend(self.rw.iter().cloned());
|
||||
v.extend(Self::tmp_dirs());
|
||||
v
|
||||
}
|
||||
|
||||
fn guard_write(&self, p: &Path) -> Result<(), String> {
|
||||
let c = canon(p);
|
||||
if self.writable().iter().any(|w| c.starts_with(w)) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!(
|
||||
"sandbox: {} is outside the writable paths (project dir, /tmp, sandbox.rw)",
|
||||
p.display()
|
||||
))
|
||||
}
|
||||
|
||||
fn guard_read(&self, p: &Path) -> Result<(), String> {
|
||||
let c = canon(p);
|
||||
let hidden = c.starts_with(&self.home);
|
||||
if !hidden
|
||||
|| self
|
||||
.writable()
|
||||
.iter()
|
||||
.chain(self.ro.iter())
|
||||
.any(|w| c.starts_with(w))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!(
|
||||
"sandbox: {} is hidden (under $HOME, not in sandbox.ro/rw)",
|
||||
p.display()
|
||||
))
|
||||
}
|
||||
|
||||
fn env_ok(&self, k: &str) -> bool {
|
||||
self.env_allow.iter().any(|a| match a.strip_suffix('*') {
|
||||
Some(pre) => k.starts_with(pre),
|
||||
None => a == k,
|
||||
})
|
||||
}
|
||||
|
||||
fn command(&self, program: &OsStr) -> tokio::process::Command {
|
||||
let (bin, args) = match self.backend {
|
||||
Backend::Seatbelt => ("sandbox-exec", vec!["-p".into(), self.seatbelt_profile()]),
|
||||
_ => {
|
||||
let mut a = self.bwrap_args();
|
||||
a.push("--".into());
|
||||
("bwrap", a)
|
||||
}
|
||||
};
|
||||
let mut c = tokio::process::Command::new(bin);
|
||||
c.args(&args).arg(program).env_clear();
|
||||
for (k, v) in std::env::vars_os() {
|
||||
if k.to_str().is_some_and(|k| self.env_ok(k)) {
|
||||
c.env(k, v);
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn bwrap_args(&self) -> Vec<String> {
|
||||
let s = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut a: Vec<String> = [
|
||||
"--ro-bind",
|
||||
"/",
|
||||
"/",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--unshare-pid",
|
||||
"--unshare-ipc",
|
||||
"--unshare-uts",
|
||||
"--die-with-parent",
|
||||
"--new-session",
|
||||
]
|
||||
.map(String::from)
|
||||
.into();
|
||||
a.push(
|
||||
if self.network {
|
||||
"--share-net"
|
||||
} else {
|
||||
"--unshare-net"
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
// hide $HOME and /tmp, then bring back what is allowed (later mounts win)
|
||||
for t in Self::tmp_dirs() {
|
||||
a.extend(["--tmpfs".into(), s(&t)]);
|
||||
}
|
||||
if self.home != Path::new("/") && !self.home.as_os_str().is_empty() {
|
||||
a.extend(["--tmpfs".into(), s(&self.home)]);
|
||||
}
|
||||
for p in &self.ro {
|
||||
a.extend(["--ro-bind".into(), s(p), s(p)]);
|
||||
}
|
||||
for p in self.rw.iter().chain([&self.cwd]) {
|
||||
a.extend(["--bind".into(), s(p), s(p)]);
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn seatbelt_profile(&self) -> String {
|
||||
let q = |p: &Path| {
|
||||
format!(
|
||||
"(subpath \"{}\")",
|
||||
p.to_string_lossy()
|
||||
.replace('\\', "\\\\")
|
||||
.replace('"', "\\\"")
|
||||
)
|
||||
};
|
||||
let list = |v: &[PathBuf]| v.iter().map(|p| q(p)).collect::<Vec<_>>().join(" ");
|
||||
let mut p = String::from(
|
||||
"(version 1)\n(deny default)\n(allow process-exec)\n(allow process-fork)\n\
|
||||
(allow signal (target self))\n(allow sysctl-read)\n(allow mach-lookup)\n\
|
||||
(allow ipc-posix-shm)\n(allow file-read*)\n",
|
||||
);
|
||||
// last matching rule wins: hide $HOME, then re-allow
|
||||
p += &format!("(deny file-read* {})\n", q(&self.home));
|
||||
let w = self.writable();
|
||||
let readable: Vec<PathBuf> = w.iter().chain(self.ro.iter()).cloned().collect();
|
||||
p += &format!("(allow file-read* {})\n", list(&readable));
|
||||
p += &format!("(allow file-write* {})\n", list(&w));
|
||||
p += "(allow file-write* (literal \"/dev/null\") (literal \"/dev/tty\"))\n";
|
||||
if self.network {
|
||||
p += "(allow network*)\n";
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sb(backend: Backend, network: bool) -> Sandbox {
|
||||
Sandbox {
|
||||
backend,
|
||||
network,
|
||||
home: "/home/u".into(),
|
||||
cwd: "/home/u/proj".into(),
|
||||
rw: vec!["/home/u/.cargo/registry".into()],
|
||||
ro: vec!["/home/u/.cargo".into()],
|
||||
env_allow: vec!["PATH".into(), "LC_*".into()],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bwrap_hides_home_then_rebinds() {
|
||||
let a = sb(Backend::Bwrap, false).bwrap_args().join(" ");
|
||||
assert!(a.contains("--unshare-net") && !a.contains("--share-net"));
|
||||
let tmpfs = a.find("--tmpfs /home/u").unwrap();
|
||||
let bind = a.find("--bind /home/u/proj /home/u/proj").unwrap();
|
||||
assert!(
|
||||
tmpfs < bind,
|
||||
"home must be hidden before the project is bound"
|
||||
);
|
||||
assert!(
|
||||
sb(Backend::Bwrap, true)
|
||||
.bwrap_args()
|
||||
.join(" ")
|
||||
.contains("--share-net")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seatbelt_profile_rules() {
|
||||
let p = sb(Backend::Seatbelt, false).seatbelt_profile();
|
||||
assert!(p.contains("(deny default)") && !p.contains("network"));
|
||||
assert!(
|
||||
p.find("(deny file-read* (subpath \"/home/u\"))").unwrap()
|
||||
< p.find("(allow file-read* (subpath \"/home/u/proj\"")
|
||||
.unwrap()
|
||||
);
|
||||
assert!(p.contains("(allow file-write* (subpath \"/home/u/proj\")"));
|
||||
assert!(
|
||||
sb(Backend::Seatbelt, true)
|
||||
.seatbelt_profile()
|
||||
.contains("(allow network*)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guards() {
|
||||
let s = sb(Backend::Bwrap, false);
|
||||
assert!(s.guard_write(Path::new("/home/u/proj/new/a.rs")).is_ok());
|
||||
assert!(s.guard_write(Path::new("/home/u/.ssh/x")).is_err());
|
||||
assert!(s.guard_write(Path::new("/home/u/proj/../.bashrc")).is_err());
|
||||
assert!(s.guard_read(Path::new("/home/u/.ssh/id_rsa")).is_err());
|
||||
assert!(
|
||||
s.guard_read(Path::new("/home/u/.cargo/config.toml"))
|
||||
.is_ok()
|
||||
);
|
||||
assert!(s.guard_read(Path::new("/etc/hosts")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_filter() {
|
||||
let s = sb(Backend::Bwrap, false);
|
||||
assert!(s.env_ok("PATH") && s.env_ok("LC_ALL"));
|
||||
assert!(!s.env_ok("ANTHROPIC_API_KEY") && !s.env_ok("PATHX"));
|
||||
}
|
||||
|
||||
/// Real confinement; skipped where no backend works (CI without user namespaces).
|
||||
#[tokio::test]
|
||||
async fn confines() {
|
||||
let b = if cfg!(target_os = "macos") {
|
||||
Backend::Seatbelt
|
||||
} else {
|
||||
Backend::Bwrap
|
||||
};
|
||||
let proj = tempfile::tempdir().unwrap();
|
||||
let cfg = Cfg {
|
||||
mode: Mode::On,
|
||||
backend: b,
|
||||
rw: vec![],
|
||||
ro: vec![],
|
||||
..Cfg::default()
|
||||
};
|
||||
let Ok(sb) = Sandbox::new(&cfg, proj.path()) else {
|
||||
eprintln!("skipped: no sandbox backend");
|
||||
return;
|
||||
};
|
||||
let home = sb.home.clone();
|
||||
let run = |script: String| {
|
||||
let mut c = sb.command(OsStr::new("sh"));
|
||||
c.arg("-c").arg(script).current_dir(&sb.cwd);
|
||||
async move { c.output().await.unwrap() }
|
||||
};
|
||||
assert!(
|
||||
run("touch ok.txt".into()).await.status.success(),
|
||||
"project dir writable"
|
||||
);
|
||||
assert!(sb.cwd.join("ok.txt").exists());
|
||||
let probe = home.join(".hx-sandbox-probe");
|
||||
assert!(
|
||||
!run(format!("touch {}", probe.display()))
|
||||
.await
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(!probe.exists(), "HOME must be read-only/hidden");
|
||||
// cargo sets CARGO_MANIFEST_DIR for tests; with env_allow = [PATH] it must not leak
|
||||
assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
|
||||
let o = run("echo ${CARGO_MANIFEST_DIR:-unset}".into()).await;
|
||||
assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "unset");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user