Skip to content

feat: optional OS sandbox for execute_bash - #1067

Merged
will-lamerton merged 8 commits into
Nano-Collective:mainfrom
Dhirenderchoudhary:fix/1049-os-sandbox-execute-bash
Sep 6, 2026
Merged

will-lamerton merged 8 commits into
Nano-Collective:mainfrom
Dhirenderchoudhary:fix/1049-os-sandbox-execute-bash

Conversation

@Dhirenderchoudhary

Copy link
Copy Markdown
Contributor

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 $HOME or the network.

nanocoder.sandbox (default off) wraps the same BashExecutor spawn:

  • macOS: sandbox-exec (no network, writes only in the project)
  • Linux: bwrap if present; if missing, tool error (no unsandboxed fallback)
  • Windows: tool error, documented

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

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Changeset

  • Added a changeset (pnpm changeset) describing this change for the changelog

Testing

Automated Tests

  • New features include passing tests in .spec.ts/tsx files
  • All existing tests pass (pnpm test:all completes successfully)
  • Tests cover both success and error scenarios

Manual Testing

  • Tested with Ollama
  • Tested with OpenRouter
  • Tested with OpenAI-compatible API
  • Tested MCP integration (if applicable)

Checklist

  • If this was for an open issue, I was assigned to it
  • Code follows project style guidelines
  • Self-review completed
  • Documentation updated (if needed)
  • No breaking changes (or clearly documented)
  • Appropriate logging added using structured logging (see CONTRIBUTING.md)

Comment thread source/services/bash-executor.ts Fixed
Comment thread source/services/bash-sandbox.ts Fixed
Comment thread source/services/bash-sandbox.ts Fixed
Comment thread source/services/bash-executor.ts Fixed

@will-lamerton will-lamerton left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/f gives Operation not permitted
  • echo x > "$TMPDIR/probe" blocked
  • mktemp fails

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/bwrap and /usr/local/bin/bwrap only. On NixOS (/run/wrappers/bin/bwrap), Guix or Homebrew-on-Linux, bwrap is installed and on PATH but users get "install bubblewrap". Resolve via PATH and widen BwrapBin to string.
  • spawnPlanned() re-branches on the literal paths instead of spawn(plan.bwrap, plan.args, ...), which is already type-safe. We spawn a variable binary elsewhere (source/custom-tools/handler.ts:56 spawns options.shell), so there is no rule forcing this. It is also the only reason BwrapBin has 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 their git status forever, where os.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 via isPathInside, 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()) runs realpathSync on every execute even when sandbox is off. Move it inside the if (sandbox) branch.
  • Consider --new-session on 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 planned branch) has no test, and that is the Linux-without-bwrap user path.
  • The one integration test is darwin-gated and t.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 will-lamerton left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() walks PATH, bwrap is widened to string, test covers it. Small hole: it is existsSync only, so a directory named bwrap on PATH counts as found.
  • spawnPlanned() re-branching: mostly fixed. bwrap is now spawn(plan.bwrap, plan.args). sandbox-exec still 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 .gitignore still carries the now-dead .nanocoder/cwd-* line this PR added. Please drop it from the diff.
  • $1 cwd steering: gone with the env-var fix.
  • loadSandboxConfig() non-boolean: fixed, warns via logWarning. One subtlety worth a thought: it returns null on an invalid value, so a bad project-level value falls through to the global config rather than hard-off. Consistent with loadHierarchicalConfig, 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. main now ships schemas/agents.config.schema.json, generated from DiskNanocoderConfig with additionalProperties: false. This branch is 78 commits behind and does not add sandbox, so after a rebase "sandbox": true is rejected as an unknown key by editors reading the schema. Needs sandbox?: boolean on DiskNanocoderConfig in source/types/config.ts plus a regenerated schema.
  • bwrap availability is checked, usability is not. --unshare-net needs unprivileged user namespaces. Where those are off (hardened distros, unprivileged containers), bwrap is on PATH so the plan succeeds and the user gets a raw bwrap failure instead of the clean "install bubblewrap" message.

Before merge

  1. Rebase on main and add sandbox to DiskNanocoderConfig plus the regenerated schema.
  2. Drop the stale .nanocoder/cwd-* line from .gitignore.
  3. 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.

@github-actions github-actions Bot added area:ci GitHub Actions and CI area:docs Documentation labels Sep 6, 2026
@will-lamerton

Copy link
Copy Markdown
Member

Nice work as always @Dhirenderchoudhary :)

@will-lamerton
will-lamerton merged commit c76d7e3 into Nano-Collective:main Sep 6, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci GitHub Actions and CI area:docs Documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] OS sandbox for execute_bash

3 participants