From feb5c0519981139a4242d1f51771577c11fc4d4a Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:57:33 -0600 Subject: [PATCH] insbx: a ready-made Claude Code policy; the offline account may read the program it runs Closes #40. policies/claude-code.toml, measured on Windows 11 with Claude Code 2.1.323 under network proxy, natively: - writes: the project and ~/.claude; CLAUDE_CONFIG_DIR=~/.claude keeps .claude.json there (Claude saves it by renaming a temp file into its folder, so ~/.claude.json alone could never be granted); - network: api.anthropic.com only. `claude -p` answered; its Write tool wrote in the project; a write outside it failed with EPERM although Claude's own permissions (--allowedTools Write --add-dir) allowed it; - CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1: without it a blocked telemetry host slowed a one-line answer from 22 s to 59 s (9 s unsandboxed; the rest is the user's own MCP servers being refused). Two insbx changes it needed: - The offline account may read the program a run was asked to start (resolved as the helper resolves it), per run like the helper itself. Without it claude.exe under ~/.local/bin could not start as the account ("not found") unless setup-windows --read opened its whole folder, which needs an administrator. - An [env] set value of `~`, `~/...` or `~\...` is the home directory, as policy paths already were, so a shared policy can say CLAUDE_CONFIG_DIR = "~/.claude". Both README examples that granted ~/.claude.json are fixed. --- README.md | 8 +++- crates/sandbox/README.md | 5 +- crates/sandbox/policies/claude-code.toml | 42 ++++++++++++++++ crates/sandbox/src/env.rs | 41 +++++++++++++++- crates/sandbox/src/lib.rs | 28 ++++++++++- crates/sandbox/src/policy.rs | 22 +++++++++ crates/sandbox/src/windows/mod.rs | 61 +++++++++++++++++++----- 7 files changed, 190 insertions(+), 17 deletions(-) create mode 100644 crates/sandbox/policies/claude-code.toml diff --git a/README.md b/README.md index 1239e2b..eb5ec0c 100644 --- a/README.md +++ b/README.md @@ -1233,9 +1233,15 @@ It refuses a policy the machine cannot enforce in full instead of running with less. To confine a whole incode run: ```sh -insbx run -w . -w ~/.claude -w ~/.claude.json -w ~/.incode --wall 1800 -- incode -t "…" +insbx run -w . -w ~/.claude -w ~/.incode --set-env CLAUDE_CONFIG_DIR=~/.claude --wall 1800 -- incode -t "…" ``` +`CLAUDE_CONFIG_DIR` keeps Claude Code's `.claude.json` inside `~/.claude`: +it saves that file by renaming a temp file into its folder, which would +otherwise need your whole home folder writable. For Claude Code itself +there is a ready-made policy, +[`crates/sandbox/policies/claude-code.toml`](crates/sandbox/policies/claude-code.toml). + Details, the policy format and what each OS enforces are in [`crates/sandbox/README.md`](crates/sandbox/README.md). diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index aafeebe..9c0cf5e 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -12,8 +12,9 @@ instead of running with less. # Write only in this project; network only to the package registry; 30 minutes. insbx run -w . --allow-host crates.io --allow-host '*.crates.io' --wall 1800 -- cargo build -# An agent CLI confined to its workspace, with a folder it must not see. -insbx run -w . -w ~/.claude -w ~/.claude.json --deny-read ../private-checks -- claude -p "fix the failing test" +# Claude Code confined to its workspace and ~/.claude, network to the API only, +# with a folder it must not see (the ready-made policy: policies/claude-code.toml). +insbx run --policy policies/claude-code.toml --deny-read ../private-checks -- claude -p "fix the failing test" # What would this machine enforce? insbx doctor diff --git a/crates/sandbox/policies/claude-code.toml b/crates/sandbox/policies/claude-code.toml new file mode 100644 index 0000000..776671f --- /dev/null +++ b/crates/sandbox/policies/claude-code.toml @@ -0,0 +1,42 @@ +# Claude Code under insbx (issue #40). +# +# insbx run --policy claude-code.toml -- claude -p "fix the failing test" +# +# Measured on Windows 11 with Claude Code 2.1.323, network proxy, native: +# `claude -p` answered with api.anthropic.com as the only allowed host. +# +# What each line is for: +# - Writes: the project, and ~/.claude, where Claude Code keeps its +# credentials, settings and sessions. Not ~/.claude.json: Claude Code saves +# that file by writing a temp file beside it in your home folder and +# renaming it in, so it would need the whole home folder writable. +# CLAUDE_CONFIG_DIR below moves it into ~/.claude instead. +# - CLAUDE_CONFIG_DIR: the sandboxed Claude keeps its own .claude.json +# (onboarding, per-project trust, user-scope MCP servers) in ~/.claude. +# A user-scope MCP server you added outside the sandbox must be added once +# more under it, or put in the project's .mcp.json. +# - CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: no telemetry or error +# reporting. Without it Claude Code also calls a logging host, and the +# blocked calls slowed a one-line answer from 22 s to 59 s. +# - Network: the API only. Every MCP server of yours that runs over HTTP is +# refused until its host is added below; each refused one also slows the +# start. mcp-proxy.anthropic.com is the claude.ai connectors' host. +# +# On Windows natively: network proxy runs the command as the insbx-offline +# account (`insbx setup-windows`, as administrator, once). insbx lets that +# account read the program it is asked to run, so claude.exe under your +# profile starts without a `--read` grant. Claude Code's Bash tool (Git +# Bash) does not start under the sandbox yet: issue #38. + +[fs] +mode = "workspace-write" +write = [".", "~/.claude"] + +[network] +mode = "proxy" +allow = ["api.anthropic.com"] +# Your HTTP MCP servers' hosts, if Claude Code should reach them: +# allow = ["api.anthropic.com", "mcp-proxy.anthropic.com", "api.githubcopilot.com"] + +[env] +set = { CLAUDE_CONFIG_DIR = "~/.claude", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1" } diff --git a/crates/sandbox/src/env.rs b/crates/sandbox/src/env.rs index d62a31f..7f5028f 100644 --- a/crates/sandbox/src/env.rs +++ b/crates/sandbox/src/env.rs @@ -138,11 +138,32 @@ pub fn compute( .chain(policy.set.iter().map(|(k, v)| (k.as_str(), v.as_str()))); for (name, value) in set { out.retain(|(n, _)| !n.to_string_lossy().eq_ignore_ascii_case(name)); - out.push((name.into(), value.into())); + out.push((name.into(), home_expanded(value))); } out } +/// A `set` value with a leading `~` as the home directory, as a policy's +/// paths have it (`policy::absolute`, the same `HOME` then `USERPROFILE`): +/// exactly `~`, or `~` then `/` or `\`. A ready-made policy can then point a +/// tool's config at the user's own home (`CLAUDE_CONFIG_DIR = "~/.claude"`). +/// Any other value, `~` inside it included, is kept as written. +fn home_expanded(value: &str) -> OsString { + let rest = if value == "~" { + Some("") + } else { + value + .strip_prefix("~/") + .or_else(|| value.strip_prefix("~\\")) + }; + let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")); + match (rest, home) { + (Some(""), Some(home)) => home, + (Some(rest), Some(home)) => std::path::Path::new(&home).join(rest).into_os_string(), + _ => value.into(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -224,4 +245,22 @@ mod tests { assert_eq!(names(&env), ["PATH", "https_proxy", "TMPDIR"]); assert_eq!(env.last().map(|(_, v)| v.clone()), Some("/policy".into())); } + + #[test] + fn a_set_value_starting_with_tilde_is_the_home_directory() { + let home = std::env::var_os("HOME") + .or_else(|| std::env::var_os("USERPROFILE")) + .expect("a home directory"); + let home = std::path::PathBuf::from(home); + assert_eq!(home_expanded("~"), home.as_os_str()); + assert_eq!(home_expanded("~/.claude"), home.join(".claude").as_os_str()); + assert_eq!( + home_expanded("~\\.claude"), + home.join(".claude").as_os_str() + ); + // Only a leading `~` followed by a separator (or alone) is home. + for kept in ["~user/x", "a~/b", "x=~/y", "~~", ""] { + assert_eq!(home_expanded(kept), OsString::from(kept), "{kept}"); + } + } } diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index e26a05b..f54e255 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -368,8 +368,26 @@ impl Sandbox { } else { windows::setup::ready().as_ref().ok().cloned() }; + // The program as the helper will find it (the parent's PATH, which + // the command's environment starts from), so the offline account + // may read it: see `windows::offline_reads`. #[cfg(windows)] - let lease = self.windows_lease(&roots, &temp, cwd, &helper, &mut offline)?; + let program_path = program.as_ref().to_str().and_then(|p| { + let path = std::env::var("PATH").ok(); + let pathext = std::env::var("PATHEXT").ok(); + let exists = |c: &str| cwd.join(c).is_file(); + windows::resolve_program(p, path.as_deref(), pathext.as_deref(), &exists) + .map(|found| cwd.join(found)) + }); + #[cfg(windows)] + let lease = self.windows_lease( + &roots, + &temp, + cwd, + &helper, + program_path.as_deref(), + &mut offline, + )?; // As the offline account, the command may only reach the loopback // ports the setup's filter permits: the proxy listens on one. #[cfg(windows)] @@ -471,6 +489,7 @@ impl Sandbox { temp: &TempDir, cwd: &Path, helper: &Path, + program: Option<&Path>, offline: &mut Option, ) -> Result, String> { if self.policy.fs.mode == FsMode::Off && offline.is_none() { @@ -488,7 +507,12 @@ impl Sandbox { let mut granted = grant.clone(); granted.push(temp.path.clone()); let account = offline.as_ref().map(|ready| { - let reads = windows::offline_reads(&granted, &real(cwd), &real(helper)); + let reads = windows::offline_reads( + &granted, + &real(cwd), + &real(helper), + program.map(real).as_deref(), + ); windows::acl::OfflineGrant { user: ready.sid.clone(), // PowerShell lists the current folder's parent to start in diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs index 7b866ac..968080b 100644 --- a/crates/sandbox/src/policy.rs +++ b/crates/sandbox/src/policy.rs @@ -374,6 +374,28 @@ fn absolute(path: &Path, cwd: &Path) -> PathBuf { mod tests { use super::*; + /// The ready-made Claude Code policy (`policies/claude-code.toml`, #40) + /// parses and says what it was measured to need. + #[test] + fn the_claude_code_policy_parses_and_allows_only_the_api() { + let p = Policy::from_toml(include_str!("../policies/claude-code.toml")).expect("parses"); + assert_eq!(p.fs.mode, FsMode::WorkspaceWrite); + assert_eq!(p.fs.write, [PathBuf::from("."), PathBuf::from("~/.claude")]); + assert_eq!(p.network.mode, NetMode::Proxy); + assert_eq!(p.network.allow, ["api.anthropic.com"]); + assert_eq!( + p.env.set.get("CLAUDE_CONFIG_DIR").map(String::as_str), + Some("~/.claude") + ); + assert_eq!( + p.env + .set + .get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") + .map(String::as_str), + Some("1") + ); + } + #[test] fn the_documented_example_parses() { let doc = include_str!("policy.rs") diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs index 4a4176f..5f986fa 100644 --- a/crates/sandbox/src/windows/mod.rs +++ b/crates/sandbox/src/windows/mod.rs @@ -439,20 +439,36 @@ pub fn fold_nested(roots: &[PathBuf]) -> Vec { /// What the offline account must also be able to read for a run whose /// roots (writable roots, temp directory) are `roots`: the folder the -/// command starts in, and the helper program it is started through, each -/// unless a root already holds it (and so grants it `Modify`). +/// command starts in, the helper program it is started through, and the +/// program it was asked to run (`program`, as [`resolve_program`] found it, +/// when it did), each unless a root already holds it (and so grants it +/// `Modify`). The program is the one the caller named, so letting the +/// account read it shows the command nothing it was not given: without it +/// a program under the user's profile (Claude Code's `~/.local/bin/claude.exe`) +/// could not even start, measured, unless `insbx setup-windows --read` had +/// opened its whole folder. A file the user may not re-ACL (`cmd.exe` in +/// System32) is left out later, by `acl::OfflineGrant::grantable`: it is +/// readable to `Users` already. #[must_use] -pub fn offline_reads(roots: &[PathBuf], cwd: &Path, helper: &Path) -> Vec { +pub fn offline_reads( + roots: &[PathBuf], + cwd: &Path, + helper: &Path, + program: Option<&Path>, +) -> Vec { let held = |p: &Path| { roots .iter() .any(|r| holds(&r.to_string_lossy(), &p.to_string_lossy())) }; - [cwd, helper] - .into_iter() - .filter(|p| !held(p)) - .map(Path::to_path_buf) - .collect() + let mut reads: Vec = Vec::new(); + for p in [Some(cwd), Some(helper), program].into_iter().flatten() { + let key = path_key(&p.to_string_lossy()); + if !held(p) && !reads.iter().any(|r| path_key(&r.to_string_lossy()) == key) { + reads.push(p.to_path_buf()); + } + } + reads } /// The folders the offline account must be able to list for the run's @@ -1093,23 +1109,46 @@ mod tests { ]; let helper = Path::new(r"C:\tools\insbx.exe"); assert_eq!( - offline_reads(&roots, Path::new(r"C:\w\proj\sub"), helper), + offline_reads(&roots, Path::new(r"C:\w\proj\sub"), helper, None), [PathBuf::from(r"C:\tools\insbx.exe")] ); assert_eq!( offline_reads( &roots, Path::new(r"C:\w"), - Path::new(r"c:\W\PROJ\target\insbx.exe") + Path::new(r"c:\W\PROJ\target\insbx.exe"), + None ), [PathBuf::from(r"C:\w")] ); assert_eq!( - offline_reads(&[], Path::new(r"C:\w"), helper), + offline_reads(&[], Path::new(r"C:\w"), helper, None), [PathBuf::from(r"C:\w"), PathBuf::from(r"C:\tools\insbx.exe")] ); } + #[test] + fn the_offline_account_also_reads_the_program_it_was_asked_to_run() { + let roots = [PathBuf::from(r"C:\w\proj")]; + let helper = Path::new(r"C:\tools\insbx.exe"); + let claude = Path::new(r"C:\Users\me\.local\bin\claude.exe"); + assert_eq!( + offline_reads(&roots, Path::new(r"C:\w\proj"), helper, Some(claude)), + [PathBuf::from(r"C:\tools\insbx.exe"), claude.to_path_buf()] + ); + // Inside a root already: nothing more to grant. + let built = Path::new(r"c:\W\proj\target\tool.exe"); + assert_eq!( + offline_reads(&roots, Path::new(r"C:\w\proj"), helper, Some(built)), + [PathBuf::from(r"C:\tools\insbx.exe")] + ); + // The helper itself named as the program: once. + assert_eq!( + offline_reads(&roots, Path::new(r"C:\w\proj"), helper, Some(helper)), + [PathBuf::from(r"C:\tools\insbx.exe")] + ); + } + #[test] fn arguments_are_quoted_for_command_line_to_argv() { assert_eq!(line(&["cmd", "/c", "echo"]), "cmd /c echo");