Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
5 changes: 3 additions & 2 deletions crates/sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions crates/sandbox/policies/claude-code.toml
Original file line number Diff line number Diff line change
@@ -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" }
41 changes: 40 additions & 1 deletion crates/sandbox/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -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}");
}
}
}
28 changes: 26 additions & 2 deletions crates/sandbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -471,6 +489,7 @@ impl Sandbox {
temp: &TempDir,
cwd: &Path,
helper: &Path,
program: Option<&Path>,
offline: &mut Option<windows::offline::Ready>,
) -> Result<Option<windows::acl::Lease>, String> {
if self.policy.fs.mode == FsMode::Off && offline.is_none() {
Expand All @@ -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
Expand Down
22 changes: 22 additions & 0 deletions crates/sandbox/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
61 changes: 50 additions & 11 deletions crates/sandbox/src/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,20 +439,36 @@ pub fn fold_nested(roots: &[PathBuf]) -> Vec<PathBuf> {

/// 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<PathBuf> {
pub fn offline_reads(
roots: &[PathBuf],
cwd: &Path,
helper: &Path,
program: Option<&Path>,
) -> Vec<PathBuf> {
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<PathBuf> = 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
Expand Down Expand Up @@ -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");
Expand Down
Loading