From 99cfa8231b0ccac7efa46031b4c37f86ce4526cf Mon Sep 17 00:00:00 2001 From: Alexander Matveev Date: Wed, 11 Nov 2026 22:56:58 -0500 Subject: [PATCH] feat(core): add opt-in OS-level shell sandbox Wrap shell tool commands with bubblewrap on Linux and sandbox-exec on macOS. The sandbox supports read-only and workspace-write modes, denies the network by default, and fails closed when the backend is unavailable. A `sandbox: false` call requires the separate `shell_unsandboxed` permission, which defaults to ask, so approving a command never approves leaving the sandbox. Sandbox settings are pinned per workspace on first use. Amalgamator was used for AI assistance (https://github.com/amalgamator-ai/amalgamator) Signed-off-by: Alexander Matveev --- .../client/src/promise/generated/types.ts | 11 + packages/core/src/config/normalize.ts | 28 + packages/core/src/sandbox.ts | 247 +++++++ packages/core/src/shell.ts | 30 +- packages/core/src/tool/plugin/shell.ts | 22 +- packages/core/test/agent.test.ts | 25 + .../core/test/config/normalization.test.ts | 43 ++ packages/core/test/fixture/shell-daemon.ts | 8 +- packages/core/test/sandbox.test.ts | 688 ++++++++++++++++++ packages/core/test/shell-daemon.test.ts | 145 ++++ .../core/test/shell-sandbox-spawner.test.ts | 128 ++++ packages/core/test/tool-shell.test.ts | 76 +- packages/protocol/openapi.json | 35 + packages/schema/src/agent.ts | 2 + packages/schema/src/config.ts | 4 + packages/schema/src/config/sandbox.ts | 34 + packages/schema/test/config.test.ts | 16 + services/site/src/docs/content/config.mdx | 65 ++ .../site/src/docs/content/permissions.mdx | 1 + 19 files changed, 1599 insertions(+), 9 deletions(-) create mode 100644 packages/core/src/sandbox.ts create mode 100644 packages/core/test/sandbox.test.ts create mode 100644 packages/core/test/shell-sandbox-spawner.test.ts create mode 100644 packages/schema/src/config/sandbox.ts diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index cac31d2b577c..bbe5c225694e 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -372,6 +372,10 @@ export type McpProtocol = "legacy" | "auto" | "2026-07-28" export type ConfigCompactionPercent = string +export type ConfigSandboxMode = "read-only" | "workspace-write" + +export type ConfigSandboxNetwork = "deny" | "allow" + export type ConfigWorktree = { directory: string } export type ConfigModelReasoning = @@ -2530,6 +2534,13 @@ export type ConfigEntry = } websearch?: false | { provider: "random" | WebSearchID } plugins?: Array + sandbox?: { + enabled?: boolean + mode?: ConfigSandboxMode + network?: ConfigSandboxNetwork + writable_roots?: Array + readable_roots?: Array + } worktree?: ConfigWorktree warming?: boolean | { prompt?: string; interval?: "auto" | (string & {}); duration?: string } providers?: { diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index 891e6418f669..97421477a6d5 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -16,6 +16,7 @@ import { ConfigPlugin } from "@opencode/schema/config/plugin" import { ConfigPolicy } from "@opencode/schema/config/policy" import { ConfigProvider } from "@opencode/schema/config/provider" import { ConfigReference } from "@opencode/schema/config/reference" +import { ConfigSandbox } from "@opencode/schema/config/sandbox" import { ConfigExperimental } from "@opencode/schema/config/experimental" import { Permission } from "@opencode/schema/permission" import { ConfigAgentV1 } from "../v1/config/agent.js" @@ -197,6 +198,7 @@ export function normalize(input: unknown): Result { normalizeWatcher(input, encoded, diagnostics) normalizeFormatter(input, encoded, diagnostics) normalizeLsp(input, encoded, diagnostics) + normalizeSandbox(input, encoded, diagnostics) const model = own(input, "model") ? decodeValue(ConfigModel.Selection, input.model, ["model"], diagnostics) @@ -231,6 +233,32 @@ export function normalize(input: unknown): Result { return { type: "normalized", encoded, diagnostics } } +// A malformed sandbox block must not switch the sandbox off: it is a security control, so unlike other settings it is +// never dropped. Invalid input resolves to an enabled sandbox, keeping the fields that are valid and taking the +// strictest value for the rest. +function normalizeSandbox(input: Record, encoded: Record, diagnostics: Diagnostic[]) { + if (!own(input, "sandbox")) return + const value = decodeEncoded(Info.fields.sandbox, input.sandbox, ["sandbox"], []) + if (value !== undefined) { + overlay(encoded, "sandbox", value, ["sandbox"], diagnostics) + return + } + invalid(["sandbox"], diagnostics) + const raw = isRecord(input.sandbox) ? input.sandbox : {} + const mode = decodeEncoded(ConfigSandbox.Mode, raw.mode, ["sandbox", "mode"], []) + const network = decodeEncoded(ConfigSandbox.Network, raw.network, ["sandbox", "network"], []) + // Roots only widen what the sandbox can reach, so each is kept when it decodes on its own. + const writable = decodeEncoded(ConfigSandbox.Roots, raw.writable_roots, ["sandbox", "writable_roots"], []) + const readable = decodeEncoded(ConfigSandbox.Roots, raw.readable_roots, ["sandbox", "readable_roots"], []) + encoded.sandbox = { + enabled: true, + mode: mode ?? "read-only", + network: network ?? "deny", + ...(writable === undefined ? {} : { writable_roots: writable }), + ...(readable === undefined ? {} : { readable_roots: readable }), + } +} + function normalizeSkills(input: Record, encoded: Record, diagnostics: Diagnostic[]) { if (!own(input, "skills")) return if (Array.isArray(input.skills)) { diff --git a/packages/core/src/sandbox.ts b/packages/core/src/sandbox.ts new file mode 100644 index 000000000000..bc8ab2f0950a --- /dev/null +++ b/packages/core/src/sandbox.ts @@ -0,0 +1,247 @@ +export * as Sandbox from "./sandbox.js" + +import { existsSync, lstatSync, realpathSync } from "fs" +import { tmpdir } from "os" +import path from "path" +import { Schema } from "effect" +import type { Entry } from "@opencode/schema/config" +import type { ConfigSandbox } from "@opencode/schema/config/sandbox" +import { which } from "./util/which.js" + +/** + * OS-level sandbox for agent shell commands. The command is wrapped, never reimplemented: bubblewrap on Linux and + * sandbox-exec (Seatbelt) on macOS confine the shell and everything it starts. Nothing here runs a process or + * touches the filesystem except to locate the backend and resolve symlinks, so the wrapping is plain data. + * + * Filesystem: everything is readable, and only the workspace (plus temporary directories) is writable, or nothing + * with `read-only`. Network: denied unless the policy allows it. An enabled sandbox never falls back to running + * the command unconfined. + */ + +export interface Policy { + readonly mode: ConfigSandbox.Mode + readonly network: ConfigSandbox.Network + /** Extra directories a `workspace-write` sandbox may write to. */ + readonly writableRoots?: readonly string[] + /** Extra directories mounted read-only. */ + readonly readableRoots?: readonly string[] +} + +export interface Command { + readonly program: string + readonly args: readonly string[] +} + +export class UnavailableError extends Schema.TaggedError()("Sandbox.UnavailableError", { + reason: Schema.String, +}) { + override get message() { + return `Sandbox is enabled but unavailable: ${this.reason}. The command was not run. Fix the sandbox, or set sandbox.enabled to false.` + } +} + +export interface WrapInput { + readonly policy: Policy + readonly command: Command + readonly cwd: string + /** The one directory a `workspace-write` sandbox may write to. */ + readonly workspace: string + /** Remote workspaces run commands elsewhere, where this host's sandbox does not apply. */ + readonly remote?: boolean + readonly platform?: NodeJS.Platform + /** Finds an executable. Defaults to a PATH lookup. */ + readonly find?: (name: string) => string | undefined +} + +/** + * The sandbox settings of every config layer, lowest priority first, merged field by field. A layer that sets only + * `network` cannot drop `enabled` from a lower layer, and the security settings are monotonic: once any layer + * enables the sandbox, selects `"read-only"`, or denies the network, a later layer cannot loosen it. Only roots are + * additive grants, because a project may legitimately need more writable directories. + */ +export function merge(entries: readonly Entry[]): ConfigSandbox.Info | undefined { + const layers = entries.flatMap((entry) => + entry.type === "document" && entry.info.sandbox ? [entry.info.sandbox] : [], + ) + if (layers.length === 0) return undefined + const pick = (key: K) => + layers.findLast((layer) => layer[key] !== undefined)?.[key] + const roots = (key: K) => { + const all = layers.flatMap((layer) => layer[key] ?? []) + return all.length === 0 ? undefined : [...new Set(all)] + } + const enabled = layers.some((layer) => layer.enabled === true) ? true : pick("enabled") + const mode = layers.some((layer) => layer.mode === "read-only") ? "read-only" : pick("mode") + const network = layers.some((layer) => layer.network === "deny") ? "deny" : pick("network") + return { + enabled, + mode, + network, + writable_roots: roots("writable_roots"), + readable_roots: roots("readable_roots"), + } as ConfigSandbox.Info +} + +// The policy a workspace runs under, fixed when it first asks for a command. Pinning it means a config file that a +// confined command creates or rewrites cannot change the policy of the running process: the sandbox settings of a +// workspace are read once, like a command-line flag, and changing them needs a restart. Without the pin, a +// workspace-write command could write an opencode.json that grants itself network access or extra roots on its next +// invocation. +const policies = new Map() + +/** + * The policy for a workspace, pinned on first use. `entries` is read only when the workspace has no policy yet. + */ +export function policy(entries: readonly Entry[], workspace: string): Policy | undefined { + const key = canonical(workspace) + if (!policies.has(key)) policies.set(key, resolve(merge(entries))) + return policies.get(key) +} + +/** Test helper: forget every pinned workspace policy. */ +export function resetPolicies() { + policies.clear() +} + +/** + * Workspace paths a sandboxed command can never write, even in `workspace-write`: the files that configure the + * sandbox. Otherwise a confined command could write `{"sandbox":{"enabled":false}}` and run unconfined next time. + */ +export const PROTECTED = ["opencode.json", "opencode.jsonc", ".opencode"] as const + +/** The policy to enforce, or undefined when the sandbox is not enabled. Unset `network` takes the strictest value (deny); an unset `mode` takes the schema default `workspace-write`, which is NOT the strictest mode (`read-only` is). */ +export function resolve(config: ConfigSandbox.Info | undefined): Policy | undefined { + if (config?.enabled !== true) return undefined + return { + mode: config.mode ?? "workspace-write", + network: config.network ?? "deny", + ...(config.writable_roots?.length ? { writableRoots: config.writable_roots } : {}), + ...(config.readable_roots?.length ? { readableRoots: config.readable_roots } : {}), + } +} + +export function wrap(input: WrapInput): Command | UnavailableError { + const platform = input.platform ?? process.platform + if (input.remote) + return new UnavailableError({ reason: "the sandbox cannot confine commands that run in a remote workspace" }) + if (platform !== "linux" && platform !== "darwin") + return new UnavailableError({ reason: `no sandbox backend exists for ${platform}` }) + const name = platform === "linux" ? "bwrap" : "sandbox-exec" + const program = (input.find ?? find)(name) + if (!program) + return new UnavailableError({ + reason: `${name} was not found${platform === "linux" ? " (install bubblewrap)" : ""}`, + }) + const workspace = canonical(input.workspace) + const args = platform === "linux" ? bwrapArgs(input, workspace) : seatbeltArgs(input, workspace) + return { program, args: [...args, "--", input.command.program, ...input.command.args] } +} + +// Extra roots resolve against the workspace and are canonical, like the workspace itself. +function roots(list: readonly string[] | undefined, workspace: string) { + return [...new Set((list ?? []).map((root) => canonical(path.resolve(workspace, root))))] +} + +export function bwrapArgs(input: Pick, workspace: string) { + const writable = input.policy.mode === "workspace-write" ? roots(input.policy.writableRoots, workspace) : [] + const readable = roots(input.policy.readableRoots, workspace) + // Binds go after the workspace bind so they stay read-only inside it. Only regular files and directories that + // already exist are bound: bubblewrap has to create a mount point for a missing target, which would leave an + // empty file in the workspace behind, and it refuses to mount on a symlink destination at all. An absent or + // symlinked config path is workspace content a command may create or replace, like any other file. + const protectedPaths = + input.policy.mode === "workspace-write" + ? // A writable root that does not exist is not mounted, so there is nothing in it to protect. + [workspace, ...writable.filter((root) => existsSync(root))].flatMap((base) => + PROTECTED.flatMap((name) => { + const target = path.join(base, name) + const stat = lstatSync(target, { throwIfNoEntry: false }) + return stat && !stat.isSymbolicLink() ? ["--ro-bind", target, target] : [] + }), + ) + : [] + return [ + "--die-with-parent", + "--new-session", + // Every namespace, including the network. `--share-net` below joins the host's again only when allowed. + "--unshare-all", + ...(input.policy.network === "allow" ? ["--share-net"] : []), + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + // Private and ephemeral, so even a read-only sandbox has scratch space that never reaches the host. + "--tmpfs", + "/tmp", + // After the tmpfs, so a workspace under /tmp stays the real directory (writable in workspace-write mode, + // read-only otherwise — either way it must still be the real directory and not the fresh tmpfs). + ...readable.flatMap((root) => ["--ro-bind-try", root, root]), + ...(input.policy.mode === "workspace-write" + ? ["--bind", workspace, workspace] + : ["--ro-bind-try", workspace, workspace]), + ...writable.flatMap((root) => ["--bind-try", root, root]), + ...protectedPaths, + "--chdir", + input.cwd, + ] +} + +// Directories are passed as `-D` parameters and read with `(param ...)`, so no path is ever spliced into the profile. +export function seatbeltProfile(policy: Policy) { + const writable = policy.mode === "workspace-write" ? (policy.writableRoots ?? []) : [] + return [ + "(version 1)", + "(deny default)", + "(allow process-exec)", + "(allow process-fork)", + "(allow signal (target self))", + "(allow process-info* (target same-sandbox))", + "(allow sysctl-read)", + "(allow mach-lookup)", + "(allow ipc-posix-shm)", + "(allow user-preference-read)", + "(allow pseudo-tty)", + "(allow file-read*)", + '(allow file-write* (literal "/dev/null") (literal "/dev/dtracehelper") (regex #"^/dev/tty"))', + ...(policy.mode === "workspace-write" + ? [ + '(allow file-write* (subpath (param "WORKSPACE")) (subpath (param "TMPDIR")) (subpath "/private/tmp"))', + ...writable.map((_, index) => `(allow file-write* (subpath (param "WRITABLE_${index}")))`), + // Last, so it wins: the files that configure the sandbox stay read-only inside every writable directory. + ...["WORKSPACE", ...writable.map((_, index) => `WRITABLE_${index}`)].map( + (param) => + `(deny file-write* ${PROTECTED.map((name) => `(subpath (string-append (param "${param}") "/${name}"))`).join(" ")})`, + ), + ] + : []), + ...(policy.network === "allow" ? ["(allow network*)"] : []), + ].join("\n") +} + +function seatbeltArgs(input: Pick, workspace: string) { + const writable = input.policy.mode === "workspace-write" ? roots(input.policy.writableRoots, workspace) : [] + return [ + "-p", + // Indexes line up with the roots the profile refers to, which resolve here the same way. + seatbeltProfile({ ...input.policy, writableRoots: writable }), + "-D", + `WORKSPACE=${workspace}`, + "-D", + `TMPDIR=${canonical(tmpdir())}`, + ...writable.flatMap((root, index) => ["-D", `WRITABLE_${index}=${root}`]), + ] +} + +function canonical(directory: string) { + // Seatbelt and bind mounts match real paths, so a symlinked workspace (macOS /var -> /private/var) must resolve. + return existsSync(directory) ? realpathSync(directory) : directory +} + +function find(name: string) { + // macOS ships sandbox-exec at a fixed path; prefer it over whatever PATH holds. + if (name === "sandbox-exec" && existsSync("/usr/bin/sandbox-exec")) return "/usr/bin/sandbox-exec" + return which(name) ?? undefined +} diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 46d5d5167366..6557a3805b48 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -29,6 +29,7 @@ import { Location } from "./location.js" import { Global } from "@opencode/util/global" import { PersistentPty } from "./persistent-pty.js" import { ShellSelect } from "./shell/select.js" +import { Sandbox } from "./sandbox.js" import type { ShellCreateBefore } from "@opencode/plugin/effect/shell" import { PluginHooks } from "./plugin/hooks.js" import { SessionEnvironment } from "./session/environment.js" @@ -69,6 +70,8 @@ type CreateInput = Shell.CreateInput & { // A call waits on the command. A server that takes the command over moves it to the background, which clears // its timeout, so its deadline is not kept for a restart. waited?: boolean + // Runs outside the OS sandbox. The caller must already hold the `shell_unsandboxed` permission for it. + unsandboxed?: boolean } // What a server needs to take a daemon-run command back after a restart, kept in the daemon's metadata. @@ -246,6 +249,8 @@ interface Runs { /** Fails with `UnavailableError` only when the daemon could not be reached or started: spawning instead is safe. */ readonly create: (input: { readonly info: Info + // What to execute, which is the sandbox's backend when the shell runs confined. + readonly program: string readonly args: readonly string[] readonly env: Readonly> readonly timeout: number @@ -459,7 +464,7 @@ const daemonLayer = Layer.effect( done: Deferred.makeUnsafe(), } const created = yield* pty.createPipe({ - program: input.info.shell, + program: input.program, args: input.args, cwd: input.info.cwd, env: input.env, @@ -903,7 +908,25 @@ const layer = () => if (location.workspaceID === undefined) invocation.cwd = path.resolve(location.directory, invocation.cwd) const id = Shell.ID.ascending() - const args = ShellSelect.args(invocation.shell, invocation.command) + const shellArgs = ShellSelect.args(invocation.shell, invocation.command) + // Pinned per workspace on first use, so config written by a confined command cannot change this process's + // policy. Fails closed: an enabled sandbox that cannot confine the command stops it from running at all. + const entries = yield* config.entries() + const policy = Sandbox.policy(entries, location.directory) + const confined = + input.unsandboxed || !policy + ? undefined + : Sandbox.wrap({ + policy, + command: { program: invocation.shell, args: shellArgs }, + cwd: invocation.cwd, + workspace: location.directory, + remote: location.workspaceID !== undefined, + }) + if (confined instanceof Sandbox.UnavailableError) + return yield* new AppProcess.AppProcessError({ command: invocation.command, cause: confined }) + const program = confined?.program ?? invocation.shell + const args = confined?.args ?? shellArgs const file = path.join(outputDir, `${id}.out`) const info: Info = { @@ -922,6 +945,7 @@ const layer = () => const created = yield* runs .create({ info, + program, args, // The daemon replaces the environment, so variables removed by hooks stay removed, like the spawner. env: Object.fromEntries( @@ -955,7 +979,7 @@ const layer = () => Effect.gen(function* () { const handle = yield* environment.spawner .spawn( - ChildProcess.make(invocation.shell, args, { + ChildProcess.make(program, args, { cwd: invocation.cwd, env: invocation.env, stdin: "ignore", diff --git a/packages/core/src/tool/plugin/shell.ts b/packages/core/src/tool/plugin/shell.ts index a7f215ca210d..5e2c46fa2d73 100644 --- a/packages/core/src/tool/plugin/shell.ts +++ b/packages/core/src/tool/plugin/shell.ts @@ -23,6 +23,8 @@ import { ShellResult } from "../../shell/result.js" import { toolFailure } from "../runtime.js" export const name = "shell" +// Separate from `shell` so approving commands never approves leaving the OS sandbox. +export const UNSANDBOXED_PERMISSION = "shell_unsandboxed" export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000 // How long a call the user interrupted waits for its stopped command to exit before settling with the output so far. const INTERRUPT_WAIT = "500 millis" @@ -60,6 +62,10 @@ export const Input = Schema.Struct({ timeout: Schema.optionalKey(NonNegativeInt).annotate({ description: `Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to ${DEFAULT_TIMEOUT_MS} for foreground commands. Background commands have no timeout by default.`, }), + sandbox: Schema.optionalKey(Schema.Boolean).annotate({ + description: + "Set to false to run the command outside the OS sandbox. Requires separate user permission, so use it only when the sandbox blocked a command that must run, never by default. Omit it to stay sandboxed.", + }), background: Schema.optionalKey(Schema.Boolean).annotate({ description: "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion.", @@ -260,7 +266,11 @@ export const Plugin = { const permission = yield* Permission.Service const autoBackground = yield* Flag.enabled("shell_timeout_background") - const prepare = Effect.fn("ShellTool.prepare")(function* (invocation: ShellCreateBefore, context: Tool.Context) { + const prepare = Effect.fn("ShellTool.prepare")(function* ( + invocation: ShellCreateBefore, + context: Tool.Context, + unsandboxed: boolean, + ) { const target = yield* access.resolve({ path: invocation.cwd, kind: "directory" }) invocation.cwd = target.absolute const timeout = invocation.timeout @@ -272,6 +282,13 @@ export const Plugin = { }), ) yield* access.authorizeExternal([target, ...directories], context) + if (unsandboxed) + yield* permission.assert({ + action: UNSANDBOXED_PERMISSION, + resources: [invocation.command], + save: [invocation.command], + ...Permission.invocation(context), + }) if (parsed.commands.length > 0) yield* permission.assert({ action: name, @@ -354,6 +371,7 @@ export const Plugin = { shell: yield* compatibleShell, metadata: { sessionID: context.sessionID }, waited: input.background !== true, + unsandboxed: input.sandbox === false, toolCall: { sessionID: context.sessionID, assistantMessageID: context.messageID, @@ -369,7 +387,7 @@ export const Plugin = { // Asking for permission can take a while; a stop then ends the call before any command starts. finalTimeout = yield* restore( Effect.raceFirst( - prepare(invocation, context), + prepare(invocation, context, input.sandbox === false), Deferred.await(stopped).pipe( Effect.andThen( Effect.fail( diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts index 5d16cc7cbbee..1dba798ce4d8 100644 --- a/packages/core/test/agent.test.ts +++ b/packages/core/test/agent.test.ts @@ -167,6 +167,31 @@ describe("Agent", () => { }), ) + it.effect("every shipped agent asks or denies shell_unsandboxed, never allows it", () => + Effect.gen(function* () { + const agent = yield* Agent.Service + yield* AgentPlugin.Plugin.effect(host({ agent: agentHost(agent) })) + + const effects: Record = {} + for (const item of yield* agent.list()) + effects[String(item.id)] = Permission.evaluate("shell_unsandboxed", "rm -rf x", item.permissions).effect + expect(effects).toEqual({ + build: "ask", + compaction: "ask", + explore: "deny", + general: "ask", + summary: "deny", + title: "deny", + }) + // A custom agent starts from the same base policy. + const custom = Agent.ID.make("custom") + yield* agent.transform((editor) => editor.update(custom, () => {})) + expect(Permission.evaluate("shell_unsandboxed", "x", (yield* agent.get(custom))?.permissions ?? []).effect).toBe( + "ask", + ) + }), + ) + it.effect("allows external directories without opting built-in agents into bash", () => Effect.gen(function* () { const agent = yield* Agent.Service diff --git a/packages/core/test/config/normalization.test.ts b/packages/core/test/config/normalization.test.ts index 946a95cf375e..d64cdbd90405 100644 --- a/packages/core/test/config/normalization.test.ts +++ b/packages/core/test/config/normalization.test.ts @@ -86,6 +86,49 @@ describe("ConfigNormalize", () => { ]) }) + test("keeps sandbox config through normalization and reports invalid values", () => { + const sandbox = { enabled: true, mode: "workspace-write", network: "deny" } + const result = normalized({ sandbox }) + expect(result.diagnostics).toEqual([]) + expect(result.encoded.sandbox).toEqual(sandbox) + expect(Schema.decodeUnknownSync(Info)(result.encoded).sandbox).toMatchObject(sandbox) + + const roots = { enabled: true, writable_roots: ["/data/a"], readable_roots: ["/opt/r"] } + expect(normalized({ sandbox: roots }).encoded.sandbox).toEqual(roots) + // Bad roots never turn the sandbox off, and are dropped rather than trusted. + const badRoots = normalized({ sandbox: { enabled: true, writable_roots: "/etc" } }) + expect(badRoots.encoded.sandbox).toEqual({ enabled: true, mode: "read-only", network: "deny" }) + expect(badRoots.diagnostics.map((diagnostic) => diagnostic.kind)).toContain("invalid") + + // Valid roots survive an unrelated invalid field in the same block. + const mixed = normalized({ + sandbox: { enabled: true, writable_roots: ["/data/a"], readable_roots: ["/opt/r"], network: "sometimes" }, + }) + expect(mixed.encoded.sandbox).toEqual({ + enabled: true, + mode: "read-only", + network: "deny", + writable_roots: ["/data/a"], + readable_roots: ["/opt/r"], + }) + expect(mixed.diagnostics.map((diagnostic) => diagnostic.kind)).toContain("invalid") + + // An invalid block fails closed: it is reported, but the sandbox stays enabled with the strictest values. + const invalid = normalized({ + sandbox: { enabled: false, mode: "read-only", network: "sometimes" }, + shell: "/bin/sh", + }) + expect(invalid.encoded.sandbox).toEqual({ enabled: true, mode: "read-only", network: "deny" }) + expect(invalid.encoded.shell).toBe("/bin/sh") + expect(invalid.diagnostics.map((diagnostic) => diagnostic.kind)).toContain("invalid") + + for (const bad of ["on", true, [], null, { enabled: "yes" }]) { + const result = normalized({ sandbox: bad }) + expect(result.encoded.sandbox).toMatchObject({ enabled: true, network: "deny" }) + expect(result.diagnostics.map((diagnostic) => diagnostic.kind)).toContain("invalid") + } + }) + test("rejects every non-object root with one root diagnostic", () => { for (const input of [null, [], "config", true, 1]) { expect(ConfigNormalize.normalize(input)).toEqual({ diff --git a/packages/core/test/fixture/shell-daemon.ts b/packages/core/test/fixture/shell-daemon.ts index fabb399779bb..e7374d3dcc7d 100644 --- a/packages/core/test/fixture/shell-daemon.ts +++ b/packages/core/test/fixture/shell-daemon.ts @@ -3,6 +3,7 @@ import { Context, Effect, Exit, Layer, Scope } from "effect" import { ChildProcessSpawner } from "effect/process" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { Config } from "@opencode/core/config" +import type { Entry } from "@opencode/schema/config" import { Environment } from "@opencode/core/environment/index" import { Location } from "@opencode/core/location" import { PersistentPty } from "@opencode/core/persistent-pty" @@ -40,7 +41,7 @@ export const daemonShells = Effect.fn(function* () { }), ).pipe(Layer.provide(hostEnvironmentLayer)) // `server` shares one server's daemon commands between Locations; without it the Location gets a server of its own. - const shellLayer = (directory: string, server?: Shell.DaemonInterface) => + const shellLayer = (directory: string, server?: Shell.DaemonInterface, entries: Entry[] = []) => AppNodeBuilder.build(LayerNode.group([Shell.node, LocationLifecycle.node, Bus.node]), [ ...(server ? [Shell.daemonNode.replace(Layer.succeed(Shell.Daemon, server))] : []), Location.node.replace( @@ -50,7 +51,7 @@ export const daemonShells = Effect.fn(function* () { ), ), Global.node.replace(global), - Config.node.replace(Config.testLayer()), + Config.node.replace(Config.testLayer(entries)), Environment.node.replace(environment), PersistentPty.node.replace(Layer.succeed(PersistentPty.Service, pty)), ]) @@ -85,12 +86,13 @@ export const daemonShells = Effect.fn(function* () { const withShell = ( directory: string, body: (shell: Shell.Interface) => Effect.Effect, + entries?: Entry[], ) => Effect.scoped( Effect.gen(function* () { const shell = yield* Shell.Service return yield* body(shell) - }).pipe(Effect.provide(shellLayer(directory))), + }).pipe(Effect.provide(shellLayer(directory, undefined, entries))), ) const directory = (yield* tmpdirScoped()).path return { diff --git a/packages/core/test/sandbox.test.ts b/packages/core/test/sandbox.test.ts new file mode 100644 index 000000000000..b11bcd562ddb --- /dev/null +++ b/packages/core/test/sandbox.test.ts @@ -0,0 +1,688 @@ +import { describe, expect, test } from "bun:test" +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "fs" +import { tmpdir } from "os" +import path from "path" +import { Effect, Layer } from "effect" +import { Config } from "@opencode/core/config" +import { Permission } from "@opencode/core/permission" +import { Sandbox } from "@opencode/core/sandbox" +import { Agent } from "@opencode/schema/agent" +import { Directory, Document, Info } from "@opencode/schema/config" +import { AbsolutePath } from "@opencode/core/schema" +import { ConfigSandbox } from "@opencode/schema/config/sandbox" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { LayerNode } from "@opencode/util/effect/layer-node" +import { Bus } from "@opencode/core/bus" +import { Credential } from "@opencode/core/credential" +import { Global } from "@opencode/util/global" +import { Location } from "@opencode/core/location" +import { WellKnown } from "@opencode/core/wellknown" +import { Watcher } from "@opencode/core/filesystem/watcher" +import { emptyCredentialNode, emptyWellknownNode } from "./fixture/config-nodes" +import { location as locationFixture } from "./fixture/location" + +const command = { program: "/bin/sh", args: ["-c", "echo hi"] } +const input = { + policy: { mode: "workspace-write", network: "deny" } as const, + command, + cwd: "/work/project/sub", + workspace: "/work/project", + find: (name: string) => `/usr/bin/${name}`, +} + +const wrapped = (override: Partial) => { + const result = Sandbox.wrap({ ...input, ...override }) + if (result instanceof Sandbox.UnavailableError) throw result + return result +} + +describe("Sandbox permissions", () => { + test("the shipped agent defaults ask before leaving the sandbox", () => { + const rules = Agent.Info.default(Agent.ID.make("build")).permissions + expect(Permission.evaluate("shell", "ls", rules).effect).toBe("allow") + expect(Permission.evaluate("shell_unsandboxed", "ls", rules).effect).toBe("ask") + }) +}) + +describe("Sandbox.resolve", () => { + test("is off unless enabled, and defaults to the strictest settings", () => { + expect(Sandbox.resolve(undefined)).toBeUndefined() + expect(Sandbox.resolve(new ConfigSandbox.Info({ mode: "read-only", network: "allow" }))).toBeUndefined() + expect(Sandbox.resolve(new ConfigSandbox.Info({ enabled: false }))).toBeUndefined() + expect(Sandbox.resolve(new ConfigSandbox.Info({ enabled: true }))).toEqual({ + mode: "workspace-write", + network: "deny", + }) + expect(Sandbox.resolve(new ConfigSandbox.Info({ enabled: true, mode: "read-only", network: "allow" }))).toEqual({ + mode: "read-only", + network: "allow", + }) + }) +}) + +describe("Sandbox.wrap on Linux", () => { + const linux = { platform: "linux" } as const + + test("wraps the command in bwrap with every namespace unshared, a read-only root and a workspace-only write bind", () => { + const result = wrapped(linux) + expect(result.program).toBe("/usr/bin/bwrap") + expect(result.args).toEqual([ + "--die-with-parent", + "--new-session", + "--unshare-all", + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "--tmpfs", + "/tmp", + "--bind", + "/work/project", + "/work/project", + "--chdir", + "/work/project/sub", + "--", + "/bin/sh", + "-c", + "echo hi", + ]) + expect(result.args.filter((arg) => arg === "--bind")).toHaveLength(1) + }) + + test("read-only binds nothing writable from the host", () => { + const result = wrapped({ ...linux, policy: { mode: "read-only", network: "deny" } }) + expect(result.args).not.toContain("--bind") + expect(result.args).toContain("--ro-bind") + }) + + test("read-only still binds the real workspace directory after the /tmp tmpfs, so a workspace under /tmp stays reachable", () => { + // Regression: --tmpfs /tmp replaces everything under /tmp with an empty, private filesystem. Without a bind for + // the workspace itself afterwards, a workspace located under /tmp (common for tests and some sandboxed runners) + // would resolve to that empty tmpfs instead of the real directory, breaking --chdir and every file read. + const result = wrapped({ ...linux, policy: { mode: "read-only", network: "deny" }, workspace: "/tmp/ws" }) + const tmpfs = result.args.indexOf("/tmp") + const bind = result.args.findIndex( + (arg, i) => arg === "--ro-bind-try" && result.args[i + 1] === "/tmp/ws" && result.args[i + 2] === "/tmp/ws", + ) + expect(bind).toBeGreaterThan(tmpfs) + }) + + test("denies the network unless the policy allows it", () => { + expect(wrapped(linux).args).not.toContain("--share-net") + expect(wrapped({ ...linux, policy: { mode: "workspace-write", network: "allow" } }).args).toContain("--share-net") + expect(wrapped({ ...linux, policy: { mode: "workspace-write", network: "allow" } }).args).toContain("--unshare-all") + }) + + test("keeps the command argv intact after the separator, whatever it contains", () => { + const hostile = { program: "/bin/sh", args: ["-c", "echo '--bind / /'; $(rm -rf /)"] } + const result = wrapped({ ...linux, command: hostile }) + expect(result.args.slice(result.args.indexOf("--") + 1)).toEqual([hostile.program, ...hostile.args]) + }) + + test("fails closed when bwrap is missing", () => { + const result = Sandbox.wrap({ ...input, ...linux, find: () => undefined }) + expect(result).toBeInstanceOf(Sandbox.UnavailableError) + expect(String((result as Sandbox.UnavailableError).message)).toContain("bwrap was not found") + }) +}) + +describe("Sandbox.wrap on macOS", () => { + const darwin = { platform: "darwin" } as const + + test("wraps the command in sandbox-exec with a deny-default profile and parameterized directories", () => { + const result = wrapped(darwin) + expect(result.program).toBe("/usr/bin/sandbox-exec") + expect(result.args[0]).toBe("-p") + const profile = result.args[1] ?? "" + expect(profile.split("\n").slice(0, 2)).toEqual(["(version 1)", "(deny default)"]) + expect(profile).toContain('(subpath (param "WORKSPACE"))') + expect(result.args).toContain("WORKSPACE=/work/project") + expect(result.args.slice(result.args.indexOf("--") + 1)).toEqual([command.program, ...command.args]) + // A path never lands in the profile text, so it cannot break out of it. + expect(profile).not.toContain("/work/project") + }) + + test("allows writes only in workspace-write mode", () => { + const writable = Sandbox.seatbeltProfile({ mode: "workspace-write", network: "deny" }) + const readonly = Sandbox.seatbeltProfile({ mode: "read-only", network: "deny" }) + expect(writable).toContain('(subpath (param "WORKSPACE"))') + expect(readonly).not.toContain("WORKSPACE") + expect(readonly).not.toContain("/private/tmp") + }) + + test("denies the network unless the policy allows it", () => { + expect(Sandbox.seatbeltProfile({ mode: "workspace-write", network: "deny" })).not.toContain("network") + expect(Sandbox.seatbeltProfile({ mode: "workspace-write", network: "allow" })).toContain("(allow network*)") + }) + + test("fails closed when sandbox-exec is missing", () => { + const result = Sandbox.wrap({ ...input, ...darwin, find: () => undefined }) + expect(result).toBeInstanceOf(Sandbox.UnavailableError) + expect(String((result as Sandbox.UnavailableError).message)).toContain("sandbox-exec was not found") + }) +}) + +describe("Sandbox.wrap without a backend", () => { + test("fails closed on platforms without one and for remote workspaces", () => { + expect(Sandbox.wrap({ ...input, platform: "win32" })).toBeInstanceOf(Sandbox.UnavailableError) + expect(Sandbox.wrap({ ...input, platform: "linux", remote: true })).toBeInstanceOf(Sandbox.UnavailableError) + }) +}) + +const layer = (sandbox?: ConstructorParameters[0], documentPath?: string) => + new Document({ + type: "document", + ...(documentPath ? { path: AbsolutePath.make(documentPath) } : {}), + info: new Info(sandbox ? { sandbox: new ConfigSandbox.Info(sandbox) } : {}), + }) + +describe("Sandbox.merge", () => { + test("merges layers field by field, so a partial higher layer cannot drop enabled", () => { + const merged = Sandbox.merge([layer({ enabled: true, mode: "read-only" }), layer(), layer({ network: "allow" })]) + expect(merged).toMatchObject({ enabled: true, mode: "read-only", network: "allow" }) + expect(Sandbox.resolve(merged)).toEqual({ mode: "read-only", network: "allow" }) + expect(Sandbox.resolve(Sandbox.merge([layer({ enabled: true }), layer({ mode: "read-only" })]))).toEqual({ + mode: "read-only", + network: "deny", + }) + }) + + test("a later layer cannot loosen enabled, read-only or network deny", () => { + expect(Sandbox.resolve(Sandbox.merge([layer({ enabled: true }), layer({ enabled: false })]))).toEqual({ + mode: "workspace-write", + network: "deny", + }) + expect( + Sandbox.resolve(Sandbox.merge([layer({ enabled: true, mode: "read-only" }), layer({ mode: "workspace-write" })])) + ?.mode, + ).toBe("read-only") + expect( + Sandbox.resolve(Sandbox.merge([layer({ enabled: true, network: "deny" }), layer({ network: "allow" })]))?.network, + ).toBe("deny") + expect(Sandbox.merge([layer()])).toBeUndefined() + expect(Sandbox.merge([])).toBeUndefined() + }) +}) + +describe("Sandbox.policy", () => { + // The policy is read once per workspace, before any confined command runs. A config file that a command creates + // or rewrites later cannot change it, so a workspace-write command cannot grant itself network access or extra + // roots on its next invocation. + const document = (sandbox: ConstructorParameters[0]) => layer(sandbox) + const workspace = "/work/project" + + test("pins the first policy for a workspace, ignoring later config changes", () => { + Sandbox.resetPolicies() + expect(Sandbox.policy([document({ enabled: true, writable_roots: ["/data/a"] })], workspace)).toEqual({ + mode: "workspace-write", + network: "deny", + writableRoots: ["/data/a"], + }) + // What a confined command could have written after the first command started. + expect( + Sandbox.policy([document({ enabled: true, writable_roots: ["/home"], network: "allow" })], workspace), + ).toEqual({ + mode: "workspace-write", + network: "deny", + writableRoots: ["/data/a"], + }) + }) + + test("pins disabled too, and keys the policy by workspace", () => { + Sandbox.resetPolicies() + expect(Sandbox.policy([document({ network: "allow" })], workspace)).toBeUndefined() + expect(Sandbox.policy([document({ enabled: true })], "/work/other")).toEqual({ + mode: "workspace-write", + network: "deny", + }) + Sandbox.resetPolicies() + expect(Sandbox.policy([document({ enabled: true })], workspace)).toEqual({ + mode: "workspace-write", + network: "deny", + }) + }) +}) + +describe("Sandbox.merge through the config service", () => { + // The service returns documents lowest priority first, mixed with directory sources that carry no settings. + const entriesOf = (entries: Parameters[0]) => + Effect.runPromise( + Effect.gen(function* () { + const config = yield* Config.Service + return yield* config.entries() + }).pipe(Effect.provide(Config.testLayer(entries))), + ) + + test("ignores directory entries and keeps the sandbox enabled when a project document sets other fields", async () => { + const entries = await entriesOf([ + layer({ enabled: true, mode: "read-only", network: "deny", writable_roots: ["/data/a"] }), + new Directory({ type: "directory", path: AbsolutePath.make("/work/project/.opencode") }), + layer({ enabled: false, mode: "workspace-write", network: "allow", writable_roots: ["/data/b"] }), + layer(), + ]) + expect(entries).toHaveLength(4) + expect(Sandbox.resolve(Sandbox.merge(entries))).toEqual({ + mode: "read-only", + network: "deny", + writableRoots: ["/data/a", "/data/b"], + }) + }) + + test("a lone partial document does not enable anything", async () => { + const entries = await entriesOf([layer({ network: "allow" }), layer({ mode: "read-only" })]) + expect(Sandbox.resolve(Sandbox.merge(entries))).toBeUndefined() + }) +}) + +// Boots the real Config service (real discovery walking real directories, real file parsing) instead of +// Config.testLayer's synthetic entries, so the trust boundary in Sandbox.merge is proven against documents the way +// they are actually discovered and ordered in production: see packages/core/test/config/config.test.ts for the +// pattern this mirrors. +function realConfigLayer(directory: string, globalDirectory: string) { + const locationLayer = Layer.succeed( + Location.Service, + Location.Service.of(locationFixture({ directory: AbsolutePath.make(directory) })), + ) + const built = AppNodeBuilder.build(LayerNode.group([Config.node, Bus.node]), [ + Config.node.replace(Config.configured({ system: false })), + Location.node.replace(locationLayer), + Global.node.replace(Global.layerWith({ config: globalDirectory, home: path.join(globalDirectory, "home") })), + Credential.node.replace(emptyCredentialNode), + WellKnown.node.replace(emptyWellknownNode), + Watcher.node.replace(Watcher.testLayer), + ]) + return Layer.mergeAll(built, Watcher.testLayer) +} + +describe("Sandbox.merge against a real, on-disk config tree", () => { + const withRealConfig = (body: (workspace: string, global: string) => Promise | void) => { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "sandbox-real-config-"))) + const workspace = path.join(root, "workspace") + const global = path.join(root, "global") + mkdirSync(workspace, { recursive: true }) + mkdirSync(global, { recursive: true }) + return Promise.resolve(body(workspace, global)).finally(() => rmSync(root, { recursive: true, force: true })) + } + + const entriesOf = (workspace: string, global: string) => + Effect.runPromise( + Effect.gen(function* () { + const config = yield* Config.Service + return yield* config.entries() + }).pipe(Effect.provide(realConfigLayer(workspace, global))), + ) + + test("a workspace-root opencode.json can add roots, while a global network deny still wins", () => + withRealConfig(async (workspace, global) => { + writeFileSync( + path.join(global, "opencode.json"), + JSON.stringify({ + sandbox: { enabled: true, mode: "workspace-write", network: "deny", writable_roots: ["/trusted"] }, + }), + ) + // What a confined workspace-write command could have written itself, since this file did not yet exist. + writeFileSync( + path.join(workspace, "opencode.json"), + JSON.stringify({ sandbox: { writable_roots: ["/etc"], network: "allow" } }), + ) + const entries = await entriesOf(workspace, global) + // The workspace document really is discovered and really does carry its own filesystem path. + const workspaceDocument = entries.find( + (entry): entry is Document => entry.type === "document" && entry.path === path.join(workspace, "opencode.json"), + ) + expect(workspaceDocument).toBeDefined() + const merged = Sandbox.merge(entries) + expect(merged?.enabled).toBe(true) + expect(merged?.writable_roots).toEqual(["/trusted", "/etc"]) + expect(merged?.network).toBe("deny") + })) + + test("a document in the workspace's own .opencode directory contributes roots and network", () => + withRealConfig(async (workspace, global) => { + writeFileSync(path.join(global, "opencode.json"), JSON.stringify({ sandbox: { enabled: true } })) + mkdirSync(path.join(workspace, ".opencode")) + writeFileSync( + path.join(workspace, ".opencode", "opencode.json"), + JSON.stringify({ sandbox: { writable_roots: ["/etc"], network: "allow" } }), + ) + const entries = await entriesOf(workspace, global) + const merged = Sandbox.merge(entries) + expect(merged?.writable_roots).toEqual(["/etc"]) + expect(merged?.network).toBe("allow") + })) + + test("an ancestor directory's config, outside the workspace, is trusted and can widen roots", () => + withRealConfig(async (parentWorkspace, global) => { + // Nest the real workspace one level below the temp root so an ancestor file exists above it; discovery walks + // upward from location.directory, so this ancestor file is found the same way a real repo root config would be. + const nested = path.join(parentWorkspace, "nested") + mkdirSync(nested) + writeFileSync( + path.join(parentWorkspace, "opencode.json"), + JSON.stringify({ sandbox: { enabled: true, writable_roots: ["/trusted"] } }), + ) + const entries = await entriesOf(nested, global) + const merged = Sandbox.merge(entries) + expect(merged?.writable_roots).toEqual(["/trusted"]) + })) +}) + +describe("Sandbox roots", () => { + test("writable_roots and readable_roots accumulate across layers and reach the policy", () => { + const merged = Sandbox.merge([ + layer({ enabled: true, writable_roots: ["/data/a"], readable_roots: ["/opt/r"] }), + layer({ network: "allow" }), + layer({ writable_roots: ["/data/b", "/data/a"] }), + ]) + expect(merged?.writable_roots).toEqual(["/data/a", "/data/b"]) + expect(merged?.readable_roots).toEqual(["/opt/r"]) + expect(Sandbox.resolve(merged)).toEqual({ + mode: "workspace-write", + network: "allow", + writableRoots: ["/data/a", "/data/b"], + readableRoots: ["/opt/r"], + }) + expect(Sandbox.merge([layer({ enabled: true })])?.writable_roots).toBeUndefined() + }) + + test("bwrap mounts writable roots read-write and readable roots read-only, relative ones against the workspace", () => { + const policy = { + mode: "workspace-write", + network: "deny", + writableRoots: ["/data/a", "rel"], + readableRoots: ["/opt/r"], + } as const + const args = wrapped({ policy }).args + const has = (flag: string, target: string) => + args.some((arg, i) => arg === flag && args[i + 1] === target && args[i + 2] === target) + expect(has("--bind-try", "/data/a")).toBe(true) + expect(has("--bind-try", "/work/project/rel")).toBe(true) + expect(has("--ro-bind-try", "/opt/r")).toBe(true) + const readOnly = wrapped({ policy: { ...policy, mode: "read-only" } }).args + expect(readOnly).not.toContain("--bind-try") + expect(readOnly).toContain("--ro-bind-try") + }) + + test("seatbelt grants writable roots through parameters and keeps config files read-only", () => { + const policy = { mode: "workspace-write", network: "deny", writableRoots: ["/data/a"] } as const + const args = wrapped({ policy, platform: "darwin" }).args + expect(args).toContain("WRITABLE_0=/data/a") + const profile = args[args.indexOf("-p") + 1] + expect(profile).toContain('(allow file-write* (subpath (param "WRITABLE_0")))') + expect(profile).not.toContain("/data/a") + const lines = profile.split("\n") + const deny = lines.findIndex((line) => line.startsWith("(deny file-write*") && line.includes('"WORKSPACE"')) + expect(deny).toBeGreaterThan( + lines.findIndex((line) => line.includes('(param "WORKSPACE")) (subpath (param "TMPDIR"))')), + ) + for (const name of Sandbox.PROTECTED) expect(lines[deny]).toContain(`/${name}`) + expect(lines.some((line) => line.startsWith("(deny file-write*") && line.includes('"WRITABLE_0"'))).toBe(true) + expect(wrapped({ policy: { ...policy, mode: "read-only" }, platform: "darwin" }).args.join(" ")).not.toContain( + "WRITABLE_0", + ) + }) +}) + +describe("Sandbox protected config files", () => { + test("binds existing config files read-only inside the writable workspace, after the workspace bind", () => { + const workspace = realpathSync(mkdtempSync(path.join(tmpdir(), "sandbox-protect-"))) + try { + writeFileSync(path.join(workspace, "opencode.json"), "{}") + writeFileSync(path.join(workspace, "opencode.jsonc"), "{}") + mkdirSync(path.join(workspace, ".opencode")) + const args = Sandbox.bwrapArgs( + { policy: { mode: "workspace-write", network: "deny" }, cwd: workspace }, + workspace, + ) + const bind = args.indexOf("--bind") + expect(bind).toBeGreaterThan(-1) + for (const name of Sandbox.PROTECTED) { + const target = path.join(workspace, name) + const at = args.findIndex((arg, i) => arg === target && i > bind) + expect(at).toBeGreaterThan(bind) + expect(args[at - 1]).toBe("--ro-bind") + } + expect(Sandbox.PROTECTED).toEqual(["opencode.json", "opencode.jsonc", ".opencode"]) + } finally { + rmSync(workspace, { recursive: true, force: true }) + } + }) + + test("does not create mount points for config files that do not exist", () => { + const workspace = realpathSync(mkdtempSync(path.join(tmpdir(), "sandbox-protect-"))) + try { + const args = Sandbox.bwrapArgs( + { policy: { mode: "workspace-write", network: "deny" }, cwd: workspace }, + workspace, + ) + for (const name of Sandbox.PROTECTED) { + expect(args).not.toContain(path.join(workspace, name)) + } + } finally { + rmSync(workspace, { recursive: true, force: true }) + } + }) + + test("a dangling symlink at a protected name is treated like any other absent path, not bound", () => { + // A dangling symlink is ordinary workspace content a workspace-write command may create freely, like a plain + // absent file, so it gets no mount point. The policy is pinned before commands run (Sandbox.policy), so config + // written this way cannot change the running process's sandbox settings. + const workspace = realpathSync(mkdtempSync(path.join(tmpdir(), "sandbox-protect-dangling-"))) + try { + symlinkSync(path.join(workspace, "does-not-exist"), path.join(workspace, "opencode.json")) + expect(existsSync(path.join(workspace, "opencode.json"))).toBe(false) + const args = Sandbox.bwrapArgs( + { policy: { mode: "workspace-write", network: "deny" }, cwd: workspace }, + workspace, + ) + expect(args).not.toContain(path.join(workspace, "opencode.json")) + } finally { + rmSync(workspace, { recursive: true, force: true }) + } + }) +}) + +// Executes a real bubblewrap. Skipped where bwrap is missing or user namespaces are unavailable. +const bwrap = Bun.which("bwrap") +const usable = + process.platform === "linux" && + bwrap !== null && + Bun.spawnSync([bwrap, "--unshare-all", "--ro-bind", "/", "/", "--", "/bin/sh", "-c", "true"]).exitCode === 0 +const live = usable ? describe : describe.skip + +live("Sandbox on a real bubblewrap", () => { + const run = ( + workspace: string, + script: string, + policy: Sandbox.Policy = { mode: "workspace-write", network: "deny" }, + ) => { + const result = Sandbox.wrap({ + policy, + command: { program: "/bin/sh", args: ["-c", script] }, + cwd: workspace, + workspace, + platform: "linux", + }) + if (result instanceof Sandbox.UnavailableError) throw result + const proc = Bun.spawnSync([result.program, ...result.args], { cwd: workspace }) + return { code: proc.exitCode, out: proc.stdout.toString(), err: proc.stderr.toString() } + } + const withWorkspace = (body: (workspace: string, outside: string) => void) => { + const root = realpathSync(mkdtempSync(path.join(process.env.HOME ?? "/var/tmp", ".sandbox-live-"))) + const workspace = path.join(root, "workspace") + const outside = path.join(root, "outside") + mkdirSync(workspace) + mkdirSync(outside) + try { + body(workspace, outside) + } finally { + rmSync(root, { recursive: true, force: true }) + } + } + + test("writes inside the workspace and is denied everywhere else", () => + withWorkspace((workspace, outside) => { + expect(run(workspace, "echo inside > inside.txt").code).toBe(0) + expect(readFileSync(path.join(workspace, "inside.txt"), "utf8").trim()).toBe("inside") + + const escaped = run(workspace, `echo escaped > ${outside}/escaped.txt`) + expect(escaped.code).not.toBe(0) + expect(Bun.file(path.join(outside, "escaped.txt")).size).toBe(0) + expect(run(workspace, "echo x > /etc/sandbox-escape").code).not.toBe(0) + // /tmp is private, so a write there never reaches the host. + expect(run(workspace, `echo t > /tmp/sandbox-live-${path.basename(outside)}`).code).toBe(0) + expect(Bun.file(`/tmp/sandbox-live-${path.basename(outside)}`).size).toBe(0) + })) + + test("read-only mode cannot write even in the workspace", () => + withWorkspace((workspace) => { + const result = run(workspace, "echo no > file.txt", { mode: "read-only", network: "deny" }) + expect(result.code).not.toBe(0) + expect(Bun.file(path.join(workspace, "file.txt")).size).toBe(0) + })) + + test("cannot rewrite, replace or delete existing opencode config files", () => + withWorkspace((workspace) => { + const config = path.join(workspace, "opencode.json") + const configc = path.join(workspace, "opencode.jsonc") + writeFileSync(config, '{"sandbox":{"enabled":true}}') + writeFileSync(configc, '{"sandbox":{"network":"deny"}}') + mkdirSync(path.join(workspace, ".opencode")) + writeFileSync(path.join(workspace, ".opencode", "keep.txt"), "keep") + writeFileSync(path.join(workspace, "other.json"), "{}") + // Control: the same operations on an unprotected sibling succeed, so the failures below come from the protection. + expect(run(workspace, "echo x >> other.json && mv other.json moved-other.json && rm moved-other.json").code).toBe( + 0, + ) + for (const script of [ + `echo '{"sandbox":{"enabled":false}}' > opencode.json`, + `echo x >> opencode.json`, + `mv opencode.json moved.json`, + `rm -f opencode.json`, + `echo x >> opencode.jsonc`, + `rm -f opencode.jsonc`, + `echo x > .opencode/file`, + `mkdir .opencode/sub`, + `rm -f .opencode/keep.txt`, + `rm -rf .opencode`, + `mv .opencode .opencode-moved`, + // Replace by rename from a fresh file, the usual atomic-write pattern. + `echo '{}' > replacement.json && mv -f replacement.json opencode.json`, + ]) { + const result = run(workspace, script) + expect(result.code).not.toBe(0) + expect(result.err).toMatch(/Read-only file system|busy|Device or resource/i) + } + expect(readFileSync(config, "utf8")).toBe('{"sandbox":{"enabled":true}}') + expect(readFileSync(configc, "utf8")).toBe('{"sandbox":{"network":"deny"}}') + expect(readFileSync(path.join(workspace, ".opencode", "keep.txt"), "utf8")).toBe("keep") + expect(existsSync(path.join(workspace, ".opencode", "file"))).toBe(false) + expect(existsSync(path.join(workspace, ".opencode", "sub"))).toBe(false) + expect(existsSync(path.join(workspace, "moved.json"))).toBe(false) + expect(existsSync(path.join(workspace, ".opencode-moved"))).toBe(false) + })) + + test("does not leave config stubs behind in a clean workspace", () => + withWorkspace((workspace) => { + expect(run(workspace, "echo ok > inside.txt").code).toBe(0) + expect(readdirSync(workspace)).toEqual(["inside.txt"]) + })) + + test("runs with a symlinked config instead of failing to mount, and leaves the link target alone", () => + withWorkspace((workspace, outside) => { + const target = path.join(outside, "real.json") + writeFileSync(target, '{"x":1}') + symlinkSync(target, path.join(workspace, "opencode.json")) + // bubblewrap refuses to mount on a symlink destination, so the path is skipped instead of breaking every command. + expect(run(workspace, "true").code).toBe(0) + expect(run(workspace, "echo x > opencode.json").code).not.toBe(0) + expect(readFileSync(target, "utf8")).toBe('{"x":1}') + })) + + test("mounts writable_roots read-write and readable_roots, protecting config files inside them", () => + withWorkspace((workspace, outside) => { + const extra = path.join(outside, "extra") + mkdirSync(extra) + writeFileSync(path.join(extra, "opencode.json"), "{}") + writeFileSync(path.join(outside, "note.txt"), "readable") + const policy = { + mode: "workspace-write", + network: "deny", + writableRoots: [extra], + readableRoots: [outside], + } as const + expect(run(workspace, `echo ok > ${extra}/file.txt`, policy).code).toBe(0) + expect(readFileSync(path.join(extra, "file.txt"), "utf8").trim()).toBe("ok") + expect(run(workspace, `cat ${outside}/note.txt`, policy).out.trim()).toBe("readable") + expect(run(workspace, `echo x > ${outside}/other.txt`, policy).code).not.toBe(0) + expect(run(workspace, `echo x > ${extra}/opencode.json`, policy).code).not.toBe(0) + expect(readFileSync(path.join(extra, "opencode.json"), "utf8")).toBe("{}") + })) + + test("a config document written inside the workspace cannot change the pinned policy", () => + withWorkspace((workspace, outside) => { + // A workspace-write command can create or edit opencode.json inside the workspace it can already write to. + // The policy was pinned before that command ran, so asking for an extra writable root is too late. + Sandbox.resetPolicies() + const configPath = path.join(workspace, "opencode.json") + const initial = new Document({ + type: "document", + path: AbsolutePath.make(configPath), + info: new Info({ + sandbox: new ConfigSandbox.Info({ enabled: true, mode: "workspace-write", network: "deny" }), + }), + }) + const pinned = Sandbox.policy([initial], workspace)! + writeFileSync(configPath, JSON.stringify({ sandbox: { writable_roots: [outside], network: "allow" } })) + const attacker = new Document({ + type: "document", + path: AbsolutePath.make(configPath), + info: new Info({ sandbox: new ConfigSandbox.Info({ writable_roots: [outside], network: "allow" }) }), + }) + expect(Sandbox.policy([initial, attacker], workspace)).toEqual(pinned) + expect(pinned.writableRoots).toBeUndefined() + const result = run(workspace, `echo escaped > ${outside}/escaped.txt`, pinned) + expect(result.code).not.toBe(0) + expect(Bun.file(path.join(outside, "escaped.txt")).size).toBe(0) + Sandbox.resetPolicies() + })) + + test("read-only mode keeps a workspace located under /tmp reachable", () => { + const root = realpathSync(mkdtempSync(path.join("/tmp", "sandbox-live-readonly-"))) + try { + writeFileSync(path.join(root, "marker.txt"), "present") + const result = run(root, "cat marker.txt", { mode: "read-only", network: "deny" }) + expect(result.code).toBe(0) + expect(result.out.trim()).toBe("present") + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + test("denies the network by default and shares it only when allowed", () => + withWorkspace((workspace) => { + const denied = run(workspace, "cat /proc/net/dev | tail -n +3 | grep -v '^ *lo:' | wc -l") + expect(denied.code).toBe(0) + expect(denied.out.trim()).toBe("0") + const allowed = run(workspace, "cat /proc/net/dev | tail -n +3 | wc -l", { + mode: "workspace-write", + network: "allow", + }) + expect(Number(allowed.out.trim())).toBe( + readFileSync("/proc/net/dev", "utf8").split("\n").filter(Boolean).slice(2).length, + ) + })) +}) diff --git a/packages/core/test/shell-daemon.test.ts b/packages/core/test/shell-daemon.test.ts index 5051819f124f..b718b383dbaf 100644 --- a/packages/core/test/shell-daemon.test.ts +++ b/packages/core/test/shell-daemon.test.ts @@ -7,10 +7,13 @@ import { TestClock } from "effect/testing" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { PersistentPty } from "@opencode/core/persistent-pty" import { Config } from "@opencode/core/config" +import { Document, Info } from "@opencode/schema/config" +import { ConfigSandbox } from "@opencode/schema/config/sandbox" import { Environment } from "@opencode/core/environment/index" import { Location } from "@opencode/core/location" import { AbsolutePath } from "@opencode/core/schema" import { Shell } from "@opencode/core/shell" +import { Sandbox } from "@opencode/core/sandbox" import { Bus } from "@opencode/core/bus" import { Global } from "@opencode/util/global" import { FSUtil } from "@opencode/util/fs-util" @@ -552,3 +555,145 @@ describe("Shell on a real process daemon", () => { { timeout: 20_000 }, ) }) + +// Only Linux resolves `bwrap` from PATH; the other backends are covered by sandbox.test.ts. +const linuxOnly = process.platform === "linux" ? it.live : it.live.skip + +const sandboxConfig = (sandbox: ConstructorParameters[0]) => [ + new Document({ type: "document", info: new Info({ sandbox: new ConfigSandbox.Info(sandbox) }) }), +] + +// Runs with PATH holding only the given executables, so a test controls whether the backend exists. +const withPath = (executables: string[]) => + Effect.gen(function* () { + const bin = (yield* tmpdirScoped()).path + yield* Effect.promise(() => + Promise.all( + executables.map(async (name) => { + await writeFile(path.join(bin, name), "#!/bin/sh\nexit 0\n", { mode: 0o755 }) + }), + ), + ) + const previous = process.env.PATH + process.env.PATH = bin + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (previous === undefined) delete process.env.PATH + else process.env.PATH = previous + }), + ) + return bin + }) + +describe("Shell with the OS sandbox", () => { + linuxOnly("wraps the command in bwrap with a read-only root, workspace-only writes and no network", () => + Effect.gen(function* () { + const env = yield* daemonShells() + const bin = yield* withPath(["bwrap"]) + yield* env.withShell( + env.directory, + (shell) => + Effect.gen(function* () { + const info = yield* shell.create({ shell: "/bin/sh", command: "echo hi", timeout: 60_000 }) + const [request] = env.created() + const workspace = realpathSync(env.directory) + expect(request?.program).toBe(path.join(bin, "bwrap")) + expect(request?.args).toEqual([ + "--die-with-parent", + "--new-session", + "--unshare-all", + "--ro-bind", + "/", + "/", + "--dev", + "/dev", + "--proc", + "/proc", + "--tmpfs", + "/tmp", + "--bind", + workspace, + workspace, + "--chdir", + env.directory, + "--", + "/bin/sh", + "-c", + "echo hi", + ]) + // The caller still sees the command it asked for, not the wrapper. + expect(info.command).toBe("echo hi") + expect(info.shell).toBe("/bin/sh") + }), + sandboxConfig({ enabled: true }), + ) + }), + ) + + linuxOnly("shares the network only when sandbox.network is allow", () => + Effect.gen(function* () { + const env = yield* daemonShells() + yield* withPath(["bwrap"]) + yield* env.withShell( + env.directory, + (shell) => shell.create({ shell: "/bin/sh", command: "true" }), + sandboxConfig({ enabled: true, network: "deny" }), + ) + // The policy is pinned per workspace on first use; this test deliberately reconfigures the same workspace. + Sandbox.resetPolicies() + yield* env.withShell( + env.directory, + (shell) => shell.create({ shell: "/bin/sh", command: "true" }), + sandboxConfig({ enabled: true, network: "allow" }), + ) + const [denied, allowed] = env.created() + expect(denied?.args).not.toContain("--share-net") + expect(allowed?.args).toContain("--share-net") + expect(allowed?.args).toContain("--unshare-all") + }), + ) + + linuxOnly("fails closed when bwrap is unavailable instead of running the command unconfined", () => + Effect.gen(function* () { + const env = yield* daemonShells() + yield* withPath([]) + yield* env.withShell( + env.directory, + (shell) => + Effect.gen(function* () { + const error = yield* Effect.flip(shell.create({ shell: "/bin/sh", command: "touch escaped" })) + expect(error).toBeInstanceOf(AppProcess.AppProcessError) + expect(error.message).toContain("Sandbox is enabled but unavailable") + expect(error.message).toContain("bwrap was not found") + expect(env.created()).toEqual([]) + expect(env.spawned()).toBe(0) + expect(yield* shell.list()).toEqual([]) + }), + sandboxConfig({ enabled: true }), + ) + }), + ) + + linuxOnly("runs an explicit unsandboxed request directly, and leaves a disabled sandbox alone", () => + Effect.gen(function* () { + const env = yield* daemonShells() + yield* withPath([]) + yield* env.withShell( + env.directory, + (shell) => shell.create({ shell: "/bin/sh", command: "echo out", unsandboxed: true }), + sandboxConfig({ enabled: true }), + ) + // A pinned policy would otherwise keep this workspace sandboxed for the second call. + Sandbox.resetPolicies() + yield* env.withShell( + env.directory, + (shell) => shell.create({ shell: "/bin/sh", command: "echo off" }), + sandboxConfig({ enabled: false, mode: "read-only" }), + ) + expect(env.created().map((request) => [request.program, request.args])).toEqual([ + ["/bin/sh", ["-c", "echo out"]], + ["/bin/sh", ["-c", "echo off"]], + ]) + }), + ) +}) diff --git a/packages/core/test/shell-sandbox-spawner.test.ts b/packages/core/test/shell-sandbox-spawner.test.ts new file mode 100644 index 000000000000..4f5108c8f2f6 --- /dev/null +++ b/packages/core/test/shell-sandbox-spawner.test.ts @@ -0,0 +1,128 @@ +import { expect } from "bun:test" +import { chmod, writeFile } from "fs/promises" +import path from "path" +import { Effect, Layer, Sink, Stream } from "effect" +import { ChildProcessSpawner } from "effect/process" +import { ExitCode, makeHandle, ProcessId } from "effect/process/ChildProcessSpawner" +import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" +import { Config } from "@opencode/core/config" +import { Environment } from "@opencode/core/environment/index" +import { Location } from "@opencode/core/location" +import { PersistentPty } from "@opencode/core/persistent-pty" +import { Shell } from "@opencode/core/shell" +import { Document, Info } from "@opencode/schema/config" +import { ConfigSandbox } from "@opencode/schema/config/sandbox" +import { Global } from "@opencode/util/global" +import { disabledPersistentPtyLayer } from "./fixture/persistent-pty" +import { hostEnvironmentLayer } from "./fixture/environment" +import { tempGlobalLayer } from "./fixture/global" +import { tempLocationLayer } from "./fixture/location" +import { tmpdirScoped } from "./fixture/tmpdir" +import { it } from "./lib/effect" + +// With no daemon, commands go through the spawner. That path must be confined exactly like the daemon's. +const run = ( + sandbox: ConstructorParameters[0], + body: (shell: Shell.Interface) => Effect.Effect, +) => + Effect.gen(function* () { + const spawned: { command: string; args: readonly string[] }[] = [] + const environment = Layer.effect( + Environment.Service, + Effect.gen(function* () { + const host = yield* Environment.Service + return Environment.Service.of({ + ...host, + spawner: ChildProcessSpawner.make((command) => + Effect.sync(() => { + const standard = command as unknown as { command: string; args: readonly string[] } + spawned.push({ command: standard.command, args: standard.args }) + return makeHandle({ + pid: ProcessId(1), + exitCode: Effect.succeed(ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }) + }), + ), + }) + }), + ).pipe(Layer.provide(hostEnvironmentLayer)) + const bin = (yield* tmpdirScoped()).path + yield* Effect.promise(async () => { + await writeFile(path.join(bin, "bwrap"), "#!/bin/sh\nexit 0\n") + await chmod(path.join(bin, "bwrap"), 0o755) + }) + const previous = process.env.PATH + process.env.PATH = bin + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (previous === undefined) delete process.env.PATH + else process.env.PATH = previous + }), + ) + const exit = yield* Effect.gen(function* () { + return yield* body(yield* Shell.Service) + }).pipe( + Effect.exit, + Effect.provide( + AppNodeBuilder.build(Shell.node, [ + Location.node.replace(tempLocationLayer), + Global.node.replace(tempGlobalLayer), + Config.node.replace( + Config.testLayer([ + new Document({ type: "document", info: new Info({ sandbox: new ConfigSandbox.Info(sandbox) }) }), + ]), + ), + Environment.node.replace(environment), + PersistentPty.node.replace(disabledPersistentPtyLayer), + ]), + ), + ) + return { spawned, exit, bin } + }) + +const linux = process.platform === "linux" ? it.live : it.live.skip + +linux("wraps the spawner path in bwrap when the daemon is unavailable", () => + Effect.gen(function* () { + const { spawned, exit, bin } = yield* run({ enabled: true }, (shell) => + shell.create({ shell: "/bin/sh", command: "echo hi", timeout: 0 }), + ) + expect(exit._tag).toBe("Success") + expect(spawned).toHaveLength(1) + expect(spawned[0]?.command).toBe(path.join(bin, "bwrap")) + expect(spawned[0]?.args).toContain("--unshare-all") + expect(spawned[0]?.args.slice(-4)).toEqual(["--", "/bin/sh", "-c", "echo hi"]) + }), +) + +linux("runs the spawner path directly when the sandbox is not enabled", () => + Effect.gen(function* () { + const { spawned } = yield* run({ enabled: false }, (shell) => + shell.create({ shell: "/bin/sh", command: "echo hi", timeout: 0 }), + ) + expect(spawned.map((item) => [item.command, item.args])).toEqual([["/bin/sh", ["-c", "echo hi"]]]) + }), +) + +linux("fails closed on the spawner path when bwrap is missing", () => + Effect.gen(function* () { + const { spawned, exit } = yield* run({ enabled: true }, (shell) => + Effect.gen(function* () { + process.env.PATH = "/nonexistent" + return yield* shell.create({ shell: "/bin/sh", command: "touch escaped", timeout: 0 }) + }), + ) + expect(exit._tag).toBe("Failure") + expect(spawned).toEqual([]) + expect(JSON.stringify(exit)).toContain("bwrap was not found") + }), +) diff --git a/packages/core/test/tool-shell.test.ts b/packages/core/test/tool-shell.test.ts index 0954d32c4d4a..37791320111a 100644 --- a/packages/core/test/tool-shell.test.ts +++ b/packages/core/test/tool-shell.test.ts @@ -231,7 +231,11 @@ const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({ }) const isWindows = process.platform === "win32" - +// Executes a real bubblewrap, like packages/core/test/sandbox.test.ts. Skipped where bwrap is missing or unusable. +const bwrapBinary = process.platform === "linux" ? Bun.which("bwrap") : null +const bwrapUsable = + bwrapBinary !== null && + Bun.spawnSync([bwrapBinary, "--unshare-all", "--ro-bind", "/", "/", "--", "/bin/sh", "-c", "true"]).exitCode === 0 // The process daemon keeps a finished command's zombie until the command is forgotten. const running = (pid: number) => { try { @@ -1240,6 +1244,76 @@ describe("ShellTool", () => { { timeout: 15_000 }, ) + it.live( + "requires the separate shell_unsandboxed permission for an explicit unsandboxed request", + () => + withTempDir((tmp) => + Effect.gen(function* () { + reset() + const command = isWindows ? "Write-Output unsandboxed" : "printf unsandboxed" + const approved = yield* withSession(tmp.path, (registry) => + executeTool(registry, call({ command, sandbox: false })), + ) + expect(approved).toMatchObject({ status: "completed" }) + // The escape is its own approval, asked before the ordinary command permission. + expect(assertions.map((item) => item.action)).toEqual(["shell_unsandboxed", "shell"]) + expect(assertions[0]).toMatchObject({ resources: [command], save: [command] }) + + reset() + yield* withSession(tmp.path, (registry) => executeTool(registry, call({ command }))) + expect(assertions.map((item) => item.action)).toEqual(["shell"]) + + reset() + denyAction = "shell_unsandboxed" + const denied = yield* withSession(tmp.path, (registry) => + executeTool(registry, call({ command, sandbox: false })), + ) + expect(denied).toMatchObject({ status: "error" }) + // A denied escape never reaches the shell permission or a process. + expect(assertions.map((item) => item.action)).toEqual(["shell_unsandboxed"]) + }), + ), + { timeout: 15_000 }, + ) + ;(bwrapUsable ? it.live : it.live.skip)( + "sandbox: false reaches Shell.create as unsandboxed and actually disables the OS-level sandbox, not just the permission gate", + () => + withTempDir((tmp) => + Effect.gen(function* () { + const workspace = path.join(tmp.path, "workspace") + const outside = path.join(tmp.path, "outside") + yield* Effect.promise(() => Promise.all([fs.mkdir(workspace), fs.mkdir(outside)])) + // Enabled through the real, on-disk config pipeline (ConfigDiscovery + Config.layer), not a test stub, so + // this proves the whole path from config through Shell.create to the real bwrap wrapping. + yield* Effect.promise(() => + Bun.write( + path.join(workspace, "opencode.json"), + JSON.stringify({ sandbox: { enabled: true, mode: "workspace-write", network: "deny" } }), + ), + ) + const marker = path.join(outside, "marker") + const command = `printf escaped > '${marker}'` + + reset() + const confined = yield* withSession(workspace, (registry) => executeTool(registry, call({ command }))) + expect(assertions.map((item) => item.action)).toEqual(["shell"]) + // The sandbox is enabled, so a write outside the workspace fails and never reaches the host. + expect(confined.metadata?.exit).not.toBe(0) + expect(yield* Effect.promise(() => Bun.file(marker).exists())).toBe(false) + + reset() + const unsandboxed = yield* withSession(workspace, (registry) => + executeTool(registry, call({ command, sandbox: false })), + ) + expect(assertions.map((item) => item.action)).toEqual(["shell_unsandboxed", "shell"]) + // The same command, the same enabled sandbox config, but sandbox: false really ran it unconfined. + expect(unsandboxed).toMatchObject({ status: "completed", metadata: { exit: 0 } }) + expect(yield* Effect.promise(() => Bun.file(marker).text())).toBe("escaped") + }), + ), + { timeout: 15_000 }, + ) + it.live("rejects malformed syntax across channels without partial execution", () => Effect.gen(function* () { if (isWindows) return diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 797d2807508f..def48be1cebe 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -16624,6 +16624,33 @@ ] } }, + "sandbox": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "mode": { + "$ref": "#/components/schemas/Config.Sandbox.Mode" + }, + "network": { + "$ref": "#/components/schemas/Config.Sandbox.Network" + }, + "writable_roots": { + "type": "array", + "items": { + "type": "string" + } + }, + "readable_roots": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + }, "worktree": { "$ref": "#/components/schemas/Config.Worktree" }, @@ -17257,6 +17284,14 @@ "required": ["path"], "additionalProperties": false }, + "Config.Sandbox.Mode": { + "type": "string", + "enum": ["read-only", "workspace-write"] + }, + "Config.Sandbox.Network": { + "type": "string", + "enum": ["deny", "allow"] + }, "Config.WarmingEncoded": { "type": "object", "properties": { diff --git a/packages/schema/src/agent.ts b/packages/schema/src/agent.ts index c47d5e8e7ef8..126ffbced692 100644 --- a/packages/schema/src/agent.ts +++ b/packages/schema/src/agent.ts @@ -45,6 +45,8 @@ export const Info = Schema.Struct({ hidden: false, permissions: [ { action: "*", resource: "*", effect: "allow" }, + // A saved `shell` allow must not also authorize leaving the OS sandbox. + { action: "shell_unsandboxed", resource: "*", effect: "ask" }, { action: "read", resource: "*.env", effect: "ask" }, { action: "read", resource: "*.env.*", effect: "ask" }, { action: "read", resource: "*.env.example", effect: "allow" }, diff --git a/packages/schema/src/config.ts b/packages/schema/src/config.ts index e78cbae0f8e3..d6b0881181ad 100644 --- a/packages/schema/src/config.ts +++ b/packages/schema/src/config.ts @@ -17,6 +17,7 @@ import { ConfigPlugin } from "./config/plugin.js" import { ConfigPolicy } from "./config/policy.js" import { ConfigProvider } from "./config/provider.js" import { ConfigReference } from "./config/reference.js" +import { ConfigSandbox } from "./config/sandbox.js" import { ConfigWebSearch } from "./config/websearch.js" import { ConfigToolOutput } from "./config/tool-output.js" import { ConfigWatcher } from "./config/watcher.js" @@ -106,6 +107,9 @@ export class Info extends Schema.Class("Config.Info")({ plugins: ConfigPlugin.Plugins.pipe(optional).annotate({ description: "Ordered plugin enablement directives and external package declarations", }), + sandbox: ConfigSandbox.Info.pipe(optional).annotate({ + description: "OS-level sandbox for agent shell commands (disabled unless enabled is true)", + }), worktree: ConfigWorktree.Info.pipe(optional).annotate({ description: "Directory defaults for local worktree creation", }), diff --git a/packages/schema/src/config/sandbox.ts b/packages/schema/src/config/sandbox.ts new file mode 100644 index 000000000000..536d0c0fac95 --- /dev/null +++ b/packages/schema/src/config/sandbox.ts @@ -0,0 +1,34 @@ +export * as ConfigSandbox from "./sandbox.js" + +import { Schema } from "effect" +import { optional } from "../schema.js" + +export const Mode = Schema.Literals(["read-only", "workspace-write"]).annotate({ identifier: "Config.Sandbox.Mode" }) +export type Mode = typeof Mode.Type + +export const Network = Schema.Literals(["deny", "allow"]).annotate({ identifier: "Config.Sandbox.Network" }) +export type Network = typeof Network.Type + +export const Roots = Schema.Array(Schema.String) + +export class Info extends Schema.Class("Config.Sandbox")({ + enabled: Schema.Boolean.pipe(optional).annotate({ + description: + "Run agent shell commands inside an OS-level sandbox (bubblewrap on Linux, sandbox-exec on macOS). Fails closed when the backend is unavailable (default: false)", + }), + mode: Mode.pipe(optional).annotate({ + description: + 'Filesystem access inside the sandbox: "read-only" mounts everything read-only, "workspace-write" also allows writes to the workspace and temporary directories (default: "workspace-write")', + }), + network: Network.pipe(optional).annotate({ + description: 'Network access inside the sandbox: "deny" blocks it, "allow" permits it (default: "deny")', + }), + writable_roots: Roots.pipe(optional).annotate({ + description: + 'Extra directories a "workspace-write" sandbox may write to, besides the workspace. Relative paths resolve against the workspace. Layers add to each other', + }), + readable_roots: Roots.pipe(optional).annotate({ + description: + "Extra directories mounted read-only inside the sandbox, such as paths the host root does not expose. Relative paths resolve against the workspace. Layers add to each other", + }), +}) {} diff --git a/packages/schema/test/config.test.ts b/packages/schema/test/config.test.ts index 37f9c94e5960..531d6ea8941e 100644 --- a/packages/schema/test/config.test.ts +++ b/packages/schema/test/config.test.ts @@ -85,6 +85,22 @@ describe("Config.Entry", () => { expect(() => decode({ worktree: { directory: " " } })).toThrow() expect(() => decode({ worktree: { directory: false } })).toThrow() }) + test("validates sandbox config and omits it when absent", () => { + const decode = Schema.decodeUnknownSync(Config.Info) + const input = { sandbox: { enabled: true, mode: "read-only", network: "allow" } } as const + expect(Schema.encodeSync(Config.Info)(decode(input))).toEqual(input) + expect(Schema.encodeSync(Config.Info)(decode({ sandbox: {} }))).toEqual({ sandbox: {} }) + expect(Schema.encodeSync(Config.Info)(new Config.Info({ sandbox: undefined }))).not.toHaveProperty("sandbox") + expect(() => decode({ sandbox: { enabled: "yes" } })).toThrow() + expect(() => decode({ sandbox: { mode: "read-write" } })).toThrow() + expect(() => decode({ sandbox: { network: true } })).toThrow() + expect(() => decode({ sandbox: true })).toThrow() + const roots = { sandbox: { enabled: true, writable_roots: ["/a"], readable_roots: ["/b"] } } + expect(Schema.encodeSync(Config.Info)(decode(roots))).toEqual(roots) + expect(() => decode({ sandbox: { writable_roots: "/a" } })).toThrow() + expect(() => decode({ sandbox: { readable_roots: [1] } })).toThrow() + }) + test("round-trips canonical provider IDs without changing config keys", () => { const input = { providers: { "console-anthropic": { canonical: "anthropic" } } } const decoded = Schema.decodeUnknownSync(Config.Info)(input) diff --git a/services/site/src/docs/content/config.mdx b/services/site/src/docs/content/config.mdx index 0cded3ea2dae..a9fcfcc98b29 100644 --- a/services/site/src/docs/content/config.mdx +++ b/services/site/src/docs/content/config.mdx @@ -478,6 +478,71 @@ context. See the [references guide](/references) for shorthand, visibility, and path resolution. +### Shell sandbox + +Run the agent's shell commands inside an OS-level sandbox. It is off by default. + +```jsonc +{ + "sandbox": { + "enabled": true, + "mode": "workspace-write", + "network": "deny", + }, +} +``` + +- `enabled`: turn the sandbox on. Linux uses [bubblewrap](https://github.com/containers/bubblewrap) (`bwrap`) and + macOS uses `sandbox-exec`. Windows has no backend. +- `mode`: `"workspace-write"` (default) mounts the filesystem read-only and lets the command write only to the + project directory and temporary files. `"read-only"` allows no writes outside a private scratch `/tmp` on Linux, + and none at all on macOS. +- `network`: `"deny"` (default) cuts off all network access. `"allow"` shares the host network. +- `writable_roots`: extra directories a `"workspace-write"` sandbox may write to. Relative paths resolve against the + project. The config files `opencode.json`, `opencode.jsonc` and `.opencode` stay read-only inside them too. +- `readable_roots`: extra directories mounted read-only. Relative paths resolve against the project. On macOS the + whole filesystem is already readable, so this has no effect there. + +Sandbox settings merge field by field across config layers, and the security settings only tighten: once any layer +enables the sandbox, selects `"read-only"`, or denies the network, a later layer cannot loosen it. A project file +that sets only `network` therefore cannot drop `enabled` from a lower layer. An invalid `sandbox` block is reported +and keeps the sandbox enabled with the strictest values. + +Existing regular `opencode.json`, `opencode.jsonc` and `.opencode` paths in the workspace are bound read-only, so a +confined command cannot rewrite, replace or delete them. A symlinked config path is not bound, because bubblewrap +refuses to mount on a symlink destination; the link stays ordinary workspace content. A config file that does not +exist is not created by the sandbox itself. + +Sandbox settings are read once per workspace, before its first command runs, and stay fixed for the life of the +process; change them by restarting. That pinning is what stops a confined command from changing its own sandbox: even +if it writes an `opencode.json` or `.opencode` directory inside the workspace, the running process keeps the policy it +started with, so it cannot grant itself network access or extra writable roots on the next command. A file written by +a command is still loaded by the next process, so treat a project's config as trusted input and review it before +restarting. + +`network: "allow"` shares the host network while the whole filesystem stays readable, so anything the command can +read, including credentials in your home directory, can be sent out. Keep the network denied unless a task needs it. +The macOS profile is deny-default, but it permits process execution, Mach lookups and shared memory so ordinary +tools run; only file writes and the network are restricted. + +An enabled sandbox fails closed. If `bwrap` or `sandbox-exec` is missing, the platform has no backend, or the +workspace is remote, the command does not run, and the error says why. Install the backend or set +`sandbox.enabled` to `false`. Commands never fall back to running unconfined. + +The sandbox applies to the `shell` tool, not to other tools, plugins or MCP servers. Because commands cannot reach +the network or write outside the project by default, tools that need either (package installs, writes to your home +directory, or `git` operations that touch files outside the project) fail inside it. + +When a command cannot work in the sandbox, the model can set `sandbox: false` on the `shell` tool call. That +needs the separate `shell_unsandboxed` permission, so approving `shell` commands never approves leaving the +sandbox. It asks by default. A blanket `"*"` allow rule also covers it, so deny it explicitly where that matters: + +```jsonc +{ + "permissions": [{ "action": "shell_unsandboxed", "resource": "*", "effect": "deny" }], +} +``` + ### Worktrees Set the parent directory for new local worktrees. OpenCode appends the requested or generated worktree name. diff --git a/services/site/src/docs/content/permissions.mdx b/services/site/src/docs/content/permissions.mdx index b5acd30b4bb8..f80480be6994 100644 --- a/services/site/src/docs/content/permissions.mdx +++ b/services/site/src/docs/content/permissions.mdx @@ -113,6 +113,7 @@ currently use these actions and resources: | `glob` | Requested glob pattern | | `grep` | Requested regular expression, not the search path | | `shell` | Scanner-produced command string; compound commands may produce several | +| `shell_unsandboxed` | Raw command for a run with `sandbox: false`; defaults to `ask` | | `subagent` | Target agent ID | | `skill` | Skill ID | | `question` | `*` |