From 001428a2d6253e9857a3562537a635561e64d040 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 30 Aug 2026 15:40:02 -0500 Subject: [PATCH] feat(runner): isolate ACPX runtime state (#12397) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - ACPX agents read homes, configuration files, caches, and environment variables. > - Reusing the server user's ambient state would leak unrelated credentials and make recovery nondeterministic. > - Recovery identity already assigns each session a collision-resistant runtime root. > - This pull request materializes that root as a private, bounded sandbox and separates launch-only secrets from persistable configuration. > - The benefit is an isolated runtime boundary before any ACP process is hosted. ## Linked Issues or Issue Description **Agent or provider** The qualified Pi, Claude, and Codex ACPX profiles. **Why this adapter is useful** Each agent expects different home and configuration variables, but none should inherit the Paperclip server user's general home, provider credentials for another agent, or unrelated process secrets. Runtime recovery also needs stable non-secret paths without persisting API keys, OAuth tokens, proxy credentials, or MCP bootstrap tickets. **How the agent is invoked** A later runtime-host pull request will prepare this sandbox, then pass its frozen launch environment and private directories to a verified ACPX command lease. This pull request does not spawn an agent, add dependencies, register an adapter, or alter server execution selection. **Additional context** This pull request is stacked on #12395. It uses that pull request's canonical workspace and collision-resistant runtime binding. All filesystem and environment behavior remains package-local. ## What Changed - Create a normalized session root beneath the private `acpx` runtime namespace. - Create isolated home, configuration, data, cache, state, and agent-specific directories with mode `0700`. - Reject symbolic links, non-directory paths, namespace escapes, and non-normalized roots. - Write the canonical workspace record and Pi trust settings atomically through exclusive no-follow temporary files with mode `0600`. - Give Pi, Claude, and Codex only their qualified home and isolation variables. - Reuse the existing per-agent environment allowlist for launch-time credentials and bound the final environment size. - Return a separate persistence-safe environment containing only stable paths, locale values, and non-secret agent flags. - Explicitly exclude provider credentials, proxy URLs, MCP URLs, and MCP tokens from the persisted projection. - Add table-driven tests for all three agents, file modes, state contents, secret splitting, idempotence, and symbolic-link rejection. ## Verification - Runner TypeScript typecheck — passed. - Runner protocol and TypeScript tests — passed: 12 protocol tests and 413 Vitest tests, including 5 runtime-sandbox tests. - `pnpm -r typecheck` — passed for all applicable workspaces. - `pnpm build` — passed, including runner binary, server, UI, and workspace packages. - Prettier and `git diff --check` — passed. - The diff contains 2 files and does not change `pnpm-lock.yaml`, a workflow, a dependency, a public package export, server selection, or UI behavior. ## Risks The main risks are following attacker-controlled filesystem aliases or persisting a credential under an unexpected variable name. Every created path is checked against its physical parent, the session root must already be absolute and normalized, temporary files use exclusive no-follow opens, and the persisted projection is a positive allowlist rather than a credential-name blacklist. The launch environment remains available only in memory and is bounded before use. ## Model Used OpenAI Codex with GPT-5 and repository tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either linked an existing public item or described the issue in this PR - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal task identifier - [x] I have run the affected tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have documented the runtime isolation and secret-persistence boundary - [ ] All applicable GitHub Actions are green - [ ] Greptile is 5/5 with every actionable comment resolved - [x] I will address all review findings before requesting merge --- .../src/drivers/acpx/runtime-sandbox.test.ts | 177 ++++++++++ .../src/drivers/acpx/runtime-sandbox.ts | 308 ++++++++++++++++++ 2 files changed, 485 insertions(+) create mode 100644 packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts new file mode 100644 index 00000000000..e50f8e2bca8 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.test.ts @@ -0,0 +1,177 @@ +import { + chmod, + lstat, + mkdir, + mkdtemp, + readFile, + rm, + stat, + symlink, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; +import { createAcpxRecoveryBinding } from "./recovery-identity.js"; +import { prepareAcpxRuntimeSandbox } from "./runtime-sandbox.js"; + +const temporaryDirectories: string[] = []; + +afterEach(async () => { + await Promise.all( + temporaryDirectories + .splice(0) + .map((directory) => rm(directory, { force: true, recursive: true })), + ); +}); + +describe("ACPX runtime sandbox", () => { + it.each([ + ["pi", "OPENROUTER_API_KEY", "pi-home"], + ["claude", "ANTHROPIC_API_KEY", "claude-home"], + ["codex", "OPENAI_API_KEY", "codex-home"], + ] as const)( + "creates a private %s filesystem and split environment", + async (agent, credentialName, homeSuffix) => { + const fixture = await sandboxFixture(agent); + const sandbox = await prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent, + environment: { + PATH: process.env.PATH, + [credentialName]: "provider-secret", + UNRELATED_SECRET: "must-not-enter", + HTTPS_PROXY: "https://proxy-user:proxy-password@example.test", + PAPERCLIP_NATIVE_MCP_URL: + "https://mcp.example.test/connect?ticket=secret", + PAPERCLIP_NATIVE_MCP_TOKEN: "native-secret", + }, + }); + + expect(sandbox.agentHomeDirectory).toContain(homeSuffix); + expect(sandbox.launchEnvironment[credentialName]).toBe("provider-secret"); + expect(sandbox.launchEnvironment.HTTPS_PROXY).toContain("proxy-password"); + expect(sandbox.launchEnvironment.UNRELATED_SECRET).toBeUndefined(); + expect( + sandbox.launchEnvironment.PAPERCLIP_NATIVE_MCP_TOKEN, + ).toBeUndefined(); + expect(sandbox.launchEnvironment.HOME).toBe(sandbox.homeDirectory); + expect(sandbox.launchEnvironment.XDG_CONFIG_HOME).toBe( + sandbox.configDirectory, + ); + expect(sandbox.launchEnvironment.XDG_DATA_HOME).toBe( + sandbox.dataDirectory, + ); + expect(sandbox.launchEnvironment.XDG_CACHE_HOME).toBe( + sandbox.cacheDirectory, + ); + expect(Object.isFrozen(sandbox.launchEnvironment)).toBe(true); + expect(sandbox.persistedEnvironment[credentialName]).toBeUndefined(); + expect(sandbox.persistedEnvironment.HTTPS_PROXY).toBeUndefined(); + expect( + sandbox.persistedEnvironment.PAPERCLIP_NATIVE_MCP_URL, + ).toBeUndefined(); + expect( + sandbox.persistedEnvironment.PAPERCLIP_NATIVE_MCP_TOKEN, + ).toBeUndefined(); + expect(sandbox.persistedEnvironment.HOME).toBe(sandbox.homeDirectory); + expect(await readFile(sandbox.workspaceRecordPath, "utf8")).toBe( + `${fixture.binding.workspacePath}\n`, + ); + expect((await lstat(sandbox.root)).isSymbolicLink()).toBe(false); + if (process.platform !== "win32") { + expect((await stat(sandbox.root)).mode & 0o777).toBe(0o700); + expect((await stat(sandbox.workspaceRecordPath)).mode & 0o777).toBe( + 0o600, + ); + } + if (agent === "pi") { + await expect( + readFile(join(sandbox.agentHomeDirectory, "settings.json"), "utf8"), + ).resolves.toContain('"defaultProjectTrust":"never"'); + } + }, + ); + + it("re-prepares and re-synchronizes an existing private sandbox", async () => { + const fixture = await sandboxFixture("claude"); + const first = await prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent: "claude", + environment: { ANTHROPIC_API_KEY: "first" }, + }); + const second = await prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent: "claude", + environment: { ANTHROPIC_API_KEY: "second" }, + }); + + expect(second.root).toBe(first.root); + expect(second.launchEnvironment.ANTHROPIC_API_KEY).toBe("second"); + expect(await readFile(second.workspaceRecordPath, "utf8")).toBe( + `${fixture.binding.workspacePath}\n`, + ); + }); + + it.runIf(process.platform !== "win32")( + "repairs existing directory permissions through its no-follow handle", + async () => { + const fixture = await sandboxFixture("codex"); + const first = await prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent: "codex", + }); + await chmod(first.root, 0o755); + + const second = await prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent: "codex", + }); + + expect(second.root).toBe(first.root); + expect((await stat(second.root)).mode & 0o777).toBe(0o700); + }, + ); + + it.runIf(process.platform !== "win32")( + "rejects a symbolic-link ACPX namespace", + async () => { + const fixture = await sandboxFixture("codex"); + const namespace = dirname(fixture.binding.runtimeRoot); + const outside = join(fixture.root, "outside"); + await mkdir(outside); + await symlink(outside, namespace); + + await expect( + prepareAcpxRuntimeSandbox({ + binding: fixture.binding, + agent: "codex", + }), + ).rejects.toThrow(/real directory|escaped/); + }, + ); +}); + +async function sandboxFixture(agent: "pi" | "claude" | "codex") { + const root = await mkdtemp(join(tmpdir(), "paperclip-acpx-sandbox-")); + temporaryDirectories.push(root); + const workspace = join(root, "workspace"); + const runtimeDirectory = join(root, "runtime"); + await Promise.all([mkdir(workspace), mkdir(runtimeDirectory)]); + const models = { + pi: "openrouter/deepseek/deepseek-v4-flash-0731", + claude: "claude-sonnet-5", + codex: "gpt-5.6-sol", + } as const; + const binding = await createAcpxRecoveryBinding({ + runtimeDirectory, + normalizedSessionId: `sandbox-${agent}`, + workingDirectory: workspace, + profile: resolveQualifiedAcpxProfile(agent, models[agent]), + requestedModel: models[agent], + permissionMode: "approve-reads", + }); + return { root, binding }; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts new file mode 100644 index 00000000000..968ff4dea66 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts @@ -0,0 +1,308 @@ +import { randomBytes } from "node:crypto"; +import { constants, type Stats } from "node:fs"; +import { + lstat, + mkdir, + open, + realpath, + rename, + unlink, + type FileHandle, +} from "node:fs/promises"; +import { + basename, + dirname, + isAbsolute, + join, + relative, + resolve, +} from "node:path"; + +import { createSanitizedAcpxSpawnInput } from "./environment.js"; +import type { QualifiedAcpxAgent } from "./qualified-profiles.js"; +import type { AcpxRecoveryBinding } from "./recovery-identity.js"; + +const PRIVATE_DIRECTORY_MODE = 0o700; +const PRIVATE_FILE_MODE = 0o600; +const MAX_SANDBOX_ENVIRONMENT_BYTES = 512 * 1024; + +export interface AcpxRuntimeSandbox { + root: string; + stateDirectory: string; + homeDirectory: string; + configDirectory: string; + dataDirectory: string; + cacheDirectory: string; + agentHomeDirectory: string; + workspaceRecordPath: string; + launchEnvironment: Readonly; + persistedEnvironment: Readonly; +} + +/** Prepare the private filesystem and environment visible to an ACPX agent. */ +export async function prepareAcpxRuntimeSandbox(input: { + binding: AcpxRecoveryBinding; + agent: QualifiedAcpxAgent; + environment?: NodeJS.ProcessEnv; +}): Promise { + const expectedRoot = input.binding.runtimeRoot; + if (resolve(expectedRoot) !== expectedRoot) { + throw new Error("ACPX runtime root must be an absolute normalized path"); + } + const acpxDirectory = dirname(expectedRoot); + const runtimeDirectory = dirname(acpxDirectory); + if (basename(acpxDirectory) !== "acpx") { + throw new Error("ACPX runtime root is outside its expected namespace"); + } + const physicalRuntimeDirectory = await realpath(runtimeDirectory); + const physicalAcpxDirectory = await ensurePrivateDirectory( + acpxDirectory, + physicalRuntimeDirectory, + ); + const root = await ensurePrivateDirectory( + expectedRoot, + physicalAcpxDirectory, + ); + const stateDirectory = await ensurePrivateDirectory( + join(root, "acpx-state"), + root, + ); + const homeDirectory = await ensurePrivateDirectory(join(root, "home"), root); + const configDirectory = await ensurePrivateDirectory( + join(root, "config"), + root, + ); + const dataDirectory = await ensurePrivateDirectory(join(root, "data"), root); + const cacheDirectory = await ensurePrivateDirectory( + join(root, "cache"), + root, + ); + const agentHomeDirectory = await ensurePrivateDirectory( + join(root, `${input.agent}-home`), + root, + ); + const workspaceRecordPath = join(root, "workspace"); + await writePrivateFile( + workspaceRecordPath, + `${input.binding.workspacePath}\n`, + ); + if (input.agent === "pi") { + await writePrivateFile( + join(agentHomeDirectory, "settings.json"), + `${JSON.stringify({ + quietStartup: true, + defaultProjectTrust: "never", + enableInstallTelemetry: false, + })}\n`, + ); + } + + const sanitizedSpawnInput = createSanitizedAcpxSpawnInput( + input.environment, + input.agent, + ); + // The sanitizer deliberately returns an opaque, frozen launch boundary. + // Build the sandbox-owned mutable copy only from that projected environment + // before adding paths that were created and validated above. + const launchEnvironment: NodeJS.ProcessEnv = { + ...sanitizedSpawnInput.env, + }; + Object.assign(launchEnvironment, { + HOME: homeDirectory, + XDG_CONFIG_HOME: configDirectory, + XDG_DATA_HOME: dataDirectory, + XDG_CACHE_HOME: cacheDirectory, + PAPERCLIP_ACPX_PROFILE: input.agent, + PAPERCLIP_ACPX_ISOLATED_CONTEXT: "1", + ...(input.agent === "pi" + ? { + PI_CODING_AGENT_DIR: agentHomeDirectory, + PI_SKIP_VERSION_CHECK: "1", + PI_TELEMETRY: "0", + } + : {}), + ...(input.agent === "claude" + ? { CLAUDE_CONFIG_DIR: agentHomeDirectory } + : {}), + ...(input.agent === "codex" + ? { + CODEX_HOME: agentHomeDirectory, + NO_BROWSER: "1", + ...(launchEnvironment.CODEX_API_KEY || + launchEnvironment.OPENAI_API_KEY + ? { DEFAULT_AUTH_REQUEST: JSON.stringify({ methodId: "api-key" }) } + : {}), + } + : {}), + }); + validateEnvironmentSize(launchEnvironment); + const persistedEnvironment = Object.fromEntries( + Object.entries(launchEnvironment).filter( + ([name, value]) => + typeof value === "string" && isPersistableEnvironmentName(name), + ), + ); + return { + root, + stateDirectory, + homeDirectory, + configDirectory, + dataDirectory, + cacheDirectory, + agentHomeDirectory, + workspaceRecordPath, + launchEnvironment: Object.freeze({ ...launchEnvironment }), + persistedEnvironment: Object.freeze(persistedEnvironment), + }; +} + +async function ensurePrivateDirectory( + directory: string, + physicalParent: string, +): Promise { + try { + await mkdir(directory, { mode: PRIVATE_DIRECTORY_MODE }); + } catch (error) { + if (errorCode(error) !== "EEXIST") throw error; + } + let handle: FileHandle; + try { + handle = await open( + directory, + constants.O_RDONLY | + (constants.O_DIRECTORY ?? 0) | + (constants.O_NOFOLLOW ?? 0), + ); + } catch { + throw new Error("ACPX sandbox path must be a real directory"); + } + let physical: string; + try { + const opened = await handle.stat(); + const entry = await lstat(directory); + if ( + !opened.isDirectory() || + entry.isSymbolicLink() || + !entry.isDirectory() || + !sameFile(entry, opened) + ) { + throw new Error("ACPX sandbox path must be a real directory"); + } + // Apply permissions to the inode that was opened without following links. + // A directory-entry swap can therefore never redirect chmod to its target. + await handle.chmod(PRIVATE_DIRECTORY_MODE); + physical = await realpath(directory); + const verifiedEntry = await lstat(directory); + if (!sameFile(verifiedEntry, opened)) { + throw new Error("ACPX sandbox directory changed during preparation"); + } + if (!isInside(physicalParent, physical)) { + throw new Error("ACPX sandbox directory escaped its private parent"); + } + // Persist the child inode before the directory entry that names it. + if (process.platform !== "win32") await handle.sync(); + } finally { + await handle.close(); + } + // Sync the parent even during recovery: an earlier process may have created + // the entry and crashed before making that mkdir durable. + await syncDirectory(physicalParent); + return physical; +} + +async function writePrivateFile( + filePath: string, + value: string, +): Promise { + const bytes = Buffer.from(value, "utf8"); + if (bytes.length < 1 || bytes.length > 64 * 1024) { + throw new Error("ACPX sandbox file exceeds its bounded size"); + } + const temporaryPath = `${filePath}.tmp-${randomBytes(12).toString("hex")}`; + let handle: FileHandle; + try { + handle = await open( + temporaryPath, + constants.O_WRONLY | + constants.O_CREAT | + constants.O_EXCL | + (constants.O_NOFOLLOW ?? 0), + PRIVATE_FILE_MODE, + ); + } catch { + throw new Error("ACPX sandbox file could not be opened without links"); + } + try { + const metadata = await handle.stat(); + if (!metadata.isFile()) throw new Error("ACPX sandbox path is not a file"); + await handle.chmod(PRIVATE_FILE_MODE); + await handle.writeFile(bytes); + await handle.sync(); + await handle.close(); + await rename(temporaryPath, filePath); + await syncDirectory(dirname(filePath)); + return; + } finally { + bytes.fill(0); + await handle.close().catch(() => undefined); + await unlink(temporaryPath).catch(() => undefined); + } +} + +async function syncDirectory(directory: string): Promise { + if (process.platform === "win32") return; + const handle = await open( + directory, + constants.O_RDONLY | (constants.O_DIRECTORY ?? 0), + ); + try { + await handle.sync(); + } finally { + await handle.close(); + } +} + +function validateEnvironmentSize(environment: NodeJS.ProcessEnv): void { + const bytes = Object.entries(environment).reduce( + (total, [name, value]) => + total + Buffer.byteLength(name) + Buffer.byteLength(value ?? ""), + 0, + ); + if (bytes > MAX_SANDBOX_ENVIRONMENT_BYTES) { + throw new Error("ACPX launch environment exceeds its bounded size"); + } +} + +function isPersistableEnvironmentName(name: string): boolean { + return ( + /^(?:PATH|LANG|LANGUAGE|TZ|TMPDIR|TEMP|TMP|LC_[A-Z0-9_]{1,32})$/.test( + name, + ) || + /^(?:HOME|XDG_CONFIG_HOME|XDG_DATA_HOME|XDG_CACHE_HOME)$/.test(name) || + /^(?:PAPERCLIP_ACPX_PROFILE|PAPERCLIP_ACPX_ISOLATED_CONTEXT)$/.test(name) || + /^(?:PI_CODING_AGENT_DIR|PI_SKIP_VERSION_CHECK|PI_TELEMETRY)$/.test(name) || + /^(?:CLAUDE_CONFIG_DIR|CODEX_HOME|NO_BROWSER|DEFAULT_AUTH_REQUEST)$/.test( + name, + ) + ); +} + +function isInside(parent: string, child: string): boolean { + const childPath = relative(parent, child); + return ( + childPath.length > 0 && + childPath !== ".." && + !childPath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) && + !isAbsolute(childPath) + ); +} + +function sameFile(left: Stats, right: Stats): boolean { + return left.dev === right.dev && left.ino === right.ino; +} + +function errorCode(error: unknown): string | null { + return typeof error === "object" && error !== null && "code" in error + ? String((error as { code?: unknown }).code) + : null; +}