From ab74f6a2cebba1b9f5c5faf31f1774522ab20351 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Sun, 16 Aug 2026 13:43:54 -0500 Subject: [PATCH 1/8] Add a fail-closed native sandbox runner for portable skill execution Pin Anthropic's sandbox runtime and translate trusted skill profiles into lightweight, on-demand filesystem, network, credential, and process-tree restrictions. Add readiness diagnostics, secure command and Git workspace discovery, signal-safe cleanup, Linux and macOS integration coverage, packaged-runtime checks, and practical compatibility guidance for Codex, Claude Code, OpenCode, and Pi. --- .github/workflows/ci.yml | 28 + .github/workflows/publish-github-package.yml | 1 + README.md | 18 +- bin/opencode-power-pack.mjs | 93 +- bin/sandbox/policy.mjs | 28 +- bin/sandbox/runtime.mjs | 1225 ++++++++++++++++++ docs/sandbox-compatibility.md | 135 ++ package-lock.json | 74 ++ package.json | 10 +- tests/package-surface.test.mjs | 28 +- tests/sandbox-policy.test.mjs | 106 +- tests/sandbox-runtime.integration.test.mjs | 363 ++++++ tests/sandbox-runtime.test.mjs | 893 +++++++++++++ 13 files changed, 2981 insertions(+), 21 deletions(-) create mode 100644 bin/sandbox/runtime.mjs create mode 100644 docs/sandbox-compatibility.md create mode 100644 package-lock.json create mode 100644 tests/sandbox-runtime.integration.test.mjs create mode 100644 tests/sandbox-runtime.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be523d6..af1aa31 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: "lts/*" + - run: npm ci - run: node --test - uses: actions/setup-python@v5 with: @@ -23,3 +24,30 @@ jobs: for skill in skills/*; do agentskills validate "$skill" done + + sandbox-runtime: + name: sandbox-runtime-${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20.11.1" + - name: Install Linux sandbox dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y bubblewrap socat ripgrep curl + if sysctl -n kernel.apparmor_restrict_unprivileged_userns >/dev/null 2>&1; then + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + - run: npm ci + - name: Run sandbox contract and real containment tests + run: npm run test:sandbox + env: + OPP_SANDBOX_INTEGRATION: "1" diff --git a/.github/workflows/publish-github-package.yml b/.github/workflows/publish-github-package.yml index 354c83d..6fa9c29 100644 --- a/.github/workflows/publish-github-package.yml +++ b/.github/workflows/publish-github-package.yml @@ -33,6 +33,7 @@ jobs: node-version: "20" registry-url: "https://npm.pkg.github.com" scope: "@waybarrios" + - run: npm ci - name: Verify tag matches package version run: | node --input-type=module -e ' diff --git a/README.md b/README.md index 241b041..fe0a3fd 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ The package assigns every bundled skill a default least-capability profile and a opencode-power-pack sandbox doctor opencode-power-pack sandbox resolve --skill code-review opencode-power-pack sandbox resolve --sandbox-profile publish --json +opencode-power-pack sandbox exec --skill code-review -- rg TODO . ``` | Sandbox profile | Workspace | Network and credentials | External side effects | @@ -164,7 +165,13 @@ opencode-power-pack sandbox resolve --sandbox-profile publish --json | `network-read` | Write | Explicitly approved | Denied | | `publish` | Write | Explicitly approved | Explicit confirmation required | -This first contract version reports `advisory` enforcement. It describes the capability boundary that host adapters must enforce, but it does not isolate commands or replace the permissions configured by Codex, Claude Code, OpenCode, or Pi. `sandbox doctor` therefore reports `Backend: not-configured` and `Strict ready: no` instead of implying a stronger guarantee. +The contract continues to report `advisory` because skill metadata does not enforce itself. The npm package also provides an opt-in `sandbox exec` runner backed by a pinned native runtime. When its operational preflight succeeds, `sandbox doctor` reports `shell-contained`; `Strict ready` remains `no` until a host adapter blocks ordinary tool bypasses. + +For `network-read`, the runner enforces conventional HTTP read methods (GET, HEAD, and OPTIONS). This is a best-effort side-effect boundary because an approved endpoint can still implement unsafe GET behavior. Use narrow destination grants and expose only credentials required for the retrieval. + +The runner is lightweight and on demand: it contains one command tree with native OS primitives, starts no persistent container or daemon, denies unrelated host reads, and deletes its private temporary directory after execution. `sandbox doctor` exits nonzero when the native boundary is unavailable. + +See [Sandbox Compatibility Across Coding Agents](docs/sandbox-compatibility.md) for the current Codex, Claude Code, OpenCode, and Pi matrix, platform requirements, activation design, fail-closed behavior, and adapter roadmap. Selective installations include a generated `SANDBOX_POLICY.json` beside each copied `SKILL.md`. The file is self-describing and preserves the skill's default profile even when the central package is not present. It remains advisory until an enforcement backend and host adapter are active. @@ -252,7 +259,7 @@ They are complementary rather than duplicate workflows. Codex shows distinct use ### Prerequisites - Git -- Node.js 20 or newer, including npm/npx, for [selective installation](#selective-install-with-npm) +- Node.js 20.11.0 or newer, including npm/npx, for [selective installation](#selective-install-with-npm) and the sandbox runner - One supported host: - A current Claude Code installation with plugin support: - OpenCode 1.18.7 or newer: @@ -482,6 +489,9 @@ opencode-power-pack +-- bin/sandbox/policy.mjs | +-- validates, resolves, and reports the shared capability contract | ++-- bin/sandbox/runtime.mjs +| +-- runs opt-in commands in the pinned native sandbox backend +| +-- .opencode/plugins/opencode-power-pack.js | +-- registers skills/ in config.skills.paths | +-- registers code-explorer as a read-only subagent @@ -505,11 +515,11 @@ The packaged agents deny edits, external network access, and nested tasks. `code | In scope | Out of scope | |---|---| -| Claude Code, Codex, OpenCode, and Pi skills and invocation | Claude Code hook contracts | +| Claude Code, Codex, OpenCode, and Pi skills and invocation | Whole-agent, browser, connector, or desktop isolation | | Portable and host-native subagent orchestration | Proprietary or non-redistributable plugins | | Licensed adaptations with immutable provenance | Automatic trust of third-party skill catalogs | | Explicit permission boundaries and regression tests | Supporting OpenCode versions older than 1.18.7 or obsolete Codex plugin formats | -| Versioned sandbox capability contracts and honest enforcement reporting | Treating advisory metadata as an OS security boundary | +| Versioned sandbox contracts and an opt-in shell-contained runner | Claiming whole-agent containment before host adapters block bypass tools | ## Contributing diff --git a/bin/opencode-power-pack.mjs b/bin/opencode-power-pack.mjs index 30d7988..3ea72a3 100755 --- a/bin/opencode-power-pack.mjs +++ b/bin/opencode-power-pack.mjs @@ -19,9 +19,14 @@ import { fileURLToPath } from "node:url"; import { loadSandboxContract, portableSkillPolicy, + resolveSandboxExecutionProfile, resolveSandboxProfile, sandboxDoctorReport, } from "./sandbox/policy.mjs"; +import { + probeSandboxRuntime, + runSandboxedCommand, +} from "./sandbox/runtime.mjs"; const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const USAGE = `OpenCode Power Pack selective skill installer @@ -34,6 +39,7 @@ Usage: npx @waybarrios/opencode-power-pack sandbox doctor [--json] npx @waybarrios/opencode-power-pack sandbox resolve --skill [--json] npx @waybarrios/opencode-power-pack sandbox resolve --sandbox-profile [--json] + npx @waybarrios/opencode-power-pack sandbox exec --skill [options] -- [args...] Options: --profile Install a curated profile. Repeatable. @@ -42,6 +48,11 @@ Options: --global Install into ~/.agents/skills. This is the default. --force Replace an existing skill directory with rollback on failure. --dry-run Show what would change without writing files. + --sandbox-profile Select an allowed profile escalation for sandbox exec. + --allow-domain Allow one network destination. Repeatable. + --allow-env Expose one existing environment variable. Repeatable. + --confirm-external-side-effects + Confirm a publish profile before sandbox exec. -h, --help Show this help. The .agents/skills location is shared by Codex, OpenCode, and Pi.`; @@ -340,7 +351,8 @@ function printCatalog(catalog, skills, write) { export function parseSandboxArgs(args) { const [command, ...rest] = args; - if (!command) throw new Error("Choose a sandbox command: doctor or resolve."); + if (!command) throw new Error("Choose a sandbox command: doctor, resolve, or exec."); + if (command === "exec") return parseSandboxExecArgs(rest); if (!["doctor", "resolve"].includes(command)) { throw new Error(`Unknown sandbox command: ${command}`); } @@ -371,6 +383,50 @@ export function parseSandboxArgs(args) { return options; } +export function parseSandboxExecArgs(args) { + const separator = args.indexOf("--"); + if (separator === -1) throw new Error("sandbox exec requires -- before the command."); + const optionArgs = args.slice(0, separator); + const command = args.slice(separator + 1); + if (command.length === 0 || command[0] === "") { + throw new Error("sandbox exec requires a non-empty command after --."); + } + const options = { + command: "exec", + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + childCommand: command, + }; + + for (let index = 0; index < optionArgs.length; index += 1) { + const value = optionArgs[index]; + if (["--skill", "--sandbox-profile", "--allow-domain", "--allow-env"].includes(value)) { + const target = optionArgs[index + 1]; + if (!target || target.startsWith("-")) throw new Error(`${value} requires a value.`); + if (value === "--skill" || value === "--sandbox-profile") { + const key = value === "--skill" ? "skillName" : "profileName"; + if (options[key]) throw new Error(`${value} may be provided only once.`); + options[key] = target; + } else if (value === "--allow-domain") { + options.allowedDomains.push(target); + } else { + options.allowedEnvironment.push(target); + } + index += 1; + } else if (value === "--confirm-external-side-effects") { + if (options.confirmExternalSideEffects) { + throw new Error("--confirm-external-side-effects may be provided only once."); + } + options.confirmExternalSideEffects = true; + } else { + throw new Error(`Unknown sandbox exec option: ${value}`); + } + } + if (!options.skillName) throw new Error("sandbox exec requires --skill."); + return options; +} + function printSandboxResolution(resolution, write) { if (resolution.skill) write(`Skill: ${resolution.skill}\n`); write(`Profile: ${resolution.profile.name}\n`); @@ -395,6 +451,8 @@ function printSandboxDoctor(report, write) { write(`Assigned skills: ${report.assignedSkills}/${report.packagedSkills}\n`); write(`Enforcement: ${report.enforcementLevel}\n`); write(`Backend: ${report.backend}\n`); + write(`Runner ready: ${report.runnerReady ? "yes" : "no"}\n`); + write(`Execution level: ${report.executionLevel}\n`); write(`Strict ready: ${report.strictReady ? "yes" : "no"}\n`); for (const warning of report.warnings) write(`Warning: ${warning}\n`); } @@ -404,18 +462,38 @@ export async function runSandboxCommand(args, context) { const skills = await discoverSkills(context.packageRoot); const availableSkillNames = skills.map((skill) => skill.name); const contract = await loadSandboxContract(context.packageRoot, availableSkillNames); + if (options.command === "exec") { + const profile = resolveSandboxExecutionProfile(contract, options); + return runSandboxedCommand({ + profile, + allowedDomains: options.allowedDomains, + allowedEnvironment: options.allowedEnvironment, + confirmExternalSideEffects: options.confirmExternalSideEffects, + command: options.childCommand, + }, context); + } + const result = options.command === "doctor" - ? sandboxDoctorReport(contract, availableSkillNames) + ? sandboxDoctorReport( + contract, + availableSkillNames, + await probeSandboxRuntime({ + cwd: context.cwd, + env: context.env || process.env, + ...context.runtimeProbeContext, + }), + ) : resolveSandboxProfile(contract, options); if (options.json) context.write(`${JSON.stringify(result, null, 2)}\n`); else if (options.command === "doctor") printSandboxDoctor(result, context.write); else printSandboxResolution(result, context.write); - return 0; + return options.command === "doctor" && !result.runnerReady ? 1 : 0; } export async function main(args = process.argv.slice(2), context = {}) { const write = context.write || ((text) => process.stdout.write(text)); + const writeError = context.writeError || ((text) => process.stderr.write(text)); const cwd = context.cwd || process.cwd(); const home = context.home || os.homedir(); const packageRoot = context.packageRoot || PACKAGE_ROOT; @@ -427,7 +505,14 @@ export async function main(args = process.argv.slice(2), context = {}) { } if (command === "sandbox") { - return runSandboxCommand(rest, { packageRoot, write }); + return runSandboxCommand(rest, { + ...context, + cwd, + home, + packageRoot, + write, + writeError, + }); } const catalog = await loadCatalog(packageRoot); diff --git a/bin/sandbox/policy.mjs b/bin/sandbox/policy.mjs index 6f95550..06bfad3 100644 --- a/bin/sandbox/policy.mjs +++ b/bin/sandbox/policy.mjs @@ -174,6 +174,17 @@ export function resolveSandboxProfile(contract, { skillName, profileName }) { }; } +export function resolveSandboxExecutionProfile(contract, { skillName, profileName }) { + if (!skillName) throw new Error("sandbox exec requires --skill."); + const resolution = resolveSandboxProfile(contract, { skillName }); + if (!profileName || profileName === resolution.profile.name) return resolution.profile; + const escalation = resolution.allowedEscalations.find((profile) => profile.name === profileName); + if (!escalation) { + throw new Error(`Skill ${skillName} does not permit sandbox profile: ${profileName}`); + } + return escalation; +} + export function portableSkillPolicy(contract, skillName) { const resolution = resolveSandboxProfile(contract, { skillName }); return { @@ -187,19 +198,30 @@ export function portableSkillPolicy(contract, skillName) { }; } -export function sandboxDoctorReport(contract, availableSkillNames) { +export function sandboxDoctorReport(contract, availableSkillNames, runtimeStatus) { validateSandboxContract(contract, availableSkillNames); + const status = runtimeStatus || { + backend: "not-configured", + runnerReady: false, + executionLevel: "advisory", + errors: [], + warnings: [], + }; return { ok: true, schemaVersion: contract.schemaVersion, enforcementLevel: contract.enforcementLevel, - backend: "not-configured", + backend: status.backend, + runnerReady: status.runnerReady, + executionLevel: status.executionLevel, strictReady: false, profiles: Object.keys(contract.profiles).length, assignedSkills: Object.keys(contract.skills).length, packagedSkills: availableSkillNames.length, warnings: [ - "Capability profiles are advisory until an enforcement backend and host adapter are active.", + ...status.errors.map((error) => `Runtime unavailable: ${error}`), + ...status.warnings, + "Skill metadata remains advisory until a host adapter routes commands through sandbox exec.", ], }; } diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs new file mode 100644 index 0000000..07a60ea --- /dev/null +++ b/bin/sandbox/runtime.mjs @@ -0,0 +1,1225 @@ +import { randomUUID } from "node:crypto"; +import { spawn as nodeSpawn } from "node:child_process"; +import { + access, + lstat, + mkdir, + mkdtemp, + open, + readFile, + readdir, + realpath, + rm, + stat, +} from "node:fs/promises"; +import { createServer } from "node:net"; +import os from "node:os"; +import path from "node:path"; + +export const SANDBOX_RUNTIME_PACKAGE = "@anthropic-ai/sandbox-runtime"; +export const SANDBOX_RUNTIME_VERSION = "0.0.73"; +export const SANDBOX_EXECUTION_LEVEL = "shell-contained"; + +const SUPPORTED_PLATFORMS = new Set(["linux", "darwin"]); +const READ_ONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); +const PROTECTED_ENVIRONMENT = new Set([ + "BASH_ENV", + "ENV", + "HOME", + "NODE_OPTIONS", + "PATH", + "SHELL", + "TMP", + "TMPDIR", + "TEMP", + "ZDOTDIR", +]); +const SAFE_ENVIRONMENT = new Set([ + "COLORTERM", + "FORCE_COLOR", + "LANG", + "LC_ALL", + "LC_CTYPE", + "NO_COLOR", + "TERM", + "TZ", +]); +let sandboxExecutionActive = false; + +function isWithin(parent, candidate) { + const relative = path.relative(parent, candidate); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +} + +function unique(values) { + return [...new Set(values)]; +} + +function assertEnvironmentName(name) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) { + throw new Error(`Invalid environment variable name: ${name}`); + } + if (PROTECTED_ENVIRONMENT.has(name) || /^(?:DYLD_|LD_)/.test(name)) { + throw new Error(`Sandbox control variable cannot be granted: ${name}`); + } +} + +export function quotePosixArgument(value) { + if (value.includes("\0")) throw new Error("Command arguments cannot contain NUL bytes."); + return `'${value.replaceAll("'", `'"'"'`)}'`; +} + +export function commandToShellString(command) { + if (!Array.isArray(command) || command.length === 0 || command[0] === "") { + throw new Error("sandbox exec requires a non-empty command after --."); + } + return command.map(quotePosixArgument).join(" "); +} + +export function buildChildEnvironment({ sourceEnvironment, allowedEnvironment, workspace, runRoot }) { + const childEnvironment = { + HOME: path.join(runRoot, "home"), + PATH: unique( + (sourceEnvironment.PATH || "") + .split(path.delimiter) + .filter((entry) => entry && path.isAbsolute(entry)) + .map((entry) => path.resolve(entry)) + .filter((entry) => !isWithin(workspace, entry)), + ).join(path.delimiter), + SHELL: "/bin/sh", + TMP: path.join(runRoot, "tmp"), + TMPDIR: path.join(runRoot, "tmp"), + TEMP: path.join(runRoot, "tmp"), + XDG_CACHE_HOME: path.join(runRoot, "cache"), + XDG_CONFIG_HOME: path.join(runRoot, "config"), + XDG_DATA_HOME: path.join(runRoot, "data"), + }; + + for (const name of SAFE_ENVIRONMENT) { + if (sourceEnvironment[name] !== undefined) childEnvironment[name] = sourceEnvironment[name]; + } + for (const name of unique(allowedEnvironment)) { + assertEnvironmentName(name); + if (sourceEnvironment[name] === undefined) { + throw new Error(`Requested environment variable is not set: ${name}`); + } + childEnvironment[name] = sourceEnvironment[name]; + } + return childEnvironment; +} + +function workspaceCredentialPaths(workspace) { + const relativePaths = [ + ".env", + ".env.local", + ".aws", + path.join(".config", "gh"), + path.join(".config", "gcloud"), + path.join(".docker", "config.json"), + ".git-credentials", + path.join(".kube", "config"), + ".netrc", + ".npmrc", + ".pypirc", + ".ssh", + ]; + return unique([ + ...relativePaths.map((relativePath) => path.join(workspace, relativePath)), + path.join(workspace, "**", ".env"), + path.join(workspace, "**", ".env.*"), + ...relativePaths.slice(2).map((relativePath) => path.join(workspace, "**", relativePath)), + ]); +} + +function credentialFiles(workspace, originalHome, additionalWorkspaceRoots = []) { + return unique([ + path.join(originalHome, ".ssh"), + path.join(originalHome, ".aws"), + path.join(originalHome, ".config", "gh"), + path.join(originalHome, ".config", "gcloud"), + path.join(originalHome, ".docker", "config.json"), + path.join(originalHome, ".git-credentials"), + path.join(originalHome, ".kube", "config"), + path.join(originalHome, ".netrc"), + path.join(originalHome, ".npmrc"), + path.join(originalHome, ".pypirc"), + ...unique([workspace, ...additionalWorkspaceRoots]).flatMap(workspaceCredentialPaths), + ]).map((filePath) => ({ path: filePath, mode: "deny" })); +} + +function unsafeSharedWriteRoots(originalHome, temporaryRoot) { + return unique([ + path.join(originalHome, ".claude", "debug"), + path.join(originalHome, ".npm", "_logs"), + path.join(temporaryRoot, "claude"), + "/tmp/claude", + "/private/tmp/claude", + ]); +} + +function protectedWritePaths( + workspace, + originalHome, + temporaryRoot, + additionalPaths = [], + additionalWorkspaceRoots = [], +) { + return unique([ + ...unsafeSharedWriteRoots(originalHome, temporaryRoot), + ...workspaceCredentialPaths(workspace), + path.join(workspace, ".agents"), + path.join(workspace, ".claude"), + path.join(workspace, ".codex"), + path.join(workspace, ".git", "config"), + path.join(workspace, ".git", "hooks"), + path.join(workspace, ".opencode"), + path.join(workspace, ".pi"), + ...additionalWorkspaceRoots.flatMap(workspaceCredentialPaths), + ...additionalPaths, + ]); +} + +export function compileSandboxExecution({ + profile, + workspace, + runRoot, + sourceEnvironment, + allowedDomains = [], + allowedEnvironment = [], + confirmExternalSideEffects = false, + originalHome = os.homedir(), + temporaryRoot = os.tmpdir(), + platform = process.platform, + helperPaths = {}, + readOnlySocksProxyPort, + readDenyPaths = [path.parse(path.resolve(workspace)).root], + readAllowPaths = [workspace, runRoot], + additionalDenyWritePaths = [], + additionalCredentialRoots = [], +}) { + if (!profile?.capabilities) throw new Error("A resolved sandbox profile is required."); + const capabilities = profile.capabilities; + const domains = unique(allowedDomains); + const environmentNames = unique(allowedEnvironment); + + if (domains.length > 0 && capabilities.network !== "explicit") { + throw new Error(`Profile ${profile.name} does not permit network grants.`); + } + if (environmentNames.length > 0 && capabilities.credentials !== "explicit") { + throw new Error(`Profile ${profile.name} does not permit credential grants.`); + } + if (capabilities.externalSideEffects === "confirm" && !confirmExternalSideEffects) { + throw new Error(`Profile ${profile.name} requires --confirm-external-side-effects.`); + } + if (capabilities.externalSideEffects === "deny" && confirmExternalSideEffects) { + throw new Error(`Profile ${profile.name} does not permit external side-effect confirmation.`); + } + if (profile.name === "network-read" && domains.length > 0 && !readOnlySocksProxyPort) { + throw new Error("network-read requires a fail-closed raw-network guard."); + } + + for (const name of environmentNames) assertEnvironmentName(name); + const childEnvironment = buildChildEnvironment({ + sourceEnvironment, + allowedEnvironment: environmentNames, + workspace, + runRoot, + }); + const deniedEnvironment = Object.keys(sourceEnvironment) + .filter((name) => !Object.hasOwn(childEnvironment, name)) + .map((name) => ({ name, mode: "deny" })); + const workspaceWrites = capabilities.workspace === "write" ? [workspace] : []; + const network = { + allowedDomains: capabilities.network === "explicit" ? domains : [], + deniedDomains: [], + strictAllowlist: true, + allowUnixSockets: [], + allowAllUnixSockets: false, + allowLocalBinding: false, + }; + + if (profile.name === "network-read" && domains.length > 0) { + network.socksProxyPort = readOnlySocksProxyPort; + network.tlsTerminate = {}; + network.filterRequest = async (request) => READ_ONLY_METHODS.has(request.method.toUpperCase()) + ? { action: "allow" } + : { action: "deny", reason: "network-read permits only GET, HEAD, and OPTIONS" }; + } + + const runtimeConfig = { + network, + filesystem: { + denyRead: unique(readDenyPaths), + allowRead: unique(readAllowPaths), + allowWrite: unique([...workspaceWrites, runRoot]), + denyWrite: protectedWritePaths( + workspace, + originalHome, + temporaryRoot, + additionalDenyWritePaths, + additionalCredentialRoots, + ), + allowGitConfig: false, + }, + credentials: { + files: credentialFiles(workspace, originalHome, additionalCredentialRoots), + envVars: deniedEnvironment, + }, + enableWeakerNestedSandbox: false, + enableWeakerNetworkIsolation: false, + allowAppleEvents: false, + allowPty: false, + mandatoryDenySearchDepth: 10, + ...(helperPaths.rg ? { ripgrep: { command: helperPaths.rg } } : {}), + ...(helperPaths.bwrap ? { bwrapPath: helperPaths.bwrap } : {}), + ...(helperPaths.socat ? { socatPath: helperPaths.socat } : {}), + }; + + return { + childEnvironment, + runtimeConfig, + summary: { + profile: profile.name, + executionLevel: SANDBOX_EXECUTION_LEVEL, + workspace: capabilities.workspace, + network: domains.length > 0 ? "explicit" : "denied", + credentials: environmentNames.length > 0 ? "explicit" : "denied", + externalSideEffects: capabilities.externalSideEffects, + }, + }; +} + +export async function existingSystemReadRoots(platform) { + const candidates = [ + "/bin", + "/sbin", + "/usr/bin", + "/usr/sbin", + "/usr/lib", + "/usr/lib64", + "/usr/libexec", + "/usr/share", + "/usr/local/bin", + "/usr/local/sbin", + "/usr/local/lib", + "/usr/local/lib64", + "/usr/local/share", + "/usr/local/go", + "/usr/local/cuda", + "/lib", + "/lib64", + "/etc/alternatives", + "/etc/ca-certificates", + "/etc/ssl", + "/etc/pki", + "/etc/hosts", + "/etc/resolv.conf", + "/etc/nsswitch.conf", + "/etc/passwd", + "/etc/group", + "/etc/localtime", + "/etc/os-release", + "/etc/services", + "/etc/protocols", + "/dev/null", + "/dev/zero", + "/dev/random", + "/dev/urandom", + ...(platform === "linux" ? ["/proc", "/sys", "/nix/store", "/snap"] : []), + ...(platform === "darwin" ? [ + "/System", + "/opt/homebrew/bin", + "/opt/homebrew/sbin", + "/opt/homebrew/Cellar", + "/opt/homebrew/opt", + "/opt/homebrew/lib", + "/opt/homebrew/share", + "/usr/local/Homebrew", + "/usr/local/Cellar", + "/usr/local/opt", + ] : []), + ]; + const resolved = []; + for (const candidate of candidates) { + try { + await access(candidate); + resolved.push(path.resolve(candidate), await realpath(candidate)); + } catch { + // Optional system paths differ by platform and installation. + } + } + return unique(resolved); +} + +async function discoverRuntimeBundleRoots(executable, { workspace, originalHome, temporaryRoot }) { + const roots = []; + let current = path.dirname(executable); + for (let depth = 0; depth <= 4; depth += 1) { + if ( + current === path.parse(current).root + || current === originalHome + || current === temporaryRoot + || isWithin(workspace, current) + ) break; + try { + await Promise.any([ + access(path.join(current, "package.json")), + access(path.join(current, "pyvenv.cfg")), + ]); + roots.push(current, await realpath(current)); + break; + } catch { + // Continue toward a bounded package or virtual-environment root. + } + current = path.dirname(current); + } + + const localBin = path.join(originalHome, ".local", "bin"); + if (isWithin(localBin, executable)) { + const localLibraries = path.join(originalHome, ".local", "lib"); + try { + await access(localLibraries); + roots.push(localLibraries, await realpath(localLibraries)); + } catch { + // User-level Python libraries are optional. + } + } + return unique(roots); +} + +async function readFirstLine(filePath) { + const handle = await open(filePath, "r"); + try { + const buffer = Buffer.alloc(4096); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); + return buffer.subarray(0, bytesRead).toString("utf8").split(/\r?\n/, 1)[0]; + } finally { + await handle.close(); + } +} + +function splitShebangWords(value) { + const words = []; + let word = ""; + let quote; + let escaped = false; + let started = false; + for (const character of value.trim()) { + if (escaped) { + word += character; + escaped = false; + started = true; + } else if (character === "\\" && quote !== "'") { + escaped = true; + started = true; + } else if (quote) { + if (character === quote) quote = undefined; + else word += character; + started = true; + } else if (character === "'" || character === '"') { + quote = character; + started = true; + } else if (/\s/.test(character)) { + if (started) { + words.push(word); + word = ""; + started = false; + } + } else { + word += character; + started = true; + } + } + if (escaped || quote) return []; + if (started) words.push(word); + return words; +} + +function envShebangCommand(arguments_) { + let words = [...arguments_]; + const splitIndex = words.findIndex((word) => word === "-S" || word === "--split-string"); + if (splitIndex !== -1) words = splitShebangWords(words.slice(splitIndex + 1).join(" ")); + const optionsWithValues = new Set(["-u", "--unset", "-C", "--chdir"]); + for (let index = 0; index < words.length; index += 1) { + const word = words[index]; + if (word === "--") return words[index + 1]; + if (optionsWithValues.has(word)) { + index += 1; + continue; + } + if (word.startsWith("-") || /^[^=]+=/.test(word)) continue; + return word; + } + return undefined; +} + +async function executableReadRoots(executable, environmentPath, cwd, boundaries, depth = 0) { + if (!executable) return []; + const candidates = path.isAbsolute(executable) + ? [executable] + : executable.includes(path.sep) + ? [path.resolve(cwd, executable)] + : (environmentPath || "") + .split(path.delimiter) + .filter((directory) => directory && path.isAbsolute(directory)) + .map((directory) => path.join(directory, executable)); + for (const candidate of candidates) { + try { + const resolved = await realpath(candidate); + const info = await stat(resolved); + await access(resolved, 1); + if (info.isFile()) { + const roots = [ + path.resolve(candidate), + resolved, + ...await discoverRuntimeBundleRoots(resolved, boundaries), + ]; + if (depth < 2) { + const firstLine = await readFirstLine(resolved); + if (firstLine.startsWith("#!")) { + const shebang = splitShebangWords(firstLine.slice(2)); + const interpreter = shebang.length > 0 && path.basename(shebang[0]) === "env" + ? envShebangCommand(shebang.slice(1)) + : shebang[0]; + if (interpreter) { + const interpreterRoots = await executableReadRoots( + interpreter, + environmentPath, + cwd, + boundaries, + depth + 1, + ); + roots.push(...interpreterRoots); + } + } + } + return unique(roots); + } + } catch { + // The child shell reports command-not-found when no candidate resolves. + } + } + return []; +} + +async function commandReadRoots(command, environmentPath, cwd, boundaries) { + return executableReadRoots(command?.[0], environmentPath, cwd, boundaries); +} + +async function readBoundedRegularFile(filePath, maximumSize, label) { + const info = await lstat(filePath); + if (!info.isFile() || info.size > maximumSize) { + throw new Error(`${label} is not a bounded regular file: ${filePath}`); + } + return readFile(filePath, "utf8"); +} + +async function readSmallMetadataFile(filePath) { + return readBoundedRegularFile(filePath, 8192, "Git metadata pointer"); +} + +async function findAncestorGitContext(start) { + let current = start; + while (true) { + const marker = path.join(current, ".git"); + try { + const info = await lstat(marker); + if (info.isDirectory()) { + const gitDirectory = await realpath(marker); + return { workspace: current, gitDirectory, commonDirectory: gitDirectory }; + } + if (info.isFile()) { + const pointer = (await readSmallMetadataFile(marker)).trim().match(/^gitdir:\s*(.+)$/i); + if (pointer) { + const gitDirectory = await realpath(path.resolve(current, pointer[1])); + let commonDirectory = gitDirectory; + try { + const commonPointer = (await readSmallMetadataFile( + path.join(gitDirectory, "commondir"), + )).trim(); + commonDirectory = await realpath(path.resolve(gitDirectory, commonPointer)); + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + return { workspace: current, gitDirectory, commonDirectory }; + } + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + const parent = path.dirname(current); + if (parent === current) return undefined; + current = parent; + } +} + +async function readGitModules(workspace) { + const filePath = path.join(workspace, ".gitmodules"); + return readBoundedRegularFile(filePath, 1024 * 1024, "Submodule mapping"); +} + +function parseSubmoduleMappings(contents) { + const mappings = []; + let current; + for (const line of contents.split(/\r?\n/)) { + const section = line.match(/^\s*\[submodule\s+"([^"\\]+)"\]\s*$/); + if (section) { + current = { name: section[1] }; + mappings.push(current); + continue; + } + const pathEntry = line.match(/^\s*path\s*=\s*(.+?)\s*$/i); + if (current && pathEntry) current.path = pathEntry[1]; + } + return mappings.filter((mapping) => mapping.path); +} + +function parseCoreWorktree(contents) { + let inCore = false; + for (const line of contents.split(/\r?\n/)) { + const section = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (section) { + inCore = section[1].trim().toLowerCase() === "core"; + continue; + } + if (!inCore) continue; + const entry = line.match(/^\s*worktree\s*=\s*(.+?)\s*$/i); + if (entry && !/["'\\]/.test(entry[1])) return entry[1]; + } + return undefined; +} + +async function validateSubmoduleGitDirectory(workspace, gitDirectory) { + const parent = await findAncestorGitContext(path.dirname(workspace)); + if (!parent) return false; + const mappings = parseSubmoduleMappings(await readGitModules(parent.workspace)); + const mapping = mappings.find((candidate) => { + if (path.isAbsolute(candidate.path)) return false; + return path.resolve(parent.workspace, candidate.path) === workspace; + }); + if (!mapping) return false; + const modulesDirectory = path.join(parent.commonDirectory, "modules"); + const expectedDirectory = path.resolve(modulesDirectory, mapping.name); + if ( + expectedDirectory === modulesDirectory + || !isWithin(modulesDirectory, expectedDirectory) + || await realpath(expectedDirectory) !== gitDirectory + ) return false; + const configContents = await readBoundedRegularFile( + path.join(gitDirectory, "config"), + 1024 * 1024, + "Submodule Git config", + ); + const configuredWorktree = parseCoreWorktree(configContents); + if ( + !configuredWorktree + || await realpath(path.resolve(gitDirectory, configuredWorktree)) !== workspace + ) return false; + const [head, config, objects, refs] = await Promise.all([ + stat(path.join(gitDirectory, "HEAD")), + stat(path.join(gitDirectory, "config")), + stat(path.join(gitDirectory, "objects")), + stat(path.join(gitDirectory, "refs")), + ]); + return head.isFile() && config.isFile() && objects.isDirectory() && refs.isDirectory(); +} + +function isCredentialPath(relativePath, directory) { + const parts = relativePath.split(path.sep); + const basename = parts.at(-1); + const parent = parts.at(-2); + if (basename === ".env" || basename.startsWith(".env.")) return true; + if ([".git-credentials", ".netrc", ".npmrc", ".pypirc"].includes(basename)) return true; + if (directory && [".aws", ".ssh"].includes(basename)) return true; + if (parent === ".config" && ["gh", "gcloud"].includes(basename)) return true; + if (parent === ".docker" && basename === "config.json") return true; + return parent === ".kube" && basename === "config"; +} + +async function discoverExistingWorkspaceCredentialPaths(workspace) { + const discovered = []; + const pending = [workspace]; + while (pending.length > 0) { + const directory = pending.pop(); + const entries = await readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + const candidate = path.join(directory, entry.name); + const info = await lstat(candidate); + if (info.isSymbolicLink()) continue; + const relative = path.relative(workspace, candidate); + const credential = isCredentialPath(relative, info.isDirectory()); + if (credential) discovered.push(candidate); + if ( + info.isDirectory() + && !credential + && entry.name !== ".git" + ) pending.push(candidate); + } + } + return unique(discovered); +} + +async function discoverExistingGitControlPaths(workspace) { + const discovered = []; + const workspaceDirectories = [workspace]; + const gitDirectories = []; + while (workspaceDirectories.length > 0) { + const directory = workspaceDirectories.pop(); + const entries = await readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + const candidate = path.join(directory, entry.name); + const info = await lstat(candidate); + if (info.isSymbolicLink()) continue; + if (entry.name === ".git") { + if (info.isFile()) discovered.push(candidate); + else if (info.isDirectory()) gitDirectories.push(candidate); + continue; + } + if (info.isFile() && entry.name === ".gitmodules") discovered.push(candidate); + if (info.isDirectory()) workspaceDirectories.push(candidate); + } + } + while (gitDirectories.length > 0) { + const directory = gitDirectories.pop(); + const entries = await readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + const candidate = path.join(directory, entry.name); + const info = await lstat(candidate); + if (info.isSymbolicLink()) continue; + if (info.isDirectory()) { + if (entry.name === "hooks") discovered.push(candidate); + else gitDirectories.push(candidate); + } else if ( + info.isFile() + && ["config", "config.worktree", "commondir", "gitdir"].includes(entry.name) + ) discovered.push(candidate); + } + } + return unique(discovered); +} + +async function validateCommonGitDirectory(gitDirectory) { + if (path.basename(gitDirectory) !== ".git" && !path.basename(gitDirectory).endsWith(".git")) { + return false; + } + const [head, config, objects, refs] = await Promise.all([ + stat(path.join(gitDirectory, "HEAD")), + stat(path.join(gitDirectory, "config")), + stat(path.join(gitDirectory, "objects")), + stat(path.join(gitDirectory, "refs")), + ]); + return head.isFile() && config.isFile() && objects.isDirectory() && refs.isDirectory(); +} + +async function discoverGitWorkspace(cwd) { + let current = cwd; + while (true) { + const marker = path.join(current, ".git"); + let markerInfo; + try { + markerInfo = await lstat(marker); + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + if (markerInfo?.isDirectory()) { + const gitDirectory = await realpath(marker); + return { + workspace: current, + readRoots: unique([marker, gitDirectory]), + denyWritePaths: [ + path.join(gitDirectory, "config"), + path.join(gitDirectory, "hooks"), + ], + }; + } + if (markerInfo && !markerInfo.isFile()) { + throw new Error(`Unsupported .git metadata marker: ${marker}`); + } + if (markerInfo?.isFile()) { + const pointer = (await readSmallMetadataFile(marker)).trim().match(/^gitdir:\s*(.+)$/i); + if (!pointer) throw new Error(`Invalid linked-worktree .git pointer: ${marker}`); + const gitDirectory = await realpath(path.resolve(current, pointer[1])); + const [commonResult, backlinkResult] = await Promise.allSettled([ + readSmallMetadataFile(path.join(gitDirectory, "commondir")), + readSmallMetadataFile(path.join(gitDirectory, "gitdir")), + ]); + if (commonResult.status === "rejected" && backlinkResult.status === "rejected") { + if ( + commonResult.reason?.code === "ENOENT" + && backlinkResult.reason?.code === "ENOENT" + && await validateSubmoduleGitDirectory(current, gitDirectory) + ) { + return { + workspace: current, + readRoots: unique([marker, gitDirectory]), + denyWritePaths: [ + marker, + path.join(gitDirectory, "config"), + path.join(gitDirectory, "hooks"), + ], + }; + } + throw new Error(`Untrusted submodule Git metadata relationship: ${marker}`); + } + if (commonResult.status !== "fulfilled" || backlinkResult.status !== "fulfilled") { + throw new Error(`Incomplete linked-worktree metadata relationship: ${marker}`); + } + const commonDirectory = await realpath(path.resolve(gitDirectory, commonResult.value.trim())); + const backlinkPath = path.resolve(gitDirectory, backlinkResult.value.trim()); + if ( + backlinkPath !== marker + || !isWithin(path.join(commonDirectory, "worktrees"), gitDirectory) + || !await validateCommonGitDirectory(commonDirectory) + ) { + throw new Error(`Untrusted linked-worktree metadata relationship: ${marker}`); + } + await access(path.join(commonDirectory, "HEAD")); + return { + workspace: current, + readRoots: unique([marker, gitDirectory, commonDirectory]), + denyWritePaths: [ + marker, + path.join(gitDirectory, "config.worktree"), + path.join(commonDirectory, "config"), + path.join(commonDirectory, "hooks"), + ], + }; + } + const parent = path.dirname(current); + if (parent === current) return { workspace: cwd, readRoots: [], denyWritePaths: [] }; + current = parent; + } +} + +export async function assertNoExternalHardlinks(workspace) { + const linkedFiles = new Map(); + const pending = [workspace]; + while (pending.length > 0) { + const directory = pending.pop(); + const entries = await readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + const candidate = path.join(directory, entry.name); + if (entry.isSymbolicLink()) continue; + const info = await lstat(candidate); + if (info.isDirectory()) { + pending.push(candidate); + } else if (info.isFile() && info.nlink > 1) { + const key = `${info.dev}:${info.ino}`; + const record = linkedFiles.get(key) || { expected: info.nlink, observed: 0, path: candidate }; + record.observed += 1; + linkedFiles.set(key, record); + } + } + } + const external = [...linkedFiles.values()].find((record) => record.observed !== record.expected); + if (external) { + throw new Error(`Sandbox workspace contains an external hardlink: ${external.path}`); + } +} + +async function isTrustedExecutable(resolved, blockedRoots) { + if (blockedRoots.some((root) => isWithin(root, resolved))) return false; + let current = resolved; + while (true) { + const info = await stat(current); + if (info.uid !== 0 || (info.mode & 0o022) !== 0) return false; + const parent = path.dirname(current); + if (parent === current) return true; + current = parent; + } +} + +async function resolveExecutable(name, environmentPath, blockedRoots) { + for (const directory of (environmentPath || "").split(path.delimiter)) { + if (!directory || !path.isAbsolute(directory)) continue; + const candidate = path.join(directory, name); + try { + const resolved = await realpath(candidate); + await access(resolved, 1); + const info = await stat(resolved); + if (info.isFile() && await isTrustedExecutable(resolved, blockedRoots)) return resolved; + } catch { + // Continue looking through trusted absolute PATH entries. + } + } + throw new Error(`Sandbox dependency not found in trusted host paths: ${name}`); +} + +async function resolveHelperPaths(platform, environmentPath, blockedRoots) { + if (platform !== "linux") return {}; + const [bwrap, rg, socat] = await Promise.all([ + resolveExecutable("bwrap", environmentPath, blockedRoots), + resolveExecutable("rg", environmentPath, blockedRoots), + resolveExecutable("socat", environmentPath, blockedRoots), + ]); + return { bwrap, rg, socat }; +} + +async function createDenyProxy() { + const server = createServer((socket) => socket.destroy()); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Could not bind raw-network guard."); + return { + port: address.port, + close: () => new Promise((resolve, reject) => { + server.close((error) => error ? reject(error) : resolve()); + }), + }; +} + +function spawnResult(spawn, argv, options, lifecycle = {}) { + return new Promise((resolve, reject) => { + const child = spawn(argv[0], argv.slice(1), options); + const signalSource = lifecycle.signalSource || process; + const killProcess = lifecycle.killProcess || process.kill.bind(process); + const signalGraceMs = lifecycle.signalGraceMs ?? 5_000; + let settled = false; + let forwardedSignal; + let escalationTimer; + + const killChildTree = (signal) => { + try { + if (Number.isInteger(child.pid)) killProcess(-child.pid, signal); + else if (typeof child.kill === "function") child.kill(signal); + } catch (error) { + if (error?.code !== "ESRCH" && typeof child.kill === "function") child.kill(signal); + } + }; + const signalHandlers = new Map(["SIGHUP", "SIGINT", "SIGTERM"].map((signal) => [signal, () => { + if (settled) return; + forwardedSignal ||= signal; + killChildTree(signal); + if (settled) return; + if (!escalationTimer) { + escalationTimer = setTimeout(() => killChildTree("SIGKILL"), signalGraceMs); + escalationTimer.unref?.(); + } + }])); + const cleanup = () => { + if (escalationTimer) clearTimeout(escalationTimer); + for (const [signal, handler] of signalHandlers) signalSource.removeListener(signal, handler); + }; + for (const [signal, handler] of signalHandlers) signalSource.prependListener(signal, handler); + + child.once("error", (error) => { + if (!settled) { + settled = true; + cleanup(); + reject(error); + } + }); + child.once("close", (code, signal) => { + if (!settled) { + settled = true; + cleanup(); + resolve({ code, signal: signal || forwardedSignal }); + } + }); + }); +} + +function signalExitCode(signal) { + const number = os.constants.signals[signal]; + return Number.isInteger(number) ? 128 + number : 1; +} + +const RUNTIME_CLEANUP_EVENTS = ["exit", "SIGINT", "SIGTERM"]; + +function snapshotRuntimeCleanupListeners(source) { + return new Map(RUNTIME_CLEANUP_EVENTS.map((event) => [event, new Set(source.rawListeners(event))])); +} + +function removeAddedRuntimeCleanupListeners(source, snapshot) { + for (const event of RUNTIME_CLEANUP_EVENTS) { + const previous = snapshot.get(event); + for (const listener of source.rawListeners(event)) { + const callback = listener.listener || listener; + if (!previous.has(listener) && callback.name === "cleanupHandler") { + source.removeListener(event, listener); + } + } + } +} + +async function defaultLoadRuntime() { + return import(SANDBOX_RUNTIME_PACKAGE); +} + +async function probeHostIsolation({ platform, cwd, env }) { + if (platform === "linux") { + const helpers = await resolveHelperPaths(platform, env.PATH, [ + cwd, + await realpath(os.homedir()), + await realpath(os.tmpdir()), + ]); + const result = await spawnResult(nodeSpawn, [ + helpers.bwrap, + "--unshare-user", + "--unshare-pid", + "--unshare-net", + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "/bin/true", + ], { + cwd, + detached: true, + env: { PATH: env.PATH }, + shell: false, + stdio: "ignore", + }); + return result.code === 0 && !result.signal + ? { errors: [], warnings: [] } + : { errors: ["bubblewrap cannot create the required user and network namespaces"], warnings: [] }; + } + const result = await spawnResult(nodeSpawn, [ + "/usr/bin/sandbox-exec", + "-p", + "(version 1)(allow default)", + "/usr/bin/true", + ], { + cwd, + detached: true, + env: { PATH: env.PATH }, + shell: false, + stdio: "ignore", + }); + return result.code === 0 && !result.signal + ? { errors: [], warnings: [] } + : { errors: ["macOS sandbox-exec preflight failed"], warnings: [] }; +} + +export async function probeSandboxRuntime({ + loadRuntime = defaultLoadRuntime, + platform = process.platform, + cwd = process.cwd(), + env = process.env, + hostProbe = probeHostIsolation, +} = {}) { + const backend = `${SANDBOX_RUNTIME_PACKAGE}@${SANDBOX_RUNTIME_VERSION}`; + if (!SUPPORTED_PLATFORMS.has(platform)) { + return { + backend, + runnerReady: false, + executionLevel: "advisory", + errors: [`Unsupported platform for this adapter: ${platform}`], + warnings: [], + }; + } + try { + const { SandboxManager } = await loadRuntime(); + if (!SandboxManager.isSupportedPlatform()) { + return { + backend, + runnerReady: false, + executionLevel: "advisory", + errors: ["Sandbox runtime does not support this host."], + warnings: [], + }; + } + const dependencies = await SandboxManager.checkDependenciesAsync(); + const host = dependencies.errors.length === 0 + ? await hostProbe({ platform, cwd: await realpath(cwd), env }) + : { errors: [], warnings: [] }; + const errors = [...dependencies.errors, ...host.errors]; + const warnings = [...dependencies.warnings, ...host.warnings]; + return { + backend, + runnerReady: errors.length === 0, + executionLevel: errors.length === 0 ? SANDBOX_EXECUTION_LEVEL : "advisory", + errors, + warnings, + }; + } catch (error) { + return { + backend, + runnerReady: false, + executionLevel: "advisory", + errors: [error.message], + warnings: [], + }; + } +} + +async function runSandboxedCommandOnce(options, context = {}) { + const platform = context.platform || process.platform; + if (!SUPPORTED_PLATFORMS.has(platform)) { + throw new Error(`Sandbox execution is unsupported on platform: ${platform}`); + } + + const executionCwd = await realpath(context.cwd || process.cwd()); + const gitWorkspace = await discoverGitWorkspace(executionCwd); + const workspace = gitWorkspace.workspace; + const workspaceInfo = await stat(workspace); + if (!workspaceInfo.isDirectory()) throw new Error("Sandbox workspace must be a directory."); + const originalHome = await realpath(context.home || os.homedir()); + const temporaryRoot = await realpath(context.temporaryRoot || os.tmpdir()); + if ( + workspace === path.parse(workspace).root + || workspace === originalHome + || workspace === temporaryRoot + ) { + throw new Error("Refusing to use a filesystem root, home, or shared temp directory as the sandbox workspace."); + } + if (unsafeSharedWriteRoots(originalHome, temporaryRoot) + .some((unsafeRoot) => isWithin(path.resolve(unsafeRoot), workspace))) { + throw new Error("Refusing to use an upstream protected shared-write path as the sandbox workspace."); + } + await assertNoExternalHardlinks(workspace); + const [existingCredentialPaths, existingGitControlPaths] = await Promise.all([ + discoverExistingWorkspaceCredentialPaths(workspace), + discoverExistingGitControlPaths(workspace), + ]); + + const sourceEnvironment = context.env || process.env; + const [helperPaths, systemReadRoots, executableReadRoots] = await Promise.all([ + context.helperPaths || resolveHelperPaths( + platform, + sourceEnvironment.PATH, + [workspace, originalHome, temporaryRoot], + ), + existingSystemReadRoots(platform), + commandReadRoots(options.command, sourceEnvironment.PATH, executionCwd, { + workspace, + originalHome, + temporaryRoot, + }), + ]); + const allowedReadRoots = unique([...systemReadRoots, ...executableReadRoots]); + const runRoot = await realpath(await mkdtemp(path.join(temporaryRoot, "opp-sandbox-"))); + let denyProxy; + let manager; + let childResult; + let operationError; + + try { + for (const directory of ["home", "tmp", "cache", "config", "data"]) { + await mkdir(path.join(runRoot, directory), { mode: 0o700 }); + } + if (options.profile.name === "network-read" && options.allowedDomains.length > 0) { + denyProxy = await createDenyProxy(); + } + const compiled = compileSandboxExecution({ + ...options, + workspace, + runRoot, + sourceEnvironment, + originalHome, + temporaryRoot, + platform, + helperPaths, + readOnlySocksProxyPort: denyProxy?.port, + readDenyPaths: [path.parse(workspace).root], + readAllowPaths: unique([ + workspace, + runRoot, + ...gitWorkspace.readRoots, + ...allowedReadRoots, + ]), + additionalDenyWritePaths: unique([ + ...gitWorkspace.denyWritePaths, + ...existingCredentialPaths, + ...existingGitControlPaths, + ]), + additionalCredentialRoots: executionCwd === workspace ? [] : [executionCwd], + }); + context.writeError?.( + `Sandbox: ${compiled.summary.profile}, ${compiled.summary.executionLevel}, ` + + `workspace ${compiled.summary.workspace}, network ${compiled.summary.network}\n`, + ); + + const runtime = await (context.loadRuntime || defaultLoadRuntime)(); + manager = runtime.SandboxManager; + if (!manager.isSupportedPlatform()) throw new Error("Sandbox runtime does not support this host."); + const runtimeConfig = runtime.SandboxRuntimeConfigSchema.parse(compiled.runtimeConfig); + const runtimeSignalSource = context.runtimeSignalSource || process; + const cleanupListenerSnapshot = snapshotRuntimeCleanupListeners(runtimeSignalSource); + try { + await manager.initialize(runtimeConfig); + } finally { + removeAddedRuntimeCleanupListeners(runtimeSignalSource, cleanupListenerSnapshot); + } + + const previousTemp = process.env.CLAUDE_CODE_TMPDIR; + process.env.CLAUDE_CODE_TMPDIR = path.join(runRoot, "tmp"); + let descriptor; + try { + descriptor = await manager.wrapWithSandboxArgv( + commandToShellString(options.command), + "/bin/sh", + undefined, + undefined, + executionCwd, + { commandId: randomUUID(), commandText: options.command[0] }, + ); + } finally { + if (previousTemp === undefined) delete process.env.CLAUDE_CODE_TMPDIR; + else process.env.CLAUDE_CODE_TMPDIR = previousTemp; + } + + childResult = await spawnResult(context.spawn || nodeSpawn, descriptor.argv, { + cwd: executionCwd, + detached: true, + env: compiled.childEnvironment, + shell: false, + stdio: "inherit", + }, { + signalSource: context.signalSource, + killProcess: context.killProcess, + signalGraceMs: context.signalGraceMs, + }); + } catch (error) { + operationError = error; + } + + const cleanupErrors = []; + if (manager) { + try { + await manager.reset(); + } catch (error) { + cleanupErrors.push(error); + } + } + if (denyProxy) { + try { + await denyProxy.close(); + } catch (error) { + cleanupErrors.push(error); + } + } + try { + await rm(runRoot, { recursive: true, force: true }); + } catch (error) { + cleanupErrors.push(error); + } + + if (operationError && cleanupErrors.length > 0) { + throw new AggregateError([operationError, ...cleanupErrors], "Sandbox execution and cleanup failed."); + } + if (operationError) throw operationError; + if (cleanupErrors.length > 0) { + throw new AggregateError(cleanupErrors, "Sandbox cleanup failed."); + } + if (childResult.signal) return signalExitCode(childResult.signal); + return Number.isInteger(childResult.code) ? childResult.code : 1; +} + +export async function runSandboxedCommand(options, context = {}) { + if (sandboxExecutionActive) { + throw new Error("Another sandbox command is already active in this process."); + } + sandboxExecutionActive = true; + try { + return await runSandboxedCommandOnce(options, context); + } finally { + sandboxExecutionActive = false; + } +} diff --git a/docs/sandbox-compatibility.md b/docs/sandbox-compatibility.md new file mode 100644 index 0000000..fa34ed9 --- /dev/null +++ b/docs/sandbox-compatibility.md @@ -0,0 +1,135 @@ +# Sandbox Compatibility Across Coding Agents + +This document defines what sandbox compatibility means for Codex, Claude Code, OpenCode, and Pi. It separates portable policy support from automatic host enforcement so installation never implies a security guarantee that is not active. + +Last verified: 2026-08-16 + +Locally inspected host versions: + +- Codex CLI 0.147.0 +- Claude Code 2.1.231 +- OpenCode 1.18.18 +- Pi 0.83.0 + +The repository smoke tests retain their separately pinned minimum versions. Host APIs evolve, so adapter tests and this matrix must be updated together. + +## Compatibility Levels + +| Level | Meaning | +|---|---| +| Skill-compatible | The host discovers and can invoke the bundled `SKILL.md` workflows. | +| Policy-compatible | The package can resolve the skill's trusted sandbox profile and allowed escalations. | +| Runner-compatible | The host can explicitly invoke `opencode-power-pack sandbox exec` from an npm installation. | +| Enforcement-integrated | A tested host adapter routes shell execution through the runner and blocks its ordinary bypass path. | +| Whole-agent isolated | Every host tool, connector, browser action, and subprocess is contained by one boundary. This project does not currently claim this level. | + +The current runner is `shell-contained`. The command and its descendants are isolated, but unrelated host-native tools are outside that process boundary. + +## Current Matrix + +| Host | Skills | Policy and manual runner | Automatic routing | Adapter direction | Important boundary | +|---|---|---|---|---|---| +| Codex | Supported through the Codex plugin and portable skill installation | Supported when the npm package is installed | Not yet implemented | Temporary native sandbox configuration plus the shared runner for explicit network access | Codex has native `read-only` and `workspace-write` shell sandboxes, but a skill cannot safely change the active session sandbox by prompt text alone. | +| Claude Code | Supported through the namespaced Claude plugin | Supported when the npm package is installed | Not yet implemented | Native sandbox settings plus hooks and permissions for tools outside Bash | Claude's native sandbox applies to Bash and descendants. Read, Edit, Write, WebFetch, MCP, and computer-use tools require separate permission controls. | +| OpenCode | Supported through the plugin and portable skill installation | Supported when the npm package is installed | Not yet implemented | A custom sandbox tool paired with per-agent denial of ordinary `bash` | File-edit and external-directory permissions also need profile-specific controls. | +| Pi | Supported through the Pi package declaration and portable skill installation | Supported when the npm package is installed | Not yet implemented | An extension that intercepts or replaces built-in shell and file tools | A skill file by itself is advisory. | + +Official host surfaces used by the adapter design: + +- [Codex configuration reference](https://developers.openai.com/codex/config-reference/) documents `sandbox_mode`, workspace-write network controls, permission profiles, and environment policy. +- [Claude Code sandboxing](https://code.claude.com/docs/en/sandboxing) documents its Bash-only OS sandbox, `/sandbox`, `failIfUnavailable`, and the unsandboxed escape hatch. [Claude Code hooks](https://code.claude.com/docs/en/hooks) documents `PreToolUse` denial and input replacement. +- [OpenCode agents](https://opencode.ai/docs/agents/) documents per-agent `allow`, `ask`, and `deny` permissions. [OpenCode custom tools](https://opencode.ai/docs/custom-tools/) provides the portable runner integration point. +- [Pi extensions](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/extensions.md) documents custom tools, built-in tool overrides, dynamic active tools, and blocking `tool_call` events. + +## What Works Before Host Adapters + +The explicit runner is the common denominator: + +```bash +opencode-power-pack sandbox doctor + +opencode-power-pack sandbox exec \ + --skill code-review \ + -- rg TODO . +``` + +`sandbox doctor` exits with a nonzero status when the native runner is unavailable, even when the portable contract itself is valid. Automation should require both a successful exit and `runnerReady: true` from JSON output before launching a contained command. + +An allowed skill escalation remains explicit: + +```bash +opencode-power-pack sandbox exec \ + --skill code-review \ + --sandbox-profile network-read \ + --allow-domain api.github.com \ + -- curl https://api.github.com/repos/owner/repository +``` + +The literal `--` boundary is required. Everything after it is treated as the child command and arguments. The runner preserves the child exit code and never falls back to executing the command without containment. + +This manual form can be called from any of the four agents, but prompt instructions are not enforcement. Until the matching host adapter lands, the agent can still choose an ordinary shell or another host-native tool. + +## Adapter Roadmap + +Automatic activation needs a host-specific adapter, not another instruction inside `SKILL.md`. Each adapter must run the doctor, resolve the trusted packaged profile, activate temporary host controls, block the ordinary tool bypass, and clean up when the session ends. Codex and Claude Code can combine native sandbox settings with their permission surfaces. OpenCode needs a custom tool plus agent permissions. Pi needs an extension that intercepts or replaces built-in tools. + +The exact adapter command and configuration format will be defined with conformance tests when each integration is implemented. Repository content may request a stricter policy, but it must never disable containment, select a weaker backend mode, authorize an escalation, or manufacture a publish confirmation. + +## Runtime Limitations + +`network-read` terminates HTTP and HTTPS connections and permits only GET, HEAD, and OPTIONS requests. This enforces conventional read semantics, not a mathematical guarantee that an endpoint has no side effects. A poorly designed GET endpoint can mutate state, an approved broad domain can receive data, and upstream documents domain-fronting limitations. Grant the narrowest destination possible and do not expose credentials unless the retrieval requires them. + +Host filesystem reads are denied by default. The runner exposes the workspace, its private per-command directory, and a narrow set of operating-system runtime paths needed to start ordinary command-line programs. It keeps secret-bearing paths such as other home directories, `/run/secrets`, unrelated mounts, and sibling temporary directories outside that read boundary. Workspaces with hardlinks to external inodes are rejected before execution. + +Selecting a command grants read access to that executable. If it belongs to a package or Python virtual environment identified by a nearby `package.json` or `pyvenv.cfg`, the bounded package root is also readable so resource-bearing CLIs can start. The runner also resolves bounded shebang dependencies, including `#!/usr/bin/env node` and `env -S`, without exposing a whole version-manager or system prefix. Commands selected from `~/.local/bin` can read `~/.local/lib` for user-level Python packages, but not user configuration, cache, or credential directories. Installing project-specific tools inside the workspace remains the most predictable option. + +When the command starts inside a Git repository, the runner treats the containing worktree root as the workspace while preserving the original working directory. Existing credential-shaped files are denied recursively, and exact credential paths in both the repository root and original working directory stay protected even when absent at startup. The runner also exposes validated linked-worktree and submodule metadata, so ordinary inspection commands work from nested directories, linked worktrees, and standard submodules. The repository's `.git/config` remains readable while writes to it and hooks remain denied. Do not store credentials in Git remote URLs or custom repository configuration. Use an explicitly granted environment variable for network credentials instead. + +The runner is intentionally lightweight and on demand. It uses native Seatbelt or Bubblewrap primitives for one command tree, creates no persistent container or daemon, and removes its private directory afterward. Because the pinned upstream manager has process-global state, a second command in the same Node.js process is rejected while one is active. Independent CLI processes have separate managers. + +On Linux, `bubblewrap`, `socat`, and `rg` must resolve to root-owned executables whose parent path is not group- or world-writable. This prevents a repository or shared temporary directory from replacing the containment helpers through `PATH`. + +## Runtime Platform Requirements + +The native backend pins `@anthropic-ai/sandbox-runtime` and requires Node.js 20.11.0 or newer. + +| Platform | Status | Requirements | +|---|---|---| +| macOS | Supported by the runner | Native Seatbelt support. The doctor performs an operational preflight. | +| Linux | Supported by the runner | Trusted system installations of `bubblewrap`, `socat`, and `rg`, plus working unprivileged user and network namespaces. | +| WSL2 | Expected through the Linux backend, pending dedicated CI | Same Linux dependencies and namespace requirements. | +| WSL1 | Unsupported | Required namespace primitives are unavailable. | +| Windows native | Intentionally fail closed | Upstream support requires elevated provisioning and platform-specific ACL and network tests that this project has not completed. | + +Ubuntu 24.04 can block Bubblewrap user namespaces through AppArmor. The doctor runs a behavioral namespace preflight instead of reporting readiness from executable presence alone. + +## Fail-Closed Rules + +The runner refuses execution when: + +- The backend package or native dependencies are missing. +- The OS cannot create the required isolation boundary. +- The platform adapter is unsupported. +- The skill or requested profile is unknown. +- The requested profile is not the skill default or a declared escalation. +- A network or credential grant is incompatible with the resolved profile. +- A `publish` profile lacks explicit external-side-effect confirmation. +- Backend initialization, wrapping, child spawning, or cleanup fails. + +None of these failures authorize an unsandboxed retry. + +## Verification Expectations + +Every enforcement adapter must test: + +- Default profile selection and declared escalation authorization. +- Denial of the host's ordinary shell bypass. +- Workspace read and write boundaries. +- Credential-environment scrubbing. +- Network denial and explicit destination grants. +- Child argument and exit-code preservation. +- Unsupported or unavailable backend failure. +- Packed installation outside the source checkout. +- The minimum pinned host version and a currently supported host version. + +Compatibility is considered implemented only when the adapter and its conformance tests land together. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..42d3190 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,74 @@ +{ + "name": "@waybarrios/opencode-power-pack", + "version": "0.4.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@waybarrios/opencode-power-pack", + "version": "0.4.0", + "license": "MIT AND Apache-2.0", + "dependencies": { + "@anthropic-ai/sandbox-runtime": "0.0.73" + }, + "bin": { + "opencode-power-pack": "bin/opencode-power-pack.mjs" + }, + "engines": { + "node": ">=20.11.0", + "opencode": ">=1.18.7" + } + }, + "node_modules/@anthropic-ai/sandbox-runtime": { + "version": "0.0.73", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.73.tgz", + "integrity": "sha512-F608iUirrCqwvInZYGRRgJWDQj0tt6fNVE9aPagpotLJ5LhC4JbrMFIIZww5MFjb+HRCkpE0+xdI79c30tdVYg==", + "license": "Apache-2.0", + "dependencies": { + "@pondwader/socks5-server": "^1.0.10", + "commander": "^12.1.0", + "node-forge": "^1.4.0", + "zod": "^3.24.1" + }, + "bin": { + "srt": "dist/cli.js" + }, + "engines": { + "node": ">=20.11.0" + } + }, + "node_modules/@pondwader/socks5-server": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@pondwader/socks5-server/-/socks5-server-1.0.10.tgz", + "integrity": "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/node-forge": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.0.tgz", + "integrity": "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==", + "license": "(BSD-3-Clause OR GPL-2.0)", + "engines": { + "node": ">= 6.13.0" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/package.json b/package.json index d748947..692b8f3 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "registry": "https://registry.npmjs.org/" }, "engines": { - "node": ">=20", + "node": ">=20.11.0", "opencode": ">=1.18.7" }, "files": [ @@ -22,6 +22,7 @@ ".opencode", "bin", "sandbox", + "docs/sandbox-compatibility.md", "assets", "skillsets.json", "UPSTREAMS.json", @@ -30,7 +31,7 @@ ], "scripts": { "test": "node --test", - "test:sandbox": "node --test tests/sandbox-policy.test.mjs", + "test:sandbox": "node --test tests/sandbox-policy.test.mjs tests/sandbox-runtime.test.mjs tests/sandbox-runtime.integration.test.mjs", "prepublishOnly": "npm test", "eval:behavioral": "node scripts/behavioral-evals.mjs run", "eval:behavioral:accept": "node scripts/behavioral-evals.mjs accept", @@ -65,5 +66,8 @@ "mcp-builder", "multi-agent", "plugin" - ] + ], + "dependencies": { + "@anthropic-ai/sandbox-runtime": "0.0.73" + } } diff --git a/tests/package-surface.test.mjs b/tests/package-surface.test.mjs index 5da75f2..b072107 100644 --- a/tests/package-surface.test.mjs +++ b/tests/package-surface.test.mjs @@ -16,7 +16,7 @@ import { join } from "node:path"; const REPO = process.env.REPO || process.cwd(); -test("published package relies on native commands and ships every skill", () => { +test("published package ships every skill and the sandbox runtime entrypoint", () => { const output = execFileSync("npm", ["pack", "--dry-run", "--json"], { cwd: REPO, encoding: "utf8", @@ -54,8 +54,13 @@ test("published package relies on native commands and ships every skill", () => ); assert.ok(packaged.has("bin/opencode-power-pack.mjs"), "selective installer is published"); assert.ok(packaged.has("bin/sandbox/policy.mjs"), "sandbox policy resolver is published"); + assert.ok(packaged.has("bin/sandbox/runtime.mjs"), "sandbox runtime adapter is published"); assert.ok(packaged.has("sandbox/contract.json"), "sandbox contract is published"); assert.ok(packaged.has("sandbox/contract.schema.json"), "sandbox schema is published"); + assert.ok( + packaged.has("docs/sandbox-compatibility.md"), + "cross-agent sandbox compatibility documentation is published", + ); assert.ok(packaged.has("skillsets.json"), "selective profiles are published"); for (const prefix of ["evals/", "scripts/", "tests/", "docs/superpowers/"]) { assert.equal( @@ -125,13 +130,32 @@ test("packed npm artifact exposes a working selective-installer executable", () assert.match(output, /Profiles:/); assert.match(output, /recommended/); assert.match(output, /code-review/); - const sandboxOutput = execFileSync(executable, ["sandbox", "doctor"], { + const sandboxDoctor = spawnSync(executable, ["sandbox", "doctor"], { cwd: installRoot, encoding: "utf8", }); + const sandboxOutput = sandboxDoctor.stdout; assert.match(sandboxOutput, /Sandbox contract: valid/); assert.match(sandboxOutput, /Assigned skills: 54\/54/); + assert.match(sandboxOutput, /Backend: @anthropic-ai\/sandbox-runtime@0\.0\.73/); assert.match(sandboxOutput, /Strict ready: no/); + assert.equal( + sandboxDoctor.status, + /Runner ready: yes/.test(sandboxOutput) ? 0 : 1, + sandboxDoctor.stderr, + ); + const installedManifest = JSON.parse( + readFileSync( + join(installRoot, "node_modules", "@waybarrios", "opencode-power-pack", "package.json"), + "utf8", + ), + ); + assert.equal(installedManifest.dependencies["@anthropic-ai/sandbox-runtime"], "0.0.73"); + execFileSync(process.execPath, [ + "--input-type=module", + "--eval", + "const r=await import('@anthropic-ai/sandbox-runtime');if(typeof r.SandboxManager?.initialize!=='function')process.exit(2)", + ], { cwd: installRoot, encoding: "utf8" }); mkdirSync(join(installRoot, ".git")); execFileSync(executable, ["install", "code-review", "--project"], { cwd: installRoot, diff --git a/tests/sandbox-policy.test.mjs b/tests/sandbox-policy.test.mjs index 4487b9e..7135c57 100644 --- a/tests/sandbox-policy.test.mjs +++ b/tests/sandbox-policy.test.mjs @@ -6,10 +6,12 @@ import { discoverSkills, main, parseSandboxArgs, + parseSandboxExecArgs, } from "../bin/opencode-power-pack.mjs"; import { loadSandboxContract, portableSkillPolicy, + resolveSandboxExecutionProfile, resolveSandboxProfile, sandboxDoctorReport, validateSandboxContract, @@ -129,6 +131,33 @@ test("skill and direct-profile resolution report advisory capabilities explicitl ); }); +test("sandbox execution authorizes only a skill default or declared escalation", async () => { + const contract = await loadSandboxContract(REPO); + + assert.equal( + resolveSandboxExecutionProfile(contract, { skillName: "code-review" }).name, + "observe", + ); + assert.equal( + resolveSandboxExecutionProfile(contract, { + skillName: "code-review", + profileName: "network-read", + }).name, + "network-read", + ); + assert.throws( + () => resolveSandboxExecutionProfile(contract, { + skillName: "frontend-design", + profileName: "publish", + }), + /does not permit sandbox profile/, + ); + assert.throws( + () => resolveSandboxExecutionProfile(contract, { profileName: "publish" }), + /requires --skill/, + ); +}); + test("portable policies remain self-describing and never claim enforcement", async () => { const contract = await loadSandboxContract(REPO); const policy = portableSkillPolicy(contract, "huggingface-spaces"); @@ -140,23 +169,31 @@ test("portable policies remain self-describing and never claim enforcement", asy assert.match(policy.warning, /advisory/i); }); -test("sandbox doctor reports complete coverage and no configured backend", async () => { +test("sandbox doctor reports complete coverage and the opt-in runner separately", async () => { const skills = await discoverSkills(REPO); const names = skills.map((skill) => skill.name); const contract = await loadSandboxContract(REPO, names); - const report = sandboxDoctorReport(contract, names); + const report = sandboxDoctorReport(contract, names, { + backend: "@anthropic-ai/sandbox-runtime@0.0.73", + runnerReady: true, + executionLevel: "shell-contained", + errors: [], + warnings: [], + }); assert.deepEqual(report, { ok: true, schemaVersion: 1, enforcementLevel: "advisory", - backend: "not-configured", + backend: "@anthropic-ai/sandbox-runtime@0.0.73", + runnerReady: true, + executionLevel: "shell-contained", strictReady: false, profiles: 4, assignedSkills: 54, packagedSkills: 54, warnings: [ - "Capability profiles are advisory until an enforcement backend and host adapter are active.", + "Skill metadata remains advisory until a host adapter routes commands through sandbox exec.", ], }); }); @@ -168,13 +205,35 @@ test("sandbox CLI supports deterministic text and JSON output", async () => { home: REPO, packageRoot: REPO, write: (text) => { output += text; }, + runtimeProbeContext: { + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: { + isSupportedPlatform: () => true, + checkDependenciesAsync: async () => ({ errors: [], warnings: [] }), + }, + }), + hostProbe: async () => ({ errors: [], warnings: [] }), + }, }; assert.equal(await main(["sandbox", "doctor"], context), 0); assert.match(output, /Assigned skills: 54\/54/); assert.match(output, /Enforcement: advisory/); + assert.match(output, /Runner ready: yes/); + assert.match(output, /Execution level: shell-contained/); assert.match(output, /Strict ready: no/); + output = ""; + assert.equal(await main(["sandbox", "doctor", "--json"], { + ...context, + runtimeProbeContext: { + platform: "linux", + loadRuntime: async () => { throw new Error("runtime unavailable"); }, + }, + }), 1); + assert.equal(JSON.parse(output).runnerReady, false); + output = ""; assert.equal( await main(["sandbox", "resolve", "--skill", "code-review", "--json"], context), @@ -191,7 +250,7 @@ test("sandbox CLI parser fails closed on ambiguous and malformed selectors", () command: "doctor", json: true, }); - assert.throws(() => parseSandboxArgs([]), /doctor or resolve/); + assert.throws(() => parseSandboxArgs([]), /doctor, resolve, or exec/); assert.throws(() => parseSandboxArgs(["missing"]), /Unknown sandbox command/); assert.throws(() => parseSandboxArgs(["resolve"]), /requires --skill or --sandbox-profile/); assert.throws( @@ -200,3 +259,40 @@ test("sandbox CLI parser fails closed on ambiguous and malformed selectors", () ); assert.throws(() => parseSandboxArgs(["doctor", "--skill", "code-review"]), /only valid/); }); + +test("sandbox exec parser preserves the argv boundary and rejects incomplete grants", () => { + assert.deepEqual( + parseSandboxExecArgs([ + "--skill", + "code-review", + "--sandbox-profile", + "network-read", + "--allow-domain", + "api.github.com", + "--allow-env", + "GH_TOKEN", + "--", + "node", + "--skill", + "literal child argument", + ]), + { + command: "exec", + skillName: "code-review", + profileName: "network-read", + allowedDomains: ["api.github.com"], + allowedEnvironment: ["GH_TOKEN"], + confirmExternalSideEffects: false, + childCommand: ["node", "--skill", "literal child argument"], + }, + ); + assert.throws( + () => parseSandboxExecArgs(["--skill", "code-review", "node", "script.mjs"]), + /requires --/, + ); + assert.throws(() => parseSandboxExecArgs(["--", "node"]), /requires --skill/); + assert.throws( + () => parseSandboxExecArgs(["--skill", "code-review", "--allow-env", "--", "node"]), + /--allow-env requires a value/, + ); +}); diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs new file mode 100644 index 0000000..5fc1a78 --- /dev/null +++ b/tests/sandbox-runtime.integration.test.mjs @@ -0,0 +1,363 @@ +import { createServer } from "node:http"; +import { execFileSync } from "node:child_process"; +import { chmod, link, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + probeSandboxRuntime, + runSandboxedCommand, +} from "../bin/sandbox/runtime.mjs"; + +const ENABLED = process.env.OPP_SANDBOX_INTEGRATION === "1"; + +function profile(name, capabilities) { + return { + name, + description: name, + riskLevel: 0, + capabilities, + enforcementLevel: "advisory", + }; +} + +const OBSERVE = profile("observe", { + workspace: "read", + temporaryFiles: "write", + network: "deny", + credentials: "deny", + externalSideEffects: "deny", +}); +const DEVELOP = profile("develop", { + workspace: "write", + temporaryFiles: "write", + network: "deny", + credentials: "deny", + externalSideEffects: "deny", +}); +const NETWORK_READ = profile("network-read", { + workspace: "write", + temporaryFiles: "write", + network: "explicit", + credentials: "explicit", + externalSideEffects: "deny", +}); + +async function run(profileValue, workspace, command, overrides = {}) { + const { contextEnvironment = {}, ...executionOverrides } = overrides; + return runSandboxedCommand({ + profile: profileValue, + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command, + ...executionOverrides, + }, { + cwd: workspace, + home: os.homedir(), + env: { + ...process.env, + ...contextEnvironment, + OPP_INTEGRATION_SECRET: "must-not-leak", + }, + }); +} + +test("real runtime enforces filesystem, environment, network, argv, and exit boundaries", { + skip: !ENABLED, + timeout: 120_000, +}, async () => { + const readiness = await probeSandboxRuntime(); + assert.equal(readiness.runnerReady, true, readiness.errors.join("; ")); + + const workspace = await mkdtemp(path.join(os.tmpdir(), "opp-runtime-workspace-")); + const outside = await mkdtemp(path.join(os.tmpdir(), "opp-runtime-outside-")); + const toolBundle = await mkdtemp(path.join(os.tmpdir(), "opp-runtime-tool-")); + const linkedParent = await mkdtemp(path.join(os.tmpdir(), "opp-runtime-linked-")); + const outsideFile = path.join(outside, "canary.txt"); + const bundledTool = path.join(toolBundle, "bin", "bundled-tool"); + const envTool = path.join(toolBundle, "bin", "env-tool"); + const interpreterBin = path.join(toolBundle, "interpreter-bin"); + const customNode = path.join(interpreterBin, "custom-node"); + const nestedWorkspace = path.join(workspace, "src", "nested"); + const linkedWorktree = path.join(linkedParent, "checkout"); + const submodule = path.join(workspace, "submodule"); + const submoduleGitDirectory = path.join(workspace, ".git", "modules", "submodule"); + const credentialSibling = path.join(workspace, "src", "sibling"); + const deepCredential = path.join( + workspace, + ...Array.from({ length: 12 }, (_value, index) => `level-${index}`), + ".npmrc", + ); + await writeFile(path.join(workspace, "readable.txt"), "workspace-readable", "utf8"); + await writeFile(path.join(workspace, ".env"), "TOP_SECRET=do-not-read", "utf8"); + await mkdir(path.join(workspace, ".ssh")); + await writeFile(path.join(workspace, ".ssh", "id_test"), "private-key", "utf8"); + await writeFile(outsideFile, "outside-unchanged", "utf8"); + await mkdir(path.join(toolBundle, "bin")); + await mkdir(path.join(toolBundle, "lib")); + await mkdir(interpreterBin); + await mkdir(nestedWorkspace, { recursive: true }); + await writeFile(path.join(nestedWorkspace, ".env"), "NESTED_SECRET=blocked", "utf8"); + await writeFile(path.join(nestedWorkspace, ".npmrc"), "//registry.example/:_authToken=blocked", "utf8"); + await mkdir(path.join(nestedWorkspace, ".ssh")); + await writeFile(path.join(nestedWorkspace, ".ssh", "id_test"), "nested-private-key", "utf8"); + await mkdir(path.join(credentialSibling, ".ssh"), { recursive: true }); + await writeFile(path.join(credentialSibling, ".npmrc"), "sibling-token", "utf8"); + await writeFile(path.join(credentialSibling, ".ssh", "id_test"), "sibling-key", "utf8"); + await mkdir(path.dirname(deepCredential), { recursive: true }); + await writeFile(deepCredential, "deep-token", "utf8"); + await writeFile(path.join(toolBundle, "package.json"), "{}\n", "utf8"); + await writeFile(path.join(toolBundle, "lib", "value"), "ok\n", "utf8"); + await writeFile( + bundledTool, + "#!/bin/sh\ntest \"$(cat \"$(dirname \"$0\")/../lib/value\")\" = ok\n", + "utf8", + ); + await chmod(bundledTool, 0o755); + await writeFile( + envTool, + "#!/usr/bin/env custom-node\nprocess.exit(require('fs').readFileSync(require('path').join(__dirname,'../lib/value'),'utf8').trim() === 'ok' ? 0 : 9)\n", + "utf8", + ); + await chmod(envTool, 0o755); + await symlink(process.execPath, customNode); + execFileSync("git", ["init", "--quiet"], { cwd: workspace, stdio: "ignore" }); + execFileSync("git", ["worktree", "add", "--quiet", "--orphan", linkedWorktree], { + cwd: workspace, + stdio: "ignore", + }); + await mkdir(path.join(linkedWorktree, "nested")); + await mkdir(path.dirname(submoduleGitDirectory), { recursive: true }); + execFileSync("git", [ + "init", + "--quiet", + "--separate-git-dir", + submoduleGitDirectory, + submodule, + ], { stdio: "ignore" }); + execFileSync("git", [ + "config", + "--file", + path.join(submoduleGitDirectory, "config"), + "core.worktree", + "../../../submodule", + ], { stdio: "ignore" }); + await writeFile(path.join(workspace, ".gitmodules"), [ + '[submodule "submodule"]', + "\tpath = submodule", + "", + ].join("\n"), "utf8"); + await mkdir(path.join(submodule, "nested")); + await symlink(outsideFile, path.join(workspace, "outside-link")); + + try { + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "process.exit(require('fs').readFileSync('readable.txt','utf8') === 'workspace-readable' ? 0 : 9)", + ]), 0); + + assert.equal(await run(OBSERVE, workspace, [bundledTool]), 0); + + assert.equal(await run(OBSERVE, workspace, [envTool], { + contextEnvironment: { + PATH: `${interpreterBin}${path.delimiter}${process.env.PATH || ""}`, + }, + }), 0); + + assert.equal(await run(OBSERVE, workspace, ["git", "status", "--short"]), 0); + assert.equal(await run(OBSERVE, nestedWorkspace, ["git", "status", "--short"]), 0); + assert.equal(await run(OBSERVE, path.join(linkedWorktree, "nested"), [ + "git", + "status", + "--short", + ]), 0); + assert.equal(await run(OBSERVE, path.join(submodule, "nested"), [ + "git", + "status", + "--short", + ]), 0); + + assert.equal(await run(OBSERVE, nestedWorkspace, [ + process.execPath, + "-e", + "for(const f of ['.env','.npmrc','.ssh/id_test']){try{require('fs').readFileSync(f);process.exit(9)}catch{}}process.exit(7)", + ]), 7); + assert.notEqual(await run(DEVELOP, nestedWorkspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('.npmrc','changed')", + ]), 0); + assert.equal( + await readFile(path.join(nestedWorkspace, ".npmrc"), "utf8"), + "//registry.example/:_authToken=blocked", + ); + assert.notEqual(await run(DEVELOP, nestedWorkspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('../sibling/.npmrc','changed')", + ]), 0); + assert.equal(await readFile(path.join(credentialSibling, ".npmrc"), "utf8"), "sibling-token"); + assert.notEqual(await run(DEVELOP, nestedWorkspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('../sibling/.ssh/id_test','changed')", + ]), 0); + assert.equal( + await readFile(path.join(credentialSibling, ".ssh", "id_test"), "utf8"), + "sibling-key", + ); + assert.notEqual(await run(DEVELOP, nestedWorkspace, [ + process.execPath, + "-e", + `require('fs').writeFileSync(${JSON.stringify(deepCredential)},'changed')`, + ]), 0); + assert.equal(await readFile(deepCredential, "utf8"), "deep-token"); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "process.exit(require('fs').readFileSync('/dev/null').length === 0 ? 0 : 9)", + ]), 0); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "try{require('fs').readFileSync('.env');process.exit(0)}catch{process.exit(7)}", + ]), 7); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "try{require('fs').readFileSync('.ssh/id_test');process.exit(0)}catch{process.exit(7)}", + ]), 7); + + assert.notEqual(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('blocked.txt','bad')", + ]), 0); + await assert.rejects(readFile(path.join(workspace, "blocked.txt")), /ENOENT/); + + assert.equal(await run(DEVELOP, workspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('allowed.txt','ok')", + ]), 0); + assert.equal(await readFile(path.join(workspace, "allowed.txt"), "utf8"), "ok"); + + assert.notEqual(await run(DEVELOP, workspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('.env.local','blocked')", + ]), 0); + await assert.rejects(stat(path.join(workspace, ".env.local")), /ENOENT/); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "try{require('fs').readFileSync('outside-link');process.exit(0)}catch{process.exit(7)}", + ]), 7); + + assert.notEqual(await run(DEVELOP, workspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('outside-link','changed')", + ]), 0); + assert.equal(await readFile(outsideFile, "utf8"), "outside-unchanged"); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + `try{require('fs').readFileSync(${JSON.stringify(outsideFile)});process.exit(0)}catch{process.exit(7)}`, + ]), 7); + + const hardlink = path.join(workspace, "outside-hardlink"); + await link(outsideFile, hardlink); + await assert.rejects(run(OBSERVE, workspace, [ + process.execPath, + "-e", + "require('fs').readFileSync('outside-hardlink')", + ]), /external hardlink/); + await rm(hardlink, { force: true }); + + assert.equal(await run(DEVELOP, workspace, [ + process.execPath, + "-e", + "require('fs').writeFileSync('environment.txt', process.env.OPP_INTEGRATION_SECRET || 'missing')", + ]), 0); + assert.equal(await readFile(path.join(workspace, "environment.txt"), "utf8"), "missing"); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "const f=require('path').join(process.env.TMPDIR,'probe');require('fs').writeFileSync(f,'ok');process.exit(require('fs').readFileSync(f,'utf8')==='ok'?0:8)", + ]), 0); + + assert.equal(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "const a=process.argv.slice(1);process.exit(JSON.stringify(a)===JSON.stringify(['space value',';$(literal)','雪'])?0:6)", + "space value", + ";$(literal)", + "雪", + ]), 0); + assert.equal(await run(OBSERVE, workspace, [process.execPath, "-e", "process.exit(7)"]), 7); + + const networkDenied = await run(OBSERVE, workspace, [ + process.execPath, + "-e", + "const s=require('net').connect(9,'127.0.0.1');s.on('connect',()=>process.exit(0));s.on('error',()=>process.exit(7));setTimeout(()=>process.exit(7),1000)", + ]); + assert.equal(networkDenied, 7); + + const sharedTemporaryProbe = `/tmp/claude/opp-${process.pid}-probe`; + assert.notEqual(await run(OBSERVE, workspace, [ + process.execPath, + "-e", + `require('fs').mkdirSync('/tmp/claude',{recursive:true});require('fs').writeFileSync(${JSON.stringify(sharedTemporaryProbe)},'bad')`, + ]), 0); + await assert.rejects(stat(sharedTemporaryProbe), /ENOENT/); + + let requests = []; + const server = createServer((request, response) => { + requests.push(request.method); + response.end("ok"); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + const destination = `127.0.0.1:${address.port}`; + try { + assert.equal(await run(NETWORK_READ, workspace, [ + "curl", + "--fail", + "--silent", + `http://${destination}/read`, + ], { allowedDomains: [destination] }), 0); + assert.notEqual(await run(NETWORK_READ, workspace, [ + "curl", + "--fail", + "--silent", + "--request", + "POST", + `http://${destination}/write`, + ], { allowedDomains: [destination] }), 0); + assert.deepEqual(requests, ["GET"]); + } finally { + await new Promise((resolve, reject) => { + server.close((error) => error ? reject(error) : resolve()); + }); + } + } finally { + await rm(workspace, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + await rm(toolBundle, { recursive: true, force: true }); + await rm(linkedParent, { recursive: true, force: true }); + } +}); diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs new file mode 100644 index 0000000..708cd0a --- /dev/null +++ b/tests/sandbox-runtime.test.mjs @@ -0,0 +1,893 @@ +import { execFile } from "node:child_process"; +import { EventEmitter } from "node:events"; +import { + chmod, + link, + mkdir, + mkdtemp, + readFile, + realpath, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + buildChildEnvironment, + commandToShellString, + compileSandboxExecution, + assertNoExternalHardlinks, + existingSystemReadRoots, + probeSandboxRuntime, + quotePosixArgument, + runSandboxedCommand, +} from "../bin/sandbox/runtime.mjs"; + +const execFileAsync = promisify(execFile); +const REPO = process.env.REPO || process.cwd(); + +function profile(name, overrides = {}) { + const capabilities = { + workspace: "read", + temporaryFiles: "write", + network: "deny", + credentials: "deny", + externalSideEffects: "deny", + ...overrides, + }; + return { name, description: name, riskLevel: 0, capabilities, enforcementLevel: "advisory" }; +} + +function compile(overrides = {}) { + return compileSandboxExecution({ + profile: profile("observe"), + workspace: REPO, + runRoot: "/tmp/opp-sandbox-unit", + sourceEnvironment: { + PATH: "/usr/bin:/bin", + LANG: "C.UTF-8", + GH_TOKEN: "secret-gh-token", + SSH_AUTH_SOCK: "/tmp/agent.sock", + }, + originalHome: os.homedir(), + helperPaths: { + bwrap: "/usr/bin/bwrap", + rg: "/usr/bin/rg", + socat: "/usr/bin/socat", + }, + ...overrides, + }); +} + +test("observe compiles to read-only workspace, private temporary writes, and a scrubbed environment", () => { + const result = compile(); + + assert.deepEqual(result.runtimeConfig.filesystem.allowRead, [REPO, "/tmp/opp-sandbox-unit"]); + assert.deepEqual(result.runtimeConfig.filesystem.allowWrite, ["/tmp/opp-sandbox-unit"]); + assert.deepEqual(result.runtimeConfig.filesystem.denyRead, [path.parse(REPO).root]); + assert.equal(result.runtimeConfig.network.strictAllowlist, true); + assert.deepEqual(result.runtimeConfig.network.allowedDomains, []); + assert.equal(result.runtimeConfig.enableWeakerNestedSandbox, false); + assert.equal(result.runtimeConfig.enableWeakerNetworkIsolation, false); + assert.equal(result.runtimeConfig.allowAppleEvents, false); + assert.equal(result.childEnvironment.GH_TOKEN, undefined); + assert.equal(result.childEnvironment.SSH_AUTH_SOCK, undefined); + assert.equal(result.childEnvironment.HOME, "/tmp/opp-sandbox-unit/home"); + assert.equal(result.childEnvironment.TMPDIR, "/tmp/opp-sandbox-unit/tmp"); + assert.ok( + result.runtimeConfig.credentials.files.some((entry) => entry.path === path.join(REPO, ".env")), + ); +}); + +test("system runtime reads do not expose all of usr or usr-local configuration", async () => { + const roots = await existingSystemReadRoots(process.platform); + assert.equal(roots.includes("/usr"), false); + assert.equal(roots.includes("/usr/local"), false); + assert.ok(roots.includes(await realpath("/usr/bin"))); +}); + +function isParent(candidate, target) { + const relative = path.relative(candidate, target); + return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative); +} + +test("develop permits workspace writes without granting network or credentials", () => { + const result = compile({ + profile: profile("develop", { workspace: "write" }), + }); + + assert.deepEqual(result.runtimeConfig.filesystem.allowWrite, [REPO, "/tmp/opp-sandbox-unit"]); + assert.deepEqual(result.runtimeConfig.network.allowedDomains, []); + assert.equal(result.childEnvironment.GH_TOKEN, undefined); + assert.ok(result.runtimeConfig.filesystem.denyWrite.includes(path.join(REPO, ".git", "hooks"))); + assert.ok(result.runtimeConfig.filesystem.denyWrite.includes(path.join(REPO, ".agents"))); +}); + +test("compilation denies upstream shared Claude temporary paths on every platform", () => { + const result = compile({ + temporaryRoot: "/private/var/folders/example/T", + }); + + assert.ok(result.runtimeConfig.filesystem.denyWrite.includes("/tmp/claude")); + assert.ok(result.runtimeConfig.filesystem.denyWrite.includes("/private/tmp/claude")); + assert.ok( + result.runtimeConfig.filesystem.denyWrite.includes("/private/var/folders/example/T/claude"), + ); +}); + +test("workspace hardlink scan allows internal links and rejects links to external inodes", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-hardlink-unit-")); + const workspace = path.join(fixture, "workspace"); + const outside = path.join(fixture, "outside.txt"); + await mkdir(workspace); + await writeFile(outside, "outside", "utf8"); + await link(outside, path.join(workspace, "external-link")); + try { + await assert.rejects(assertNoExternalHardlinks(workspace), /external hardlink/); + await rm(path.join(workspace, "external-link")); + await writeFile(path.join(workspace, "internal-a"), "inside", "utf8"); + await link(path.join(workspace, "internal-a"), path.join(workspace, "internal-b")); + await assert.doesNotReject(assertNoExternalHardlinks(workspace)); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("network-read blocks raw protocols and mutation-oriented HTTP methods", async () => { + const result = compile({ + profile: profile("network-read", { + workspace: "write", + network: "explicit", + credentials: "explicit", + }), + allowedDomains: ["api.github.com:443"], + readOnlySocksProxyPort: 43123, + }); + + assert.deepEqual(result.runtimeConfig.network.allowedDomains, ["api.github.com:443"]); + assert.equal(result.runtimeConfig.network.socksProxyPort, 43123); + assert.deepEqual(result.runtimeConfig.network.tlsTerminate, {}); + assert.deepEqual( + await result.runtimeConfig.network.filterRequest(new Request("https://api.github.com", { + method: "GET", + })), + { action: "allow" }, + ); + assert.equal( + (await result.runtimeConfig.network.filterRequest(new Request("https://api.github.com", { + method: "POST", + }))).action, + "deny", + ); +}); + +test("capability grants and publish confirmation fail closed", () => { + assert.throws(() => compile({ allowedDomains: ["example.com"] }), /does not permit network/); + assert.throws(() => compile({ allowedEnvironment: ["GH_TOKEN"] }), /does not permit credential/); + assert.throws( + () => compile({ confirmExternalSideEffects: true }), + /does not permit external side-effect confirmation/, + ); + assert.throws( + () => compile({ + profile: profile("publish", { + workspace: "write", + network: "explicit", + credentials: "explicit", + externalSideEffects: "confirm", + }), + }), + /requires --confirm-external-side-effects/, + ); + assert.throws( + () => compile({ + profile: profile("publish", { + workspace: "write", + network: "explicit", + credentials: "explicit", + externalSideEffects: "confirm", + }), + allowedEnvironment: ["NODE_OPTIONS"], + confirmExternalSideEffects: true, + }), + /cannot be granted/, + ); +}); + +test("an explicit credential exposes only the named variable", () => { + const result = compile({ + profile: profile("publish", { + workspace: "write", + network: "explicit", + credentials: "explicit", + externalSideEffects: "confirm", + }), + allowedEnvironment: ["GH_TOKEN"], + confirmExternalSideEffects: true, + }); + + assert.equal(result.childEnvironment.GH_TOKEN, "secret-gh-token"); + assert.equal(result.childEnvironment.SSH_AUTH_SOCK, undefined); + assert.ok(result.runtimeConfig.credentials.envVars.some((entry) => entry.name === "SSH_AUTH_SOCK")); + assert.ok(!result.runtimeConfig.credentials.envVars.some((entry) => entry.name === "GH_TOKEN")); +}); + +test("child environment removes workspace-controlled PATH entries", () => { + const environment = buildChildEnvironment({ + sourceEnvironment: { + PATH: `${REPO}/bin${path.delimiter}/usr/bin${path.delimiter}relative/bin`, + LANG: "C", + }, + allowedEnvironment: [], + workspace: REPO, + runRoot: "/tmp/opp-sandbox-unit", + }); + + assert.equal(environment.PATH, "/usr/bin"); + assert.equal(environment.LANG, "C"); +}); + +test("POSIX quoting preserves shell metacharacters as literal argv", async () => { + const values = [ + "plain", + "space value", + "", + "single'quote", + "$(printf injected)", + "`printf injected`", + "semi;colon", + "line\nbreak", + "*.mjs", + "--skill", + "unicode-雪", + ]; + const command = commandToShellString([ + process.execPath, + "-e", + "process.stdout.write(JSON.stringify(process.argv.slice(1)))", + ...values, + ]); + const { stdout } = await execFileAsync("/bin/sh", ["-c", command], { cwd: REPO }); + + assert.deepEqual(JSON.parse(stdout), values); + assert.equal(quotePosixArgument("a'b"), `'a'"'"'b'`); + assert.throws(() => quotePosixArgument("bad\0value"), /NUL/); +}); + +test("runtime probing reports readiness and fails closed on unsupported or missing backends", async () => { + const ready = await probeSandboxRuntime({ + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: { + isSupportedPlatform: () => true, + checkDependenciesAsync: async () => ({ errors: [], warnings: ["preview"] }), + }, + }), + hostProbe: async () => ({ errors: [], warnings: [] }), + }); + assert.equal(ready.runnerReady, true); + assert.equal(ready.executionLevel, "shell-contained"); + assert.deepEqual(ready.warnings, ["preview"]); + + const unsupported = await probeSandboxRuntime({ platform: "win32" }); + assert.equal(unsupported.runnerReady, false); + assert.match(unsupported.errors[0], /Unsupported platform/); + + const missing = await probeSandboxRuntime({ + platform: "linux", + loadRuntime: async () => { throw new Error("module missing"); }, + }); + assert.equal(missing.runnerReady, false); + assert.deepEqual(missing.errors, ["module missing"]); +}); + +function fakeSpawn(exitCode, onSpawn) { + return (file, args, options) => { + onSpawn?.(file, args, options); + const child = new EventEmitter(); + queueMicrotask(() => child.emit("close", exitCode, null)); + return child; + }; +} + +test("runner initializes before spawn, uses shell false, propagates exit codes, and resets once", async () => { + let initialized; + let resetCount = 0; + let spawnOptions; + let wrappedCommand; + const manager = { + isSupportedPlatform: () => true, + initialize: async (config) => { initialized = config; }, + wrapWithSandboxArgv: async (command) => { + wrappedCommand = command; + return { argv: ["/fake/sandbox", "wrapped"], env: { SHOULD_NOT_LEAK: "yes" } }; + }, + reset: async () => { resetCount += 1; }, + }; + let diagnostics = ""; + const exitCode = await runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["printf", "%s", "literal;$(not-run)"], + }, { + cwd: REPO, + home: os.homedir(), + env: { PATH: "/usr/bin:/bin", GH_TOKEN: "secret" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(7, (_file, _args, options) => { spawnOptions = options; }), + writeError: (text) => { diagnostics += text; }, + }); + + assert.equal(exitCode, 7); + assert.equal(resetCount, 1); + assert.equal(spawnOptions.shell, false); + assert.equal(spawnOptions.env.GH_TOKEN, undefined); + assert.equal(spawnOptions.env.SHOULD_NOT_LEAK, undefined); + assert.equal(initialized.enableWeakerNestedSandbox, false); + assert.equal(wrappedCommand, `'printf' '%s' 'literal;$(not-run)'`); + assert.match(diagnostics, /Sandbox: observe, shell-contained/); + assert.doesNotMatch(diagnostics, /GH_TOKEN|secret|literal/); +}); + +test("runner canonicalizes a symlinked temporary root before compiling private paths", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-canonical-temp-")); + const actualTemporaryRoot = path.join(fixture, "actual-temp"); + const linkedTemporaryRoot = path.join(fixture, "linked-temp"); + const workspace = path.join(fixture, "workspace"); + await mkdir(actualTemporaryRoot); + await mkdir(workspace); + await symlink(actualTemporaryRoot, linkedTemporaryRoot); + let spawnEnvironment; + const manager = { + isSupportedPlatform: () => true, + initialize: async () => {}, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + + try { + assert.equal(await runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: linkedTemporaryRoot, + env: { PATH: "/usr/bin:/bin" }, + platform: "darwin", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(0, (_file, _args, options) => { spawnEnvironment = options.env; }), + }), 0); + assert.ok(spawnEnvironment.HOME.startsWith(`${await realpath(actualTemporaryRoot)}${path.sep}`)); + assert.ok(spawnEnvironment.TMPDIR.startsWith(`${await realpath(actualTemporaryRoot)}${path.sep}`)); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner rejects a workspace inside an upstream shared-write compatibility path", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-shared-write-root-")); + const workspace = path.join(fixture, "claude", "project"); + await mkdir(workspace, { recursive: true }); + try { + await assert.rejects(runSandboxedCommand({ + profile: profile("develop", { workspace: "write" }), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: "/usr/bin:/bin" }, + platform: "darwin", + }), /protected shared-write path/); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner rejects Linux helpers from an attacker-writable PATH directory", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-helper-trust-")); + const workspace = path.join(fixture, "workspace"); + const hostileBin = path.join(fixture, "hostile-bin"); + await mkdir(workspace); + await mkdir(hostileBin); + for (const helper of ["bwrap", "rg", "socat"]) { + const executable = path.join(hostileBin, helper); + await writeFile(executable, "#!/bin/sh\nexit 0\n", "utf8"); + await chmod(executable, 0o755); + } + try { + await assert.rejects(runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: hostileBin }, + platform: "linux", + }), /trusted host paths/); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner exposes an explicitly selected executable outside static system roots", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-command-root-")); + const workspace = path.join(fixture, "workspace"); + const tools = path.join(fixture, "toolcache", "bin"); + const executable = path.join(tools, "custom-node"); + const runtimeResource = path.join(fixture, "toolcache", "lib", "resource.txt"); + await mkdir(workspace); + await mkdir(tools, { recursive: true }); + await mkdir(path.dirname(runtimeResource), { recursive: true }); + await writeFile(path.join(fixture, "toolcache", "package.json"), "{}\n", "utf8"); + await writeFile(runtimeResource, "runtime-resource", "utf8"); + await writeFile(executable, "#!/bin/sh\nexit 0\n", "utf8"); + await chmod(executable, 0o755); + let runtimeConfig; + const manager = { + isSupportedPlatform: () => true, + initialize: async (config) => { runtimeConfig = config; }, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + try { + assert.equal(await runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: [executable], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(0), + }), 0); + assert.ok(runtimeConfig.filesystem.allowRead.some( + (allowed) => allowed === executable || isParent(allowed, executable), + )); + assert.ok(runtimeConfig.filesystem.allowRead.some( + (allowed) => allowed === runtimeResource || isParent(allowed, runtimeResource), + )); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner exposes an env shebang interpreter and its bounded runtime", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-shebang-root-")); + const workspace = path.join(fixture, "workspace"); + const toolRoot = path.join(fixture, "tool"); + const executable = path.join(toolRoot, "bin", "env-tool"); + const fakeHome = path.join(fixture, "home"); + const interpreterBin = path.join(fakeHome, "bin"); + const interpreter = path.join(interpreterBin, "custom-node"); + await mkdir(workspace); + await mkdir(path.dirname(executable), { recursive: true }); + await mkdir(interpreterBin, { recursive: true }); + await mkdir(path.join(fakeHome, "lib", "node_modules"), { recursive: true }); + await writeFile(path.join(toolRoot, "package.json"), "{}\n", "utf8"); + await writeFile(executable, "#!/usr/bin/env -S custom-node --no-warnings\n", "utf8"); + await chmod(executable, 0o755); + await symlink(process.execPath, interpreter); + let runtimeConfig; + const manager = { + isSupportedPlatform: () => true, + initialize: async (config) => { runtimeConfig = config; }, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + try { + assert.equal(await runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: [executable], + }, { + cwd: workspace, + home: fakeHome, + temporaryRoot: fixture, + env: { PATH: `${interpreterBin}${path.delimiter}/usr/bin:/bin` }, + platform: "darwin", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(0), + }), 0); + assert.ok(runtimeConfig.filesystem.allowRead.includes(interpreter)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(await realpath(process.execPath))); + for (const broadRoot of ["/usr", "/usr/local", fakeHome, fixture]) { + assert.equal(runtimeConfig.filesystem.allowRead.includes(broadRoot), false); + } + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner discovers Git roots from nested directories and validates linked worktrees", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-git-root-")); + const repository = path.join(fixture, "repository"); + const nested = path.join(repository, "src", "nested"); + const linkedWorktree = path.join(fixture, "linked-worktree"); + const submodule = path.join(repository, "submodule"); + const submoduleGitDirectory = path.join(repository, ".git", "modules", "submodule"); + const siblingSubmodule = path.join(repository, "sibling-submodule"); + const siblingSubmoduleGitDirectory = path.join(repository, ".git", "modules", "sibling-submodule"); + const credentialSibling = path.join(repository, "src", "sibling"); + const deepCredential = path.join( + repository, + ...Array.from({ length: 12 }, (_value, index) => `level-${index}`), + ".npmrc", + ); + await mkdir(nested, { recursive: true }); + await mkdir(path.join(credentialSibling, ".ssh"), { recursive: true }); + await writeFile(path.join(credentialSibling, ".npmrc"), "credential", "utf8"); + await mkdir(path.dirname(deepCredential), { recursive: true }); + await writeFile(deepCredential, "deep-credential", "utf8"); + await execFileAsync("git", ["init", "--quiet", repository]); + await mkdir(path.dirname(submoduleGitDirectory), { recursive: true }); + await execFileAsync("git", [ + "init", + "--quiet", + "--separate-git-dir", + submoduleGitDirectory, + submodule, + ]); + await execFileAsync("git", [ + "init", + "--quiet", + "--separate-git-dir", + siblingSubmoduleGitDirectory, + siblingSubmodule, + ]); + await execFileAsync("git", [ + "config", + "--file", + path.join(submoduleGitDirectory, "config"), + "core.worktree", + "../../../submodule", + ]); + await execFileAsync("git", [ + "config", + "--file", + path.join(siblingSubmoduleGitDirectory, "config"), + "core.worktree", + "../../../sibling-submodule", + ]); + await writeFile(path.join(repository, ".gitmodules"), [ + '[submodule "submodule"]', + "\tpath = submodule", + '[submodule "sibling-submodule"]', + "\tpath = sibling-submodule", + "", + ].join("\n"), "utf8"); + const submoduleNested = path.join(submodule, "nested"); + await mkdir(submoduleNested); + await execFileAsync("git", [ + "-C", + repository, + "worktree", + "add", + "--quiet", + "--orphan", + linkedWorktree, + ]); + const linkedNested = path.join(linkedWorktree, "src"); + await mkdir(linkedNested); + let runtimeConfig; + let wrappedCwd; + const manager = { + isSupportedPlatform: () => true, + initialize: async (config) => { runtimeConfig = config; }, + wrapWithSandboxArgv: async (_command, _shell, _a, _b, cwd) => { + wrappedCwd = cwd; + return { argv: ["/fake/sandbox"], env: {} }; + }, + reset: async () => {}, + }; + const execute = (cwd) => runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["git", "status", "--short"], + }, { + cwd, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: "/usr/bin:/bin" }, + platform: "darwin", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(0), + }); + try { + assert.equal(await execute(nested), 0); + assert.equal(wrappedCwd, nested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(repository)); + assert.ok(runtimeConfig.credentials.files.some( + (entry) => entry.path === path.join(nested, ".env") && entry.mode === "deny", + )); + assert.ok(runtimeConfig.credentials.files.some( + (entry) => entry.path === path.join(repository, "**", ".env") && entry.mode === "deny", + )); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(nested, ".npmrc"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(credentialSibling, ".npmrc"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(credentialSibling, ".ssh"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(deepCredential)); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(submodule, ".git"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes( + path.join(submoduleGitDirectory, "config"), + )); + + assert.equal(await execute(linkedNested), 0); + assert.equal(wrappedCwd, linkedNested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(linkedWorktree)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(path.join(repository, ".git"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(repository, ".git", "config"))); + + assert.equal(await execute(submoduleNested), 0); + assert.equal(wrappedCwd, submoduleNested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(submodule)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(submoduleGitDirectory)); + assert.equal(runtimeConfig.filesystem.allowRead.includes(repository), false); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(submodule, ".git"))); + + await writeFile( + path.join(submodule, ".git"), + `gitdir: ${siblingSubmoduleGitDirectory}\n`, + "utf8", + ); + await writeFile(path.join(repository, ".gitmodules"), [ + '[submodule "sibling-submodule"]', + "\tpath = submodule", + "", + ].join("\n"), "utf8"); + await assert.rejects(execute(submoduleNested), /Untrusted submodule Git metadata/); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + +test("runner rejects concurrent in-process execution instead of sharing global sandbox state", async () => { + let releaseSpawn; + const spawnStarted = new Promise((resolve) => { releaseSpawn = resolve; }); + let finishChild; + const childFinished = new Promise((resolve) => { finishChild = resolve; }); + const manager = { + isSupportedPlatform: () => true, + initialize: async () => {}, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + const context = { + cwd: REPO, + home: os.homedir(), + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: () => { + const child = new EventEmitter(); + releaseSpawn(); + childFinished.then(() => child.emit("close", 0, null)); + return child; + }, + }; + const options = { + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }; + + const first = runSandboxedCommand(options, context); + await spawnStarted; + await assert.rejects(runSandboxedCommand(options, context), /already active/); + finishChild(); + assert.equal(await first, 0); + assert.equal(await runSandboxedCommand(options, { + ...context, + spawn: fakeSpawn(0), + }), 0); +}); + +test("runner forwards termination to the isolated child group and restores signal handlers", async () => { + const signalSource = new EventEmitter(); + let existingSignalHandlerRuns = 0; + const existingSignalHandler = () => { existingSignalHandlerRuns += 1; }; + signalSource.on("SIGTERM", existingSignalHandler); + const child = new EventEmitter(); + child.pid = 4321; + let spawnOptions; + let notifySpawn; + const spawned = new Promise((resolve) => { notifySpawn = resolve; }); + const kills = []; + let backendSignalCleanupRan = false; + function cleanupHandler() { backendSignalCleanupRan = true; } + const manager = { + isSupportedPlatform: () => true, + initialize: async () => { + signalSource.once("SIGINT", cleanupHandler); + signalSource.once("SIGTERM", cleanupHandler); + signalSource.once("exit", cleanupHandler); + }, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + const execution = runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: REPO, + home: os.homedir(), + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: (_file, _args, options) => { + spawnOptions = options; + notifySpawn(); + return child; + }, + signalSource, + runtimeSignalSource: signalSource, + killProcess: (pid, signal) => { + kills.push([pid, signal]); + queueMicrotask(() => child.emit("close", 0, null)); + }, + }); + + await spawned; + signalSource.emit("SIGTERM"); + assert.equal(await execution, 143); + assert.equal(spawnOptions.detached, true); + assert.deepEqual(kills, [[-4321, "SIGTERM"]]); + assert.equal(backendSignalCleanupRan, false); + assert.equal(existingSignalHandlerRuns, 1); + assert.equal(signalSource.listenerCount("exit"), 0); + assert.equal(signalSource.listenerCount("SIGINT"), 0); + assert.deepEqual(signalSource.listeners("SIGTERM"), [existingSignalHandler]); + signalSource.removeListener("SIGTERM", existingSignalHandler); +}); + +test("runner treats SIGHUP as fail-closed child-group termination", async () => { + const signalSource = new EventEmitter(); + const child = new EventEmitter(); + child.pid = 9876; + let notifySpawn; + const spawned = new Promise((resolve) => { notifySpawn = resolve; }); + const kills = []; + const manager = { + isSupportedPlatform: () => true, + initialize: async () => {}, + wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + reset: async () => {}, + }; + const execution = runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: REPO, + home: os.homedir(), + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: () => { + notifySpawn(); + return child; + }, + signalSource, + runtimeSignalSource: signalSource, + killProcess: (pid, signal) => { + kills.push([pid, signal]); + queueMicrotask(() => child.emit("close", 0, null)); + }, + }); + + await spawned; + signalSource.emit("SIGHUP"); + assert.equal(await execution, 129); + assert.deepEqual(kills, [[-9876, "SIGHUP"]]); + assert.equal(signalSource.listenerCount("SIGHUP"), 0); +}); + +test("initialization failures never spawn and still reset the backend", async () => { + let spawned = false; + let resetCount = 0; + const manager = { + isSupportedPlatform: () => true, + initialize: async () => { throw new Error("backend init failed"); }, + reset: async () => { resetCount += 1; }, + }; + + await assert.rejects( + runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: REPO, + home: os.homedir(), + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: () => { spawned = true; }, + }), + /backend init failed/, + ); + assert.equal(spawned, false); + assert.equal(resetCount, 1); +}); + +test("the runtime dependency is exactly pinned in package metadata and lock data", async () => { + const packageJson = JSON.parse(await readFile(path.join(REPO, "package.json"), "utf8")); + const lock = JSON.parse(await readFile(path.join(REPO, "package-lock.json"), "utf8")); + + assert.equal(packageJson.dependencies["@anthropic-ai/sandbox-runtime"], "0.0.73"); + assert.equal(packageJson.engines.node, ">=20.11.0"); + assert.equal(lock.packages[""].dependencies["@anthropic-ai/sandbox-runtime"], "0.0.73"); + assert.equal( + lock.packages["node_modules/@anthropic-ai/sandbox-runtime"].integrity, + "sha512-F608iUirrCqwvInZYGRRgJWDQj0tt6fNVE9aPagpotLJ5LhC4JbrMFIIZww5MFjb+HRCkpE0+xdI79c30tdVYg==", + ); +}); From 3194dadffd63bb5423278748c3701202fa26382d Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Sun, 16 Aug 2026 19:03:06 -0500 Subject: [PATCH 2/8] Keep sandbox readiness and runtime resources consistent across Linux and macOS Resolve and expose the pinned seccomp helper before Linux execution, make doctor validate the same platform resources, filter invalid host environment keys from backend declarations, and canonicalize cross-platform path assertions so real containment checks behave consistently on GitHub runners. --- bin/sandbox/runtime.mjs | 70 +++++++++++++++++++++++++--- tests/sandbox-runtime.test.mjs | 85 +++++++++++++++++++++++++--------- 2 files changed, 127 insertions(+), 28 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index 07a60ea..4d08fc7 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -15,6 +15,7 @@ import { import { createServer } from "node:net"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; export const SANDBOX_RUNTIME_PACKAGE = "@anthropic-ai/sandbox-runtime"; export const SANDBOX_RUNTIME_VERSION = "0.0.73"; @@ -55,8 +56,12 @@ function unique(values) { return [...new Set(values)]; } +function isEnvironmentName(name) { + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name); +} + function assertEnvironmentName(name) { - if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) { + if (!isEnvironmentName(name)) { throw new Error(`Invalid environment variable name: ${name}`); } if (PROTECTED_ENVIRONMENT.has(name) || /^(?:DYLD_|LD_)/.test(name)) { @@ -226,7 +231,7 @@ export function compileSandboxExecution({ runRoot, }); const deniedEnvironment = Object.keys(sourceEnvironment) - .filter((name) => !Object.hasOwn(childEnvironment, name)) + .filter((name) => isEnvironmentName(name) && !Object.hasOwn(childEnvironment, name)) .map((name) => ({ name, mode: "deny" })); const workspaceWrites = capabilities.workspace === "write" ? [workspace] : []; const network = { @@ -273,6 +278,9 @@ export function compileSandboxExecution({ ...(helperPaths.rg ? { ripgrep: { command: helperPaths.rg } } : {}), ...(helperPaths.bwrap ? { bwrapPath: helperPaths.bwrap } : {}), ...(helperPaths.socat ? { socatPath: helperPaths.socat } : {}), + ...(helperPaths.applySeccomp + ? { seccomp: { applyPath: helperPaths.applySeccomp } } + : {}), }; return { @@ -855,6 +863,43 @@ async function resolveHelperPaths(platform, environmentPath, blockedRoots) { return { bwrap, rg, socat }; } +async function resolveSandboxRuntimeResources(platform, architecture = process.arch) { + if (platform !== "linux") return {}; + const architectureDirectory = { x64: "x64", arm64: "arm64" }[architecture]; + if (!architectureDirectory) { + throw new Error(`Sandbox seccomp helper is unsupported on architecture: ${architecture}`); + } + let current = path.dirname(fileURLToPath(import.meta.resolve(SANDBOX_RUNTIME_PACKAGE))); + for (let depth = 0; depth <= 3; depth += 1) { + const manifestPath = path.join(current, "package.json"); + try { + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + if ( + manifest.name === SANDBOX_RUNTIME_PACKAGE + && manifest.version === SANDBOX_RUNTIME_VERSION + ) { + const applySeccomp = await realpath(path.join( + current, + "vendor", + "seccomp", + architectureDirectory, + "apply-seccomp", + )); + const info = await stat(applySeccomp); + await access(applySeccomp, 1); + if (!info.isFile()) throw new Error("Sandbox seccomp helper is not a regular file."); + return { applySeccomp }; + } + } catch (error) { + if (error?.code !== "ENOENT") throw error; + } + const parent = path.dirname(current); + if (parent === current) break; + current = parent; + } + throw new Error(`Could not locate pinned ${SANDBOX_RUNTIME_PACKAGE} runtime resources.`); +} + async function createDenyProxy() { const server = createServer((socket) => socket.destroy()); await new Promise((resolve, reject) => { @@ -1002,7 +1047,9 @@ export async function probeSandboxRuntime({ platform = process.platform, cwd = process.cwd(), env = process.env, + architecture = process.arch, hostProbe = probeHostIsolation, + resourceProbe = resolveSandboxRuntimeResources, } = {}) { const backend = `${SANDBOX_RUNTIME_PACKAGE}@${SANDBOX_RUNTIME_VERSION}`; if (!SUPPORTED_PLATFORMS.has(platform)) { @@ -1026,9 +1073,12 @@ export async function probeSandboxRuntime({ }; } const dependencies = await SandboxManager.checkDependenciesAsync(); - const host = dependencies.errors.length === 0 - ? await hostProbe({ platform, cwd: await realpath(cwd), env }) - : { errors: [], warnings: [] }; + const [host] = dependencies.errors.length === 0 + ? await Promise.all([ + hostProbe({ platform, cwd: await realpath(cwd), env }), + resourceProbe(platform, architecture), + ]) + : [{ errors: [], warnings: [] }]; const errors = [...dependencies.errors, ...host.errors]; const warnings = [...dependencies.warnings, ...host.warnings]; return { @@ -1080,12 +1130,13 @@ async function runSandboxedCommandOnce(options, context = {}) { ]); const sourceEnvironment = context.env || process.env; - const [helperPaths, systemReadRoots, executableReadRoots] = await Promise.all([ + const [containmentHelpers, runtimeResources, systemReadRoots, executableReadRoots] = await Promise.all([ context.helperPaths || resolveHelperPaths( platform, sourceEnvironment.PATH, [workspace, originalHome, temporaryRoot], ), + resolveSandboxRuntimeResources(platform, context.architecture), existingSystemReadRoots(platform), commandReadRoots(options.command, sourceEnvironment.PATH, executionCwd, { workspace, @@ -1093,7 +1144,12 @@ async function runSandboxedCommandOnce(options, context = {}) { temporaryRoot, }), ]); - const allowedReadRoots = unique([...systemReadRoots, ...executableReadRoots]); + const helperPaths = { ...containmentHelpers, ...runtimeResources }; + const allowedReadRoots = unique([ + ...systemReadRoots, + ...executableReadRoots, + ...Object.values(runtimeResources), + ]); const runRoot = await realpath(await mkdtemp(path.join(temporaryRoot, "opp-sandbox-"))); let denyProxy; let manager; diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index 708cd0a..7302aa5 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -273,6 +273,20 @@ test("runtime probing reports readiness and fails closed on unsupported or missi assert.equal(ready.executionLevel, "shell-contained"); assert.deepEqual(ready.warnings, ["preview"]); + const unsupportedArchitecture = await probeSandboxRuntime({ + platform: "linux", + architecture: "s390x", + loadRuntime: async () => ({ + SandboxManager: { + isSupportedPlatform: () => true, + checkDependenciesAsync: async () => ({ errors: [], warnings: [] }), + }, + }), + hostProbe: async () => ({ errors: [], warnings: [] }), + }); + assert.equal(unsupportedArchitecture.runnerReady, false); + assert.match(unsupportedArchitecture.errors[0], /unsupported on architecture/); + const unsupported = await probeSandboxRuntime({ platform: "win32" }); assert.equal(unsupported.runnerReady, false); assert.match(unsupported.errors[0], /Unsupported platform/); @@ -318,7 +332,11 @@ test("runner initializes before spawn, uses shell false, propagates exit codes, }, { cwd: REPO, home: os.homedir(), - env: { PATH: "/usr/bin:/bin", GH_TOKEN: "secret" }, + env: { + PATH: "/usr/bin:/bin", + GH_TOKEN: "secret", + "JAVA_HOME_17.0.16_x64": "/invalid-host-key", + }, helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, platform: "linux", loadRuntime: async () => ({ @@ -333,8 +351,19 @@ test("runner initializes before spawn, uses shell false, propagates exit codes, assert.equal(resetCount, 1); assert.equal(spawnOptions.shell, false); assert.equal(spawnOptions.env.GH_TOKEN, undefined); + assert.equal(spawnOptions.env["JAVA_HOME_17.0.16_x64"], undefined); assert.equal(spawnOptions.env.SHOULD_NOT_LEAK, undefined); assert.equal(initialized.enableWeakerNestedSandbox, false); + assert.ok(initialized.seccomp.applyPath.endsWith(path.join( + "vendor", + "seccomp", + process.arch === "arm64" ? "arm64" : "x64", + "apply-seccomp", + ))); + assert.ok(initialized.filesystem.allowRead.includes(initialized.seccomp.applyPath)); + assert.equal(initialized.credentials.envVars.some( + (entry) => entry.name === "JAVA_HOME_17.0.16_x64", + ), false); assert.equal(wrappedCommand, `'printf' '%s' 'literal;$(not-run)'`); assert.match(diagnostics, /Sandbox: observe, shell-contained/); assert.doesNotMatch(diagnostics, /GH_TOKEN|secret|literal/); @@ -478,8 +507,10 @@ test("runner exposes an explicitly selected executable outside static system roo assert.ok(runtimeConfig.filesystem.allowRead.some( (allowed) => allowed === executable || isParent(allowed, executable), )); + const canonicalRuntimeResource = await realpath(runtimeResource); assert.ok(runtimeConfig.filesystem.allowRead.some( - (allowed) => allowed === runtimeResource || isParent(allowed, runtimeResource), + (allowed) => allowed === canonicalRuntimeResource + || isParent(allowed, canonicalRuntimeResource), )); } finally { await rm(fixture, { recursive: true, force: true }); @@ -608,6 +639,16 @@ test("runner discovers Git roots from nested directories and validates linked wo ]); const linkedNested = path.join(linkedWorktree, "src"); await mkdir(linkedNested); + const canonicalRepository = await realpath(repository); + const canonicalNested = await realpath(nested); + const canonicalCredentialSibling = await realpath(credentialSibling); + const canonicalDeepCredential = await realpath(deepCredential); + const canonicalLinkedWorktree = await realpath(linkedWorktree); + const canonicalLinkedNested = await realpath(linkedNested); + const canonicalSubmodule = await realpath(submodule); + const canonicalSubmoduleNested = await realpath(submoduleNested); + const canonicalSubmoduleGitDirectory = await realpath(submoduleGitDirectory); + const canonicalRepositoryGitDirectory = await realpath(path.join(repository, ".git")); let runtimeConfig; let wrappedCwd; const manager = { @@ -639,35 +680,37 @@ test("runner discovers Git roots from nested directories and validates linked wo }); try { assert.equal(await execute(nested), 0); - assert.equal(wrappedCwd, nested); - assert.ok(runtimeConfig.filesystem.allowRead.includes(repository)); + assert.equal(wrappedCwd, canonicalNested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(canonicalRepository)); assert.ok(runtimeConfig.credentials.files.some( - (entry) => entry.path === path.join(nested, ".env") && entry.mode === "deny", + (entry) => entry.path === path.join(canonicalNested, ".env") && entry.mode === "deny", )); assert.ok(runtimeConfig.credentials.files.some( - (entry) => entry.path === path.join(repository, "**", ".env") && entry.mode === "deny", + (entry) => entry.path === path.join(canonicalRepository, "**", ".env") && entry.mode === "deny", )); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(nested, ".npmrc"))); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(credentialSibling, ".npmrc"))); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(credentialSibling, ".ssh"))); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(deepCredential)); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(submodule, ".git"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(canonicalNested, ".npmrc"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(canonicalCredentialSibling, ".npmrc"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(canonicalCredentialSibling, ".ssh"))); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(canonicalDeepCredential)); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(canonicalSubmodule, ".git"))); assert.ok(runtimeConfig.filesystem.denyWrite.includes( - path.join(submoduleGitDirectory, "config"), + path.join(canonicalSubmoduleGitDirectory, "config"), )); assert.equal(await execute(linkedNested), 0); - assert.equal(wrappedCwd, linkedNested); - assert.ok(runtimeConfig.filesystem.allowRead.includes(linkedWorktree)); - assert.ok(runtimeConfig.filesystem.allowRead.includes(path.join(repository, ".git"))); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(repository, ".git", "config"))); + assert.equal(wrappedCwd, canonicalLinkedNested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(canonicalLinkedWorktree)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(canonicalRepositoryGitDirectory)); + assert.ok(runtimeConfig.filesystem.denyWrite.includes( + path.join(canonicalRepositoryGitDirectory, "config"), + )); assert.equal(await execute(submoduleNested), 0); - assert.equal(wrappedCwd, submoduleNested); - assert.ok(runtimeConfig.filesystem.allowRead.includes(submodule)); - assert.ok(runtimeConfig.filesystem.allowRead.includes(submoduleGitDirectory)); - assert.equal(runtimeConfig.filesystem.allowRead.includes(repository), false); - assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(submodule, ".git"))); + assert.equal(wrappedCwd, canonicalSubmoduleNested); + assert.ok(runtimeConfig.filesystem.allowRead.includes(canonicalSubmodule)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(canonicalSubmoduleGitDirectory)); + assert.equal(runtimeConfig.filesystem.allowRead.includes(canonicalRepository), false); + assert.ok(runtimeConfig.filesystem.denyWrite.includes(path.join(canonicalSubmodule, ".git"))); await writeFile( path.join(submodule, ".git"), From 432ce60bb269c21eedb4822c9e3f7f9af28f96b0 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Sun, 16 Aug 2026 23:54:05 -0500 Subject: [PATCH 3/8] Resolve native sandbox executable paths safely across Linux and macOS Allow bounded parent directories for symlinked interpreters required by Bubblewrap, expose the macOS shell selector, and reject executable paths that overlap credential directories even through filesystem aliases. Add unit and real containment regressions for these platform-specific cases. --- bin/sandbox/runtime.mjs | 107 +++++++++++++++------ tests/sandbox-runtime.integration.test.mjs | 9 ++ tests/sandbox-runtime.test.mjs | 44 ++++++++- 3 files changed, 129 insertions(+), 31 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index 4d08fc7..0f22392 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -56,6 +56,20 @@ function unique(values) { return [...new Set(values)]; } +async function withCanonicalPaths(paths) { + const canonical = []; + for (const filePath of paths) { + const absolute = path.resolve(filePath); + canonical.push(absolute); + try { + canonical.push(await realpath(absolute)); + } catch { + // Missing credential paths still need their declared spelling protected. + } + } + return unique(canonical); +} + function isEnvironmentName(name) { return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name); } @@ -336,6 +350,7 @@ export async function existingSystemReadRoots(platform) { ...(platform === "linux" ? ["/proc", "/sys", "/nix/store", "/snap"] : []), ...(platform === "darwin" ? [ "/System", + "/private/var/select/sh", "/opt/homebrew/bin", "/opt/homebrew/sbin", "/opt/homebrew/Cellar", @@ -472,40 +487,65 @@ async function executableReadRoots(executable, environmentPath, cwd, boundaries, .filter((directory) => directory && path.isAbsolute(directory)) .map((directory) => path.join(directory, executable)); for (const candidate of candidates) { + let candidateInfo; + let resolved; + let info; try { - const resolved = await realpath(candidate); - const info = await stat(resolved); + candidateInfo = await lstat(candidate); + resolved = await realpath(candidate); + info = await stat(resolved); await access(resolved, 1); - if (info.isFile()) { - const roots = [ - path.resolve(candidate), - resolved, - ...await discoverRuntimeBundleRoots(resolved, boundaries), - ]; - if (depth < 2) { - const firstLine = await readFirstLine(resolved); - if (firstLine.startsWith("#!")) { - const shebang = splitShebangWords(firstLine.slice(2)); - const interpreter = shebang.length > 0 && path.basename(shebang[0]) === "env" - ? envShebangCommand(shebang.slice(1)) - : shebang[0]; - if (interpreter) { - const interpreterRoots = await executableReadRoots( - interpreter, - environmentPath, - cwd, - boundaries, - depth + 1, - ); - roots.push(...interpreterRoots); - } - } - } - return unique(roots); - } } catch { - // The child shell reports command-not-found when no candidate resolves. + continue; } + if (!info.isFile()) continue; + + const candidatePath = path.resolve(candidate); + const candidateRoot = candidateInfo.isSymbolicLink() + ? path.dirname(candidatePath) + : candidatePath; + if (candidateInfo.isSymbolicLink()) { + const canonicalCandidateRoot = await realpath(candidateRoot); + const candidateRoots = unique([candidateRoot, canonicalCandidateRoot]); + const unsafeRoots = [ + path.parse(candidateRoot).root, + boundaries.originalHome, + boundaries.temporaryRoot, + ]; + const overlapsCredential = boundaries.protectedCredentialPaths.some( + (protectedPath) => candidateRoots.some( + (root) => isWithin(root, protectedPath) || isWithin(protectedPath, root), + ), + ); + if (candidateRoots.some((root) => unsafeRoots.includes(root)) || overlapsCredential) { + throw new Error(`Refusing to expose an unsafe executable symlink directory: ${candidateRoot}`); + } + } + const roots = [ + candidateRoot, + resolved, + ...await discoverRuntimeBundleRoots(resolved, boundaries), + ]; + if (depth < 2) { + const firstLine = await readFirstLine(resolved); + if (firstLine.startsWith("#!")) { + const shebang = splitShebangWords(firstLine.slice(2)); + const interpreter = shebang.length > 0 && path.basename(shebang[0]) === "env" + ? envShebangCommand(shebang.slice(1)) + : shebang[0]; + if (interpreter) { + const interpreterRoots = await executableReadRoots( + interpreter, + environmentPath, + cwd, + boundaries, + depth + 1, + ); + roots.push(...interpreterRoots); + } + } + } + return unique(roots); } return []; } @@ -1128,6 +1168,12 @@ async function runSandboxedCommandOnce(options, context = {}) { discoverExistingWorkspaceCredentialPaths(workspace), discoverExistingGitControlPaths(workspace), ]); + const protectedCredentialPaths = await withCanonicalPaths([ + ...credentialFiles(workspace, originalHome) + .map((credential) => credential.path) + .filter((credentialPath) => !credentialPath.includes("*")), + ...existingCredentialPaths, + ]); const sourceEnvironment = context.env || process.env; const [containmentHelpers, runtimeResources, systemReadRoots, executableReadRoots] = await Promise.all([ @@ -1142,6 +1188,7 @@ async function runSandboxedCommandOnce(options, context = {}) { workspace, originalHome, temporaryRoot, + protectedCredentialPaths, }), ]); const helperPaths = { ...containmentHelpers, ...runtimeResources }; diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs index 5fc1a78..8705685 100644 --- a/tests/sandbox-runtime.integration.test.mjs +++ b/tests/sandbox-runtime.integration.test.mjs @@ -94,6 +94,8 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou await writeFile(path.join(workspace, ".env"), "TOP_SECRET=do-not-read", "utf8"); await mkdir(path.join(workspace, ".ssh")); await writeFile(path.join(workspace, ".ssh", "id_test"), "private-key", "utf8"); + await symlink(process.execPath, path.join(workspace, ".ssh", "run")); + await symlink(path.join(workspace, ".ssh"), path.join(workspace, "credential-tools")); await writeFile(outsideFile, "outside-unchanged", "utf8"); await mkdir(path.join(toolBundle, "bin")); await mkdir(path.join(toolBundle, "lib")); @@ -167,6 +169,13 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou }, }), 0); + await assert.rejects(run(OBSERVE, workspace, [ + path.join(workspace, "credential-tools", "run"), + "-e", + "require('fs').readFileSync('.ssh/id_test')", + ]), /unsafe executable symlink directory/); + assert.equal(await readFile(path.join(workspace, ".ssh", "id_test"), "utf8"), "private-key"); + assert.equal(await run(OBSERVE, workspace, ["git", "status", "--short"]), 0); assert.equal(await run(OBSERVE, nestedWorkspace, ["git", "status", "--short"]), 0); assert.equal(await run(OBSERVE, path.join(linkedWorktree, "nested"), [ diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index 7302aa5..ac740cf 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -88,6 +88,10 @@ test("system runtime reads do not expose all of usr or usr-local configuration", assert.equal(roots.includes("/usr"), false); assert.equal(roots.includes("/usr/local"), false); assert.ok(roots.includes(await realpath("/usr/bin"))); + if (process.platform === "darwin") { + assert.ok(roots.includes("/private/var/select/sh")); + assert.ok(roots.includes(await realpath("/private/var/select/sh"))); + } }); function isParent(candidate, target) { @@ -559,7 +563,8 @@ test("runner exposes an env shebang interpreter and its bounded runtime", async }), spawn: fakeSpawn(0), }), 0); - assert.ok(runtimeConfig.filesystem.allowRead.includes(interpreter)); + assert.ok(runtimeConfig.filesystem.allowRead.includes(interpreterBin)); + assert.equal(runtimeConfig.filesystem.allowRead.includes(interpreter), false); assert.ok(runtimeConfig.filesystem.allowRead.includes(await realpath(process.execPath))); for (const broadRoot of ["/usr", "/usr/local", fakeHome, fixture]) { assert.equal(runtimeConfig.filesystem.allowRead.includes(broadRoot), false); @@ -569,6 +574,43 @@ test("runner exposes an env shebang interpreter and its bounded runtime", async } }); +test("runner rejects executable symlinks whose directory overlaps protected credentials", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-credential-command-")); + const workspace = path.join(fixture, "workspace"); + const credentialDirectory = path.join(workspace, ".ssh"); + const executable = path.join(credentialDirectory, "run"); + const credentialAlias = path.join(workspace, "tools"); + await mkdir(credentialDirectory, { recursive: true }); + await writeFile(path.join(credentialDirectory, "id_test"), "private-key", "utf8"); + await symlink(process.execPath, executable); + await symlink(credentialDirectory, credentialAlias); + let spawned = false; + try { + await assert.rejects(runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: [path.join(credentialAlias, "run"), "-e", "process.exit(0)"], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: "/usr/bin:/bin" }, + helperPaths: { bwrap: "/usr/bin/bwrap", rg: "/usr/bin/rg", socat: "/usr/bin/socat" }, + platform: "linux", + spawn: () => { + spawned = true; + return fakeSpawn(0)(); + }, + }), /unsafe executable symlink directory/); + assert.equal(spawned, false); + assert.equal(await readFile(path.join(credentialDirectory, "id_test"), "utf8"), "private-key"); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + test("runner discovers Git roots from nested directories and validates linked worktrees", async () => { const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-git-root-")); const repository = path.join(fixture, "repository"); From f45f7cfc3d209f58ff9e80b5ff580fa3bce283f8 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Mon, 17 Aug 2026 00:20:19 -0500 Subject: [PATCH 4/8] Complete portable script execution under native macOS containment Add the missing Seatbelt interpreter permission through an exact-version, fail-closed compatibility shim so shell and env shebang commands work without weakening filesystem visibility. Align the Linux credential-directory test with its disposable tmpfs behavior and document when the temporary upstream compatibility layer can be removed. --- bin/sandbox/runtime.mjs | 33 ++++++++++++++++++++ docs/sandbox-compatibility.md | 2 ++ tests/sandbox-runtime.integration.test.mjs | 2 +- tests/sandbox-runtime.test.mjs | 35 ++++++++++++++++++++-- 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index 0f22392..88254b2 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -21,6 +21,13 @@ export const SANDBOX_RUNTIME_PACKAGE = "@anthropic-ai/sandbox-runtime"; export const SANDBOX_RUNTIME_VERSION = "0.0.73"; export const SANDBOX_EXECUTION_LEVEL = "shell-contained"; +const MACOS_PROCESS_RULES = "(allow process-exec)\n(allow process-fork)"; +const MACOS_INTERPRETER_PROCESS_RULES = [ + "(allow process-exec)", + "(allow process-exec-interpreter)", + "(allow process-fork)", +].join("\n"); + const SUPPORTED_PLATFORMS = new Set(["linux", "darwin"]); const READ_ONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); const PROTECTED_ENVIRONMENT = new Set([ @@ -95,6 +102,31 @@ export function commandToShellString(command) { return command.map(quotePosixArgument).join(" "); } +export function enableMacOSInterpreterExecution(descriptor, platform) { + if (platform !== "darwin") return descriptor; + if ( + !descriptor + || !Array.isArray(descriptor.argv) + || descriptor.argv.length !== 3 + || descriptor.argv[1] !== "-c" + || typeof descriptor.argv[2] !== "string" + ) { + throw new Error("Pinned macOS sandbox runtime returned an unexpected command descriptor."); + } + const occurrences = descriptor.argv[2].split(MACOS_PROCESS_RULES).length - 1; + if (occurrences !== 1) { + throw new Error("Pinned macOS sandbox runtime process rules no longer match the verified profile."); + } + return { + ...descriptor, + argv: [ + descriptor.argv[0], + descriptor.argv[1], + descriptor.argv[2].replace(MACOS_PROCESS_RULES, MACOS_INTERPRETER_PROCESS_RULES), + ], + }; +} + export function buildChildEnvironment({ sourceEnvironment, allowedEnvironment, workspace, runRoot }) { const childEnvironment = { HOME: path.join(runRoot, "home"), @@ -1263,6 +1295,7 @@ async function runSandboxedCommandOnce(options, context = {}) { executionCwd, { commandId: randomUUID(), commandText: options.command[0] }, ); + descriptor = enableMacOSInterpreterExecution(descriptor, platform); } finally { if (previousTemp === undefined) delete process.env.CLAUDE_CODE_TMPDIR; else process.env.CLAUDE_CODE_TMPDIR = previousTemp; diff --git a/docs/sandbox-compatibility.md b/docs/sandbox-compatibility.md index fa34ed9..112bac3 100644 --- a/docs/sandbox-compatibility.md +++ b/docs/sandbox-compatibility.md @@ -83,6 +83,8 @@ Host filesystem reads are denied by default. The runner exposes the workspace, i Selecting a command grants read access to that executable. If it belongs to a package or Python virtual environment identified by a nearby `package.json` or `pyvenv.cfg`, the bounded package root is also readable so resource-bearing CLIs can start. The runner also resolves bounded shebang dependencies, including `#!/usr/bin/env node` and `env -S`, without exposing a whole version-manager or system prefix. Commands selected from `~/.local/bin` can read `~/.local/lib` for user-level Python packages, but not user configuration, cache, or credential directories. Installing project-specific tools inside the workspace remains the most predictable option. +The pinned native runtime omits macOS Seatbelt's separate `process-exec-interpreter` permission even though it permits native executable files. The adapter adds exactly that narrow operation to the generated macOS profile after verifying the pinned descriptor shape. It fails closed if the upstream profile changes. Filesystem read rules still decide which scripts and interpreters are visible, and the compatibility shim should be removed when a verified upstream release includes the permission directly. + When the command starts inside a Git repository, the runner treats the containing worktree root as the workspace while preserving the original working directory. Existing credential-shaped files are denied recursively, and exact credential paths in both the repository root and original working directory stay protected even when absent at startup. The runner also exposes validated linked-worktree and submodule metadata, so ordinary inspection commands work from nested directories, linked worktrees, and standard submodules. The repository's `.git/config` remains readable while writes to it and hooks remain denied. Do not store credentials in Git remote URLs or custom repository configuration. Use an explicitly granted environment variable for network credentials instead. The runner is intentionally lightweight and on demand. It uses native Seatbelt or Bubblewrap primitives for one command tree, creates no persistent container or daemon, and removes its private directory afterward. Because the pinned upstream manager has process-global state, a second command in the same Node.js process is rejected while one is active. Independent CLI processes have separate managers. diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs index 8705685..fcef373 100644 --- a/tests/sandbox-runtime.integration.test.mjs +++ b/tests/sandbox-runtime.integration.test.mjs @@ -209,7 +209,7 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou "require('fs').writeFileSync('../sibling/.npmrc','changed')", ]), 0); assert.equal(await readFile(path.join(credentialSibling, ".npmrc"), "utf8"), "sibling-token"); - assert.notEqual(await run(DEVELOP, nestedWorkspace, [ + assert.equal(await run(DEVELOP, nestedWorkspace, [ process.execPath, "-e", "require('fs').writeFileSync('../sibling/.ssh/id_test','changed')", diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index ac740cf..73ef917 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -20,6 +20,7 @@ import { buildChildEnvironment, commandToShellString, compileSandboxExecution, + enableMacOSInterpreterExecution, assertNoExternalHardlinks, existingSystemReadRoots, probeSandboxRuntime, @@ -312,6 +313,34 @@ function fakeSpawn(exitCode, onSpawn) { }; } +function fakeMacSandboxDescriptor() { + return { + argv: [ + "/bin/sh", + "-c", + "sandbox-exec -p '(allow process-exec)\n(allow process-fork)' /bin/sh -c true", + ], + env: {}, + }; +} + +test("macOS descriptor shim enables shebang interpreters and fails closed on upstream drift", () => { + const original = fakeMacSandboxDescriptor(); + const patched = enableMacOSInterpreterExecution(original, "darwin"); + assert.notEqual(patched, original); + assert.match(patched.argv[2], /\(allow process-exec-interpreter\)/); + assert.doesNotMatch(original.argv[2], /process-exec-interpreter/); + assert.equal(enableMacOSInterpreterExecution(original, "linux"), original); + assert.throws( + () => enableMacOSInterpreterExecution({ argv: ["/bin/sh", "-c", "changed"] }, "darwin"), + /process rules no longer match/, + ); + assert.throws( + () => enableMacOSInterpreterExecution({ argv: ["unexpected"] }, "darwin"), + /unexpected command descriptor/, + ); +}); + test("runner initializes before spawn, uses shell false, propagates exit codes, and resets once", async () => { let initialized; let resetCount = 0; @@ -385,7 +414,7 @@ test("runner canonicalizes a symlinked temporary root before compiling private p const manager = { isSupportedPlatform: () => true, initialize: async () => {}, - wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + wrapWithSandboxArgv: async () => fakeMacSandboxDescriptor(), reset: async () => {}, }; @@ -541,7 +570,7 @@ test("runner exposes an env shebang interpreter and its bounded runtime", async const manager = { isSupportedPlatform: () => true, initialize: async (config) => { runtimeConfig = config; }, - wrapWithSandboxArgv: async () => ({ argv: ["/fake/sandbox"], env: {} }), + wrapWithSandboxArgv: async () => fakeMacSandboxDescriptor(), reset: async () => {}, }; try { @@ -698,7 +727,7 @@ test("runner discovers Git roots from nested directories and validates linked wo initialize: async (config) => { runtimeConfig = config; }, wrapWithSandboxArgv: async (_command, _shell, _a, _b, cwd) => { wrappedCwd = cwd; - return { argv: ["/fake/sandbox"], env: {} }; + return fakeMacSandboxDescriptor(); }, reset: async () => {}, }; From f6677eec96ac641769942d5a30f14b231fd4d3d3 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Mon, 17 Aug 2026 00:33:11 -0500 Subject: [PATCH 5/8] Report native sandbox violations and verify disposable temporary mounts Enable correlated macOS Seatbelt diagnostics for failed commands so runtime denials identify the exact blocked operation while preserving exit codes and cleanup. Update the Linux shared temporary-path integration assertion to verify its isolated tmpfs behavior and confirm that no host file is created. --- bin/sandbox/runtime.mjs | 12 +++++- tests/sandbox-runtime.integration.test.mjs | 7 +++- tests/sandbox-runtime.test.mjs | 49 ++++++++++++++++++++++ 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index 88254b2..f5b80a2 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -1278,13 +1278,14 @@ async function runSandboxedCommandOnce(options, context = {}) { const runtimeSignalSource = context.runtimeSignalSource || process; const cleanupListenerSnapshot = snapshotRuntimeCleanupListeners(runtimeSignalSource); try { - await manager.initialize(runtimeConfig); + await manager.initialize(runtimeConfig, undefined, platform === "darwin"); } finally { removeAddedRuntimeCleanupListeners(runtimeSignalSource, cleanupListenerSnapshot); } const previousTemp = process.env.CLAUDE_CODE_TMPDIR; process.env.CLAUDE_CODE_TMPDIR = path.join(runRoot, "tmp"); + const commandId = randomUUID(); let descriptor; try { descriptor = await manager.wrapWithSandboxArgv( @@ -1293,7 +1294,7 @@ async function runSandboxedCommandOnce(options, context = {}) { undefined, undefined, executionCwd, - { commandId: randomUUID(), commandText: options.command[0] }, + { commandId, commandText: options.command[0] }, ); descriptor = enableMacOSInterpreterExecution(descriptor, platform); } finally { @@ -1312,6 +1313,13 @@ async function runSandboxedCommandOnce(options, context = {}) { killProcess: context.killProcess, signalGraceMs: context.signalGraceMs, }); + if (platform === "darwin" && childResult.code !== 0 && manager.getSandboxViolationStore) { + await new Promise((resolve) => setTimeout(resolve, 200)); + const violations = manager.getSandboxViolationStore().getViolationsForCommand(commandId); + for (const violation of violations) { + context.writeError?.(`Sandbox violation: ${violation.line}\n`); + } + } } catch (error) { operationError = error; } diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs index fcef373..9cf5096 100644 --- a/tests/sandbox-runtime.integration.test.mjs +++ b/tests/sandbox-runtime.integration.test.mjs @@ -61,6 +61,7 @@ async function run(profileValue, workspace, command, overrides = {}) { ...contextEnvironment, OPP_INTEGRATION_SECRET: "must-not-leak", }, + writeError: process.platform === "darwin" ? (message) => process.stderr.write(message) : undefined, }); } @@ -323,11 +324,13 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou assert.equal(networkDenied, 7); const sharedTemporaryProbe = `/tmp/claude/opp-${process.pid}-probe`; - assert.notEqual(await run(OBSERVE, workspace, [ + const sharedTemporaryExit = await run(OBSERVE, workspace, [ process.execPath, "-e", `require('fs').mkdirSync('/tmp/claude',{recursive:true});require('fs').writeFileSync(${JSON.stringify(sharedTemporaryProbe)},'bad')`, - ]), 0); + ]); + if (process.platform === "linux") assert.equal(sharedTemporaryExit, 0); + else assert.notEqual(sharedTemporaryExit, 0); await assert.rejects(stat(sharedTemporaryProbe), /ENOENT/); let requests = []; diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index 73ef917..3a8c2a5 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -402,6 +402,55 @@ test("runner initializes before spawn, uses shell false, propagates exit codes, assert.doesNotMatch(diagnostics, /GH_TOKEN|secret|literal/); }); +test("macOS runner enables correlated violation diagnostics for failed commands", async () => { + const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-macos-diagnostic-")); + const workspace = path.join(fixture, "workspace"); + await mkdir(workspace); + let monitorEnabled; + let commandId; + let diagnostics = ""; + const manager = { + isSupportedPlatform: () => true, + initialize: async (_config, _callback, enabled) => { monitorEnabled = enabled; }, + wrapWithSandboxArgv: async (_command, _shell, _a, _b, _cwd, options) => { + commandId = options.commandId; + return fakeMacSandboxDescriptor(); + }, + getSandboxViolationStore: () => ({ + getViolationsForCommand: (id) => id === commandId + ? [{ line: "deny process-exec-interpreter /bin/sh" }] + : [], + }), + reset: async () => {}, + }; + try { + assert.equal(await runSandboxedCommand({ + profile: profile("observe"), + allowedDomains: [], + allowedEnvironment: [], + confirmExternalSideEffects: false, + command: ["true"], + }, { + cwd: workspace, + home: os.homedir(), + temporaryRoot: fixture, + env: { PATH: "/usr/bin:/bin" }, + platform: "darwin", + loadRuntime: async () => ({ + SandboxManager: manager, + SandboxRuntimeConfigSchema: { parse: (config) => config }, + }), + spawn: fakeSpawn(126), + writeError: (message) => { diagnostics += message; }, + }), 126); + assert.equal(monitorEnabled, true); + assert.match(commandId, /^[0-9a-f-]{36}$/); + assert.match(diagnostics, /Sandbox violation: deny process-exec-interpreter \/bin\/sh/); + } finally { + await rm(fixture, { recursive: true, force: true }); + } +}); + test("runner canonicalizes a symlinked temporary root before compiling private paths", async () => { const fixture = await mkdtemp(path.join(os.tmpdir(), "opp-canonical-temp-")); const actualTemporaryRoot = path.join(fixture, "actual-temp"); From 932bd0314dca90cb7c05d7ae597ff93785c3d6b9 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Mon, 17 Aug 2026 00:48:28 -0500 Subject: [PATCH 6/8] Make native sandbox checks work across macOS temporary paths and Linux filtered network proxies Add a narrow Seatbelt metadata grant for the /var symlink and force the loopback integration fixture through the runtime proxy. --- bin/sandbox/runtime.mjs | 24 ++++++++++---- docs/sandbox-compatibility.md | 2 +- tests/sandbox-runtime.integration.test.mjs | 12 +++++++ tests/sandbox-runtime.test.mjs | 37 +++++++++++++++++----- 4 files changed, 60 insertions(+), 15 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index f5b80a2..f22f115 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -27,6 +27,15 @@ const MACOS_INTERPRETER_PROCESS_RULES = [ "(allow process-exec-interpreter)", "(allow process-fork)", ].join("\n"); +const MACOS_DIRECTORY_METADATA_RULE = [ + "(allow file-read-metadata", + " (vnode-type DIRECTORY))", +].join("\n"); +const MACOS_TEMP_SYMLINK_METADATA_RULE = [ + MACOS_DIRECTORY_METADATA_RULE, + "(allow file-read-metadata", + " (literal \"/var\"))", +].join("\n"); const SUPPORTED_PLATFORMS = new Set(["linux", "darwin"]); const READ_ONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); @@ -102,7 +111,7 @@ export function commandToShellString(command) { return command.map(quotePosixArgument).join(" "); } -export function enableMacOSInterpreterExecution(descriptor, platform) { +export function applyMacOSCompatibilityProfile(descriptor, platform) { if (platform !== "darwin") return descriptor; if ( !descriptor @@ -113,16 +122,19 @@ export function enableMacOSInterpreterExecution(descriptor, platform) { ) { throw new Error("Pinned macOS sandbox runtime returned an unexpected command descriptor."); } - const occurrences = descriptor.argv[2].split(MACOS_PROCESS_RULES).length - 1; - if (occurrences !== 1) { - throw new Error("Pinned macOS sandbox runtime process rules no longer match the verified profile."); + const profile = descriptor.argv[2]; + const anchors = [MACOS_PROCESS_RULES, MACOS_DIRECTORY_METADATA_RULE]; + if (anchors.some((anchor) => profile.split(anchor).length - 1 !== 1)) { + throw new Error("Pinned macOS sandbox runtime rules no longer match the verified profile."); } return { ...descriptor, argv: [ descriptor.argv[0], descriptor.argv[1], - descriptor.argv[2].replace(MACOS_PROCESS_RULES, MACOS_INTERPRETER_PROCESS_RULES), + profile + .replace(MACOS_PROCESS_RULES, MACOS_INTERPRETER_PROCESS_RULES) + .replace(MACOS_DIRECTORY_METADATA_RULE, MACOS_TEMP_SYMLINK_METADATA_RULE), ], }; } @@ -1296,7 +1308,7 @@ async function runSandboxedCommandOnce(options, context = {}) { executionCwd, { commandId, commandText: options.command[0] }, ); - descriptor = enableMacOSInterpreterExecution(descriptor, platform); + descriptor = applyMacOSCompatibilityProfile(descriptor, platform); } finally { if (previousTemp === undefined) delete process.env.CLAUDE_CODE_TMPDIR; else process.env.CLAUDE_CODE_TMPDIR = previousTemp; diff --git a/docs/sandbox-compatibility.md b/docs/sandbox-compatibility.md index 112bac3..057831a 100644 --- a/docs/sandbox-compatibility.md +++ b/docs/sandbox-compatibility.md @@ -83,7 +83,7 @@ Host filesystem reads are denied by default. The runner exposes the workspace, i Selecting a command grants read access to that executable. If it belongs to a package or Python virtual environment identified by a nearby `package.json` or `pyvenv.cfg`, the bounded package root is also readable so resource-bearing CLIs can start. The runner also resolves bounded shebang dependencies, including `#!/usr/bin/env node` and `env -S`, without exposing a whole version-manager or system prefix. Commands selected from `~/.local/bin` can read `~/.local/lib` for user-level Python packages, but not user configuration, cache, or credential directories. Installing project-specific tools inside the workspace remains the most predictable option. -The pinned native runtime omits macOS Seatbelt's separate `process-exec-interpreter` permission even though it permits native executable files. The adapter adds exactly that narrow operation to the generated macOS profile after verifying the pinned descriptor shape. It fails closed if the upstream profile changes. Filesystem read rules still decide which scripts and interpreters are visible, and the compatibility shim should be removed when a verified upstream release includes the permission directly. +The pinned native runtime needs two narrow macOS Seatbelt compatibility rules. It omits the separate `process-exec-interpreter` permission even though it permits native executable files, and its directory-only metadata rule cannot traverse the `/var` symlink used in temporary command paths. The adapter adds the interpreter operation and metadata access to the literal `/var` symlink after verifying the pinned descriptor shape. It does not expose the `/var` subtree and fails closed if the upstream profile changes. Filesystem read rules still decide which scripts, interpreters, and canonical temporary paths are visible. The compatibility shim should be reduced or removed when a verified upstream release covers these cases directly. When the command starts inside a Git repository, the runner treats the containing worktree root as the workspace while preserving the original working directory. Existing credential-shaped files are denied recursively, and exact credential paths in both the repository root and original working directory stay protected even when absent at startup. The runner also exposes validated linked-worktree and submodule metadata, so ordinary inspection commands work from nested directories, linked worktrees, and standard submodules. The repository's `.git/config` remains readable while writes to it and hooks remain denied. Do not store credentials in Git remote URLs or custom repository configuration. Use an explicitly granted environment variable for network credentials instead. diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs index 9cf5096..b3c1e93 100644 --- a/tests/sandbox-runtime.integration.test.mjs +++ b/tests/sandbox-runtime.integration.test.mjs @@ -346,13 +346,25 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou assert.ok(address && typeof address !== "string"); const destination = `127.0.0.1:${address.port}`; try { + // The upstream proxy excludes loopback by default. Remove that client-side + // bypass so this host-side fixture exercises the filtered proxy path. assert.equal(await run(NETWORK_READ, workspace, [ + "env", + "-u", + "NO_PROXY", + "-u", + "no_proxy", "curl", "--fail", "--silent", `http://${destination}/read`, ], { allowedDomains: [destination] }), 0); assert.notEqual(await run(NETWORK_READ, workspace, [ + "env", + "-u", + "NO_PROXY", + "-u", + "no_proxy", "curl", "--fail", "--silent", diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index 3a8c2a5..d91a6cb 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -20,7 +20,7 @@ import { buildChildEnvironment, commandToShellString, compileSandboxExecution, - enableMacOSInterpreterExecution, + applyMacOSCompatibilityProfile, assertNoExternalHardlinks, existingSystemReadRoots, probeSandboxRuntime, @@ -318,25 +318,46 @@ function fakeMacSandboxDescriptor() { argv: [ "/bin/sh", "-c", - "sandbox-exec -p '(allow process-exec)\n(allow process-fork)' /bin/sh -c true", + "sandbox-exec -p '(allow file-read-metadata\n (vnode-type DIRECTORY))\n(allow process-exec)\n(allow process-fork)' /bin/sh -c true", ], env: {}, }; } -test("macOS descriptor shim enables shebang interpreters and fails closed on upstream drift", () => { +test("macOS descriptor shim enables scripts and raw temp paths, then fails closed on drift", () => { const original = fakeMacSandboxDescriptor(); - const patched = enableMacOSInterpreterExecution(original, "darwin"); + const patched = applyMacOSCompatibilityProfile(original, "darwin"); assert.notEqual(patched, original); assert.match(patched.argv[2], /\(allow process-exec-interpreter\)/); + assert.match( + patched.argv[2], + /\(vnode-type DIRECTORY\)\)\n\(allow file-read-metadata\n \(literal "\/var"\)\)/, + ); + assert.doesNotMatch(patched.argv[2], /\(subpath "\/var"\)/); assert.doesNotMatch(original.argv[2], /process-exec-interpreter/); - assert.equal(enableMacOSInterpreterExecution(original, "linux"), original); + assert.equal(applyMacOSCompatibilityProfile(original, "linux"), original); assert.throws( - () => enableMacOSInterpreterExecution({ argv: ["/bin/sh", "-c", "changed"] }, "darwin"), - /process rules no longer match/, + () => applyMacOSCompatibilityProfile({ + argv: [ + "/bin/sh", + "-c", + "(allow file-read-metadata\n (vnode-type DIRECTORY))\nchanged", + ], + }, "darwin"), + /rules no longer match/, ); assert.throws( - () => enableMacOSInterpreterExecution({ argv: ["unexpected"] }, "darwin"), + () => applyMacOSCompatibilityProfile({ + argv: [ + "/bin/sh", + "-c", + "(allow process-exec)\n(allow process-fork)", + ], + }, "darwin"), + /rules no longer match/, + ); + assert.throws( + () => applyMacOSCompatibilityProfile({ argv: ["unexpected"] }, "darwin"), /unexpected command descriptor/, ); }); From 4a1cdf22a4f8284ca9402ef13b5e207b663bbcc2 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Mon, 17 Aug 2026 01:05:31 -0500 Subject: [PATCH 7/8] Keep sandbox runtime resources private while preserving portable Git inspection Create upstream proxy sockets, generated certificates, and temporary files inside each command's disposable root, and disable mutable host system Git configuration without broadening filesystem access. --- bin/sandbox/runtime.mjs | 49 +++++++++++++++++++++++----------- docs/sandbox-compatibility.md | 4 +-- tests/sandbox-runtime.test.mjs | 26 +++++++++++++++++- 3 files changed, 61 insertions(+), 18 deletions(-) diff --git a/bin/sandbox/runtime.mjs b/bin/sandbox/runtime.mjs index f22f115..ac2066b 100644 --- a/bin/sandbox/runtime.mjs +++ b/bin/sandbox/runtime.mjs @@ -42,6 +42,7 @@ const READ_ONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); const PROTECTED_ENVIRONMENT = new Set([ "BASH_ENV", "ENV", + "GIT_CONFIG_NOSYSTEM", "HOME", "NODE_OPTIONS", "PATH", @@ -94,7 +95,10 @@ function assertEnvironmentName(name) { if (!isEnvironmentName(name)) { throw new Error(`Invalid environment variable name: ${name}`); } - if (PROTECTED_ENVIRONMENT.has(name) || /^(?:DYLD_|LD_)/.test(name)) { + if ( + PROTECTED_ENVIRONMENT.has(name) + || /^(?:DYLD_|GIT_CONFIG_|LD_)/.test(name) + ) { throw new Error(`Sandbox control variable cannot be granted: ${name}`); } } @@ -141,6 +145,7 @@ export function applyMacOSCompatibilityProfile(descriptor, platform) { export function buildChildEnvironment({ sourceEnvironment, allowedEnvironment, workspace, runRoot }) { const childEnvironment = { + GIT_CONFIG_NOSYSTEM: "1", HOME: path.join(runRoot, "home"), PATH: unique( (sourceEnvironment.PATH || "") @@ -1056,6 +1061,19 @@ function signalExitCode(signal) { return Number.isInteger(number) ? 128 + number : 1; } +async function withProcessEnvironment(overrides, operation) { + const previous = new Map(Object.keys(overrides).map((name) => [name, process.env[name]])); + for (const [name, value] of Object.entries(overrides)) process.env[name] = value; + try { + return await operation(); + } finally { + for (const [name, value] of previous) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + } +} + const RUNTIME_CLEANUP_EVENTS = ["exit", "SIGINT", "SIGTERM"]; function snapshotRuntimeCleanupListeners(source) { @@ -1288,18 +1306,22 @@ async function runSandboxedCommandOnce(options, context = {}) { if (!manager.isSupportedPlatform()) throw new Error("Sandbox runtime does not support this host."); const runtimeConfig = runtime.SandboxRuntimeConfigSchema.parse(compiled.runtimeConfig); const runtimeSignalSource = context.runtimeSignalSource || process; - const cleanupListenerSnapshot = snapshotRuntimeCleanupListeners(runtimeSignalSource); - try { - await manager.initialize(runtimeConfig, undefined, platform === "darwin"); - } finally { - removeAddedRuntimeCleanupListeners(runtimeSignalSource, cleanupListenerSnapshot); - } - - const previousTemp = process.env.CLAUDE_CODE_TMPDIR; - process.env.CLAUDE_CODE_TMPDIR = path.join(runRoot, "tmp"); + const privateTemporaryDirectory = path.join(runRoot, "tmp"); const commandId = randomUUID(); let descriptor; - try { + await withProcessEnvironment({ + CLAUDE_CODE_TMPDIR: privateTemporaryDirectory, + TEMP: privateTemporaryDirectory, + TMP: privateTemporaryDirectory, + TMPDIR: privateTemporaryDirectory, + }, async () => { + const cleanupListenerSnapshot = snapshotRuntimeCleanupListeners(runtimeSignalSource); + try { + await manager.initialize(runtimeConfig, undefined, platform === "darwin"); + } finally { + removeAddedRuntimeCleanupListeners(runtimeSignalSource, cleanupListenerSnapshot); + } + descriptor = await manager.wrapWithSandboxArgv( commandToShellString(options.command), "/bin/sh", @@ -1309,10 +1331,7 @@ async function runSandboxedCommandOnce(options, context = {}) { { commandId, commandText: options.command[0] }, ); descriptor = applyMacOSCompatibilityProfile(descriptor, platform); - } finally { - if (previousTemp === undefined) delete process.env.CLAUDE_CODE_TMPDIR; - else process.env.CLAUDE_CODE_TMPDIR = previousTemp; - } + }); childResult = await spawnResult(context.spawn || nodeSpawn, descriptor.argv, { cwd: executionCwd, diff --git a/docs/sandbox-compatibility.md b/docs/sandbox-compatibility.md index 057831a..06a558e 100644 --- a/docs/sandbox-compatibility.md +++ b/docs/sandbox-compatibility.md @@ -85,9 +85,9 @@ Selecting a command grants read access to that executable. If it belongs to a pa The pinned native runtime needs two narrow macOS Seatbelt compatibility rules. It omits the separate `process-exec-interpreter` permission even though it permits native executable files, and its directory-only metadata rule cannot traverse the `/var` symlink used in temporary command paths. The adapter adds the interpreter operation and metadata access to the literal `/var` symlink after verifying the pinned descriptor shape. It does not expose the `/var` subtree and fails closed if the upstream profile changes. Filesystem read rules still decide which scripts, interpreters, and canonical temporary paths are visible. The compatibility shim should be reduced or removed when a verified upstream release covers these cases directly. -When the command starts inside a Git repository, the runner treats the containing worktree root as the workspace while preserving the original working directory. Existing credential-shaped files are denied recursively, and exact credential paths in both the repository root and original working directory stay protected even when absent at startup. The runner also exposes validated linked-worktree and submodule metadata, so ordinary inspection commands work from nested directories, linked worktrees, and standard submodules. The repository's `.git/config` remains readable while writes to it and hooks remain denied. Do not store credentials in Git remote URLs or custom repository configuration. Use an explicitly granted environment variable for network credentials instead. +When the command starts inside a Git repository, the runner treats the containing worktree root as the workspace while preserving the original working directory. Existing credential-shaped files are denied recursively, and exact credential paths in both the repository root and original working directory stay protected even when absent at startup. The runner also exposes validated linked-worktree and submodule metadata, so ordinary inspection commands work from nested directories, linked worktrees, and standard submodules. The repository's `.git/config` remains readable while writes to it and hooks remain denied. Host system Git configuration is disabled so a package-manager Git installation cannot pull mutable configuration into the sandbox. Do not store credentials in Git remote URLs or custom repository configuration. Use an explicitly granted environment variable for network credentials instead. -The runner is intentionally lightweight and on demand. It uses native Seatbelt or Bubblewrap primitives for one command tree, creates no persistent container or daemon, and removes its private directory afterward. Because the pinned upstream manager has process-global state, a second command in the same Node.js process is rejected while one is active. Independent CLI processes have separate managers. +The runner is intentionally lightweight and on demand. It uses native Seatbelt or Bubblewrap primitives for one command tree, creates no persistent container or daemon, and removes its private directory afterward. The adapter also directs the upstream proxy sockets, generated certificates, and temporary files into that private directory so root-level read denial does not expose or hide shared temporary resources. Because the pinned upstream manager has process-global state, a second command in the same Node.js process is rejected while one is active. Independent CLI processes have separate managers. On Linux, `bubblewrap`, `socat`, and `rg` must resolve to root-owned executables whose parent path is not group- or world-writable. This prevents a repository or shared temporary directory from replacing the containment helpers through `PATH`. diff --git a/tests/sandbox-runtime.test.mjs b/tests/sandbox-runtime.test.mjs index d91a6cb..c09e72d 100644 --- a/tests/sandbox-runtime.test.mjs +++ b/tests/sandbox-runtime.test.mjs @@ -77,6 +77,7 @@ test("observe compiles to read-only workspace, private temporary writes, and a s assert.equal(result.runtimeConfig.allowAppleEvents, false); assert.equal(result.childEnvironment.GH_TOKEN, undefined); assert.equal(result.childEnvironment.SSH_AUTH_SOCK, undefined); + assert.equal(result.childEnvironment.GIT_CONFIG_NOSYSTEM, "1"); assert.equal(result.childEnvironment.HOME, "/tmp/opp-sandbox-unit/home"); assert.equal(result.childEnvironment.TMPDIR, "/tmp/opp-sandbox-unit/tmp"); assert.ok( @@ -173,6 +174,10 @@ test("network-read blocks raw protocols and mutation-oriented HTTP methods", asy test("capability grants and publish confirmation fail closed", () => { assert.throws(() => compile({ allowedDomains: ["example.com"] }), /does not permit network/); assert.throws(() => compile({ allowedEnvironment: ["GH_TOKEN"] }), /does not permit credential/); + assert.throws(() => compile({ + profile: profile("network-read", { network: "explicit", credentials: "explicit" }), + allowedEnvironment: ["GIT_CONFIG_SYSTEM"], + }), /Sandbox control variable cannot be granted/); assert.throws( () => compile({ confirmExternalSideEffects: true }), /does not permit external side-effect confirmation/, @@ -364,14 +369,27 @@ test("macOS descriptor shim enables scripts and raw temp paths, then fails close test("runner initializes before spawn, uses shell false, propagates exit codes, and resets once", async () => { let initialized; + let initializationTemporaryEnvironment; let resetCount = 0; let spawnOptions; + let wrappingTemporaryEnvironment; let wrappedCommand; + const temporaryNames = ["CLAUDE_CODE_TMPDIR", "TEMP", "TMP", "TMPDIR"]; + const originalTemporaryEnvironment = Object.fromEntries( + temporaryNames.map((name) => [name, process.env[name]]), + ); + const captureTemporaryEnvironment = () => Object.fromEntries( + temporaryNames.map((name) => [name, process.env[name]]), + ); const manager = { isSupportedPlatform: () => true, - initialize: async (config) => { initialized = config; }, + initialize: async (config) => { + initialized = config; + initializationTemporaryEnvironment = captureTemporaryEnvironment(); + }, wrapWithSandboxArgv: async (command) => { wrappedCommand = command; + wrappingTemporaryEnvironment = captureTemporaryEnvironment(); return { argv: ["/fake/sandbox", "wrapped"], env: { SHOULD_NOT_LEAK: "yes" } }; }, reset: async () => { resetCount += 1; }, @@ -407,6 +425,12 @@ test("runner initializes before spawn, uses shell false, propagates exit codes, assert.equal(spawnOptions.env.GH_TOKEN, undefined); assert.equal(spawnOptions.env["JAVA_HOME_17.0.16_x64"], undefined); assert.equal(spawnOptions.env.SHOULD_NOT_LEAK, undefined); + assert.equal(spawnOptions.env.GIT_CONFIG_NOSYSTEM, "1"); + assert.deepEqual(initializationTemporaryEnvironment, wrappingTemporaryEnvironment); + assert.ok(Object.values(initializationTemporaryEnvironment).every( + (value) => value.endsWith(`${path.sep}tmp`) && value.includes("opp-sandbox-"), + )); + assert.deepEqual(captureTemporaryEnvironment(), originalTemporaryEnvironment); assert.equal(initialized.enableWeakerNestedSandbox, false); assert.ok(initialized.seccomp.applyPath.endsWith(path.join( "vendor", From 11d55d11aa524a81bb3d78621a285ecd1dcbe7c9 Mon Sep 17 00:00:00 2001 From: Wayner Barrios Date: Mon, 17 Aug 2026 01:23:43 -0500 Subject: [PATCH 8/8] Verify credential write isolation according to each native sandbox backend Accept Bubblewrap's disposable shadow write and Seatbelt's direct rejection while requiring both platforms to preserve the protected host key. --- tests/sandbox-runtime.integration.test.mjs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/sandbox-runtime.integration.test.mjs b/tests/sandbox-runtime.integration.test.mjs index b3c1e93..2b6b7eb 100644 --- a/tests/sandbox-runtime.integration.test.mjs +++ b/tests/sandbox-runtime.integration.test.mjs @@ -210,11 +210,15 @@ test("real runtime enforces filesystem, environment, network, argv, and exit bou "require('fs').writeFileSync('../sibling/.npmrc','changed')", ]), 0); assert.equal(await readFile(path.join(credentialSibling, ".npmrc"), "utf8"), "sibling-token"); - assert.equal(await run(DEVELOP, nestedWorkspace, [ + const siblingSshWriteExit = await run(DEVELOP, nestedWorkspace, [ process.execPath, "-e", "require('fs').writeFileSync('../sibling/.ssh/id_test','changed')", - ]), 0); + ]); + // Bubblewrap shadows denied directories with disposable mounts, while + // Seatbelt rejects the write directly. Neither backend may alter the host. + if (process.platform === "linux") assert.equal(siblingSshWriteExit, 0); + else assert.notEqual(siblingSshWriteExit, 0); assert.equal( await readFile(path.join(credentialSibling, ".ssh", "id_test"), "utf8"), "sibling-key",