Merge pull request 'claude_cli: sandboxed by default, outside only with user consent' (#165) from feat/claude-cli-sandbox into main
This commit was merged in pull request #165.
This commit is contained in:
commit
785effef11
3 files changed
+173
-2
No files matched your search
@@ -14,7 +14,18 @@ use serde_json::{Value, json};
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
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<Box<dyn std::future::Future<Output = tokio::process::Command> + Send>>
|
||||||
|
+ Send
|
||||||
|
+ Sync,
|
||||||
|
>;
|
||||||
|
|
||||||
pub struct ClaudeCli {
|
pub struct ClaudeCli {
|
||||||
|
spawner: Option<Spawner>,
|
||||||
bin: String,
|
bin: String,
|
||||||
/// extra args, e.g. `["--permission-mode", "acceptEdits"]`
|
/// extra args, e.g. `["--permission-mode", "acceptEdits"]`
|
||||||
args: Vec<String>,
|
args: Vec<String>,
|
||||||
@@ -29,11 +40,17 @@ impl ClaudeCli {
|
|||||||
bin: std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()),
|
bin: std::env::var("HX_CLAUDE_BIN").unwrap_or_else(|_| "claude".into()),
|
||||||
args,
|
args,
|
||||||
mcp: None,
|
mcp: None,
|
||||||
|
spawner: None,
|
||||||
session: Default::default(),
|
session: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `env` also carries the permission socket: claude then asks hx (`mcp__hx__approve`) before tools run.
|
/// `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<String>, env: Value) -> Self {
|
pub fn with_mcp(mut self, command: String, args: Vec<String>, env: Value) -> Self {
|
||||||
self.mcp = Some((command, args, env));
|
self.mcp = Some((command, args, env));
|
||||||
self
|
self
|
||||||
@@ -95,7 +112,10 @@ impl Provider for ClaudeCli {
|
|||||||
|
|
||||||
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>> {
|
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>> {
|
||||||
let sid = self.session.lock().ok().and_then(|s| s.clone());
|
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([
|
cmd.args([
|
||||||
"-p",
|
"-p",
|
||||||
"--output-format",
|
"--output-format",
|
||||||
|
|||||||
@@ -224,6 +224,102 @@ impl Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tool context for the claude sandbox question (set once the agent exists).
|
||||||
|
static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new();
|
||||||
|
/// Answer to "run claude outside the sandbox?" for this process.
|
||||||
|
static CLAUDE_OUTSIDE: std::sync::Mutex<Option<bool>> = 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).
|
/// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes).
|
||||||
/// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers.
|
/// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers.
|
||||||
fn command_specs(
|
fn command_specs(
|
||||||
@@ -366,6 +462,7 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
|||||||
Kind::Claude if CLAUDE_CLI.get().is_some() => {
|
Kind::Claude if CLAUDE_CLI.get().is_some() => {
|
||||||
let c =
|
let c =
|
||||||
hx_ai::claude_cli::ClaudeCli::new(CLAUDE_CLI.get().cloned().unwrap_or_default());
|
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() {
|
Arc::new(match std::env::current_exe() {
|
||||||
Ok(e) => c.with_mcp(
|
Ok(e) => c.with_mcp(
|
||||||
e.to_string_lossy().into(),
|
e.to_string_lossy().into(),
|
||||||
@@ -901,6 +998,7 @@ async fn main() -> Result<()> {
|
|||||||
if CLAUDE_CLI.get().is_some() {
|
if CLAUDE_CLI.get().is_some() {
|
||||||
// claude asks here (via `hx mcp-serve`) before running its tools
|
// claude asks here (via `hx mcp-serve`) before running its tools
|
||||||
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
|
||||||
|
let _ = CLAUDE_CX.set(cx.clone());
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let _ = hx_core::approve::serve(&p, cx).await;
|
let _ = hx_core::approve::serve(&p, cx).await;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ impl Default for Cfg {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Sandbox {
|
pub struct Sandbox {
|
||||||
backend: Backend,
|
backend: Backend,
|
||||||
network: bool,
|
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`.
|
/// Error if the file tools may not read `p`.
|
||||||
pub fn guard_read(p: &Path) -> Result<(), String> {
|
pub fn guard_read(p: &Path) -> Result<(), String> {
|
||||||
active().map_or(Ok(()), |sb| sb.guard_read(p))
|
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 {
|
pub fn describe(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
"{}, network {}",
|
"{}, network {}",
|
||||||
@@ -508,4 +538,27 @@ mod tests {
|
|||||||
let o = run("echo ${CARGO_MANIFEST_DIR:-unset}".into()).await;
|
let o = run("echo ${CARGO_MANIFEST_DIR:-unset}".into()).await;
|
||||||
assert_eq!(String::from_utf8_lossy(&o.stdout).trim(), "unset");
|
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"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user