Merge pull request 'Optional sandbox for bash, LSP servers and lens/test runners' (#148) from feat/sandbox into main
This commit was merged in pull request #148.
This commit is contained in:
commit
5c6c8befa9
12 files changed
+638
-17
No files matched your search
@@ -55,6 +55,17 @@ max_tokens = 16384
|
|||||||
# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider
|
# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider
|
||||||
# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended
|
# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended
|
||||||
|
|
||||||
|
## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS).
|
||||||
|
## Project dir + /tmp writable, $HOME hidden except `ro`/`rw`, filtered env (no API keys/tokens), no network.
|
||||||
|
## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start.
|
||||||
|
# [sandbox]
|
||||||
|
# mode = "off" # off | on (CLI: --sandbox / --no-sandbox)
|
||||||
|
# backend = "auto" # auto | bwrap | seatbelt
|
||||||
|
# network = false
|
||||||
|
# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths
|
||||||
|
# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME
|
||||||
|
# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix
|
||||||
|
|
||||||
[lsp]
|
[lsp]
|
||||||
mode = "turn_end" # turn_end | agent_end | off
|
mode = "turn_end" # turn_end | agent_end | off
|
||||||
disable = ["clangd"]
|
disable = ["clangd"]
|
||||||
|
|||||||
@@ -14,6 +14,17 @@
|
|||||||
# codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox
|
# codemode = false # `codemode` tool: JS scripts that call other tools in a sandbox
|
||||||
# system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended
|
# system_prompt = "..." # replaces the built-in prompt; AGENTS.md is still appended
|
||||||
|
|
||||||
|
## Sandbox: bash, LSP servers, lens and test runners run under bwrap (Linux) / sandbox-exec (macOS).
|
||||||
|
## Project dir + /tmp writable, $HOME hidden except `ro`/`rw`, filtered env (no API keys/tokens), no network.
|
||||||
|
## File tools (read/write/edit) obey the same paths. mode = "on" without a working backend refuses to start.
|
||||||
|
# [sandbox]
|
||||||
|
# mode = "off" # off | on (CLI: --sandbox / --no-sandbox)
|
||||||
|
# backend = "auto" # auto | bwrap | seatbelt
|
||||||
|
# network = false
|
||||||
|
# rw = ["~/.cargo/registry", "~/.cargo/git"] # extra writable paths
|
||||||
|
# ro = ["~/.cargo", "~/.rustup", "~/.local", "~/.nvm", "~/.npm"] # readable parts of $HOME
|
||||||
|
# env_allow = ["PATH", "HOME", "TERM", "LC_*", "CARGO_*"] # trailing * = prefix
|
||||||
|
|
||||||
## OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter), used with provider = "custom".
|
## OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter), used with provider = "custom".
|
||||||
# [openai_compat]
|
# [openai_compat]
|
||||||
# base_url = "http://localhost:11434/v1"
|
# base_url = "http://localhost:11434/v1"
|
||||||
|
|||||||
@@ -39,6 +39,12 @@ struct Cli {
|
|||||||
/// Skip permission prompts for bash/write/edit (also `permissions = "yolo"` in config.toml).
|
/// Skip permission prompts for bash/write/edit (also `permissions = "yolo"` in config.toml).
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
yolo: bool,
|
yolo: bool,
|
||||||
|
/// Run bash, LSP servers and lens runners in a sandbox (bwrap / seatbelt).
|
||||||
|
#[arg(long, conflicts_with = "no_sandbox")]
|
||||||
|
sandbox: bool,
|
||||||
|
/// Force the sandbox off (overrides config).
|
||||||
|
#[arg(long)]
|
||||||
|
no_sandbox: bool,
|
||||||
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
|
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
|
||||||
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
@@ -129,6 +135,8 @@ struct Config {
|
|||||||
permissions: Option<String>,
|
permissions: Option<String>,
|
||||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||||
system_prompt: Option<String>,
|
system_prompt: Option<String>,
|
||||||
|
/// confine child processes: mode = "on", backend, network, rw, ro, env_allow
|
||||||
|
sandbox: Option<hx_core::sandbox::Cfg>,
|
||||||
lsp: Option<LspCfg>,
|
lsp: Option<LspCfg>,
|
||||||
/// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated
|
/// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated
|
||||||
extensions: Vec<hx_core::ext::ExtCfg>,
|
extensions: Vec<hx_core::ext::ExtCfg>,
|
||||||
@@ -177,6 +185,7 @@ impl Config {
|
|||||||
remember_model: o.remember_model.or(c.remember_model),
|
remember_model: o.remember_model.or(c.remember_model),
|
||||||
permissions: o.permissions.or(c.permissions),
|
permissions: o.permissions.or(c.permissions),
|
||||||
system_prompt: o.system_prompt.or(c.system_prompt),
|
system_prompt: o.system_prompt.or(c.system_prompt),
|
||||||
|
sandbox: o.sandbox.or(c.sandbox),
|
||||||
lsp: o.lsp.or(c.lsp),
|
lsp: o.lsp.or(c.lsp),
|
||||||
extensions: [c.extensions, o.extensions].concat(),
|
extensions: [c.extensions, o.extensions].concat(),
|
||||||
};
|
};
|
||||||
@@ -574,6 +583,14 @@ async fn main() -> Result<()> {
|
|||||||
let cwd = std::env::current_dir()?;
|
let cwd = std::env::current_dir()?;
|
||||||
let cfg = Config::load(&cwd)?;
|
let cfg = Config::load(&cwd)?;
|
||||||
trace("config");
|
trace("config");
|
||||||
|
let mut sb = cfg.sandbox.clone().unwrap_or_default();
|
||||||
|
if cli.sandbox {
|
||||||
|
sb.mode = hx_core::sandbox::Mode::On;
|
||||||
|
}
|
||||||
|
if cli.no_sandbox {
|
||||||
|
sb.mode = hx_core::sandbox::Mode::Off;
|
||||||
|
}
|
||||||
|
hx_core::sandbox::init(&sb, &cwd).map_err(anyhow::Error::msg)?;
|
||||||
if let Some(oc) = cfg.openai_compat.clone() {
|
if let Some(oc) = cfg.openai_compat.clone() {
|
||||||
let _ = COMPAT.set(oc);
|
let _ = COMPAT.set(oc);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,10 @@ pub enum Error {
|
|||||||
Aborted,
|
Aborted,
|
||||||
#[error("stream ended without Done")]
|
#[error("stream ended without Done")]
|
||||||
Truncated,
|
Truncated,
|
||||||
|
#[error(
|
||||||
|
"empty reply from the provider (stop: {0:?}), also on retry; try /compact or /model, or lower the effort"
|
||||||
|
)]
|
||||||
|
EmptyReply(StopReason),
|
||||||
#[error("max turns ({0}) reached")]
|
#[error("max turns ({0}) reached")]
|
||||||
MaxTurns(u32),
|
MaxTurns(u32),
|
||||||
}
|
}
|
||||||
@@ -351,6 +355,7 @@ impl Agent {
|
|||||||
|
|
||||||
async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> {
|
async fn run_inner(&mut self, prompt: String) -> Result<Message, Error> {
|
||||||
self.push(Message::user(prompt))?;
|
self.push(Message::user(prompt))?;
|
||||||
|
let mut empty_retries = 0;
|
||||||
for _ in 0..self.max_turns {
|
for _ in 0..self.max_turns {
|
||||||
if self.aborted() {
|
if self.aborted() {
|
||||||
return Err(Error::Aborted);
|
return Err(Error::Aborted);
|
||||||
@@ -390,6 +395,25 @@ impl Agent {
|
|||||||
}
|
}
|
||||||
let (msg, stop, usage) = done.ok_or(Error::Truncated)?;
|
let (msg, stop, usage) = done.ok_or(Error::Truncated)?;
|
||||||
self.usage.add(&usage);
|
self.usage.add(&usage);
|
||||||
|
// no text and no tool call (e.g. output_tokens 0): never store it, it would poison
|
||||||
|
// the context and every "continue" would hit the same empty reply
|
||||||
|
let useful = msg.content.iter().any(|b| match b {
|
||||||
|
ContentBlock::Text { text } => !text.trim().is_empty(),
|
||||||
|
ContentBlock::ToolUse { .. } => true,
|
||||||
|
_ => false,
|
||||||
|
});
|
||||||
|
if !useful {
|
||||||
|
if empty_retries == 0 {
|
||||||
|
empty_retries += 1;
|
||||||
|
self.emit(Event::Info(format!(
|
||||||
|
"empty reply from the provider (stop: {stop:?}); retrying once"
|
||||||
|
)))
|
||||||
|
.await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return Err(Error::EmptyReply(stop));
|
||||||
|
}
|
||||||
|
empty_retries = 0;
|
||||||
let total = (usage.input_tokens
|
let total = (usage.input_tokens
|
||||||
+ usage.cache_read_tokens
|
+ usage.cache_read_tokens
|
||||||
+ usage.cache_write_tokens
|
+ usage.cache_write_tokens
|
||||||
@@ -594,6 +618,34 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn empty_reply_retries_once_and_is_not_stored() {
|
||||||
|
let text = |t: &str| asst(vec![ContentBlock::Text { text: t.into() }]);
|
||||||
|
let mk = |v| {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let cx = ToolCtx {
|
||||||
|
cwd: dir.path().into(),
|
||||||
|
state: Default::default(),
|
||||||
|
};
|
||||||
|
let script = Arc::new(Script(Mutex::new(v), Mutex::new(vec![])));
|
||||||
|
let (a, _h) = Agent::new(
|
||||||
|
script,
|
||||||
|
Registry::default(),
|
||||||
|
Session::open(dir.path().join("s.jsonl")).unwrap(),
|
||||||
|
cx,
|
||||||
|
);
|
||||||
|
(a, dir)
|
||||||
|
};
|
||||||
|
// empty, then text: retried, only the good reply is stored
|
||||||
|
let (mut a, _d) = mk(vec![asst(vec![]), text("ok")]);
|
||||||
|
assert_eq!(a.run("p").await.unwrap().text(), "ok");
|
||||||
|
assert_eq!(a.session.messages().len(), 2);
|
||||||
|
// empty twice: error, nothing stored besides the prompt
|
||||||
|
let (mut a, _d) = mk(vec![asst(vec![]), asst(vec![])]);
|
||||||
|
assert!(matches!(a.run("p").await, Err(Error::EmptyReply(_))));
|
||||||
|
assert_eq!(a.session.messages().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn btw_reads_snapshot_without_touching_session() {
|
async fn btw_reads_snapshot_without_touching_session() {
|
||||||
let script = Arc::new(Script(
|
let script = Arc::new(Script(
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ mod mask;
|
|||||||
pub mod memory;
|
pub mod memory;
|
||||||
pub mod nudge;
|
pub mod nudge;
|
||||||
pub mod permit;
|
pub mod permit;
|
||||||
|
pub mod sandbox;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod stats;
|
pub mod stats;
|
||||||
pub mod subagent;
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
//! Minimal LSP JSON-RPC client over stdio.
|
//! Minimal LSP JSON-RPC client over stdio.
|
||||||
|
|
||||||
|
use hx_core::sandbox::command as sandboxed;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -8,7 +9,7 @@ use std::sync::Arc;
|
|||||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||||
use tokio::process::{Child, ChildStdin, Command};
|
use tokio::process::{Child, ChildStdin};
|
||||||
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
|
use tokio::sync::{Mutex, Notify, mpsc, oneshot};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -230,7 +231,7 @@ impl Client {
|
|||||||
root: &Path,
|
root: &Path,
|
||||||
init_options: Value,
|
init_options: Value,
|
||||||
) -> std::io::Result<Arc<Self>> {
|
) -> std::io::Result<Arc<Self>> {
|
||||||
let mut c = Command::new(&cmd[0]);
|
let mut c = sandboxed(&cmd[0]);
|
||||||
c.args(&cmd[1..])
|
c.args(&cmd[1..])
|
||||||
.current_dir(root)
|
.current_dir(root)
|
||||||
.stdin(Stdio::piped())
|
.stdin(Stdio::piped())
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
//! All runners report `Finding`s; the dispatcher runs the applicable ones in parallel with a timeout.
|
//! All runners report `Finding`s; the dispatcher runs the applicable ones in parallel with a timeout.
|
||||||
|
|
||||||
use crate::manager::which;
|
use crate::manager::which;
|
||||||
|
use hx_core::sandbox::command as sandboxed;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
@@ -204,7 +205,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration)
|
|||||||
"eslint" => eslint(root, files, timeout).await,
|
"eslint" => eslint(root, files, timeout).await,
|
||||||
"ast-grep" => ast_grep(root, files, timeout).await,
|
"ast-grep" => ast_grep(root, files, timeout).await,
|
||||||
"rustfmt" => exec(
|
"rustfmt" => exec(
|
||||||
Command::new("rustfmt")
|
sandboxed("rustfmt")
|
||||||
.args(["--edition", "2024"])
|
.args(["--edition", "2024"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -213,7 +214,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration)
|
|||||||
.await
|
.await
|
||||||
.map(|_| vec![]),
|
.map(|_| vec![]),
|
||||||
"ruff-format" => exec(
|
"ruff-format" => exec(
|
||||||
Command::new("ruff")
|
sandboxed("ruff")
|
||||||
.args(["format", "--quiet"])
|
.args(["format", "--quiet"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -222,7 +223,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration)
|
|||||||
.await
|
.await
|
||||||
.map(|_| vec![]),
|
.map(|_| vec![]),
|
||||||
"biome-format" => exec(
|
"biome-format" => exec(
|
||||||
Command::new("biome")
|
sandboxed("biome")
|
||||||
.args(["format", "--write"])
|
.args(["format", "--write"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -248,7 +249,7 @@ pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration)
|
|||||||
/// clippy checks the whole crate; `run` filters to changed files.
|
/// clippy checks the whole crate; `run` filters to changed files.
|
||||||
async fn clippy(root: &Path, timeout: Duration) -> Result<Vec<Finding>, String> {
|
async fn clippy(root: &Path, timeout: Duration) -> Result<Vec<Finding>, String> {
|
||||||
let (o, _) = exec(
|
let (o, _) = exec(
|
||||||
Command::new("cargo")
|
sandboxed("cargo")
|
||||||
.args([
|
.args([
|
||||||
"clippy",
|
"clippy",
|
||||||
"--quiet",
|
"--quiet",
|
||||||
@@ -299,7 +300,7 @@ async fn clippy(root: &Path, timeout: Duration) -> Result<Vec<Finding>, String>
|
|||||||
|
|
||||||
async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
||||||
let (o, _) = exec(
|
let (o, _) = exec(
|
||||||
Command::new("ruff")
|
sandboxed("ruff")
|
||||||
.args(["check", "--output-format=json", "--no-fix", "--quiet"])
|
.args(["check", "--output-format=json", "--no-fix", "--quiet"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -327,7 +328,7 @@ async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<F
|
|||||||
|
|
||||||
async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
||||||
let (o, _) = exec(
|
let (o, _) = exec(
|
||||||
Command::new("biome")
|
sandboxed("biome")
|
||||||
.args(["lint", "--reporter=json"])
|
.args(["lint", "--reporter=json"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -360,7 +361,7 @@ async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<
|
|||||||
|
|
||||||
async fn eslint(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
async fn eslint(root: &Path, files: &[PathBuf], timeout: Duration) -> Result<Vec<Finding>, String> {
|
||||||
let (o, _) = exec(
|
let (o, _) = exec(
|
||||||
Command::new("eslint")
|
sandboxed("eslint")
|
||||||
.args(["--format", "json"])
|
.args(["--format", "json"])
|
||||||
.args(files)
|
.args(files)
|
||||||
.current_dir(root),
|
.current_dir(root),
|
||||||
@@ -412,7 +413,7 @@ async fn ast_grep(
|
|||||||
return Ok(vec![]);
|
return Ok(vec![]);
|
||||||
}
|
}
|
||||||
let (o, _) = exec(
|
let (o, _) = exec(
|
||||||
Command::new("ast-grep")
|
sandboxed("ast-grep")
|
||||||
.args(["scan", "--json=compact", "--inline-rules"])
|
.args(["scan", "--json=compact", "--inline-rules"])
|
||||||
.arg(rules.join("\n---\n"))
|
.arg(rules.join("\n---\n"))
|
||||||
.args(files)
|
.args(files)
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
|
|
||||||
use crate::manager::which;
|
use crate::manager::which;
|
||||||
use crate::runners::marker_root;
|
use crate::runners::marker_root;
|
||||||
|
use hx_core::sandbox::command as sandboxed;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::process::Command;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum Adapter {
|
pub enum Adapter {
|
||||||
@@ -120,33 +120,33 @@ pub async fn run(r: &Run, timeout: Duration) -> Result<Outcome, String> {
|
|||||||
};
|
};
|
||||||
let mut cmd = match r.adapter {
|
let mut cmd = match r.adapter {
|
||||||
Adapter::Cargo => {
|
Adapter::Cargo => {
|
||||||
let mut c = Command::new("cargo");
|
let mut c = sandboxed("cargo");
|
||||||
c.args(["test", "--no-fail-fast", "--color", "never"]);
|
c.args(["test", "--no-fail-fast", "--color", "never"]);
|
||||||
c
|
c
|
||||||
}
|
}
|
||||||
Adapter::Pytest => {
|
Adapter::Pytest => {
|
||||||
let mut c = Command::new("pytest");
|
let mut c = sandboxed("pytest");
|
||||||
c.args(["-q", "-p", "no:cacheprovider", "--junitxml"])
|
c.args(["-q", "-p", "no:cacheprovider", "--junitxml"])
|
||||||
.arg(&tmp)
|
.arg(&tmp)
|
||||||
.args(&r.targets);
|
.args(&r.targets);
|
||||||
c
|
c
|
||||||
}
|
}
|
||||||
Adapter::Vitest => {
|
Adapter::Vitest => {
|
||||||
let mut c = Command::new(bin("vitest"));
|
let mut c = sandboxed(bin("vitest"));
|
||||||
c.args(["run", "--reporter=json", "--outputFile"])
|
c.args(["run", "--reporter=json", "--outputFile"])
|
||||||
.arg(&tmp)
|
.arg(&tmp)
|
||||||
.args(&r.targets);
|
.args(&r.targets);
|
||||||
c
|
c
|
||||||
}
|
}
|
||||||
Adapter::Jest => {
|
Adapter::Jest => {
|
||||||
let mut c = Command::new(bin("jest"));
|
let mut c = sandboxed(bin("jest"));
|
||||||
c.args(["--json", "--outputFile"])
|
c.args(["--json", "--outputFile"])
|
||||||
.arg(&tmp)
|
.arg(&tmp)
|
||||||
.args(&r.targets);
|
.args(&r.targets);
|
||||||
c
|
c
|
||||||
}
|
}
|
||||||
Adapter::Go => {
|
Adapter::Go => {
|
||||||
let mut c = Command::new("go");
|
let mut c = sandboxed("go");
|
||||||
c.args(["test", "-json"]);
|
c.args(["test", "-json"]);
|
||||||
c.args(r.targets.iter().map(|d| {
|
c.args(r.targets.iter().map(|d| {
|
||||||
let rel = d.strip_prefix(&r.root).unwrap_or(d);
|
let rel = d.strip_prefix(&r.root).unwrap_or(d);
|
||||||
|
|||||||
@@ -87,6 +87,9 @@ impl Tool for Read {
|
|||||||
}
|
}
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
||||||
|
if let Err(e) = hx_core::sandbox::guard_read(&p) {
|
||||||
|
return ToolResult::err(e);
|
||||||
|
}
|
||||||
let bytes = match tokio::fs::read(&p).await {
|
let bytes = match tokio::fs::read(&p).await {
|
||||||
Ok(b) => b,
|
Ok(b) => b,
|
||||||
Err(e) => return ToolResult::err(format!("{}: {e}", p.display())),
|
Err(e) => return ToolResult::err(format!("{}: {e}", p.display())),
|
||||||
@@ -161,6 +164,9 @@ impl Tool for Write {
|
|||||||
}
|
}
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
||||||
|
if let Err(e) = hx_core::sandbox::guard_write(&p) {
|
||||||
|
return ToolResult::err(e);
|
||||||
|
}
|
||||||
let c = a["content"].as_str().unwrap_or_default();
|
let c = a["content"].as_str().unwrap_or_default();
|
||||||
if p.exists() && !cx.state.is_fresh(&p) {
|
if p.exists() && !cx.state.is_fresh(&p) {
|
||||||
return ToolResult::err(format!(
|
return ToolResult::err(format!(
|
||||||
@@ -206,6 +212,9 @@ impl Tool for Edit {
|
|||||||
}
|
}
|
||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
let p = resolve(cx, a["path"].as_str().unwrap_or_default());
|
||||||
|
if let Err(e) = hx_core::sandbox::guard_write(&p) {
|
||||||
|
return ToolResult::err(e);
|
||||||
|
}
|
||||||
let (old, new) = (
|
let (old, new) = (
|
||||||
a["old_string"].as_str().unwrap_or_default(),
|
a["old_string"].as_str().unwrap_or_default(),
|
||||||
a["new_string"].as_str().unwrap_or_default(),
|
a["new_string"].as_str().unwrap_or_default(),
|
||||||
@@ -333,7 +342,7 @@ impl Tool for Bash {
|
|||||||
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
async fn call(&self, a: Value, cx: &ToolCtx) -> ToolResult {
|
||||||
let cmd = a["command"].as_str().unwrap_or_default();
|
let cmd = a["command"].as_str().unwrap_or_default();
|
||||||
let secs = a["timeout"].as_u64().unwrap_or(120).clamp(1, 3600);
|
let secs = a["timeout"].as_u64().unwrap_or(120).clamp(1, 3600);
|
||||||
let mut c = tokio::process::Command::new("bash");
|
let mut c = hx_core::sandbox::command("bash");
|
||||||
c.arg("-c")
|
c.arg("-c")
|
||||||
.arg(format!("exec 2>&1; {cmd}"))
|
.arg(format!("exec 2>&1; {cmd}"))
|
||||||
.current_dir(&cx.cwd)
|
.current_dir(&cx.cwd)
|
||||||
|
|||||||
@@ -20,3 +20,4 @@ sh tests/m6_e2e.sh
|
|||||||
python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok"
|
python3 tests/tui_lspinstall.py | grep -q FAIL && { echo "tui lsp install FAIL"; exit 1; } || echo "tui lsp install ok"
|
||||||
sh tests/m7_e2e.sh
|
sh tests/m7_e2e.sh
|
||||||
sh tests/m8_e2e.sh
|
sh tests/m8_e2e.sh
|
||||||
|
sh tests/sandbox_e2e.sh
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Sandbox: no raw child spawns outside the chokepoint (real confinement is tested in hx-core sandbox::tests::confines).
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
bad=$(grep -rn "Command::new" crates/hx-lens/src crates/hx-tools/src --include=*.rs | grep -v "tests\?\.rs\|manager.rs\|cargo\|stty\|\"kill\"")
|
||||||
|
[ -z "$bad" ] || { echo "sandbox e2e FAIL: raw spawn: $bad"; exit 1; }
|
||||||
|
echo "sandbox e2e ok"
|
||||||
Reference in new issue
Block a user