diff --git a/packages/paperclip-runner/src/control-plane/runner-confinement.test.ts b/packages/paperclip-runner/src/control-plane/runner-confinement.test.ts index 747a2f44be0..fa55882e82f 100644 --- a/packages/paperclip-runner/src/control-plane/runner-confinement.test.ts +++ b/packages/paperclip-runner/src/control-plane/runner-confinement.test.ts @@ -8,6 +8,7 @@ import { spawnRunner, waitForProcess } from "./durable-prp-control-plane.js"; import { RUNNER_CONFINEMENT_UNAVAILABLE, confineRunnerLaunch, + ensureRunnerConfinementProbe, instanceSessionStatePaths, landlockTemporaryConflict, resetRunnerConfinementAvailability, @@ -124,6 +125,25 @@ describe("runnerConfinementUnavailableReason", () => { }); }); +describe("ensureRunnerConfinementProbe", () => { + it.skipIf(process.platform !== "darwin" && process.platform !== "linux")("probes without blocking the event loop and shares one probe", async () => { + resetRunnerConfinementAvailability(); + let ticks = 0; + const timer = setInterval(() => { ticks += 1; }, 0); + try { + const first = ensureRunnerConfinementProbe(); + expect(ensureRunnerConfinementProbe()).toBe(first); + const reason = await first; + // The event loop kept running while the probe process ran. + expect(ticks).toBeGreaterThan(0); + // A later launch reads the cached result without probing again. + expect(runnerConfinementUnavailableReason()).toBe(reason); + } finally { + clearInterval(timer); + } + }); +}); + describe("confineRunnerLaunch", () => { it("launches unconfined when turned off", () => { expect(confineRunnerLaunch({ policy: { mode: "off", instanceRoot: root }, command: "/bin/x", args: [], environment: {} })).toBeNull(); @@ -176,6 +196,8 @@ r() { if cat "$2" >/dev/null 2>&1; then echo "$1=readable"; else echo "$1=denied if mkdir -p "$state/nested/dir" 2>/dev/null; then echo ownStateMkdirP=allowed; else echo ownStateMkdirP=denied; fi if ls "$INSTANCE/runtime/paperclip-runner/durable-sessions" >/dev/null 2>&1; then echo sessionListing=listable; else echo sessionListing=denied; fi r ownOpencodeSession "$INSTANCE/runtime/paperclip-runner/opencode/own-session/config.json" + saved="$INSTANCE/runtime/paperclip-runner/durable-sessions/own-scope/opencode/own-session/data/opencode/opencode.db" + if cat "$saved" >/dev/null 2>&1 && echo resumed >> "$saved" 2>/dev/null; then echo savedProviderState=usable; else echo savedProviderState=unusable; fi if [ -n "$PAPERCLIP_PROVIDER_TRACE_PATH" ]; then if echo frame >> "$PAPERCLIP_PROVIDER_TRACE_PATH" 2>/dev/null; then echo ownNestedTrace=writable; else echo ownNestedTrace=denied; fi; fi if [ -n "$DB_PORT" ]; then if nc -z -w 2 127.0.0.1 "$DB_PORT" >/dev/null 2>&1; then echo database=reachable; else echo database=blocked; fi; fi } > "$state/probe.txt" @@ -201,6 +223,8 @@ describe.skipIf(!confinementAvailable)("a confined local runnerd launch", () => writeFixture(paths.environmentFile); writeFixture(join(instance, "companies", "c", "agents", "a", "notes.md"), "shared\n"); writeFixture(join(instance, "companies", "other", "agents", "b", "notes.md")); + // Provider state saved by an earlier launch (or an earlier release) of this session. + writeFixture(join(paths.durableSessions, "own-scope", "opencode", "own-session", "data", "opencode", "opencode.db"), "saved\n"); const ownState = join(paths.durableSessions, "own-scope", "runner"); mkdirSync(ownState, { recursive: true, mode: 0o700 }); const runnerd = join(root, "paperclip-runnerd"); @@ -258,6 +282,7 @@ describe.skipIf(!confinementAvailable)("a confined local runnerd launch", () => sessionRootStat: "allowed", ownStateMkdirP: "allowed", ownNestedTrace: "writable", + savedProviderState: "usable", ownOpencodeSession: "readable", }); }, 60_000); diff --git a/packages/paperclip-runner/src/control-plane/runner-confinement.ts b/packages/paperclip-runner/src/control-plane/runner-confinement.ts index 4b387640eb3..1d4328c1ea3 100644 --- a/packages/paperclip-runner/src/control-plane/runner-confinement.ts +++ b/packages/paperclip-runner/src/control-plane/runner-confinement.ts @@ -1,4 +1,4 @@ -import { execFileSync } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, realpathSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; @@ -353,50 +353,114 @@ export function landlockInvocation(scope: RunnerConfinementScope, python: string export const RUNNER_CONFINEMENT_PROBE_RETRY_MS = 60_000; const availability = new Map(); +type ProbePlan = + | { reason: string } + | { command: string; args: string[]; timeout: number; cleanup?: () => void }; + /** - * Proves once per process that this host can apply confinement. A server that - * already runs inside a sandbox cannot nest one, so the probe uses the same - * mechanism as a launch. Returns null when available, or the reason. + * The probe uses the same mechanism as a launch, so a server that already runs + * inside a sandbox (which cannot nest one) is detected. */ -export function runnerConfinementUnavailableReason(platform: NodeJS.Platform = process.platform): string | null { - const cached = availability.get(platform); - if (cached !== undefined && (cached.retryAt === null || Date.now() < cached.retryAt)) return cached.reason; - let reason: string | null = null; +function probePlan(platform: NodeJS.Platform): ProbePlan { + if (platform === "darwin") { + if (!existsSync("/usr/bin/sandbox-exec")) return { reason: "sandbox-exec is not installed" }; + return { command: "/usr/bin/sandbox-exec", args: ["-p", "(version 1)(allow default)", "/usr/bin/true"], timeout: 10_000 }; + } + if (platform !== "linux") return { reason: `confinement is not supported on ${platform}` }; + const python = pythonExecutable(); + if (!python) return { reason: "python3 is not installed" }; + // Apply a real domain shaped like a launch: a hidden directory with an + // exposed child. A host that passes runs every launch fail-closed. + const probeRoot = mkdtempSync(join(tmpdir(), "paperclip-confinement-probe-")); + mkdirSync(join(probeRoot, "hidden", "own"), { recursive: true }); + return { + command: python, + args: ["-I", "-S", "-c", LANDLOCK_HELPER, "--required", + "--hide", join(probeRoot, "hidden"), "--expose", join(probeRoot, "hidden", "own"), + "--", "/bin/sh", "-c", 'ls "$1" >/dev/null 2>&1 && exit 3; ls "$2" >/dev/null', "sh", join(probeRoot, "hidden"), join(probeRoot, "hidden", "own")], + timeout: 30_000, + cleanup: () => rmSync(probeRoot, { recursive: true, force: true }), + }; +} + +function recordProbe(platform: NodeJS.Platform, error: unknown, reason: string | null = null) { let transient = false; - try { - if (platform === "darwin") { - if (!existsSync("/usr/bin/sandbox-exec")) reason = "sandbox-exec is not installed"; - else execFileSync("/usr/bin/sandbox-exec", ["-p", "(version 1)(allow default)", "/usr/bin/true"], { stdio: "ignore", timeout: 10_000 }); - } else if (platform === "linux") { - const python = pythonExecutable(); - if (!python) reason = "python3 is not installed"; - else { - // Apply a real domain shaped like a launch: a hidden directory with an - // exposed child. A host that passes runs every launch fail-closed. - const probeRoot = mkdtempSync(join(tmpdir(), "paperclip-confinement-probe-")); - try { - mkdirSync(join(probeRoot, "hidden", "own"), { recursive: true }); - execFileSync(python, ["-I", "-S", "-c", LANDLOCK_HELPER, "--required", - "--hide", join(probeRoot, "hidden"), "--expose", join(probeRoot, "hidden", "own"), - "--", "/bin/sh", "-c", 'ls "$1" >/dev/null 2>&1 && exit 3; ls "$2" >/dev/null', "sh", join(probeRoot, "hidden"), join(probeRoot, "hidden", "own")], - { stdio: "ignore", timeout: 30_000 }); - } finally { - rmSync(probeRoot, { recursive: true, force: true }); - } - } - } else { - reason = `confinement is not supported on ${platform}`; - } - } catch (error) { + if (error !== undefined) { reason = `confinement probe failed: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`; // A probe that ran and exited non-zero is a definitive answer about this host. // Anything else (a timeout, a spawn or disk error) may pass on a later launch. - transient = !(typeof (error as { status?: unknown }).status === "number") || (error as { signal?: unknown }).signal != null; + const failure = error as { status?: unknown; code?: unknown; signal?: unknown; killed?: unknown }; + const exited = typeof failure.status === "number" || typeof failure.code === "number"; + transient = !exited || failure.signal != null || failure.killed === true; } availability.set(platform, { reason, retryAt: transient ? Date.now() + RUNNER_CONFINEMENT_PROBE_RETRY_MS : null }); return reason; } +function cachedReason(platform: NodeJS.Platform): { reason: string | null } | null { + const cached = availability.get(platform); + return cached !== undefined && (cached.retryAt === null || Date.now() < cached.retryAt) ? { reason: cached.reason } : null; +} + +const pendingProbes = new Map>(); + +/** + * Proves, without blocking the event loop, that this host can apply + * confinement. Concurrent launches share one probe. Launch paths await this + * before `spawnRunner`, so the launch itself reads the cached result. + */ +export function ensureRunnerConfinementProbe(platform: NodeJS.Platform = process.platform): Promise { + const cached = cachedReason(platform); + if (cached) return Promise.resolve(cached.reason); + const pending = pendingProbes.get(platform); + if (pending) return pending; + const probe = (async () => { + let plan: ProbePlan; + try { + plan = probePlan(platform); + } catch (error) { + return recordProbe(platform, error); + } + if ("reason" in plan) return recordProbe(platform, undefined, plan.reason); + try { + await new Promise((resolveProbe, rejectProbe) => { + execFile(plan.command, plan.args, { timeout: plan.timeout }, (error) => (error ? rejectProbe(error) : resolveProbe())); + }); + return recordProbe(platform, undefined, null); + } catch (error) { + return recordProbe(platform, error); + } finally { + plan.cleanup?.(); + } + })().finally(() => pendingProbes.delete(platform)); + pendingProbes.set(platform, probe); + return probe; +} + +/** + * The cached probe result, or a synchronous probe for a caller that did not + * await `ensureRunnerConfinementProbe`. Returns null when available, or the reason. + */ +export function runnerConfinementUnavailableReason(platform: NodeJS.Platform = process.platform): string | null { + const cached = cachedReason(platform); + if (cached) return cached.reason; + let plan: ProbePlan; + try { + plan = probePlan(platform); + } catch (error) { + return recordProbe(platform, error); + } + if ("reason" in plan) return recordProbe(platform, undefined, plan.reason); + try { + execFileSync(plan.command, plan.args, { stdio: "ignore", timeout: plan.timeout }); + return recordProbe(platform, undefined, null); + } catch (error) { + return recordProbe(platform, error); + } finally { + plan.cleanup?.(); + } +} + /** Test seam: forget probe results. */ export function resetRunnerConfinementAvailability() { availability.clear(); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 8fd5f278fda..e322c0065d1 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -87,6 +87,7 @@ import { type RunnerProcessConnection, type DurablePrpControlPlaneOptions, } from "../control-plane/durable-prp-control-plane.js"; +import { ensureRunnerConfinementProbe } from "../control-plane/runner-confinement.js"; import { type QualifiedAcpxAgent, } from "../drivers/acpx/qualified-profiles.js"; @@ -5684,6 +5685,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return operation; } + /** A local confined launch proves the host first without blocking the event loop. */ + async #awaitConfinementProbe(): Promise { + const confinement = this.options.runnerConfinement; + if (!confinement || confinement.mode === "off" || this.options.runnerProcessLauncher) return; + await ensureRunnerConfinementProbe(); + } + async #refreshBootstrapTicket(core: DurablePrpControlPlane): Promise { this.#assertStartupOpen(); const ticket = core.issueBootstrapTicket(RUNNER_BOOTSTRAP_TICKET_TTL_MS); @@ -6583,6 +6591,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { const bootstrapTicket = core.issueBootstrapTicket(RUNNER_BOOTSTRAP_TICKET_TTL_MS); await core.flushCheckpoint(); this.#assertStartupOpen(); + // Prove confinement off the event loop; the launch below reads the cached result. + if (prepared.runnerOpenCodeLaunchProfile) await this.#awaitConfinementProbe(); this.#startupSteps?.begin("runner.process.launch"); const handle = spawnRunner({ connection: registration?.connection ?? { @@ -7449,7 +7459,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { : Math.min(this.#waitNow() + 30_000, this.#onWaitClock(this.#sourceAttachmentDeadline)); // An adopted runner is already live: no launch step (a launch span means a fresh process). if (adoptedRunner) this.#startupSteps?.end(); - else this.#startupSteps?.begin("runner.process.launch"); + else { + // Prove confinement off the event loop; the launch below reads the cached result. + if (runnerOpenCodeLaunchProfile) await this.#awaitConfinementProbe(); + this.#startupSteps?.begin("runner.process.launch"); + } const handle = adoptedRunner ? null : spawnRunner({ diff --git a/server/src/services/native-runtime/local-runner-confinement.test.ts b/server/src/services/native-runtime/local-runner-confinement.test.ts index 1fb55f97362..5cb02b5a18f 100644 --- a/server/src/services/native-runtime/local-runner-confinement.test.ts +++ b/server/src/services/native-runtime/local-runner-confinement.test.ts @@ -38,9 +38,10 @@ describe("localRunnerConfinementPolicy", () => { vi.stubEnv("PAPERCLIP_STORAGE_PROVIDER", "local_disk"); vi.stubEnv("PAPERCLIP_STORAGE_LOCAL_DIR", "/data/storage"); vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", "/keys/master.key"); + vi.stubEnv("PAPERCLIP_CONFIG", "/etc/paperclip/config.json"); const policy = localRunnerConfinementPolicy("company-1"); expect(policy.sessionStateRoots).toEqual(["/data/runner-state"]); - expect(policy.privatePaths).toEqual(expect.arrayContaining(["/data/storage", "/keys/master.key"])); + expect(policy.privatePaths).toEqual(expect.arrayContaining(["/data/storage", "/keys/master.key", "/etc/paperclip/config.json", "/etc/paperclip/.env"])); }); it("follows the operator's confinement mode and an external database", () => { diff --git a/server/src/services/native-runtime/local-runner-confinement.ts b/server/src/services/native-runtime/local-runner-confinement.ts index 3b9ca3e878f..d7729e53bc2 100644 --- a/server/src/services/native-runtime/local-runner-confinement.ts +++ b/server/src/services/native-runtime/local-runner-confinement.ts @@ -1,6 +1,8 @@ // Type-only: the server loads this module at startup, before the runner package is built. import type { RunnerConfinementMode, RunnerConfinementPolicy } from "@paperclipai/paperclip-runner/live"; +import { existsSync } from "node:fs"; import { resolve } from "node:path"; +import { resolvePaperclipConfigPath, resolvePaperclipEnvPath } from "../../paths.js"; import { resolvePaperclipInstanceRoot } from "../../home-paths.js"; import { resolveMasterKeyFilePath } from "../../secrets/local-encrypted-provider.js"; import { loadStorageConfig } from "../../storage/config.js"; @@ -40,9 +42,15 @@ export function resolveLocalRunnerConfinementMode(env: NodeJS.ProcessEnv = proce function privatePaths(env: NodeJS.ProcessEnv) { if (configuredPrivatePaths === null) { const storage = loadStorageConfig(undefined, env); + // The configuration and environment files the server read can hold + // instance-wide credentials (provider keys, database connection strings). + const workingDirectoryEnv = resolve(process.cwd(), ".env"); configuredPrivatePaths = [ ...(storage.storageProvider === "local_disk" ? [storage.storageLocalDiskBaseDir] : []), resolveMasterKeyFilePath(env), + resolvePaperclipConfigPath(), + resolvePaperclipEnvPath(), + ...(existsSync(workingDirectoryEnv) ? [workingDirectoryEnv] : []), ].map((path) => resolve(path)); } return [...configuredPrivatePaths, ...(embeddedDatabase ? [resolve(embeddedDatabase.dataDir)] : [])];