@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -5
- package/dist/context/file-spill.d.ts +11 -1
- package/dist/context/file-spill.js +23 -8
- package/dist/context/file-spill.js.map +1 -1
- package/dist/context/spill.d.ts +5 -1
- package/dist/context/spill.js +6 -2
- package/dist/context/spill.js.map +1 -1
- package/dist/credentials/allowlist.d.ts +22 -2
- package/dist/credentials/allowlist.js +74 -17
- package/dist/credentials/allowlist.js.map +1 -1
- package/dist/credentials/egress-policy.d.ts +69 -0
- package/dist/credentials/egress-policy.js +170 -0
- package/dist/credentials/egress-policy.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +13 -1
- package/dist/credentials/egress-proxy.js +179 -11
- package/dist/credentials/egress-proxy.js.map +1 -1
- package/dist/credentials/git-route.d.ts +68 -0
- package/dist/credentials/git-route.js +288 -0
- package/dist/credentials/git-route.js.map +1 -0
- package/dist/credentials/index.d.ts +5 -1
- package/dist/credentials/index.js +5 -1
- package/dist/credentials/index.js.map +1 -1
- package/dist/credentials/scrub.d.ts +7 -0
- package/dist/credentials/scrub.js +22 -0
- package/dist/credentials/scrub.js.map +1 -1
- package/dist/errors.d.ts +9 -5
- package/dist/errors.js +8 -4
- package/dist/errors.js.map +1 -1
- package/dist/sandbox/base.d.ts +11 -1
- package/dist/sandbox/base.js +14 -0
- package/dist/sandbox/base.js.map +1 -1
- package/dist/sandbox/docker/index.d.ts +8 -2
- package/dist/sandbox/docker/index.js +63 -14
- package/dist/sandbox/docker/index.js.map +1 -1
- package/dist/sandbox/errors.d.ts +30 -2
- package/dist/sandbox/errors.js +36 -1
- package/dist/sandbox/errors.js.map +1 -1
- package/dist/sandbox/host-files.d.ts +2 -0
- package/dist/sandbox/host-files.js +10 -0
- package/dist/sandbox/host-files.js.map +1 -1
- package/dist/sandbox/index.d.ts +6 -4
- package/dist/sandbox/index.js +5 -3
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/policy.d.ts +49 -0
- package/dist/sandbox/policy.js +149 -0
- package/dist/sandbox/policy.js.map +1 -0
- package/dist/sandbox/process.js +1 -1
- package/dist/sandbox/process.js.map +1 -1
- package/dist/sandbox/srt/index.d.ts +5 -2
- package/dist/sandbox/srt/index.js +27 -8
- package/dist/sandbox/srt/index.js.map +1 -1
- package/dist/sandbox/srt/settings.d.ts +17 -5
- package/dist/sandbox/srt/settings.js +53 -0
- package/dist/sandbox/srt/settings.js.map +1 -1
- package/dist/sandbox/types.d.ts +41 -4
- package/dist/sandbox/types.js.map +1 -1
- package/dist/testing/fake-sandbox.d.ts +21 -3
- package/dist/testing/fake-sandbox.js +157 -8
- package/dist/testing/fake-sandbox.js.map +1 -1
- package/dist/testing/sandbox-conformance.js +108 -1
- package/dist/testing/sandbox-conformance.js.map +1 -1
- package/dist/tools/builtins/bash.d.ts +9 -0
- package/dist/tools/builtins/bash.js +75 -0
- package/dist/tools/builtins/bash.js.map +1 -0
- package/dist/tools/builtins/builtins.d.ts +38 -0
- package/dist/tools/builtins/builtins.js +48 -0
- package/dist/tools/builtins/builtins.js.map +1 -0
- package/dist/tools/builtins/descriptions.d.ts +69 -0
- package/dist/tools/builtins/descriptions.js +94 -0
- package/dist/tools/builtins/descriptions.js.map +1 -0
- package/dist/tools/builtins/fetch.d.ts +12 -0
- package/dist/tools/builtins/fetch.js +157 -0
- package/dist/tools/builtins/fetch.js.map +1 -0
- package/dist/tools/builtins/files.d.ts +27 -0
- package/dist/tools/builtins/files.js +274 -0
- package/dist/tools/builtins/files.js.map +1 -0
- package/dist/tools/builtins/paths.d.ts +30 -0
- package/dist/tools/builtins/paths.js +62 -0
- package/dist/tools/builtins/paths.js.map +1 -0
- package/dist/tools/builtins/results.d.ts +15 -0
- package/dist/tools/builtins/results.js +31 -0
- package/dist/tools/builtins/results.js.map +1 -0
- package/dist/tools/builtins/search.d.ts +18 -0
- package/dist/tools/builtins/search.js +217 -0
- package/dist/tools/builtins/search.js.map +1 -0
- package/dist/tools/index.d.ts +6 -2
- package/dist/tools/index.js +5 -2
- package/dist/tools/index.js.map +1 -1
- package/llms.txt +34 -0
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fake-sandbox.js","sourceRoot":"","sources":["../../src/testing/fake-sandbox.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAmCnF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB,CAAC,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;AAEvH,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,SAAS,CAAC,IAAY;IAC7B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG;YAAE,SAAS;QAC1C,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;;YAC1B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAC/B,CAAC;AAED,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,IAAY,EAAW,EAAE;IACrD,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC7B,OAAO,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,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, for tests of the code that runs on one. It enforces the policy it is given, so\n * a test can see a denial, and it records every `exec`, but it confines no process and runs no program: it understands\n * a few commands, listed at `FAKE_COMMANDS`. It is portable, so a test can use it on every target.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxDeniedError, SandboxUnavailableError } from \"../sandbox/errors.js\";\nimport type {\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n WorkspaceManifest,\n} from \"../sandbox/types.js\";\n\n/** The options of `fakeSandbox()`. */\nexport interface FakeSandboxOptions {\n /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */\n readonly unavailable?: string;\n}\n\n/** One command the fake received, with what the caller passed. */\nexport interface RecordedExec {\n readonly command: readonly string[];\n readonly cwd: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n readonly timeoutMs: number | undefined;\n}\n\n/** A fake backend, and what it has seen. */\nexport interface FakeSandboxClient extends SandboxClient {\n /** Every command run through any sandbox this client provisioned, in order. */\n readonly execs: readonly RecordedExec[];\n /** The files of the latest sandbox, by absolute path. */\n files(): ReadonlyMap<string, Uint8Array>;\n /** Makes `link` an absolute path that stands for `target` in the latest sandbox, as a symlink does. */\n symlink(link: string, target: string): void;\n}\n\n/**\n * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the\n * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,\n * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and\n * `net-probe <host>` reaches a host only if the policy allows it. Any other command exits with 127.\n */\nexport const FAKE_COMMANDS: readonly string[] = [\"echo\", \"env\", \"cat\", \"write\", \"true\", \"false\", \"sleep\", \"net-probe\"];\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n\nfunction normalize(path: string): string {\n const parts: string[] = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nconst within = (path: string, root: string): boolean => {\n const base = normalize(root);\n return base === \"/\" || path === base || path.startsWith(`${base}/`);\n};\n\nclass FakeSandbox implements Sandbox {\n private disposed = false;\n // What ends each command still running, so `dispose()` can reject them as a real backend does.\n private readonly running = new Set<() => void>();\n readonly store = new Map<string, Uint8Array>();\n readonly links = new Map<string, string>();\n private readonly root: string;\n private readonly policy: SandboxPolicy;\n private readonly log: RecordedExec[];\n\n constructor(root: string, policy: SandboxPolicy, log: RecordedExec[]) {\n this.root = normalize(root);\n this.policy = policy;\n this.log = log;\n }\n\n private live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */\n resolve(path: string, base = this.root): string {\n const tidy = normalize(path.startsWith(\"/\") ? path : `${base}/${path}`);\n for (const [link, target] of this.links) {\n if (tidy === link || tidy.startsWith(`${link}/`)) return normalize(`${target}${tidy.slice(link.length)}`);\n }\n return tidy;\n }\n\n private readDenial(path: string): SandboxDenial | undefined {\n const roots = [...this.policy.readRoots, ...this.policy.writeRoots];\n if (roots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_read\", target: path, reason: \"the path is outside the read roots\" };\n }\n\n private writeDenial(path: string): SandboxDenial | undefined {\n if (this.policy.writeRoots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_write\", target: path, reason: \"the path is outside the write roots\" };\n }\n\n private networkDenial(host: string): SandboxDenial | undefined {\n const { allow, deny } = this.policy.network;\n if (allow.includes(host) && !deny.includes(host)) return undefined;\n return { kind: \"network\", target: host, reason: \"the host is not on the network allowlist\" };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n const data = this.store.get(target);\n if (data === undefined) throw new HarnessError(\"sandbox_not_found\", `no such file: ${target}`);\n return data.slice();\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n this.store.set(target, data.slice());\n }\n\n /** Writes a file without a policy check, for the manifest's own files. */\n seed(path: string, data: Uint8Array): void {\n this.store.set(this.resolve(path), data.slice());\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n this.live();\n if (!Array.isArray(command) || command.length === 0) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n options.signal.throwIfAborted();\n const cwd = this.resolve(options.cwd ?? \".\");\n const denial = this.readDenial(cwd);\n if (denial) return { denied: denial };\n this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });\n const [name = \"\", ...args] = command;\n return this.run(name, args, options);\n }\n\n private async run(name: string, args: string[], options: ExecOptions): Promise<ExecResult> {\n const ok = (stdout = \"\"): ExecResult => ({ exitCode: 0, stdout, stderr: \"\" });\n switch (name) {\n case \"echo\":\n return ok(`${args.join(\" \")}\\n`);\n case \"env\":\n return ok(\n Object.entries(options.env)\n .map(([key, value]) => `${key}=${value}\\n`)\n .join(\"\"),\n );\n case \"true\":\n return ok();\n case \"false\":\n return { exitCode: 1, stdout: \"\", stderr: \"\" };\n case \"cat\":\n return this.cat(args[0] ?? \"\");\n case \"write\":\n return this.writeCommand(args[0] ?? \"\", args.slice(1).join(\" \"));\n case \"net-probe\": {\n const host = args[0] ?? \"\";\n const denial = this.networkDenial(host);\n return denial ? { denied: denial } : ok(`reached ${host}\\n`);\n }\n case \"sleep\":\n return this.sleep(Number(args[0] ?? 0) * 1000, options);\n default:\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${name}\\n` };\n }\n }\n\n private cat(path: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n return data === undefined\n ? { exitCode: 1, stdout: \"\", stderr: `no such file: ${target}\\n` }\n : { exitCode: 0, stdout: DECODER.decode(data), stderr: \"\" };\n }\n\n private writeCommand(path: string, text: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) return { denied: denial };\n this.store.set(target, ENCODER.encode(text));\n return { exitCode: 0, stdout: \"\", stderr: \"\" };\n }\n\n private sleep(ms: number, options: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const done = (result: ExecResult) => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n this.running.delete(disposed);\n resolve(result);\n };\n const aborted = () => {\n clearTimeout(timer);\n this.running.delete(disposed);\n reject(options.signal.reason);\n };\n const disposed = () => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\"));\n };\n this.running.add(disposed);\n const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;\n const timer = setTimeout(() => {\n const timedOut = stopAt < ms;\n done({ exitCode: timedOut ? 124 : 0, stdout: \"\", stderr: timedOut ? `timed out after ${stopAt} ms\\n` : \"\" });\n }, stopAt);\n options.signal.addEventListener(\"abort\", aborted, { once: true });\n });\n }\n\n async dispose(): Promise<void> {\n this.disposed = true;\n for (const stop of [...this.running]) stop();\n this.running.clear();\n }\n}\n\n/**\n * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the\n * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none.\n */\nexport function fakeSandbox(options: FakeSandboxOptions = {}): FakeSandboxClient {\n const execs: RecordedExec[] = [];\n let latest: FakeSandbox | undefined;\n return {\n tier: \"os\",\n stops: [\"mistakes\", \"exfiltration\"],\n execs,\n files: () => latest?.store ?? new Map(),\n symlink(link: string, target: string) {\n latest?.links.set(normalize(link), normalize(target));\n },\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy) {\n if (options.unavailable !== undefined) throw new SandboxUnavailableError(\"fake\", options.unavailable);\n const sandbox = new FakeSandbox(manifest.root, policy, execs);\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n sandbox.seed(path, typeof data === \"string\" ? ENCODER.encode(data) : data);\n }\n latest = sandbox;\n return sandbox;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fake-sandbox.js","sourceRoot":"","sources":["../../src/testing/fake-sandbox.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AA2CrD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB;IAC9C,MAAM;IACN,KAAK;IACL,KAAK;IACL,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,WAAW;IACX,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;CACL,CAAC;AAEF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,yEAAyE;AACzE,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAEjD,SAAS,SAAS,CAAC,IAAY;IAC7B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,GAAG;YAAE,SAAS;QAC1C,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,CAAC,GAAG,EAAE,CAAC;;YAC1B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG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AO,CAAC,WAAW,CAAC,CAAC;YACtG,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,MAAM,CAAC,IAAI,MAAM,EAAE,KAAK,CAAC,CAAC;YAC3F,OAAO,CAAC,KAAK,GAAG,MAAM,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;YAC7D,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;gBAChE,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC7E,CAAC;YACD,MAAM,GAAG,OAAO,CAAC;YACjB,OAAO,OAAO,CAAC;QACjB,CAAC;KACF,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * `fakeSandbox()`: a sandbox in memory, for tests of the code that runs on one. It enforces the policy it is given, so\n * a test can see a denial, and it records every `exec`, but it confines no process and runs no program: it understands\n * a few commands, listed at `FAKE_COMMANDS`. It is portable, so a test can use it on every target.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxDeniedError, SandboxUnavailableError } from \"../sandbox/errors.js\";\nimport { confirmPolicy } from \"../sandbox/policy.js\";\nimport type {\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n SandboxStop,\n WorkspaceManifest,\n} from \"../sandbox/types.js\";\n\n/** The options of `fakeSandbox()`. */\nexport interface FakeSandboxOptions {\n /** Makes `provision()` throw `SandboxUnavailableError` with this reason, as a backend that can't start does. */\n readonly unavailable?: string;\n /**\n * The policy the fake applies and reads back instead of the requested one, as a hosted provider's account-wide\n * override would. `provision()` then throws `SandboxPolicyMismatchError` when the two differ.\n */\n readonly applied?: (requested: SandboxPolicy) => SandboxPolicy;\n /** The stops the fake claims. Defaults to `mistakes` and `exfiltration`, which its in-memory checks deliver. */\n readonly stops?: readonly SandboxStop[];\n}\n\n/** One command the fake received, with what the caller passed. */\nexport interface RecordedExec {\n readonly command: readonly string[];\n readonly cwd: string | undefined;\n readonly env: Readonly<Record<string, string>>;\n readonly timeoutMs: number | undefined;\n}\n\n/** A fake backend, and what it has seen. */\nexport interface FakeSandboxClient extends SandboxClient {\n /** Every command run through any sandbox this client provisioned, in order. */\n readonly execs: readonly RecordedExec[];\n /** The files of the latest sandbox, by absolute path. */\n files(): ReadonlyMap<string, Uint8Array>;\n /** Makes `link` an absolute path that stands for `target` in the latest sandbox, as a symlink does. */\n symlink(link: string, target: string): void;\n}\n\n/**\n * The commands the fake runs, in the form `[name, ...arguments]`: `echo` prints its arguments, `env` prints the\n * environment it was given as `NAME=value` lines, `cat <path>` prints a file, `write <path> <text>` writes one,\n * `true` and `false` exit with 0 and 1, `sleep <seconds>` waits and honours the timeout and the signal, and\n * `net-probe <host>` reaches a host only if the policy allows it. `find <dir>` lists the files under a folder, one per\n * line or ending in NUL with `-print0`. When the command has `-prune`, it leaves out every folder named by a `-name`,\n * the starting folder included. A `! -path <start>` exempts the starting folder. It exits with 0 and prints nothing for a folder\n * with no files, and with 1 for a path that does not exist. `grep [-i] -e <pattern> -- <file>...` prints each\n * matching line as `file:line:text`, reading the pattern as a JavaScript regular expression and skipping a file that\n * holds a NUL byte. It exits with 1 when nothing matches, and with 2 after a missing file or a pattern it can't read,\n * as grep does. A command that runs past its timeout exits with 124 and `timedOut: true`, and each stream keeps at\n * most `maxOutputBytes`, with `truncated: true` when more was dropped.\n * `bash -c <script>` and `sh -c <script>` split the script on whitespace and run its words as one of these commands,\n * with no shell syntax. Any other command exits with 127.\n */\nexport const FAKE_COMMANDS: readonly string[] = [\n \"echo\",\n \"env\",\n \"cat\",\n \"write\",\n \"true\",\n \"false\",\n \"sleep\",\n \"net-probe\",\n \"find\",\n \"grep\",\n \"bash\",\n \"sh\",\n];\n\nconst ENCODER = new TextEncoder();\nconst DECODER = new TextDecoder();\n// What a real backend keeps of each stream when the caller names no cap.\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n\nfunction normalize(path: string): string {\n const parts: string[] = [];\n for (const part of path.split(\"/\")) {\n if (part === \"\" || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\n/** The lines of `text` that match, as `grep -n -H` prints them. */\nfunction matchingLines(file: string, text: string, pattern: RegExp): string {\n const lines = text.endsWith(\"\\n\") ? text.slice(0, -1).split(\"\\n\") : text.split(\"\\n\");\n return lines.map((line, index) => (pattern.test(line) ? `${file}:${index + 1}:${line}\\n` : \"\")).join(\"\");\n}\n\n/** A `find -path` pattern with its backslash escapes removed, as the literal path it names. */\nconst literalOf = (pattern: string | undefined): string | undefined => pattern?.replace(/\\\\(.)/g, \"$1\");\n\n/** `text` cut to its first `bytes` UTF-8 bytes, never splitting a character, and whether anything was cut. */\nfunction capped(text: string, bytes: number): { text: string; cut: boolean } {\n const encoded = ENCODER.encode(text);\n if (encoded.length <= bytes) return { text, cut: false };\n let end = bytes;\n while (end > 0 && ((encoded[end] as number) & 0b1100_0000) === 0b1000_0000) end -= 1;\n return { text: DECODER.decode(encoded.subarray(0, end)), cut: true };\n}\n\n/** The pattern of a `grep` command's flags, or the result grep gives for a pattern it can't read. */\nfunction patternOf(flags: readonly string[]): RegExp | ExecResult {\n const at = flags.indexOf(\"-e\");\n try {\n return new RegExp(at < 0 ? \"\" : (flags[at + 1] ?? \"\"), flags.includes(\"-i\") ? \"i\" : \"\");\n } catch (error) {\n // grep reports a pattern it can't read on standard error and exits with 2, before it reads any file.\n return { exitCode: 2, stdout: \"\", stderr: `grep: ${(error as Error).message}\\n` };\n }\n}\n\nconst within = (path: string, root: string): boolean => {\n const base = normalize(root);\n return base === \"/\" || path === base || path.startsWith(`${base}/`);\n};\n\nclass FakeSandbox implements Sandbox {\n private disposed = false;\n stops: readonly SandboxStop[] = [];\n // What ends each command still running, so `dispose()` can reject them as a real backend does.\n private readonly running = new Set<() => void>();\n readonly store = new Map<string, Uint8Array>();\n readonly links = new Map<string, string>();\n private readonly root: string;\n private readonly policy: SandboxPolicy;\n private readonly log: RecordedExec[];\n\n constructor(root: string, policy: SandboxPolicy, log: RecordedExec[]) {\n this.root = normalize(root);\n this.policy = policy;\n this.log = log;\n }\n\n private live(): void {\n if (this.disposed) throw new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\");\n }\n\n /** The policy the fake enforces, as a copy. */\n async readBack(): Promise<SandboxPolicy> {\n this.live();\n const { readRoots, writeRoots, network } = this.policy;\n return {\n readRoots: [...readRoots],\n writeRoots: [...writeRoots],\n network: { allow: [...network.allow], deny: [...network.deny] },\n };\n }\n\n /** The absolute path a name stands for: joined to the root, tidied of `.` and `..`, then followed through links. */\n resolve(path: string, base = this.root): string {\n const tidy = normalize(path.startsWith(\"/\") ? path : `${base}/${path}`);\n for (const [link, target] of this.links) {\n if (tidy === link || tidy.startsWith(`${link}/`)) return normalize(`${target}${tidy.slice(link.length)}`);\n }\n return tidy;\n }\n\n private readDenial(path: string): SandboxDenial | undefined {\n const roots = [...this.policy.readRoots, ...this.policy.writeRoots];\n if (roots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_read\", target: path, reason: \"the path is outside the read roots\" };\n }\n\n private writeDenial(path: string): SandboxDenial | undefined {\n if (this.policy.writeRoots.some((root) => within(path, root))) return undefined;\n return { kind: \"filesystem_write\", target: path, reason: \"the path is outside the write roots\" };\n }\n\n private networkDenial(host: string): SandboxDenial | undefined {\n const { allow, deny } = this.policy.network;\n if (allow.includes(host) && !deny.includes(host)) return undefined;\n return { kind: \"network\", target: host, reason: \"the host is not on the network allowlist\" };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n this.live();\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n const data = this.store.get(target);\n if (data === undefined) throw new HarnessError(\"sandbox_not_found\", `no such file: ${target}`);\n return data.slice();\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n this.live();\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) throw new SandboxDeniedError(denial);\n this.store.set(target, data.slice());\n }\n\n /** Writes a file without a policy check, for the manifest's own files. */\n seed(path: string, data: Uint8Array): void {\n this.store.set(this.resolve(path), data.slice());\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n this.live();\n if (!Array.isArray(command) || command.length === 0) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n options.signal.throwIfAborted();\n const cwd = this.resolve(options.cwd ?? \".\");\n const denial = this.readDenial(cwd);\n if (denial) return { denied: denial };\n this.log.push({ command: [...command], cwd: options.cwd, env: { ...options.env }, timeoutMs: options.timeoutMs });\n const [name = \"\", ...args] = command;\n const result = await this.run(name, args, options);\n if (\"denied\" in result) return result;\n // Each stream keeps at most `maxOutputBytes`, as a real backend's does.\n const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n const stdout = capped(result.stdout, limit);\n const stderr = capped(result.stderr, limit);\n if (!stdout.cut && !stderr.cut) return result;\n return { ...result, stdout: stdout.text, stderr: stderr.text, truncated: true };\n }\n\n private async run(name: string, args: string[], options: ExecOptions): Promise<ExecResult> {\n const ok = (stdout = \"\"): ExecResult => ({ exitCode: 0, stdout, stderr: \"\" });\n switch (name) {\n case \"echo\":\n return ok(`${args.join(\" \")}\\n`);\n case \"env\":\n return ok(\n Object.entries(options.env)\n .map(([key, value]) => `${key}=${value}\\n`)\n .join(\"\"),\n );\n case \"true\":\n return ok();\n case \"false\":\n return { exitCode: 1, stdout: \"\", stderr: \"\" };\n case \"cat\":\n return this.cat(args[0] ?? \"\");\n case \"write\":\n return this.writeCommand(args[0] ?? \"\", args.slice(1).join(\" \"));\n case \"net-probe\": {\n const host = args[0] ?? \"\";\n const denial = this.networkDenial(host);\n return denial ? { denied: denial } : ok(`reached ${host}\\n`);\n }\n case \"sleep\":\n return this.sleep(Number(args[0] ?? 0) * 1000, options);\n case \"find\":\n return this.find(args);\n case \"grep\":\n return this.grep(args);\n case \"bash\":\n case \"sh\":\n return this.shell(args, options);\n default:\n return { exitCode: 127, stdout: \"\", stderr: `command not found: ${name}\\n` };\n }\n }\n\n private cat(path: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n return data === undefined\n ? { exitCode: 1, stdout: \"\", stderr: `no such file: ${target}\\n` }\n : { exitCode: 0, stdout: DECODER.decode(data), stderr: \"\" };\n }\n\n /** The script's words as one command, so a test can drive a shell tool without a shell. */\n private shell(args: string[], options: ExecOptions): Promise<ExecResult> {\n if (args[0] !== \"-c\") return Promise.resolve({ exitCode: 2, stdout: \"\", stderr: \"the fake shell runs only -c\\n\" });\n const [name = \"\", ...rest] = (args[1] ?? \"\").trim().split(/\\s+/);\n return this.run(name, rest, options);\n }\n\n /** Whether `path` is a folder: the root, a folder above it, or a folder that holds a file. */\n private isFolder(path: string): boolean {\n if (within(this.root, path)) return true;\n const prefix = path === \"/\" ? \"/\" : `${path}/`;\n return [...this.store.keys()].some((file) => file.startsWith(prefix));\n }\n\n private find(args: string[]): ExecResult {\n const start = this.resolve(args[0] ?? \".\");\n const denial = this.readDenial(start);\n if (denial) return { denied: denial };\n if (!this.store.has(start) && !this.isFolder(start)) {\n return { exitCode: 1, stdout: \"\", stderr: `find: '${args[0] ?? \".\"}': No such file or directory\\n` };\n }\n const named = args.flatMap((arg, index) => (arg === \"-name\" ? [args[index + 1] ?? \"\"] : []));\n const pruned = new Set(args.includes(\"-prune\") ? named : []);\n // `! -path <start>` exempts the starting point from the prune, as it does for find; without it the prune tests\n // the starting point's own name too, so a search that starts in a pruned folder finds nothing.\n const exempt = args.some(\n (arg, index) => arg === \"!\" && args[index + 1] === \"-path\" && literalOf(args[index + 2]) === start,\n );\n const ownName = start.split(\"/\").at(-1) ?? \"\";\n if (!exempt && ownName !== \"\" && pruned.has(ownName)) return { exitCode: 0, stdout: \"\", stderr: \"\" };\n const files = [...this.store.keys()]\n .filter((path) => path === start || path.startsWith(`${start === \"/\" ? \"\" : start}/`))\n .filter(\n (path) =>\n !path\n .slice(start.length)\n .split(\"/\")\n .some((part) => pruned.has(part)),\n )\n .sort();\n const end = args.includes(\"-print0\") ? \"\\0\" : \"\\n\";\n return { exitCode: 0, stdout: files.map((path) => `${path}${end}`).join(\"\"), stderr: \"\" };\n }\n\n private grep(args: string[]): ExecResult {\n const split = args.indexOf(\"--\");\n const flags = split < 0 ? args : args.slice(0, split);\n const files = split < 0 ? [] : args.slice(split + 1);\n const pattern = patternOf(flags);\n if (!(pattern instanceof RegExp)) return pattern;\n let stdout = \"\";\n let stderr = \"\";\n for (const file of files) {\n const target = this.resolve(file);\n const denial = this.readDenial(target);\n if (denial) return { denied: denial };\n const data = this.store.get(target);\n if (data === undefined) stderr += `grep: ${file}: No such file or directory\\n`;\n else if (!data.includes(0)) stdout += matchingLines(file, DECODER.decode(data), pattern);\n }\n // grep exits with 2 after any error, even when other files matched.\n return { exitCode: stderr !== \"\" ? 2 : stdout === \"\" ? 1 : 0, stdout, stderr };\n }\n\n private writeCommand(path: string, text: string): ExecResult {\n const target = this.resolve(path);\n const denial = this.writeDenial(target);\n if (denial) return { denied: denial };\n this.store.set(target, ENCODER.encode(text));\n return { exitCode: 0, stdout: \"\", stderr: \"\" };\n }\n\n private sleep(ms: number, options: ExecOptions): Promise<ExecResult> {\n return new Promise((resolve, reject) => {\n const done = (result: ExecResult) => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n this.running.delete(disposed);\n resolve(result);\n };\n const aborted = () => {\n clearTimeout(timer);\n this.running.delete(disposed);\n reject(options.signal.reason);\n };\n const disposed = () => {\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", aborted);\n reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\"));\n };\n this.running.add(disposed);\n const stopAt = options.timeoutMs !== undefined && options.timeoutMs < ms ? options.timeoutMs : ms;\n const timer = setTimeout(() => {\n const timedOut = stopAt < ms;\n done(\n timedOut\n ? { exitCode: 124, stdout: \"\", stderr: `timed out after ${stopAt} ms\\n`, timedOut: true }\n : { exitCode: 0, stdout: \"\", stderr: \"\" },\n );\n }, stopAt);\n options.signal.addEventListener(\"abort\", aborted, { once: true });\n });\n }\n\n async dispose(): Promise<void> {\n this.disposed = true;\n for (const stop of [...this.running]) stop();\n this.running.clear();\n }\n}\n\n/**\n * Builds a fake backend with the tier `os` and the stops `mistakes` and `exfiltration`, because it enforces the\n * policy's file roots and network allowlist in memory. That says nothing about a real process: it runs none. It reads\n * its policy back as a real backend does, so `provision()` throws `SandboxPolicyMismatchError` when `applied` changes\n * the policy.\n */\nexport function fakeSandbox(options: FakeSandboxOptions = {}): FakeSandboxClient {\n const execs: RecordedExec[] = [];\n let latest: FakeSandbox | undefined;\n const client: FakeSandboxClient = {\n tier: \"os\",\n stops: options.stops ?? [\"mistakes\", \"exfiltration\"],\n execs,\n files: () => latest?.store ?? new Map(),\n symlink(link: string, target: string) {\n latest?.links.set(normalize(link), normalize(target));\n },\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy) {\n if (options.unavailable !== undefined) throw new SandboxUnavailableError(\"fake\", options.unavailable);\n const sandbox = new FakeSandbox(manifest.root, options.applied?.(policy) ?? policy, execs);\n sandbox.stops = await confirmPolicy(client, sandbox, policy);\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n sandbox.seed(path, typeof data === \"string\" ? ENCODER.encode(data) : data);\n }\n latest = sandbox;\n return sandbox;\n },\n };\n return client;\n}\n"]}
|
|
@@ -5,8 +5,10 @@
|
|
|
5
5
|
* import no test runner and no Node module, so any runner can call them, in workerd too.
|
|
6
6
|
*/
|
|
7
7
|
import { isHarnessError } from "../errors.js";
|
|
8
|
+
import { confirmPolicy, hasCapability, pauseSandbox, policyDifference, resumeSandbox, snapshotSandbox, stopsFor, } from "../sandbox/policy.js";
|
|
8
9
|
import { runCases } from "./run-cases.js";
|
|
9
10
|
const STOPS = ["mistakes", "exfiltration", "hostile_process"];
|
|
11
|
+
const CAPABILITIES = ["resume", "snapshot", "pause"];
|
|
10
12
|
const ALLOWED_HOST = "allowed.test";
|
|
11
13
|
const SETTLE_MS = 5000;
|
|
12
14
|
// Variables a program may add to its own environment on start, which a case ignores when it counts the variables.
|
|
@@ -167,11 +169,12 @@ function workspaceCases(sandboxed) {
|
|
|
167
169
|
}),
|
|
168
170
|
},
|
|
169
171
|
{
|
|
170
|
-
name: "a command that runs past its timeout is stopped with exit code 124",
|
|
172
|
+
name: "a command that runs past its timeout is stopped with exit code 124 and timedOut",
|
|
171
173
|
run: sandboxed(async (sandbox) => {
|
|
172
174
|
const started = Date.now();
|
|
173
175
|
const result = finished(await exec(sandbox, ["sleep", "10"], { timeoutMs: 200 }));
|
|
174
176
|
check(result.exitCode === 124, `a timed out command must exit with 124, not ${result.exitCode}`);
|
|
177
|
+
check(result.timedOut === true, "a timed out command's result must say timedOut: true");
|
|
175
178
|
check(Date.now() - started < 5000, "the command must be stopped at the timeout");
|
|
176
179
|
return undefined;
|
|
177
180
|
}),
|
|
@@ -340,6 +343,108 @@ function processCases(sandboxed) {
|
|
|
340
343
|
},
|
|
341
344
|
];
|
|
342
345
|
}
|
|
346
|
+
/** The code a call rejects with, or `"it resolved"`. */
|
|
347
|
+
async function rejection(action) {
|
|
348
|
+
return action().then(() => "it resolved", (error) => codeOf(error) ?? String(error));
|
|
349
|
+
}
|
|
350
|
+
/** Checks that a capability the client doesn't list is refused, and that one it lists works and keeps the files. */
|
|
351
|
+
async function checkCapability(sandbox, context, capability) {
|
|
352
|
+
const { client } = context.under;
|
|
353
|
+
if (!hasCapability(client, capability)) {
|
|
354
|
+
const refused = capability === "resume"
|
|
355
|
+
? await rejection(() => resumeSandbox(client, "no-such-sandbox", context.policy))
|
|
356
|
+
: await rejection(() => (capability === "snapshot" ? snapshotSandbox : pauseSandbox)(client, sandbox));
|
|
357
|
+
check(refused === "sandbox_unsupported", `an unlisted ${capability} must be refused, not ${refused}`);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const encoder = new TextEncoder();
|
|
361
|
+
await sandbox.writeFile(`kept-${capability}.txt`, encoder.encode(capability));
|
|
362
|
+
let id = sandbox.id;
|
|
363
|
+
if (capability === "snapshot")
|
|
364
|
+
id = await snapshotSandbox(client, sandbox);
|
|
365
|
+
if (capability === "pause")
|
|
366
|
+
await pauseSandbox(client, sandbox);
|
|
367
|
+
check(typeof id === "string" && id !== "", `a sandbox that can ${capability} must have an id to resume`);
|
|
368
|
+
if (!hasCapability(client, "resume"))
|
|
369
|
+
return;
|
|
370
|
+
const resumed = await resumeSandbox(client, id, context.policy);
|
|
371
|
+
try {
|
|
372
|
+
const kept = text(await resumed.readFile(`kept-${capability}.txt`));
|
|
373
|
+
check(kept === capability, `a sandbox resumed after ${capability} must keep its files`);
|
|
374
|
+
}
|
|
375
|
+
finally {
|
|
376
|
+
// A resume by the sandbox's own id reattaches to it, which the case's own dispose ends.
|
|
377
|
+
if (resumed.id !== sandbox.id)
|
|
378
|
+
await resumed.dispose();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** The case that checks the resume, snapshot and pause capabilities. */
|
|
382
|
+
function capabilityCases(sandboxed) {
|
|
383
|
+
return [
|
|
384
|
+
{
|
|
385
|
+
name: "a backend lists only known capabilities, each one it lists works, and one it doesn't is refused with sandbox_unsupported",
|
|
386
|
+
run: sandboxed(async (sandbox, context) => {
|
|
387
|
+
const listed = context.under.client.capabilities ?? [];
|
|
388
|
+
check(Array.isArray(listed) && listed.every((capability) => CAPABILITIES.includes(capability)), "every capability must be a known one");
|
|
389
|
+
for (const capability of CAPABILITIES)
|
|
390
|
+
await checkCapability(sandbox, context, capability);
|
|
391
|
+
return undefined;
|
|
392
|
+
}),
|
|
393
|
+
},
|
|
394
|
+
];
|
|
395
|
+
}
|
|
396
|
+
const NO_STOP = "the backend does not claim to stop anything, so it enforces no policy to read back";
|
|
397
|
+
/** The cases that check the policy a backend reads back, which run only when it claims a stop. */
|
|
398
|
+
function readBackCases(sandboxed) {
|
|
399
|
+
return [
|
|
400
|
+
{
|
|
401
|
+
name: "a backend that claims a stop reads back the policy it applied, which equals the request, and delivers its stops",
|
|
402
|
+
run: sandboxed(async (sandbox, context) => {
|
|
403
|
+
const { client } = context.under;
|
|
404
|
+
if (client.stops.length === 0)
|
|
405
|
+
return { skipped: NO_STOP };
|
|
406
|
+
check(typeof sandbox.readBack === "function", "a backend that claims a stop must read its policy back");
|
|
407
|
+
const applied = await sandbox.readBack();
|
|
408
|
+
const field = policyDifference(context.policy, applied);
|
|
409
|
+
check(field === undefined, `the read-back must equal the request, but ${field} differs`);
|
|
410
|
+
const delivered = stopsFor(client.tier, applied);
|
|
411
|
+
check(client.stops.every((stop) => delivered.includes(stop)), "the applied policy must deliver every stop claimed");
|
|
412
|
+
const stops = sandbox.stops ?? [];
|
|
413
|
+
check(stops.length === delivered.length && stops.every((stop) => delivered.includes(stop)), "the sandbox's stops must be the ones its applied policy delivers");
|
|
414
|
+
return undefined;
|
|
415
|
+
}),
|
|
416
|
+
},
|
|
417
|
+
{
|
|
418
|
+
name: "a read-back that differs from the request throws sandbox_policy_mismatch, names the field and disposes the sandbox",
|
|
419
|
+
run: sandboxed(async (sandbox, context) => {
|
|
420
|
+
const { client } = context.under;
|
|
421
|
+
if (client.stops.length === 0)
|
|
422
|
+
return { skipped: NO_STOP };
|
|
423
|
+
check(typeof sandbox.readBack === "function", "a backend that claims a stop must read its policy back");
|
|
424
|
+
const applied = await sandbox.readBack();
|
|
425
|
+
const { policy, outside } = context;
|
|
426
|
+
const widened = [
|
|
427
|
+
["readRoots", { ...policy, readRoots: [...policy.readRoots, outside] }],
|
|
428
|
+
["writeRoots", { ...policy, writeRoots: [] }],
|
|
429
|
+
["network.allow", { ...policy, network: { ...policy.network, allow: [...policy.network.allow, "x.test"] } }],
|
|
430
|
+
["network.deny", { ...policy, network: { ...policy.network, deny: ["y.test"] } }],
|
|
431
|
+
];
|
|
432
|
+
for (const [field, other] of widened) {
|
|
433
|
+
const found = policyDifference(other, applied);
|
|
434
|
+
check(found === field, `a request that differs in ${field} must be found to differ there, not in ${found}`);
|
|
435
|
+
}
|
|
436
|
+
const asked = widened[2]?.[1] ?? policy;
|
|
437
|
+
const error = await confirmPolicy(client, sandbox, asked).then(() => undefined, (caught) => caught);
|
|
438
|
+
check(codeOf(error) === "sandbox_policy_mismatch", "a mismatch must throw sandbox_policy_mismatch");
|
|
439
|
+
check(error.field === "network.allow", "the error must name the field");
|
|
440
|
+
check(!String(error.message).includes("x.test"), "the message must not name a host");
|
|
441
|
+
const after = await rejection(() => sandbox.readFile("a.txt"));
|
|
442
|
+
check(after === "sandbox_disposed", `a mismatch must dispose the sandbox, but a later call gave ${after}`);
|
|
443
|
+
return undefined;
|
|
444
|
+
}),
|
|
445
|
+
},
|
|
446
|
+
];
|
|
447
|
+
}
|
|
343
448
|
/** The cases, for a backend from `factory`. Run each one; a case that doesn't apply resolves with `{ skipped }`. */
|
|
344
449
|
export function sandboxConformanceCases(factory, options = {}) {
|
|
345
450
|
const sandboxed = (body) => withSandbox(factory, options, body);
|
|
@@ -349,6 +454,8 @@ export function sandboxConformanceCases(factory, options = {}) {
|
|
|
349
454
|
...processCases(sandboxed),
|
|
350
455
|
...disposeCases(factory, options, sandboxed),
|
|
351
456
|
...policyCases(sandboxed),
|
|
457
|
+
...capabilityCases(sandboxed),
|
|
458
|
+
...readBackCases(sandboxed),
|
|
352
459
|
];
|
|
353
460
|
}
|
|
354
461
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-conformance.js","sourceRoot":"","sources":["../../src/testing/sand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AI,EAAE,OAAO,CAAC,CAAC;gBACtC,MAAM,OAAO,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;gBACxC,OAAO,SAAS,CAAC;YACnB,CAAC,CAAC;SACH;KACF,CAAC;AACJ,CAAC;AAED,oHAAoH;AACpH,MAAM,UAAU,uBAAuB,CACrC,OAAuB,EACvB,OAAO,GAA8B,EAAE;IAEvC,MAAM,SAAS,GAAc,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC3E,OAAO;QACL,GAAG,YAAY,CAAC,OAAO,CAAC;QACxB,GAAG,cAAc,CAAC,SAAS,CAAC;QAC5B,GAAG,YAAY,CAAC,SAAS,CAAC;QAC1B,GAAG,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC;QAC5C,GAAG,WAAW,CAAC,SAAS,CAAC;KAC1B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAuB,EACvB,OAAO,GAA8B,EAAE;IAEvC,OAAO,QAAQ,CAAC,uBAAuB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * The sandbox conformance suite: what every `SandboxClient` must do, whatever its tier. The cases that need a backend to\n * enforce something run only when its `stops` claim it, so a `none` backend passes the rest and an honest `srt` or\n * Docker backend passes them all. A backend that can't start makes every case skip with its reason, never fail. The cases\n * import no test runner and no Node module, so any runner can call them, in workerd too.\n */\n\nimport { isHarnessError } from \"../errors.js\";\nimport type { ExecResult, Sandbox, SandboxClient, SandboxDenial, SandboxPolicy } from \"../sandbox/types.js\";\nimport { type CaseReport, type RunnableCase, runCases } from \"./run-cases.js\";\n\n/** What a factory returns: the backend, and the absolute folder to use as the workspace root. */\nexport interface SandboxUnderTest {\n readonly client: SandboxClient;\n /** An absolute folder that exists, empty. A sibling named `<root>-outside` stands for a path the policy refuses. */\n readonly root: string;\n /**\n * Makes `link` an absolute path inside the workspace that stands for `target`, as a symlink does, before or after the\n * sandbox starts. Without it the symlink case skips, because a portable command to make one doesn't exist.\n */\n readonly symlink?: (link: string, target: string) => void | Promise<void>;\n}\n\n/** Makes a fresh backend and workspace for each case. */\nexport type SandboxFactory = () => SandboxUnderTest | Promise<SandboxUnderTest>;\n\n/** The options of the suite. */\nexport interface SandboxConformanceOptions {\n /**\n * The network case: `command(host)` is a command that exits 0 if it reaches `host`. The policy allows only `allowed`,\n * so both hosts must accept a connection from the test, such as two loopback listeners the test owns: a host that never\n * resolves would fail with no policy at all and prove nothing. The case checks that `allowed` is reached and `blocked`\n * is not. Without it that case skips, because a portable command to open a connection doesn't exist.\n */\n readonly network?: {\n readonly allowed: string;\n readonly blocked: string;\n /** The command that exits 0 if it reaches `host`. */\n readonly command: (host: string) => readonly string[];\n };\n /**\n * Variables the backend adds to a command's environment on its own, such as the proxy variables an OS sandbox sets so a\n * program finds its network proxy. The environment case accepts these besides the given ones, and still fails on any\n * other variable and on any credential.\n */\n readonly addedEnvironment?: readonly string[];\n /**\n * The case that checks an abort and a timeout end the command's whole tree. `command` starts a background process,\n * writes its process id to the file `pid` in the workspace and then waits for it, and `isAlive` says whether a process\n * is still running. Without it the case skips, because a portable command that forks doesn't exist.\n */\n readonly processTree?: {\n /** The command that starts a background process, writes its id to `pid` and waits for it. */\n readonly command: readonly string[];\n /** Whether the process with id `pid` is still running. */\n readonly isAlive: (pid: number) => boolean | Promise<boolean>;\n };\n}\n\n/** One case of the sandbox conformance suite, which a runner can register as a test of its own. */\nexport type SandboxCase = RunnableCase;\n\n/** The report the sandbox conformance suite returns: which cases passed, which skipped with a reason and which failed. */\nexport type SandboxConformanceReport = CaseReport;\n\nconst STOPS = [\"mistakes\", \"exfiltration\", \"hostile_process\"];\nconst ALLOWED_HOST = \"allowed.test\";\nconst SETTLE_MS = 5000;\n// Variables a program may add to its own environment on start, which a case ignores when it counts the variables.\nconst ADDED_BY_RUNTIMES = new Set([\"PWD\", \"OLDPWD\", \"SHLVL\", \"_\"]);\nconst CREDENTIALS = [\"ANTHROPIC_API_KEY\", \"OPENAI_API_KEY\", \"GITHUB_TOKEN\", \"AWS_SECRET_ACCESS_KEY\"];\n\nfunction check(condition: boolean, message: string): asserts condition {\n if (!condition) throw new Error(`Sandbox conformance: ${message}`);\n}\n\nconst never = () => new AbortController().signal;\nconst text = (data: Uint8Array) => new TextDecoder().decode(data);\n\n/** The skip a case answers with when the backend can't start. */\ntype Skip = { readonly skipped: string };\n\ninterface Context {\n readonly under: SandboxUnderTest;\n readonly options: SandboxConformanceOptions;\n readonly policy: SandboxPolicy;\n readonly outside: string;\n}\n\n/** The error's `code` when it is a `HarnessError`, which works across two bundled copies of this package. */\nfunction codeOf(error: unknown): string | undefined {\n return isHarnessError(error) ? error.code : undefined;\n}\n\n/** The denial a `sandbox_denied` error carries, or `undefined` for any other error. */\nfunction denialOf(error: unknown): SandboxDenial | undefined {\n return codeOf(error) === \"sandbox_denied\" ? (error as { denial?: SandboxDenial }).denial : undefined;\n}\n\n/** Provisions a sandbox for a case, or the skip that a backend reporting itself unavailable gets. */\nasync function provision(context: Context): Promise<Sandbox | Skip> {\n try {\n return await context.under.client.provision({ root: context.under.root }, context.policy);\n } catch (error) {\n if (codeOf(error) === \"sandbox_unavailable\") return { skipped: (error as Error).message };\n throw error;\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** Polls until `test` is true, for at most `SETTLE_MS`. */\nasync function eventually(test: () => boolean | Promise<boolean>): Promise<boolean> {\n const stop = Date.now() + SETTLE_MS;\n while (Date.now() < stop) {\n if (await test()) return true;\n await sleep(50);\n }\n return test();\n}\n\n/** Runs `action` and returns the denial it ended in, as a thrown error or as a command's `denied` result. */\nasync function denialFrom(action: () => Promise<unknown>): Promise<SandboxDenial | undefined> {\n try {\n const result = await action();\n return typeof result === \"object\" && result !== null && \"denied\" in result\n ? (result as { denied: SandboxDenial }).denied\n : undefined;\n } catch (error) {\n return denialOf(error);\n }\n}\n\n/** Wraps a case's check so it provisions first, disposes after, and skips when the backend is unavailable. */\nfunction withSandbox(\n factory: SandboxFactory,\n options: SandboxConformanceOptions,\n body: (sandbox: Sandbox, context: Context) => Promise<Skip | undefined>,\n) {\n return async (): Promise<Skip | undefined> => {\n const under = await factory();\n const root = under.root;\n const policy: SandboxPolicy = {\n readRoots: [root],\n writeRoots: [root],\n network: { allow: [options.network?.allowed ?? ALLOWED_HOST], deny: [] },\n };\n const context: Context = { under, options, policy, outside: `${root}-outside` };\n const sandbox = await provision(context);\n if (\"skipped\" in sandbox) return sandbox;\n try {\n return await body(sandbox, context);\n } finally {\n await sandbox.dispose();\n }\n };\n}\n\nasync function exec(\n sandbox: Sandbox,\n command: readonly string[],\n extra: { env?: Record<string, string>; timeoutMs?: number; signal?: AbortSignal; cwd?: string } = {},\n): Promise<ExecResult> {\n return sandbox.exec(command, {\n env: extra.env ?? {},\n signal: extra.signal ?? never(),\n ...(extra.cwd === undefined ? {} : { cwd: extra.cwd }),\n ...(extra.timeoutMs === undefined ? {} : { timeoutMs: extra.timeoutMs }),\n });\n}\n\nfunction finished(result: ExecResult): { exitCode: number; stdout: string; stderr: string } {\n check(!(\"denied\" in result), \"a command inside the workspace must not be denied\");\n return result;\n}\n\ntype Sandboxed = (\n body: (sandbox: Sandbox, context: Context) => Promise<Skip | undefined>,\n) => () => Promise<Skip | undefined>;\n\n/** The case that checks a backend's claims about itself. */\nfunction honestyCases(factory: SandboxFactory): readonly SandboxCase[] {\n return [\n {\n name: \"a backend names its tier and stops honestly: a none tier stops nothing, and every stop is a known one\",\n async run() {\n const { client } = await factory();\n check(\n [\"none\", \"os\", \"container\", \"gvisor\", \"microvm\"].includes(client.tier),\n `unknown tier ${String(client.tier)}`,\n );\n check(\n client.stops.every((stop) => STOPS.includes(stop)),\n \"every stop must be a known one\",\n );\n check(client.tier !== \"none\" || client.stops.length === 0, \"a none tier must stop nothing\");\n return undefined;\n },\n },\n ];\n}\n\n/** The cases that run in a provisioned sandbox. */\nfunction workspaceCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a file written in the workspace reads back as the same bytes\",\n run: sandboxed(async (sandbox) => {\n await sandbox.writeFile(\"notes/a.txt\", new TextEncoder().encode(\"hello\"));\n check(text(await sandbox.readFile(\"notes/a.txt\")) === \"hello\", \"the bytes written must be the bytes read\");\n return undefined;\n }),\n },\n {\n name: \"exec resolves with the exit code and output, and a failing command is a result, not an error\",\n run: sandboxed(async (sandbox) => {\n const echoed = finished(await exec(sandbox, [\"echo\", \"hello\"]));\n check(echoed.exitCode === 0 && echoed.stdout.trim() === \"hello\", \"echo must print its argument and exit 0\");\n const failed = finished(await exec(sandbox, [\"false\"]));\n check(failed.exitCode !== 0, \"a failing command must resolve with a non-zero exit code\");\n return undefined;\n }),\n },\n {\n name: \"exec's environment holds only the variables it was given, and no credential\",\n run: sandboxed(async (sandbox, context) => {\n const given = { ALPHA: \"1\", BETA: \"2\" };\n const printed = finished(await exec(sandbox, [\"env\"], { env: given }));\n const lines = printed.stdout.split(\"\\n\").filter((line) => line !== \"\");\n const names = lines.map((line) => line.slice(0, line.indexOf(\"=\")));\n check(lines.includes(\"ALPHA=1\") && lines.includes(\"BETA=2\"), \"the given variables must reach the command\");\n const addedByBackend = new Set(context.options.addedEnvironment ?? []);\n const extra = names.filter(\n (name) => !(name in given) && !ADDED_BY_RUNTIMES.has(name) && !addedByBackend.has(name),\n );\n check(extra.length === 0, `the command saw variables that were not given: ${extra.join(\", \")}`);\n check(!names.some((name) => CREDENTIALS.includes(name)), \"no credential may be in the environment\");\n return undefined;\n }),\n },\n {\n name: \"reading a file that doesn't exist rejects with sandbox_not_found\",\n run: sandboxed(async (sandbox) => {\n const code = await sandbox.readFile(\"no/such/file.txt\").then(\n () => \"it resolved\",\n (error: unknown) => codeOf(error) ?? String(error),\n );\n check(code === \"sandbox_not_found\", `a missing file must reject with sandbox_not_found, not ${code}`);\n return undefined;\n }),\n },\n {\n name: \"an already aborted signal rejects exec before the command runs\",\n run: sandboxed(async (sandbox) => {\n const controller = new AbortController();\n controller.abort(new Error(\"stop\"));\n let rejected = false;\n await exec(sandbox, [\"echo\", \"never\"], { signal: controller.signal }).catch(() => {\n rejected = true;\n });\n check(rejected, \"exec must reject for an aborted signal\");\n return undefined;\n }),\n },\n {\n name: \"a command that runs past its timeout is stopped with exit code 124\",\n run: sandboxed(async (sandbox) => {\n const started = Date.now();\n const result = finished(await exec(sandbox, [\"sleep\", \"10\"], { timeoutMs: 200 }));\n check(result.exitCode === 124, `a timed out command must exit with 124, not ${result.exitCode}`);\n check(Date.now() - started < 5000, \"the command must be stopped at the timeout\");\n return undefined;\n }),\n },\n ];\n}\n\n/** The case that checks `dispose()`. */\nfunction disposeCases(\n factory: SandboxFactory,\n options: SandboxConformanceOptions,\n sandboxed: Sandboxed,\n): readonly SandboxCase[] {\n return [\n {\n name: \"dispose ends a command that is still running, which rejects with sandbox_disposed\",\n run: sandboxed(async (sandbox) => {\n const running = exec(sandbox, [\"sleep\", \"30\"]).then(\n () => \"it resolved\",\n (error: unknown) => codeOf(error) ?? String(error),\n );\n await sleep(100);\n await sandbox.dispose();\n const outcome = await Promise.race([running, sleep(SETTLE_MS).then(() => \"it never settled\")]);\n check(\n outcome === \"sandbox_disposed\",\n `a command running at dispose must reject with sandbox_disposed, not ${outcome}`,\n );\n return undefined;\n }),\n },\n {\n name: \"dispose ends the sandbox: a later call rejects, and a second dispose does nothing\",\n async run() {\n const under = await factory();\n const context: Context = {\n under,\n options,\n policy: { readRoots: [under.root], writeRoots: [under.root], network: { allow: [], deny: [] } },\n outside: `${under.root}-outside`,\n };\n const sandbox = await provision(context);\n if (\"skipped\" in sandbox) return sandbox;\n await sandbox.dispose();\n await sandbox.dispose();\n let code = \"\";\n await sandbox.readFile(\"a.txt\").catch((error: unknown) => {\n code = isHarnessError(error) ? error.code : String(error);\n });\n check(code === \"sandbox_disposed\", `a call after dispose must reject with sandbox_disposed, not ${code}`);\n return undefined;\n },\n },\n ];\n}\n\nconst MISTAKES = \"the backend does not claim to stop mistakes\";\n\n/** The name of the workspace's folder, for a path that climbs out of it and back into its sibling. */\nfunction outsideViaParent(context: Context): string {\n const root = context.under.root;\n return `../${root.slice(root.lastIndexOf(\"/\") + 1)}-outside`;\n}\n\n/** The cases that need a backend to enforce its policy, which run only when its `stops` claim it. */\nfunction policyCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a write outside the write roots is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => sandbox.writeFile(`${context.outside}/x.txt`, new Uint8Array([1])));\n check(denial?.kind === \"filesystem_write\", \"a write outside the write roots must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a read outside the read roots is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => sandbox.readFile(`${context.outside}/x.txt`));\n check(denial?.kind === \"filesystem_read\", \"a read outside the read roots must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a path that climbs out of the workspace with .. is denied for reads and writes\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const climb = `${outsideViaParent(context)}/x.txt`;\n const write = await denialFrom(() => sandbox.writeFile(climb, new Uint8Array([1])));\n check(write?.kind === \"filesystem_write\", \"a write that climbs out with .. must be denied\");\n const read = await denialFrom(() => sandbox.readFile(climb));\n check(read?.kind === \"filesystem_read\", \"a read that climbs out with .. must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a symlink in the workspace that points outside it is denied for reads and writes\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const symlink = context.under.symlink;\n if (symlink === undefined) return { skipped: \"the factory gave no symlink function\" };\n await symlink(`${context.under.root}/link`, context.outside);\n const write = await denialFrom(() => sandbox.writeFile(\"link/x.txt\", new Uint8Array([1])));\n check(write?.kind === \"filesystem_write\", \"a write through a symlink that points outside must be denied\");\n const read = await denialFrom(() => sandbox.readFile(\"link/x.txt\"));\n check(read?.kind === \"filesystem_read\", \"a read through a symlink that points outside must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a working directory outside the workspace is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => exec(sandbox, [\"echo\", \"hi\"], { cwd: \"../..\" }));\n check(denial !== undefined, \"a command whose cwd climbs out of the workspace must be denied\");\n return undefined;\n }),\n },\n {\n name: \"the network is denied unless the host is on the allowlist\",\n run: sandboxed(async (sandbox, context) => {\n const network = context.options.network;\n if (!context.under.client.stops.includes(\"exfiltration\"))\n return { skipped: \"the backend does not claim to stop exfiltration\" };\n if (network === undefined) return { skipped: \"no network probe was given\" };\n const reached = await exec(sandbox, network.command(network.allowed));\n check(!(\"denied\" in reached) && reached.exitCode === 0, \"the allowed host must be reached\");\n const blocked = await exec(sandbox, network.command(network.blocked));\n check(\"denied\" in blocked || blocked.exitCode !== 0, \"a host that is not allowed must not be reached\");\n return undefined;\n }),\n },\n ];\n}\n\ntype ProcessTree = NonNullable<SandboxConformanceOptions[\"processTree\"]>;\n\n/** Starts the tree's command, stops it by `stop`, and checks that exec settled the right way and the tree is dead. */\nasync function endTree(sandbox: Sandbox, tree: ProcessTree, stop: \"abort\" | \"timeout\"): Promise<void> {\n // Clear the previous round's id, so a stale one can't pass for this round's.\n await sandbox.writeFile(\"pid\", new Uint8Array());\n const controller = new AbortController();\n const running = exec(sandbox, tree.command, {\n signal: controller.signal,\n ...(stop === \"timeout\" ? { timeoutMs: 1500 } : {}),\n }).then(\n (result) => ({ result }),\n (error: unknown) => ({ error }),\n );\n let pid = Number.NaN;\n const wrote = await eventually(async () => {\n pid = Number(text(await sandbox.readFile(\"pid\").catch(() => new Uint8Array())).trim());\n return Number.isInteger(pid) && pid > 0;\n });\n check(wrote, \"the command must write its background process's id\");\n if (stop === \"abort\") controller.abort(new Error(\"stop\"));\n const outcome = await Promise.race([running, sleep(SETTLE_MS).then(() => undefined)]);\n check(outcome !== undefined, `exec must settle after ${stop}, though a background process held its pipes`);\n check(\n stop === \"abort\" ? \"error\" in outcome : \"result\" in outcome,\n `${stop} must ${stop === \"abort\" ? \"reject\" : \"resolve\"}`,\n );\n check(await eventually(async () => !(await tree.isAlive(pid))), `the background process must die on ${stop}`);\n}\n\n/** The case that checks an abort and a timeout end a command's whole process tree. */\nfunction processCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"an abort and a timeout end the command's whole process tree, and exec settles\",\n run: sandboxed(async (sandbox, context) => {\n const tree = context.options.processTree;\n if (tree === undefined) return { skipped: \"no processTree was given\" };\n await endTree(sandbox, tree, \"abort\");\n await endTree(sandbox, tree, \"timeout\");\n return undefined;\n }),\n },\n ];\n}\n\n/** The cases, for a backend from `factory`. Run each one; a case that doesn't apply resolves with `{ skipped }`. */\nexport function sandboxConformanceCases(\n factory: SandboxFactory,\n options: SandboxConformanceOptions = {},\n): readonly SandboxCase[] {\n const sandboxed: Sandboxed = (body) => withSandbox(factory, options, body);\n return [\n ...honestyCases(factory),\n ...workspaceCases(sandboxed),\n ...processCases(sandboxed),\n ...disposeCases(factory, options, sandboxed),\n ...policyCases(sandboxed),\n ];\n}\n\n/**\n * Runs every case against backends from `factory` and reports which passed, which skipped with a reason and which\n * failed. A backend that reports itself unavailable skips; any other error fails the case.\n */\nexport async function runSandboxConformance(\n factory: SandboxFactory,\n options: SandboxConformanceOptions = {},\n): Promise<SandboxConformanceReport> {\n return runCases(sandboxConformanceCases(factory, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sandbox-conformance.js","sourceRoot":"","sources":["../../src/testing/sandbox-conformance.ts"],"names":[],"mappings":"A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gBAC3G,OAAO,SAAS,CAAC;YACnB,CAAC,CAAC;SACH;KACF,CAAC;AACJ,CAAC;AAED,oHAAoH;AACpH,MAAM,UAAU,uBAAuB,CACrC,OAAuB,EACvB,OAAO,GAA8B,EAAE;IAEvC,MAAM,SAAS,GAAc,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC3E,OAAO;QACL,GAAG,YAAY,CAAC,OAAO,CAAC;QACxB,GAAG,cAAc,CAAC,SAAS,CAAC;QAC5B,GAAG,YAAY,CAAC,SAAS,CAAC;QAC1B,GAAG,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC;QAC5C,GAAG,WAAW,CAAC,SAAS,CAAC;QACzB,GAAG,eAAe,CAAC,SAAS,CAAC;QAC7B,GAAG,aAAa,CAAC,SAAS,CAAC;KAC5B,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,OAAuB,EACvB,OAAO,GAA8B,EAAE;IAEvC,OAAO,QAAQ,CAAC,uBAAuB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * The sandbox conformance suite: what every `SandboxClient` must do, whatever its tier. The cases that need a backend to\n * enforce something run only when its `stops` claim it, so a `none` backend passes the rest and an honest `srt` or\n * Docker backend passes them all. A backend that can't start makes every case skip with its reason, never fail. The cases\n * import no test runner and no Node module, so any runner can call them, in workerd too.\n */\n\nimport { isHarnessError } from \"../errors.js\";\nimport {\n confirmPolicy,\n hasCapability,\n pauseSandbox,\n policyDifference,\n resumeSandbox,\n snapshotSandbox,\n stopsFor,\n} from \"../sandbox/policy.js\";\nimport type {\n ExecResult,\n Sandbox,\n SandboxCapability,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n} from \"../sandbox/types.js\";\nimport { type CaseReport, type RunnableCase, runCases } from \"./run-cases.js\";\n\n/** What a factory returns: the backend, and the absolute folder to use as the workspace root. */\nexport interface SandboxUnderTest {\n readonly client: SandboxClient;\n /** An absolute folder that exists, empty. A sibling named `<root>-outside` stands for a path the policy refuses. */\n readonly root: string;\n /**\n * Makes `link` an absolute path inside the workspace that stands for `target`, as a symlink does, before or after the\n * sandbox starts. Without it the symlink case skips, because a portable command to make one doesn't exist.\n */\n readonly symlink?: (link: string, target: string) => void | Promise<void>;\n}\n\n/** Makes a fresh backend and workspace for each case. */\nexport type SandboxFactory = () => SandboxUnderTest | Promise<SandboxUnderTest>;\n\n/** The options of the suite. */\nexport interface SandboxConformanceOptions {\n /**\n * The network case: `command(host)` is a command that exits 0 if it reaches `host`. The policy allows only `allowed`,\n * so both hosts must accept a connection from the test, such as two loopback listeners the test owns: a host that never\n * resolves would fail with no policy at all and prove nothing. The case checks that `allowed` is reached and `blocked`\n * is not. Without it that case skips, because a portable command to open a connection doesn't exist.\n */\n readonly network?: {\n readonly allowed: string;\n readonly blocked: string;\n /** The command that exits 0 if it reaches `host`. */\n readonly command: (host: string) => readonly string[];\n };\n /**\n * Variables the backend adds to a command's environment on its own, such as the proxy variables an OS sandbox sets so a\n * program finds its network proxy. The environment case accepts these besides the given ones, and still fails on any\n * other variable and on any credential.\n */\n readonly addedEnvironment?: readonly string[];\n /**\n * The case that checks an abort and a timeout end the command's whole tree. `command` starts a background process,\n * writes its process id to the file `pid` in the workspace and then waits for it, and `isAlive` says whether a process\n * is still running. Without it the case skips, because a portable command that forks doesn't exist.\n */\n readonly processTree?: {\n /** The command that starts a background process, writes its id to `pid` and waits for it. */\n readonly command: readonly string[];\n /** Whether the process with id `pid` is still running. */\n readonly isAlive: (pid: number) => boolean | Promise<boolean>;\n };\n}\n\n/** One case of the sandbox conformance suite, which a runner can register as a test of its own. */\nexport type SandboxCase = RunnableCase;\n\n/** The report the sandbox conformance suite returns: which cases passed, which skipped with a reason and which failed. */\nexport type SandboxConformanceReport = CaseReport;\n\nconst STOPS = [\"mistakes\", \"exfiltration\", \"hostile_process\"];\nconst CAPABILITIES: readonly SandboxCapability[] = [\"resume\", \"snapshot\", \"pause\"];\nconst ALLOWED_HOST = \"allowed.test\";\nconst SETTLE_MS = 5000;\n// Variables a program may add to its own environment on start, which a case ignores when it counts the variables.\nconst ADDED_BY_RUNTIMES = new Set([\"PWD\", \"OLDPWD\", \"SHLVL\", \"_\"]);\nconst CREDENTIALS = [\"ANTHROPIC_API_KEY\", \"OPENAI_API_KEY\", \"GITHUB_TOKEN\", \"AWS_SECRET_ACCESS_KEY\"];\n\nfunction check(condition: boolean, message: string): asserts condition {\n if (!condition) throw new Error(`Sandbox conformance: ${message}`);\n}\n\nconst never = () => new AbortController().signal;\nconst text = (data: Uint8Array) => new TextDecoder().decode(data);\n\n/** The skip a case answers with when the backend can't start. */\ntype Skip = { readonly skipped: string };\n\ninterface Context {\n readonly under: SandboxUnderTest;\n readonly options: SandboxConformanceOptions;\n readonly policy: SandboxPolicy;\n readonly outside: string;\n}\n\n/** The error's `code` when it is a `HarnessError`, which works across two bundled copies of this package. */\nfunction codeOf(error: unknown): string | undefined {\n return isHarnessError(error) ? error.code : undefined;\n}\n\n/** The denial a `sandbox_denied` error carries, or `undefined` for any other error. */\nfunction denialOf(error: unknown): SandboxDenial | undefined {\n return codeOf(error) === \"sandbox_denied\" ? (error as { denial?: SandboxDenial }).denial : undefined;\n}\n\n/** Provisions a sandbox for a case, or the skip that a backend reporting itself unavailable gets. */\nasync function provision(context: Context): Promise<Sandbox | Skip> {\n try {\n return await context.under.client.provision({ root: context.under.root }, context.policy);\n } catch (error) {\n if (codeOf(error) === \"sandbox_unavailable\") return { skipped: (error as Error).message };\n throw error;\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/** Polls until `test` is true, for at most `SETTLE_MS`. */\nasync function eventually(test: () => boolean | Promise<boolean>): Promise<boolean> {\n const stop = Date.now() + SETTLE_MS;\n while (Date.now() < stop) {\n if (await test()) return true;\n await sleep(50);\n }\n return test();\n}\n\n/** Runs `action` and returns the denial it ended in, as a thrown error or as a command's `denied` result. */\nasync function denialFrom(action: () => Promise<unknown>): Promise<SandboxDenial | undefined> {\n try {\n const result = await action();\n return typeof result === \"object\" && result !== null && \"denied\" in result\n ? (result as { denied: SandboxDenial }).denied\n : undefined;\n } catch (error) {\n return denialOf(error);\n }\n}\n\n/** Wraps a case's check so it provisions first, disposes after, and skips when the backend is unavailable. */\nfunction withSandbox(\n factory: SandboxFactory,\n options: SandboxConformanceOptions,\n body: (sandbox: Sandbox, context: Context) => Promise<Skip | undefined>,\n) {\n return async (): Promise<Skip | undefined> => {\n const under = await factory();\n const root = under.root;\n const policy: SandboxPolicy = {\n readRoots: [root],\n writeRoots: [root],\n network: { allow: [options.network?.allowed ?? ALLOWED_HOST], deny: [] },\n };\n const context: Context = { under, options, policy, outside: `${root}-outside` };\n const sandbox = await provision(context);\n if (\"skipped\" in sandbox) return sandbox;\n try {\n return await body(sandbox, context);\n } finally {\n await sandbox.dispose();\n }\n };\n}\n\nasync function exec(\n sandbox: Sandbox,\n command: readonly string[],\n extra: { env?: Record<string, string>; timeoutMs?: number; signal?: AbortSignal; cwd?: string } = {},\n): Promise<ExecResult> {\n return sandbox.exec(command, {\n env: extra.env ?? {},\n signal: extra.signal ?? never(),\n ...(extra.cwd === undefined ? {} : { cwd: extra.cwd }),\n ...(extra.timeoutMs === undefined ? {} : { timeoutMs: extra.timeoutMs }),\n });\n}\n\nfunction finished(result: ExecResult): Extract<ExecResult, { exitCode: number }> {\n check(!(\"denied\" in result), \"a command inside the workspace must not be denied\");\n return result;\n}\n\ntype Sandboxed = (\n body: (sandbox: Sandbox, context: Context) => Promise<Skip | undefined>,\n) => () => Promise<Skip | undefined>;\n\n/** The case that checks a backend's claims about itself. */\nfunction honestyCases(factory: SandboxFactory): readonly SandboxCase[] {\n return [\n {\n name: \"a backend names its tier and stops honestly: a none tier stops nothing, and every stop is a known one\",\n async run() {\n const { client } = await factory();\n check(\n [\"none\", \"os\", \"container\", \"gvisor\", \"microvm\"].includes(client.tier),\n `unknown tier ${String(client.tier)}`,\n );\n check(\n client.stops.every((stop) => STOPS.includes(stop)),\n \"every stop must be a known one\",\n );\n check(client.tier !== \"none\" || client.stops.length === 0, \"a none tier must stop nothing\");\n return undefined;\n },\n },\n ];\n}\n\n/** The cases that run in a provisioned sandbox. */\nfunction workspaceCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a file written in the workspace reads back as the same bytes\",\n run: sandboxed(async (sandbox) => {\n await sandbox.writeFile(\"notes/a.txt\", new TextEncoder().encode(\"hello\"));\n check(text(await sandbox.readFile(\"notes/a.txt\")) === \"hello\", \"the bytes written must be the bytes read\");\n return undefined;\n }),\n },\n {\n name: \"exec resolves with the exit code and output, and a failing command is a result, not an error\",\n run: sandboxed(async (sandbox) => {\n const echoed = finished(await exec(sandbox, [\"echo\", \"hello\"]));\n check(echoed.exitCode === 0 && echoed.stdout.trim() === \"hello\", \"echo must print its argument and exit 0\");\n const failed = finished(await exec(sandbox, [\"false\"]));\n check(failed.exitCode !== 0, \"a failing command must resolve with a non-zero exit code\");\n return undefined;\n }),\n },\n {\n name: \"exec's environment holds only the variables it was given, and no credential\",\n run: sandboxed(async (sandbox, context) => {\n const given = { ALPHA: \"1\", BETA: \"2\" };\n const printed = finished(await exec(sandbox, [\"env\"], { env: given }));\n const lines = printed.stdout.split(\"\\n\").filter((line) => line !== \"\");\n const names = lines.map((line) => line.slice(0, line.indexOf(\"=\")));\n check(lines.includes(\"ALPHA=1\") && lines.includes(\"BETA=2\"), \"the given variables must reach the command\");\n const addedByBackend = new Set(context.options.addedEnvironment ?? []);\n const extra = names.filter(\n (name) => !(name in given) && !ADDED_BY_RUNTIMES.has(name) && !addedByBackend.has(name),\n );\n check(extra.length === 0, `the command saw variables that were not given: ${extra.join(\", \")}`);\n check(!names.some((name) => CREDENTIALS.includes(name)), \"no credential may be in the environment\");\n return undefined;\n }),\n },\n {\n name: \"reading a file that doesn't exist rejects with sandbox_not_found\",\n run: sandboxed(async (sandbox) => {\n const code = await sandbox.readFile(\"no/such/file.txt\").then(\n () => \"it resolved\",\n (error: unknown) => codeOf(error) ?? String(error),\n );\n check(code === \"sandbox_not_found\", `a missing file must reject with sandbox_not_found, not ${code}`);\n return undefined;\n }),\n },\n {\n name: \"an already aborted signal rejects exec before the command runs\",\n run: sandboxed(async (sandbox) => {\n const controller = new AbortController();\n controller.abort(new Error(\"stop\"));\n let rejected = false;\n await exec(sandbox, [\"echo\", \"never\"], { signal: controller.signal }).catch(() => {\n rejected = true;\n });\n check(rejected, \"exec must reject for an aborted signal\");\n return undefined;\n }),\n },\n {\n name: \"a command that runs past its timeout is stopped with exit code 124 and timedOut\",\n run: sandboxed(async (sandbox) => {\n const started = Date.now();\n const result = finished(await exec(sandbox, [\"sleep\", \"10\"], { timeoutMs: 200 }));\n check(result.exitCode === 124, `a timed out command must exit with 124, not ${result.exitCode}`);\n check(result.timedOut === true, \"a timed out command's result must say timedOut: true\");\n check(Date.now() - started < 5000, \"the command must be stopped at the timeout\");\n return undefined;\n }),\n },\n ];\n}\n\n/** The case that checks `dispose()`. */\nfunction disposeCases(\n factory: SandboxFactory,\n options: SandboxConformanceOptions,\n sandboxed: Sandboxed,\n): readonly SandboxCase[] {\n return [\n {\n name: \"dispose ends a command that is still running, which rejects with sandbox_disposed\",\n run: sandboxed(async (sandbox) => {\n const running = exec(sandbox, [\"sleep\", \"30\"]).then(\n () => \"it resolved\",\n (error: unknown) => codeOf(error) ?? String(error),\n );\n await sleep(100);\n await sandbox.dispose();\n const outcome = await Promise.race([running, sleep(SETTLE_MS).then(() => \"it never settled\")]);\n check(\n outcome === \"sandbox_disposed\",\n `a command running at dispose must reject with sandbox_disposed, not ${outcome}`,\n );\n return undefined;\n }),\n },\n {\n name: \"dispose ends the sandbox: a later call rejects, and a second dispose does nothing\",\n async run() {\n const under = await factory();\n const context: Context = {\n under,\n options,\n policy: { readRoots: [under.root], writeRoots: [under.root], network: { allow: [], deny: [] } },\n outside: `${under.root}-outside`,\n };\n const sandbox = await provision(context);\n if (\"skipped\" in sandbox) return sandbox;\n await sandbox.dispose();\n await sandbox.dispose();\n let code = \"\";\n await sandbox.readFile(\"a.txt\").catch((error: unknown) => {\n code = isHarnessError(error) ? error.code : String(error);\n });\n check(code === \"sandbox_disposed\", `a call after dispose must reject with sandbox_disposed, not ${code}`);\n return undefined;\n },\n },\n ];\n}\n\nconst MISTAKES = \"the backend does not claim to stop mistakes\";\n\n/** The name of the workspace's folder, for a path that climbs out of it and back into its sibling. */\nfunction outsideViaParent(context: Context): string {\n const root = context.under.root;\n return `../${root.slice(root.lastIndexOf(\"/\") + 1)}-outside`;\n}\n\n/** The cases that need a backend to enforce its policy, which run only when its `stops` claim it. */\nfunction policyCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a write outside the write roots is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => sandbox.writeFile(`${context.outside}/x.txt`, new Uint8Array([1])));\n check(denial?.kind === \"filesystem_write\", \"a write outside the write roots must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a read outside the read roots is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => sandbox.readFile(`${context.outside}/x.txt`));\n check(denial?.kind === \"filesystem_read\", \"a read outside the read roots must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a path that climbs out of the workspace with .. is denied for reads and writes\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const climb = `${outsideViaParent(context)}/x.txt`;\n const write = await denialFrom(() => sandbox.writeFile(climb, new Uint8Array([1])));\n check(write?.kind === \"filesystem_write\", \"a write that climbs out with .. must be denied\");\n const read = await denialFrom(() => sandbox.readFile(climb));\n check(read?.kind === \"filesystem_read\", \"a read that climbs out with .. must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a symlink in the workspace that points outside it is denied for reads and writes\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const symlink = context.under.symlink;\n if (symlink === undefined) return { skipped: \"the factory gave no symlink function\" };\n await symlink(`${context.under.root}/link`, context.outside);\n const write = await denialFrom(() => sandbox.writeFile(\"link/x.txt\", new Uint8Array([1])));\n check(write?.kind === \"filesystem_write\", \"a write through a symlink that points outside must be denied\");\n const read = await denialFrom(() => sandbox.readFile(\"link/x.txt\"));\n check(read?.kind === \"filesystem_read\", \"a read through a symlink that points outside must be denied\");\n return undefined;\n }),\n },\n {\n name: \"a working directory outside the workspace is denied\",\n run: sandboxed(async (sandbox, context) => {\n if (!context.under.client.stops.includes(\"mistakes\")) return { skipped: MISTAKES };\n const denial = await denialFrom(() => exec(sandbox, [\"echo\", \"hi\"], { cwd: \"../..\" }));\n check(denial !== undefined, \"a command whose cwd climbs out of the workspace must be denied\");\n return undefined;\n }),\n },\n {\n name: \"the network is denied unless the host is on the allowlist\",\n run: sandboxed(async (sandbox, context) => {\n const network = context.options.network;\n if (!context.under.client.stops.includes(\"exfiltration\"))\n return { skipped: \"the backend does not claim to stop exfiltration\" };\n if (network === undefined) return { skipped: \"no network probe was given\" };\n const reached = await exec(sandbox, network.command(network.allowed));\n check(!(\"denied\" in reached) && reached.exitCode === 0, \"the allowed host must be reached\");\n const blocked = await exec(sandbox, network.command(network.blocked));\n check(\"denied\" in blocked || blocked.exitCode !== 0, \"a host that is not allowed must not be reached\");\n return undefined;\n }),\n },\n ];\n}\n\ntype ProcessTree = NonNullable<SandboxConformanceOptions[\"processTree\"]>;\n\n/** Starts the tree's command, stops it by `stop`, and checks that exec settled the right way and the tree is dead. */\nasync function endTree(sandbox: Sandbox, tree: ProcessTree, stop: \"abort\" | \"timeout\"): Promise<void> {\n // Clear the previous round's id, so a stale one can't pass for this round's.\n await sandbox.writeFile(\"pid\", new Uint8Array());\n const controller = new AbortController();\n const running = exec(sandbox, tree.command, {\n signal: controller.signal,\n ...(stop === \"timeout\" ? { timeoutMs: 1500 } : {}),\n }).then(\n (result) => ({ result }),\n (error: unknown) => ({ error }),\n );\n let pid = Number.NaN;\n const wrote = await eventually(async () => {\n pid = Number(text(await sandbox.readFile(\"pid\").catch(() => new Uint8Array())).trim());\n return Number.isInteger(pid) && pid > 0;\n });\n check(wrote, \"the command must write its background process's id\");\n if (stop === \"abort\") controller.abort(new Error(\"stop\"));\n const outcome = await Promise.race([running, sleep(SETTLE_MS).then(() => undefined)]);\n check(outcome !== undefined, `exec must settle after ${stop}, though a background process held its pipes`);\n check(\n stop === \"abort\" ? \"error\" in outcome : \"result\" in outcome,\n `${stop} must ${stop === \"abort\" ? \"reject\" : \"resolve\"}`,\n );\n check(await eventually(async () => !(await tree.isAlive(pid))), `the background process must die on ${stop}`);\n}\n\n/** The case that checks an abort and a timeout end a command's whole process tree. */\nfunction processCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"an abort and a timeout end the command's whole process tree, and exec settles\",\n run: sandboxed(async (sandbox, context) => {\n const tree = context.options.processTree;\n if (tree === undefined) return { skipped: \"no processTree was given\" };\n await endTree(sandbox, tree, \"abort\");\n await endTree(sandbox, tree, \"timeout\");\n return undefined;\n }),\n },\n ];\n}\n\n/** The code a call rejects with, or `\"it resolved\"`. */\nasync function rejection(action: () => Promise<unknown>): Promise<string> {\n return action().then(\n () => \"it resolved\",\n (error: unknown) => codeOf(error) ?? String(error),\n );\n}\n\n/** Checks that a capability the client doesn't list is refused, and that one it lists works and keeps the files. */\nasync function checkCapability(sandbox: Sandbox, context: Context, capability: SandboxCapability): Promise<void> {\n const { client } = context.under;\n if (!hasCapability(client, capability)) {\n const refused =\n capability === \"resume\"\n ? await rejection(() => resumeSandbox(client, \"no-such-sandbox\", context.policy))\n : await rejection(() => (capability === \"snapshot\" ? snapshotSandbox : pauseSandbox)(client, sandbox));\n check(refused === \"sandbox_unsupported\", `an unlisted ${capability} must be refused, not ${refused}`);\n return;\n }\n const encoder = new TextEncoder();\n await sandbox.writeFile(`kept-${capability}.txt`, encoder.encode(capability));\n let id = sandbox.id;\n if (capability === \"snapshot\") id = await snapshotSandbox(client, sandbox);\n if (capability === \"pause\") await pauseSandbox(client, sandbox);\n check(typeof id === \"string\" && id !== \"\", `a sandbox that can ${capability} must have an id to resume`);\n if (!hasCapability(client, \"resume\")) return;\n const resumed = await resumeSandbox(client, id, context.policy);\n try {\n const kept = text(await resumed.readFile(`kept-${capability}.txt`));\n check(kept === capability, `a sandbox resumed after ${capability} must keep its files`);\n } finally {\n // A resume by the sandbox's own id reattaches to it, which the case's own dispose ends.\n if (resumed.id !== sandbox.id) await resumed.dispose();\n }\n}\n\n/** The case that checks the resume, snapshot and pause capabilities. */\nfunction capabilityCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a backend lists only known capabilities, each one it lists works, and one it doesn't is refused with sandbox_unsupported\",\n run: sandboxed(async (sandbox, context) => {\n const listed = context.under.client.capabilities ?? [];\n check(\n Array.isArray(listed) && listed.every((capability) => CAPABILITIES.includes(capability)),\n \"every capability must be a known one\",\n );\n for (const capability of CAPABILITIES) await checkCapability(sandbox, context, capability);\n return undefined;\n }),\n },\n ];\n}\n\nconst NO_STOP = \"the backend does not claim to stop anything, so it enforces no policy to read back\";\n\n/** The cases that check the policy a backend reads back, which run only when it claims a stop. */\nfunction readBackCases(sandboxed: Sandboxed): readonly SandboxCase[] {\n return [\n {\n name: \"a backend that claims a stop reads back the policy it applied, which equals the request, and delivers its stops\",\n run: sandboxed(async (sandbox, context) => {\n const { client } = context.under;\n if (client.stops.length === 0) return { skipped: NO_STOP };\n check(typeof sandbox.readBack === \"function\", \"a backend that claims a stop must read its policy back\");\n const applied = await sandbox.readBack();\n const field = policyDifference(context.policy, applied);\n check(field === undefined, `the read-back must equal the request, but ${field} differs`);\n const delivered = stopsFor(client.tier, applied);\n check(\n client.stops.every((stop) => delivered.includes(stop)),\n \"the applied policy must deliver every stop claimed\",\n );\n const stops = sandbox.stops ?? [];\n check(\n stops.length === delivered.length && stops.every((stop) => delivered.includes(stop)),\n \"the sandbox's stops must be the ones its applied policy delivers\",\n );\n return undefined;\n }),\n },\n {\n name: \"a read-back that differs from the request throws sandbox_policy_mismatch, names the field and disposes the sandbox\",\n run: sandboxed(async (sandbox, context) => {\n const { client } = context.under;\n if (client.stops.length === 0) return { skipped: NO_STOP };\n check(typeof sandbox.readBack === \"function\", \"a backend that claims a stop must read its policy back\");\n const applied = await sandbox.readBack();\n const { policy, outside } = context;\n const widened: [string, SandboxPolicy][] = [\n [\"readRoots\", { ...policy, readRoots: [...policy.readRoots, outside] }],\n [\"writeRoots\", { ...policy, writeRoots: [] }],\n [\"network.allow\", { ...policy, network: { ...policy.network, allow: [...policy.network.allow, \"x.test\"] } }],\n [\"network.deny\", { ...policy, network: { ...policy.network, deny: [\"y.test\"] } }],\n ];\n for (const [field, other] of widened) {\n const found = policyDifference(other, applied);\n check(found === field, `a request that differs in ${field} must be found to differ there, not in ${found}`);\n }\n const asked = widened[2]?.[1] ?? policy;\n const error = await confirmPolicy(client, sandbox, asked).then(\n () => undefined,\n (caught: unknown) => caught,\n );\n check(codeOf(error) === \"sandbox_policy_mismatch\", \"a mismatch must throw sandbox_policy_mismatch\");\n check((error as { field?: unknown }).field === \"network.allow\", \"the error must name the field\");\n check(!String((error as Error).message).includes(\"x.test\"), \"the message must not name a host\");\n const after = await rejection(() => sandbox.readFile(\"a.txt\"));\n check(after === \"sandbox_disposed\", `a mismatch must dispose the sandbox, but a later call gave ${after}`);\n return undefined;\n }),\n },\n ];\n}\n\n/** The cases, for a backend from `factory`. Run each one; a case that doesn't apply resolves with `{ skipped }`. */\nexport function sandboxConformanceCases(\n factory: SandboxFactory,\n options: SandboxConformanceOptions = {},\n): readonly SandboxCase[] {\n const sandboxed: Sandboxed = (body) => withSandbox(factory, options, body);\n return [\n ...honestyCases(factory),\n ...workspaceCases(sandboxed),\n ...processCases(sandboxed),\n ...disposeCases(factory, options, sandboxed),\n ...policyCases(sandboxed),\n ...capabilityCases(sandboxed),\n ...readBackCases(sandboxed),\n ];\n}\n\n/**\n * Runs every case against backends from `factory` and reports which passed, which skipped with a reason and which\n * failed. A backend that reports itself unavailable skips; any other error fails the case.\n */\nexport async function runSandboxConformance(\n factory: SandboxFactory,\n options: SandboxConformanceOptions = {},\n): Promise<SandboxConformanceReport> {\n return runCases(sandboxConformanceCases(factory, options));\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bash`: runs a shell command through `Sandbox.exec()` only, never on the host, with the environment the host chose
|
|
3
|
+
* and a timeout. Its output reaches the model through the context policy's write cap like every tool result, and the
|
|
4
|
+
* sandbox drops what passes the per-stream bound first, so one command can't hold the host's memory.
|
|
5
|
+
*/
|
|
6
|
+
import { type ToolDefinition } from "@buildanagent/sdk";
|
|
7
|
+
import type { Sandbox } from "../../sandbox/types.js";
|
|
8
|
+
/** The `bash` tool, which runs each command with `env` as its whole environment. */
|
|
9
|
+
export declare function bashTool(sandbox: Sandbox, env: Readonly<Record<string, string>>): ToolDefinition<unknown, unknown, unknown>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bash`: runs a shell command through `Sandbox.exec()` only, never on the host, with the environment the host chose
|
|
3
|
+
* and a timeout. Its output reaches the model through the context policy's write cap like every tool result, and the
|
|
4
|
+
* sandbox drops what passes the per-stream bound first, so one command can't hold the host's memory.
|
|
5
|
+
*/
|
|
6
|
+
import { defineTool } from "@buildanagent/sdk";
|
|
7
|
+
import { BUILTIN_TOOL_DEFAULTS } from "./descriptions.js";
|
|
8
|
+
import { deniedResult, errorResult, failureResult, textResult } from "./results.js";
|
|
9
|
+
/** The text the model reads for a command that ran: its output, its standard error and how it ended. */
|
|
10
|
+
function report(result, timeoutMs) {
|
|
11
|
+
const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.bash;
|
|
12
|
+
const parts = [result.stdout];
|
|
13
|
+
if (result.stderr !== "")
|
|
14
|
+
parts.push(`[stderr]\n${result.stderr}`);
|
|
15
|
+
if (result.truncated === true)
|
|
16
|
+
parts.push(`[output past ${maxOutputBytes} bytes per stream was dropped]`);
|
|
17
|
+
// Only the sandbox's flag means the timeout stopped it: a command may exit with 124 itself, as `timeout` does.
|
|
18
|
+
const timedOut = result.timedOut === true;
|
|
19
|
+
const ending = timedOut
|
|
20
|
+
? `[timed out after ${timeoutMs} ms]`
|
|
21
|
+
: `[exit code ${result.exitCode}${result.signal === undefined ? "" : `, killed by ${result.signal}`}]`;
|
|
22
|
+
parts.push(ending);
|
|
23
|
+
const text = parts.filter((part) => part !== "").join("\n");
|
|
24
|
+
const details = {
|
|
25
|
+
exitCode: result.exitCode,
|
|
26
|
+
...(result.signal === undefined ? {} : { signal: result.signal }),
|
|
27
|
+
...(timedOut ? { timedOut } : {}),
|
|
28
|
+
};
|
|
29
|
+
return timedOut ? { ...errorResult(text), details } : textResult(text, details);
|
|
30
|
+
}
|
|
31
|
+
/** The `bash` tool, which runs each command with `env` as its whole environment. */
|
|
32
|
+
export function bashTool(sandbox, env) {
|
|
33
|
+
const { defaultTimeoutMs, maxTimeoutMs, maxOutputBytes, description } = BUILTIN_TOOL_DEFAULTS.bash;
|
|
34
|
+
return defineTool({
|
|
35
|
+
name: "bash",
|
|
36
|
+
description,
|
|
37
|
+
inputSchema: {
|
|
38
|
+
type: "object",
|
|
39
|
+
properties: {
|
|
40
|
+
command: { type: "string", minLength: 1, description: "The command to run, as bash reads it." },
|
|
41
|
+
timeout_ms: {
|
|
42
|
+
type: "integer",
|
|
43
|
+
minimum: 1,
|
|
44
|
+
maximum: maxTimeoutMs,
|
|
45
|
+
description: `Milliseconds before the command is stopped. Default ${defaultTimeoutMs}.`,
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
required: ["command"],
|
|
49
|
+
additionalProperties: false,
|
|
50
|
+
},
|
|
51
|
+
firstParty: true,
|
|
52
|
+
effect: { kind: "write" },
|
|
53
|
+
// A command may read or change anything in the workspace, so the calls around it wait their turn.
|
|
54
|
+
executionMode: "sequential",
|
|
55
|
+
async execute(input, ctx) {
|
|
56
|
+
const timeoutMs = Math.min(input.timeout_ms ?? defaultTimeoutMs, maxTimeoutMs);
|
|
57
|
+
let result;
|
|
58
|
+
try {
|
|
59
|
+
result = await sandbox.exec(["bash", "-c", input.command], {
|
|
60
|
+
env,
|
|
61
|
+
signal: ctx.signal,
|
|
62
|
+
timeoutMs,
|
|
63
|
+
maxOutputBytes,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return failureResult(error);
|
|
68
|
+
}
|
|
69
|
+
if ("denied" in result)
|
|
70
|
+
return deniedResult(result.denied);
|
|
71
|
+
return report(result, timeoutMs);
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=bash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../../src/tools/builtins/bash.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAwC,MAAM,mBAAmB,CAAC;AAErF,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAOpF,wGAAwG;AACxG,SAAS,MAAM,CAAC,MAAiD,EAAE,SAAiB;IAClF,MAAM,EAAE,cAAc,EAAE,GAAG,qBAAqB,CAAC,IAAI,CAAC;IACtD,MAAM,KAAK,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9B,IAAI,MAAM,CAAC,MAAM,KAAK,EAAE;QAAE,KAAK,CAAC,IAAI,CAAC,a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QACnC,CAAC;KACF,CAA8C,CAAC;AAClD,CAAC","sourcesContent":["/**\n * `bash`: runs a shell command through `Sandbox.exec()` only, never on the host, with the environment the host chose\n * and a timeout. Its output reaches the model through the context policy's write cap like every tool result, and the\n * sandbox drops what passes the per-stream bound first, so one command can't hold the host's memory.\n */\nimport { defineTool, type ToolDefinition, type ToolResult } from \"@buildanagent/sdk\";\nimport type { ExecResult, Sandbox } from \"../../sandbox/types.js\";\nimport { BUILTIN_TOOL_DEFAULTS } from \"./descriptions.js\";\nimport { deniedResult, errorResult, failureResult, textResult } from \"./results.js\";\n\ninterface BashInput {\n readonly command: string;\n readonly timeout_ms?: number;\n}\n\n/** The text the model reads for a command that ran: its output, its standard error and how it ended. */\nfunction report(result: Extract<ExecResult, { exitCode: number }>, timeoutMs: number): ToolResult {\n const { maxOutputBytes } = BUILTIN_TOOL_DEFAULTS.bash;\n const parts = [result.stdout];\n if (result.stderr !== \"\") parts.push(`[stderr]\\n${result.stderr}`);\n if (result.truncated === true) parts.push(`[output past ${maxOutputBytes} bytes per stream was dropped]`);\n // Only the sandbox's flag means the timeout stopped it: a command may exit with 124 itself, as `timeout` does.\n const timedOut = result.timedOut === true;\n const ending = timedOut\n ? `[timed out after ${timeoutMs} ms]`\n : `[exit code ${result.exitCode}${result.signal === undefined ? \"\" : `, killed by ${result.signal}`}]`;\n parts.push(ending);\n const text = parts.filter((part) => part !== \"\").join(\"\\n\");\n const details = {\n exitCode: result.exitCode,\n ...(result.signal === undefined ? {} : { signal: result.signal }),\n ...(timedOut ? { timedOut } : {}),\n };\n return timedOut ? { ...errorResult(text), details } : textResult(text, details);\n}\n\n/** The `bash` tool, which runs each command with `env` as its whole environment. */\nexport function bashTool(\n sandbox: Sandbox,\n env: Readonly<Record<string, string>>,\n): ToolDefinition<unknown, unknown, unknown> {\n const { defaultTimeoutMs, maxTimeoutMs, maxOutputBytes, description } = BUILTIN_TOOL_DEFAULTS.bash;\n return defineTool<BashInput>({\n name: \"bash\",\n description,\n inputSchema: {\n type: \"object\",\n properties: {\n command: { type: \"string\", minLength: 1, description: \"The command to run, as bash reads it.\" },\n timeout_ms: {\n type: \"integer\",\n minimum: 1,\n maximum: maxTimeoutMs,\n description: `Milliseconds before the command is stopped. Default ${defaultTimeoutMs}.`,\n },\n },\n required: [\"command\"],\n additionalProperties: false,\n },\n firstParty: true,\n effect: { kind: \"write\" },\n // A command may read or change anything in the workspace, so the calls around it wait their turn.\n executionMode: \"sequential\",\n async execute(input, ctx) {\n const timeoutMs = Math.min(input.timeout_ms ?? defaultTimeoutMs, maxTimeoutMs);\n let result: ExecResult;\n try {\n result = await sandbox.exec([\"bash\", \"-c\", input.command], {\n env,\n signal: ctx.signal,\n timeoutMs,\n maxOutputBytes,\n });\n } catch (error) {\n return failureResult(error);\n }\n if (\"denied\" in result) return deniedResult(result.denied);\n return report(result, timeoutMs);\n },\n }) as ToolDefinition<unknown, unknown, unknown>;\n}\n"]}
|