mirror of
https://github.com/waybarrios/opencode-power-pack.git
synced 2026-11-18 18:03:43 +00:00
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.
This commit is contained in:
+34
-15
@@ -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,
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user