From 3756c1235709ee451e6d4fc1e95f9b0ae3ba224d Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 16 Oct 2026 20:29:15 +0000 Subject: [PATCH] claude_cli: run claude inside the sandbox, outside only after the user allows it --- crates/hx-ai/src/claude_cli.rs | 22 +++++++- crates/hx-cli/src/main.rs | 98 ++++++++++++++++++++++++++++++++++ crates/hx-core/src/sandbox.rs | 55 ++++++++++++++++++- 3 files changed, 173 insertions(+), 2 deletions(-) diff --git a/crates/hx-ai/src/claude_cli.rs b/crates/hx-ai/src/claude_cli.rs index bc83c61..3efa994 100644 --- a/crates/hx-ai/src/claude_cli.rs +++ b/crates/hx-ai/src/claude_cli.rs @@ -14,7 +14,18 @@ use serde_json::{Value, json}; use std::sync::{Arc, Mutex}; use tokio::io::{AsyncBufReadExt, BufReader}; +/// Builds the `claude` command (lets the caller wrap it in a sandbox). +pub type Spawner = Arc< + dyn Fn( + String, + ) + -> std::pin::Pin + Send>> + + Send + + Sync, +>; + pub struct ClaudeCli { + spawner: Option, bin: String, /// extra args, e.g. `["--permission-mode", "acceptEdits"]` args: Vec, @@ -29,11 +40,17 @@ impl ClaudeCli { bin: std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()), args, mcp: None, + spawner: None, session: Default::default(), } } /// `env` also carries the permission socket: claude then asks hx (`mcp__hx__approve`) before tools run. + pub fn with_spawner(mut self, f: Spawner) -> Self { + self.spawner = Some(f); + self + } + pub fn with_mcp(mut self, command: String, args: Vec, env: Value) -> Self { self.mcp = Some((command, args, env)); self @@ -95,7 +112,10 @@ impl Provider for ClaudeCli { async fn stream(&self, req: Request) -> Result>> { let sid = self.session.lock().ok().and_then(|s| s.clone()); - let mut cmd = tokio::process::Command::new(&self.bin); + let mut cmd = match &self.spawner { + Some(f) => f(self.bin.clone()).await, + None => tokio::process::Command::new(&self.bin), + }; cmd.args([ "-p", "--output-format", diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 573707b..9e903d8 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -224,6 +224,102 @@ impl Config { } } +/// Tool context for the claude sandbox question (set once the agent exists). +static CLAUDE_CX: std::sync::OnceLock = std::sync::OnceLock::new(); +/// Answer to "run claude outside the sandbox?" for this process. +static CLAUDE_OUTSIDE: std::sync::Mutex> = std::sync::Mutex::new(None); +const OUTSIDE_RULE: &str = "claude:unsandboxed"; + +/// Allowed to leave the sandbox? A stored rule says yes; else the TUI asks (once per run, "always" +/// is stored in `.hx/allow.json`); without a prompt hook (`-p`) the answer is no. +async fn claude_outside() -> bool { + if let Some(v) = *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) { + return v; + } + let ok = match CLAUDE_CX.get() { + Some(cx) if cx.state.permit.get().is_some() => { + hx_core::tool::gate( + cx, + hx_core::permit::Request { + tool: "claude".into(), + detail: "run claude outside the sandbox (its tools then run unconfined)".into(), + rule: OUTSIDE_RULE.into(), + }, + ) + .await + } + Some(cx) => cx + .state + .allow + .lock() + .unwrap_or_else(|e| e.into_inner()) + .allows(&hx_core::permit::Request { + tool: "claude".into(), + detail: String::new(), + rule: OUTSIDE_RULE.into(), + }), + None => false, + }; + *CLAUDE_OUTSIDE.lock().unwrap_or_else(|e| e.into_inner()) = Some(ok); + ok +} + +/// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config, +/// the network, hx itself and the permission socket. +fn claude_extra(bin: &str) -> hx_core::sandbox::Extra { + let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default()); + let mut ro = vec![]; + let found = if bin.contains('/') { + Some(bin.into()) + } else { + std::env::var_os("PATH").and_then(|p| { + std::env::split_paths(&p) + .map(|d| d.join(bin)) + .find(|f| f.is_file()) + }) + }; + for f in found + .into_iter() + .chain(std::env::current_exe().ok()) + .flat_map(|f: std::path::PathBuf| [f.canonicalize().ok(), Some(f)]) + .flatten() + { + ro.extend(f.parent().map(Into::into)); + } + // claude's install dir (versions/..) sits next to the resolved symlink target + hx_core::sandbox::Extra { + ro, + rw: vec![ + home.join(".claude"), + home.join(".claude.json"), + home.join(".config/claude"), + hx_core::approve::sock_path(), + ], + network: true, + env: [ + "ANTHROPIC_*", + "CLAUDE_*", + "NODE_*", + "XDG_*", + "HTTP_PROXY", + "HTTPS_PROXY", + "NO_PROXY", + "SSL_CERT_*", + "HX_PERMIT_SOCK", + ] + .map(String::from) + .into(), + } +} + +/// The `claude` command: sandboxed when the sandbox is on, unless the user let it out. +async fn claude_command(bin: String) -> tokio::process::Command { + if hx_core::sandbox::active().is_none() || claude_outside().await { + return tokio::process::Command::new(bin); + } + hx_core::sandbox::command_with(&bin, &claude_extra(&bin)) +} + /// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes). /// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers. fn command_specs( @@ -366,6 +462,7 @@ fn provider(k: Kind) -> hx_ai::Result> { Kind::Claude if CLAUDE_CLI.get().is_some() => { let c = hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default()); + let c = c.with_spawner(Arc::new(|bin| Box::pin(claude_command(bin)))); Arc::new(match std::env::current_exe() { Ok(e) => c.with_mcp( e.to_string_lossy().into(), @@ -901,6 +998,7 @@ async fn main() -> Result<()> { if CLAUDE_CLI.get().is_some() { // claude asks here (via `hx mcp-serve`) before running its tools let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone()); + let _ = CLAUDE_CX.set(cx.clone()); tokio::spawn(async move { let _ = hx_core::approve::serve(&p, cx).await; }); diff --git a/crates/hx-core/src/sandbox.rs b/crates/hx-core/src/sandbox.rs index 336df4d..2938fdb 100644 --- a/crates/hx-core/src/sandbox.rs +++ b/crates/hx-core/src/sandbox.rs @@ -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) -> tokio::process::Command { } } +/// Per-program additions to the sandbox policy (see [`command_with`]). +#[derive(Default, Debug, Clone)] +pub struct Extra { + pub ro: Vec, + pub rw: Vec, + pub network: bool, + /// more env patterns (same syntax as `env_allow`) + pub env: Vec, +} + +/// Like [`command`], with extra paths / network / env for this one program. Plain command when off. +pub fn command_with(program: impl AsRef, 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 { + 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" + ); + } } -- 2.54.1