Repository navigation
feat: optional OS sandbox for execute_bash - #1067
will-lamerton merged 8 commits into
Conversation
will-lamerton
left a comment
There was a problem hiding this comment.
Nice shape overall. Extracting planBashSpawn() into a pure module makes the platform matrix testable without actually jailing anything, and the fail-closed posture (no unsandboxed fallback) is right. I checked out 41605f4e: tsc --noEmit clean, biome clean, all 45 tests pass. Two things need fixing before this can go in.
Blocking
1. The $1 change leaks a positional arg into every command, including the sandbox-off default path.
Passing the capture path as argv instead of interpolating it is the safer construction, but it changes $@, $# and $1 for every command users run, sandbox on or off:
$ sh -c 'echo "args=[$@] count=$# zero=$0"' sh /tmp/capture-file
args=[/tmp/capture-file] count=1 zero=sh # after
$ sh -c 'echo "args=[$@] count=$# zero=$0"'
args=[] count=0 zero=sh # before
Any command using "$@", $# or $1 now sees the nanocoder capture path. Suggest passing it through the environment instead (env: {...process.env, NC_CWD_FILE: path} and command pwd -P > "$NC_CWD_FILE"). Equally injection-safe, leaves the positional params empty.
2. The profiles block all temp-dir writes, which breaks the tooling this feature exists to run.
Running the exact generated seatbelt profile:
echo x > /tmp/fgivesOperation not permittedecho x > "$TMPDIR/probe"blockedmktempfails
Compilers, git rebase/merge scratch, pnpm/npm, node and most test runners write to $TMPDIR, so !pnpm test and most builds will fail in non-obvious ways with the flag on. Linux has the same hole: --ro-bind / / with no --tmpfs /tmp and no $TMPDIR bind. Suggest allocating a per-execution temp dir, allowing it in both profiles, and setting TMPDIR to it in the child env. That also removes the need to relocate the cwd capture file into .nanocoder/ at all, which resolves several of the points below.
Should fix
- bwrap discovery only checks two hardcoded paths.
findBwrap()checks/usr/bin/bwrapand/usr/local/bin/bwraponly. On NixOS (/run/wrappers/bin/bwrap), Guix or Homebrew-on-Linux, bwrap is installed and onPATHbut users get "install bubblewrap". Resolve viaPATHand widenBwrapBintostring. spawnPlanned()re-branches on the literal paths instead ofspawn(plan.bwrap, plan.args, ...), which is already type-safe. We spawn a variable binary elsewhere (source/custom-tools/handler.ts:56spawnsoptions.shell), so there is no rule forcing this. It is also the only reasonBwrapBinhas to be a literal union.- The capture file moves into the user's repo.
.nanocoder/cwd-*is gitignored here, but nanocoder runs in other people's repos. A SIGKILL mid-command leaves an orphan file in theirgit statusforever, whereos.tmpdir()was reaped by the OS. If you keep the relocation, add a startup sweep. Fixing (2) avoids it entirely. - Related: the jailed command now gets the capture path in
$1, so it can write an arbitrary path there and steer the session cwd. Low impact (file tools clamp viaisPathInside, and jailed writes outside the root still fail), but the env-var fix in (1) removes the surface too. loadSandboxConfig()silently treats non-boolean as off."sandbox": "true"falls to the insecure default with no warning. For a security toggle that is the wrong direction.
Nits
resolveJailRoot(getProjectRoot())runsrealpathSyncon every execute even when sandbox is off. Move it inside theif (sandbox)branch.- Consider
--new-sessionon the bwrap args. Bubblewrap's own docs recommend it against TIOCSTI injection, and stdin is a pipe here so it costs nothing.
Tests
The pure planner is well covered across all four platform/availability combinations. Gaps:
- The executor's sandbox-error early return (the
'error' in plannedbranch) has no test, and that is the Linux-without-bwrap user path. - The one integration test is
darwin-gated andt.pass()es elsewhere. The bwrap path is never executed, only its argv is asserted, so on Linux CI nothing here runs end to end. Worth calling that out given "all existing tests pass" is unchecked. - No test that a sandboxed command can still run a normal build, which per (2) it currently cannot.
Docs
Accurate on what is enforced, incomplete on what is not. Reads are unrestricted ((allow default) / --ro-bind / /): a sandboxed command can ls ~/.ssh, and since stdout flows straight into the model's context, cat ~/.aws/credentials still reaches the provider despite the network block. Please state that plainly so nobody reads "OS jail" as "secrets are safe". Also worth noting sandbox-exec is deprecated by Apple (still functional), and what the temp-dir behaviour ends up being once (2) is addressed.
will-lamerton
left a comment
There was a problem hiding this comment.
Re-reviewed 178bb41b against my earlier notes. Both blockers are addressed and most of the should-fixes are too. I checked the branch out: the 14 sandbox specs pass, tsc --noEmit is clean, biome check is clean, and I ran the exact seatbelt profile the code generates rather than reading it.
Blocking - both fixed
1. $1 leak. The capture path now travels as NC_CWD_FILE in the child env, the epilogue is command pwd -P > "$NC_CWD_FILE", and spawn('sh', ['-c', spawnCommand]) takes no extra argv. unsandboxed commands keep empty positional args pins it. Good.
2. Temp-dir writes. A per-execution mkdtemp under os.tmpdir() is bound into both jails and exported as TMPDIR/TMP/TEMP, and it doubles as the home for the capture file, which resolves several of the follow-on points at once. Running the generated profile:
project write -> ok
$TMPDIR write -> ok
mktemp -> ok (/var/folders/.../T/tmp.ryryVOEVld)
/tmp write -> sh: /tmp/nc-probe: Operation not permitted
$HOME write -> Operation not permitted
network -> blocked (curl 000)
ls ~/.ssh -> id_rsa, id_rsa.pub
One gap left: the original echo x > /tmp/f probe still fails on macOS. Linux gets --tmpfs /tmp, so the same command succeeds there. Hardcoded /tmp/... writes are common enough in build tooling that this will bite someone, and the platform split is not documented. Either allow /private/tmp in the profile or say so in the docs.
Should fix
- bwrap discovery: fixed.
findBwrap()walksPATH,bwrapis widened tostring, test covers it. Small hole: it isexistsSynconly, so a directory namedbwraponPATHcounts as found. spawnPlanned()re-branching: mostly fixed. bwrap is nowspawn(plan.bwrap, plan.args).sandbox-execstill branches to a hardcoded/usr/bin/sandbox-exec. The type-level reason for the branch is gone, so what remains is vestigial rather than wrong.- Capture file in the repo: fixed, it lives in the per-execution temp dir. But
.gitignorestill carries the now-dead.nanocoder/cwd-*line this PR added. Please drop it from the diff. $1cwd steering: gone with the env-var fix.loadSandboxConfig()non-boolean: fixed, warns vialogWarning. One subtlety worth a thought: it returnsnullon an invalid value, so a bad project-level value falls through to the global config rather than hard-off. Consistent withloadHierarchicalConfig, mildly surprising for a security toggle.
Nits - both done
resolveJailRoot is inside the sandbox branch now, and --new-session is on the bwrap args with an assertion.
Docs - addressed
All three points are covered: reads are unrestricted and stdout still reaches the model, sandbox-exec is flagged as Apple-deprecated, and the temp-dir behaviour is explained. The macOS justification for allowing the whole per-user temp dir (bare mktemp ignores TMPDIR) checks out. I confirmed mktemp writes to /var/folders/.../T even with TMPDIR pointed elsewhere.
Tests - one gap still open
The executor error branch is covered now, and assertJail is a real end-to-end jail test. But pr-checks.yml runs ubuntu-latest only and bubblewrap is not preinstalled there, so findBwrap() returns undefined and the Linux jail test t.pass()es. The macOS test never runs at all. Net effect is unchanged from my last pass: no end-to-end sandbox test actually executes in CI. A sudo apt-get install -y bubblewrap step in the repo-local job would close it.
New since my last pass
- Schema drift.
mainnow shipsschemas/agents.config.schema.json, generated fromDiskNanocoderConfigwithadditionalProperties: false. This branch is 78 commits behind and does not addsandbox, so after a rebase"sandbox": trueis rejected as an unknown key by editors reading the schema. Needssandbox?: booleanonDiskNanocoderConfiginsource/types/config.tsplus a regenerated schema. - bwrap availability is checked, usability is not.
--unshare-netneeds unprivileged user namespaces. Where those are off (hardened distros, unprivileged containers), bwrap is onPATHso the plan succeeds and the user gets a raw bwrap failure instead of the clean "install bubblewrap" message.
Before merge
- Rebase on
mainand addsandboxtoDiskNanocoderConfigplus the regenerated schema. - Drop the stale
.nanocoder/cwd-*line from.gitignore. - Install bubblewrap in CI so the jail test actually runs, or state explicitly that it is untested there.
The macOS /tmp gap is a judgement call and defensible to ship documented. Nice work on the temp-dir fix, routing the capture file through it was the right call.
|
Nice work as always @Dhirenderchoudhary :) |
Description
execute_bash/!spawned a raw shell with the user's full privileges. File tools already stay inside the project. After yolo or a yes, nothing at the OS stopped writes to$HOMEor the network.nanocoder.sandbox(default off) wraps the sameBashExecutorspawn:sandbox-exec(no network, writes only in the project)bwrapif present; if missing, tool error (no unsandboxed fallback)Cwd capture cannot live in
os.tmpdir()under the jail, so with sandbox on it goes to.nanocoder/cwd-<id>. Timeouts and cancel are unchanged. Custom tools and MCP are out of scope.Closes #1049
Type of Change
Changeset
pnpm changeset) describing this change for the changelogTesting
Automated Tests
.spec.ts/tsxfilespnpm test:allcompletes successfully)Manual Testing
Checklist